diff --git a/.github/data/logo_256_square.png b/.github/data/logo_256_square.png
new file mode 100644
index 0000000000000..dbc4ac7ac66a6
Binary files /dev/null and b/.github/data/logo_256_square.png differ
diff --git a/.github/scripts/generate_changelog.py b/.github/scripts/generate_changelog.py
index 6cdd12652d31b..22e2bb310e39e 100644
--- a/.github/scripts/generate_changelog.py
+++ b/.github/scripts/generate_changelog.py
@@ -13,9 +13,9 @@
]
VERSION_RE = re.compile(
- r"^(\d+\.\d+(?:\.\d+)?)\s*" # version number
- r"(?:(alpha|beta|dev|stable)\s*)?" # optional tag
- r"\((\d{2})\.(\d{2})\.(\d{2,4})\)$" # date (DD.MM.YY or DD.MM.YYYY)
+ r"^(\d+\.\d+(?:\.\d+)?)\s*"
+ r"(?:(alpha|beta|dev|stable)\s*)?"
+ r"\((\d{2})\.(\d{2})\.(\d{2,4})\)$"
)
@@ -53,7 +53,6 @@ def parse_changelog(text: str) -> list[dict]:
"lines": [],
}
elif current is not None:
- # Skip blank lines at the start
if not line and not current["lines"]:
continue
# Skip stray artifact lines
@@ -64,7 +63,6 @@ def parse_changelog(text: str) -> list[dict]:
if current:
entries.append(current)
- # Trim trailing blank lines from each entry
for entry in entries:
while entry["lines"] and not entry["lines"][-1]:
entry["lines"].pop()
@@ -93,7 +91,6 @@ def render_entry(entry: dict) -> str:
for line in entry["lines"]:
stripped = line.lstrip()
if stripped.startswith("- ") or stripped.startswith("\u2014 "):
- # Bullet point (- or em dash)
if not in_list:
parts.append("
")
in_list = True
@@ -279,7 +276,6 @@ def build_html(entries: list[dict]) -> str:
}}, 150);
}});
- // Anchor links: copy URL on click
document.addEventListener('click', function(e) {{
var anchor = e.target.closest('.anchor');
if (!anchor) return;
@@ -314,7 +310,6 @@ def main():
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(html_content, encoding="utf-8")
- # Copy favicon files from resources
icons_src = repo / "Telegram" / "Resources" / "art"
for name in ("icon16.png", "icon32.png"):
icon = icons_src / name
diff --git a/.github/scripts/mint_session.py b/.github/scripts/mint_session.py
new file mode 100755
index 0000000000000..9713131ac08f1
--- /dev/null
+++ b/.github/scripts/mint_session.py
@@ -0,0 +1,25 @@
+#!/usr/bin/env python3
+"""
+One-time LOCAL session minter for the release uploader account (never run in CI).
+
+ pip install telethon
+ TG_API_ID= TG_API_HASH= python mint_session.py
+
+Logs in interactively (phone + login code, plus 2FA password if set) and prints
+a Telethon StringSession for the TG_SESSION secret. The session grants FULL
+control of the account, so use a DEDICATED account that is admin of only the two
+update channels (TG_FEED_CHANNEL, TG_FILES_CHANNEL) - not your personal one.
+"""
+import os
+from telethon.sync import TelegramClient
+from telethon.sessions import StringSession
+
+api_id = int(os.environ.get("TG_API_ID") or input("api_id: ").strip())
+api_hash = os.environ.get("TG_API_HASH") or input("api_hash: ").strip()
+
+with TelegramClient(StringSession(), api_id, api_hash) as client:
+ print("\n--- copy the line below into the TG_SESSION secret ---\n")
+ print(client.session.save())
+ print("\n--- keep it secret; anyone with it controls this account ---")
+ me = client.get_me()
+ print(f"\nlogged in as: {me.first_name} (@{me.username or 'no-username'}, id={me.id})")
diff --git a/.github/scripts/publish_channel.py b/.github/scripts/publish_channel.py
new file mode 100644
index 0000000000000..4331b88be3b6c
--- /dev/null
+++ b/.github/scripts/publish_channel.py
@@ -0,0 +1,110 @@
+#!/usr/bin/env python3
+"""
+Publish one release asset to the public announcement channel.
+"""
+import os
+import sys
+import asyncio
+from datetime import datetime, timedelta, timezone
+
+from telethon import TelegramClient
+from telethon.extensions import markdown
+from telethon.sessions import StringSession
+from telethon.tl.types import DocumentAttributeFilename
+
+CHANNEL = os.environ["TG_PUBLIC_CHANNEL"]
+ASSET_PATH = os.environ["ASSET_PATH"]
+VERSION = os.environ["ASSET_VERSION"]
+BETA = os.environ.get("ASSET_BETA", "0") == "1"
+DRY_RUN = os.environ.get("TG_DRY_RUN", "") == "1"
+SCHEDULE_DAYS = int(os.environ.get("TG_SCHEDULE_DAYS", "350") or "350")
+SEARCH_LIMIT = int(os.environ.get("TG_SEARCH_LIMIT", "200") or "200")
+THUMB = os.environ.get("TG_THUMB") or os.path.join(
+ os.path.dirname(os.path.abspath(__file__)), "..", "data",
+ "logo_256_square.png")
+
+CAPTION = ("— Updated version to "
+ "[{label}](https://github.com/telegramdesktop/tdesktop/releases/tag/v{version}).")
+
+
+def document_name(message):
+ document = message.document
+ for attribute in document.attributes if document else ():
+ if isinstance(attribute, DocumentAttributeFilename):
+ return attribute.file_name
+ return None
+
+
+async def find_previous(client, channel, name):
+ async for message in client.iter_messages(channel, limit=SEARCH_LIMIT):
+ if document_name(message) == name:
+ return message
+ return None
+
+
+async def warn_if_unsent(client, channel, name):
+ async for message in client.iter_messages(channel, scheduled=True):
+ if document_name(message) == name:
+ print(f"WARNING: scheduled message #{message.id} carries {name} and "
+ f"has not been sent yet; this upload replies past it.")
+ return
+
+
+async def main():
+ if not os.path.isfile(ASSET_PATH):
+ sys.exit(f"No asset at {ASSET_PATH!r}.")
+ if not os.path.isfile(THUMB):
+ sys.exit(f"No thumbnail at {THUMB!r} (forgot to sparse-checkout it?).")
+
+ asset_name = os.path.basename(ASSET_PATH)
+ caption = CAPTION.format(
+ label=f"{VERSION} beta" if BETA else VERSION,
+ version=VERSION)
+ size = os.path.getsize(ASSET_PATH) / 1048576
+ print(f"File: {ASSET_PATH} ({size:.0f} MiB)")
+ print(f"Caption: {caption}")
+
+ shown, entities = markdown.parse(caption)
+ print(f"Renders as: {shown}")
+ for e in entities:
+ print(f" {type(e).__name__}: {shown[e.offset:e.offset + e.length]!r} "
+ f"-> {getattr(e, 'url', '')}")
+
+ if not 0 < SCHEDULE_DAYS < 365:
+ sys.exit(f"TG_SCHEDULE_DAYS must be within 1..364, got {SCHEDULE_DAYS}.")
+ when = datetime.now(timezone.utc) + timedelta(days=SCHEDULE_DAYS)
+
+ api_id = int(os.environ["TG_API_ID"])
+ api_hash = os.environ["TG_API_HASH"]
+ session = os.environ["TG_SESSION"]
+
+ async with TelegramClient(StringSession(session), api_id, api_hash) as client:
+ channel = await client.get_entity(CHANNEL)
+
+ previous = await find_previous(client, channel, asset_name)
+ if not previous:
+ sys.exit(f"No message with {asset_name} among the last "
+ f"{SEARCH_LIMIT} in {CHANNEL} to reply to.")
+ first_line = next(iter((previous.message or "").splitlines()), "")
+ print(f"Replying to #{previous.id} of {previous.date:%Y-%m-%d}: "
+ f"{first_line!r}")
+ await warn_if_unsent(client, channel, asset_name)
+
+ if DRY_RUN:
+ print("\n[dry-run] not uploading.")
+ return
+
+ msg = await client.send_file(
+ channel, ASSET_PATH,
+ force_document=True,
+ caption=caption,
+ parse_mode="md",
+ thumb=THUMB,
+ reply_to=previous.id,
+ schedule=when)
+ print(f"\nscheduled message #{msg.id} in {CHANNEL} for {when:%Y-%m-%d} "
+ f"({SCHEDULE_DAYS} days out); send it from the Scheduled queue.")
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/.github/scripts/publish_telegram.py b/.github/scripts/publish_telegram.py
new file mode 100755
index 0000000000000..834e236947414
--- /dev/null
+++ b/.github/scripts/publish_telegram.py
@@ -0,0 +1,181 @@
+#!/usr/bin/env python3
+"""
+Publish Windows auto-update files to the Telegram update channels.
+
+The client reads the feed channel's latest message over MTProto - a JSON map of
+platform -> channel -> type -> ":#" - and
+downloads the referenced document. So: upload each update file to the files
+channel, then post one feed message pointing at the uploads. That message must
+carry every platform at once, so new entries are merged onto the previous feed
+JSON rather than replacing it.
+"""
+import os
+import re
+import sys
+import json
+import glob
+import asyncio
+from datetime import datetime, timedelta, timezone
+
+from telethon import TelegramClient
+from telethon.sessions import StringSession
+
+FEED = os.environ["TG_FEED_CHANNEL"]
+FILES = os.environ["TG_FILES_CHANNEL"]
+ARTIFACTS_DIR = os.environ.get("ARTIFACTS_DIR", "artifacts")
+ENTRY_KEY = os.environ.get("TG_ENTRY_KEY", "released")
+DRY_RUN = os.environ.get("TG_DRY_RUN", "") == "1"
+SCHEDULE_DAYS = int(os.environ.get("TG_SCHEDULE_DAYS", "0") or "0")
+MAX_AGE_DAYS = int(os.environ.get("TG_FEED_MAX_AGE_DAYS", "2") or "2")
+THUMB = os.environ.get("TG_THUMB") or os.path.join(
+ os.path.dirname(os.path.abspath(__file__)), "..", "data",
+ "logo_256_square.png")
+
+# Update file name -> platform key the client matches against Platform::AutoUpdateKey().
+# The trailing -beta is the only thing that says which channel this is.
+NAME_TO_PLATFORM = [
+ (re.compile(r"^td-update-win-x64-(\d+)(-beta)?$"), "win64"),
+ (re.compile(r"^td-update-win-arm-(\d+)(-beta)?$"), "winarm"),
+ (re.compile(r"^td-update-win-x86-(\d+)(-beta)?$"), "win"),
+ (re.compile(r"^td-update-linux-x64-(\d+)(-beta)?$"), "linux"),
+]
+
+
+def find_update_files(root):
+ """Return ({platform: (version:int, path)}, beta:bool) for the update files."""
+ result, betas = {}, set()
+ for path in sorted(glob.glob(os.path.join(root, "**", "*"), recursive=True)):
+ if not os.path.isfile(path):
+ continue
+ name = os.path.basename(path)
+ for rx, platform in NAME_TO_PLATFORM:
+ m = rx.match(name)
+ if not m:
+ continue
+ if platform in result:
+ sys.exit(f"Two update files map to {platform}: "
+ f"{result[platform][1]} and {path}")
+ result[platform] = (int(m.group(1)), path)
+ betas.add(bool(m.group(2)))
+ break
+ if len(betas) > 1:
+ sys.exit(f"Mixed beta and stable update files in {root}: {sorted(result)}")
+ return result, bool(betas and betas.pop())
+
+
+def load_previous_feed(text):
+ if not text:
+ return {}
+ try:
+ data = json.loads(text)
+ except json.JSONDecodeError:
+ print("Previous feed message is not JSON; starting fresh.")
+ return {}
+ return data if isinstance(data, dict) else {}
+
+
+def versions_in(feed):
+ """Every version integer referenced by any entry (':chan#id') in a feed."""
+ found = set()
+ for platform in feed.values():
+ if not isinstance(platform, dict):
+ continue
+ for chan in platform.values():
+ if not isinstance(chan, dict):
+ continue
+ for entry in chan.values():
+ head = entry.split(":", 1)[0] if isinstance(entry, str) else ""
+ if head.isdigit():
+ found.add(int(head))
+ return found
+
+
+async def main():
+ updates, beta = find_update_files(ARTIFACTS_DIR)
+ if not updates:
+ sys.exit(f"No update files found under {ARTIFACTS_DIR!r}.")
+ if not os.path.isfile(THUMB):
+ sys.exit(f"No thumbnail at {THUMB!r} (forgot to sparse-checkout it?).")
+
+ print("Update files to publish:")
+ for platform, (version, path) in sorted(updates.items()):
+ size = os.path.getsize(path) / 1048576
+ print(f" {platform}: version {version}, {size:.0f} MiB, {path}")
+
+ api_id = int(os.environ["TG_API_ID"])
+ api_hash = os.environ["TG_API_HASH"]
+ session = os.environ["TG_SESSION"]
+
+ async with TelegramClient(StringSession(session), api_id, api_hash) as client:
+ feed = await client.get_entity(FEED)
+ files = await client.get_entity(FILES)
+
+ previous = await client.get_messages(feed, limit=1)
+ prev_msg = previous[0] if previous else None
+ merged = load_previous_feed(prev_msg.message if prev_msg else "")
+ prev_versions = versions_in(merged)
+ release_version = max(v for v, _ in updates.values())
+
+ when = None
+ if SCHEDULE_DAYS > 0:
+ when = datetime.now(timezone.utc) + timedelta(days=SCHEDULE_DAYS)
+ print(f"Scheduling every message for {when:%Y-%m-%d} "
+ f"({SCHEDULE_DAYS} days out); nothing appears in the channels now.")
+
+ # A beta writes only its own channel, so opted-out clients stay on
+ # the last stable; a stable writes both, so beta users move on to it.
+ channels = ("beta",) if beta else ("beta", "stable")
+ keys = ("testing",) if ENTRY_KEY == "testing" else ("released", "testing")
+ targets = [(chan, key) for chan in channels for key in keys]
+ print(f"Publishing a {'beta' if beta else 'stable'} release into "
+ f"{'/'.join(channels)}.")
+
+ for platform, (version, path) in sorted(updates.items()):
+ if DRY_RUN:
+ entry = f"{version}:{FILES}#"
+ print(f"[dry-run] would upload {path} -> {platform}")
+ else:
+ msg = await client.send_file(
+ files, path,
+ force_document=True,
+ caption='',
+ thumb=THUMB,
+ schedule=when)
+ entry = f"{version}:{FILES}#{msg.id}"
+ print(f"uploaded {platform}: {entry}")
+ entry_map = merged.setdefault(platform, {})
+ for chan, key in targets:
+ entry_map.setdefault(chan, {})[key] = entry
+
+ text = json.dumps(merged, separators=(",", ":"), sort_keys=True)
+ print("\nFeed JSON:")
+ print(text)
+
+ if DRY_RUN:
+ print("\n[dry-run] not posting the feed message.")
+ return
+
+ # Edit the latest message in place when it belongs to this release wave -
+ # recent and already carrying this version (e.g. Mac published it first) -
+ # so one message covers every platform. Otherwise post a new one. A
+ # scheduled test never edits the live message.
+ age = (datetime.now(timezone.utc) - prev_msg.date) if prev_msg else None
+ same_wave = (when is None
+ and prev_msg is not None
+ and age <= timedelta(days=MAX_AGE_DAYS)
+ and release_version in prev_versions)
+ if same_wave:
+ await client.edit_message(feed, prev_msg.id, text)
+ print(f"\nedited feed message #{prev_msg.id} in {FEED} "
+ f"(age {age.days}d, version {release_version} already present).")
+ else:
+ posted = await client.send_message(feed, text, schedule=when)
+ reason = ("scheduled test" if when
+ else "no recent same-version message" if prev_msg
+ else "empty feed")
+ print(f"\n{'scheduled' if when else 'posted'} feed message "
+ f"#{posted.id} to {FEED} ({reason}).")
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/.github/scripts/requirements-legacy-uploader.txt b/.github/scripts/requirements-legacy-uploader.txt
new file mode 100644
index 0000000000000..945b246ddc619
--- /dev/null
+++ b/.github/scripts/requirements-legacy-uploader.txt
@@ -0,0 +1,9 @@
+certifi==2026.10.23 --hash=sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1
+charset-normalizer==3.5.2 --hash=sha256:3d31298449090ab8d47b7b1b2a555ff73cac7ed438a08b7ac160980c7ebed649
+idna==3.20 --hash=sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c
+Kurigram==2.2.27 --hash=sha256:75aee16496f104c553e3d742c825ea860943ddad180343da95b0273a60a0a90c
+pyaes==1.6.1 --hash=sha256:02c1b1405c38d3c370b085fb952dd8bea3fadcee6411ad99f312cc129c536d8f
+python-socks==3.2.2 --hash=sha256:e0d464617bc24fb9511cf668ce67ea87efdcfec19d60ac149ad301065058f443
+requests==2.34.2 --hash=sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0
+tgcrypto-pyrofork==1.2.8 --hash=sha256:5bcb37b87c12d989c5c974869a93d705493457b8976d97e40b37cc476c6336bb
+urllib3==2.8.0 --hash=sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3
diff --git a/.github/scripts/requirements-python-build.txt b/.github/scripts/requirements-python-build.txt
new file mode 100644
index 0000000000000..6f8bf564914d3
--- /dev/null
+++ b/.github/scripts/requirements-python-build.txt
@@ -0,0 +1,2 @@
+setuptools==80.9.0 --hash=sha256:062d34222ad13e0cc312a4c02d73f059e86a4acbfbdea8f8f76b28c99f306922
+wheel==0.45.1 --hash=sha256:708e7481cc80179af0e556bbf0cc00b8444c7321e2700b8d8580231d13017248
diff --git a/.github/scripts/requirements-telethon.txt b/.github/scripts/requirements-telethon.txt
new file mode 100644
index 0000000000000..a8a4cca4abc8b
--- /dev/null
+++ b/.github/scripts/requirements-telethon.txt
@@ -0,0 +1,4 @@
+pyaes==1.6.1 --hash=sha256:02c1b1405c38d3c370b085fb952dd8bea3fadcee6411ad99f312cc129c536d8f
+pyasn1==0.6.5 --hash=sha256:4017b0fce125096b8573b39c989fdb1a4b19cf761e683398184550fea0e66587
+rsa==4.9.1 --hash=sha256:68635866661c6836b8d39430f97a996acbd61bfa49406748ea243539fe239762
+Telethon==1.46.0 --hash=sha256:c56e55e4a1f95fde556fe13459a542fc758e8ba501c0bf76f2fc5d8409fa81cb
diff --git a/.github/workflows/canary.yml b/.github/workflows/canary.yml
index d0c2cad8686af..4d4def88f7d55 100644
--- a/.github/workflows/canary.yml
+++ b/.github/workflows/canary.yml
@@ -557,7 +557,7 @@ jobs:
# to skip them too: an empty .rs file is a legal module.
- name: Free up some disk space.
shell: bash
- run: find $LibrariesPath '(' '(' ! '(' -name '*.lib' -o -name '*.a' -o -name '*.exe' -o -name '*.h' -o -name '*.hpp' -o -name '*.inc' -o -name '*.cmake' -o -name '*.pc' -o -path '*/include/*' -o -path '*/objects-*' -o -path '*/cache_keys/*' -o -path '*/patches/*' -o -path '*/nv-codec-headers/*' -o -path '*/src/wallet_engine/*' -o '(' '(' -path '*/tlottie/*' -o -path '*/wallet-engine/*' -o -path '*/tinyasr/*' -o -path '*/tinylid/*' -o -path '*/tmath/*' -o -path '*/tmarkdown/*' ')' ! -path '*/target/*' ')' ')' -type f ')' -o '(' -empty ! -path '*/tlottie/*' ! -path '*/wallet-engine/*' ! -path '*/tinyasr/*' ! -path '*/tinylid/*' ! -path '*/tmath/*' ! -path '*/tmarkdown/*' ')' ')' -delete
+ run: find $LibrariesPath '(' '(' ! '(' -name '*.lib' -o -name '*.a' -o -name '*.exe' -o -name '*.h' -o -name '*.hpp' -o -name '*.inc' -o -name '*.cmake' -o -name '*.pc' -o -path '*/include/*' -o -path '*/objects-*' -o -path '*/cache_keys/*' -o -path '*/patches/*' -o -path '*/qt6_windows7/*' -o -path '*/nv-codec-headers/*' -o -path '*/src/wallet_engine/*' -o '(' '(' -path '*/tlottie/*' -o -path '*/wallet-engine/*' -o -path '*/tinyasr/*' -o -path '*/tinylid/*' -o -path '*/tmath/*' -o -path '*/tmarkdown/*' ')' ! -path '*/target/*' ')' ')' -type f ')' -o '(' -empty ! -path '*/tlottie/*' ! -path '*/wallet-engine/*' ! -path '*/tinyasr/*' ! -path '*/tinylid/*' ! -path '*/tmath/*' ! -path '*/tmarkdown/*' ')' ')' -delete
- name: Save ThirdParty cache.
if: steps.cache-third-party.outputs.cache-hit != 'true'
@@ -660,11 +660,12 @@ jobs:
run: |
cd $TBUILD/$REPO_NAME/out/Release
BASE=${{ needs.version.outputs.base }}
- # Unlike releases, canary does not bundle d3dcompiler_47.dll:
- # the release copy is a pinned known-good build for Windows 7,
- # while CI would grab whatever the runner's SDK ships. Canary
- # machines use the system compiler dll.
- ./Packer.exe -path Telegram.exe -path Updater.exe \
+ # ANGLE compiles its shaders through d3dcompiler_47.dll, which
+ # Windows 7 has no system copy of. The build copies the pinned
+ # one from cmake_helpers, so ship it like the releases do.
+ D3D=modules/x64/d3d/d3dcompiler_47.dll
+ [ -f "$D3D" ] || { echo "::error::missing $D3D for ANGLE"; exit 1; }
+ ./Packer.exe -path Telegram.exe -path Updater.exe -path $D3D \
-path modules/x64/TelegramWidgetHelper.exe \
-target win64 \
-version $BASE \
@@ -699,6 +700,8 @@ jobs:
mkdir -p portable/$CANARY_FOLDER/TelegramForcePortable portable/$CANARY_FOLDER/modules/x64
touch portable/$CANARY_FOLDER/TelegramForcePortable/.keep
cp Telegram.exe portable/$CANARY_FOLDER/
+ mkdir -p portable/$CANARY_FOLDER/modules/x64/d3d
+ cp $D3D portable/$CANARY_FOLDER/modules/x64/d3d/
cp modules/x64/TelegramWidgetHelper.exe portable/$CANARY_FOLDER/modules/x64/
(cd portable && 7z a -mx9 ../$PORTABLE $CANARY_FOLDER/)
diff --git a/.github/workflows/cant-reproduce.yml b/.github/workflows/cant-reproduce.yml
deleted file mode 100644
index 8e20e07349b5b..0000000000000
--- a/.github/workflows/cant-reproduce.yml
+++ /dev/null
@@ -1,25 +0,0 @@
-name: Can't reproduce.
-
-on:
- schedule:
- - cron: '0 3 * * *'
-
-jobs:
- cant-reproduce:
- runs-on: ubuntu-slim
- steps:
- - uses: lee-dohm/no-response@v0.5.0
- with:
- token: ${{ github.token }}
- responseRequiredLabel: cant reproduce
- closeComment: >
- This issue has been automatically closed because no developer succeeded to
- reproduce the issue with the given reproduction steps. With only the
- information that is currently in the issue, we don't have enough
- information to take action. Please reach out if you find what's missing to
- reproduce the issue so that we can investigate further.
-
-
- Note that GitHub is a developer communication platform. If you're an ordinary
- user seeking for help, get to support crew via `Settings -> Ask question` in
- the application.
diff --git a/.github/workflows/copyright_year_updater.yml b/.github/workflows/copyright_year_updater.yml
deleted file mode 100644
index 7ddb3d0403a77..0000000000000
--- a/.github/workflows/copyright_year_updater.yml
+++ /dev/null
@@ -1,16 +0,0 @@
-name: Copyright year updater.
-
-on:
- repository_dispatch:
- types: ["Restart copyright_year_updater workflow."]
- schedule:
- # At 03:00 on January 1.
- - cron: "0 3 1 1 *"
-
-jobs:
- Copyright-year:
- runs-on: ubuntu-slim
- steps:
- - uses: desktop-app/action_code_updater@master
- with:
- type: "license-year"
diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml
index cba00688d935d..dbe256740706d 100644
--- a/.github/workflows/docker.yml
+++ b/.github/workflows/docker.yml
@@ -1,3 +1,4 @@
+
name: Docker.
on:
diff --git a/.github/workflows/full_source.yml b/.github/workflows/full_source.yml
new file mode 100644
index 0000000000000..4f59e0be906ec
--- /dev/null
+++ b/.github/workflows/full_source.yml
@@ -0,0 +1,60 @@
+name: Upload full source to release.
+
+on:
+ release:
+ types: released
+ workflow_dispatch:
+ inputs:
+ release_version:
+ description: 'The version of the release to upload'
+ required: true
+ default: 'v1.0.0'
+
+jobs:
+ build:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Clone.
+ uses: actions/checkout@v2
+ with:
+ submodules: recursive
+ - name: Install prerequisites.
+ run: |
+ pip install git-archive-all
+
+ if [ "${{ github.event_name }}" == "workflow_dispatch" ]; then
+ # Use the release version from the input if available.
+ p="frk-${{ github.event.inputs.release_version }}-full.tar.gz"
+ else
+ # Otherwise fallback to the release event.
+ p="frk-v${GITHUB_REF##*/v}-full.tar.gz"
+ fi
+ echo "TAG=$p" >> $GITHUB_ENV
+ - name: Build assets.
+ run: |
+ mkdir -p dist/
+ echo "$TAG"
+ ~/.local/bin/git-archive-all ./dist/${TAG}
+ - name: Get release ID by tag.
+ id: get_release
+ if: github.event_name == 'workflow_dispatch'
+ uses: cardinalby/git-get-release-action@master
+ env:
+ GITHUB_TOKEN: ${{ github.token }}
+ with:
+ tag: ${{ github.event.inputs.release_version }}
+ - name: Set upload URL for release event.
+ id: set_upload_url
+ if: github.event_name == 'release'
+ run: |
+ echo "upload_url=${{ github.event.release.upload_url }}" >> $GITHUB_OUTPUT
+ - name: Upload.
+ uses: lovasoa/upload-release-asset@master
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ with:
+ upload_url: ${{ steps.get_release.outputs.upload_url || steps.set_upload_url.outputs.upload_url }}
+ asset_path: ./dist/${{ env.TAG }}
+ asset_label: Source code (tar.gz, full)
+ asset_name: ${{ env.TAG }}
+ asset_content_type: application/x-gzip
diff --git a/.github/workflows/inno.yml.disabled b/.github/workflows/inno.yml.disabled
new file mode 100644
index 0000000000000..e041f60e7cdeb
--- /dev/null
+++ b/.github/workflows/inno.yml.disabled
@@ -0,0 +1,149 @@
+name: Create Inno Setup Installers
+
+on:
+ release:
+ types: [released]
+ workflow_dispatch:
+ inputs:
+ version:
+ description: 'Version number (e.g., 1.2.3)'
+ required: true
+
+jobs:
+ create-installers:
+ runs-on: windows-latest
+
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v4
+
+ - name: Get version
+ id: version
+ run: |
+ # For workflow_dispatch
+ if (-not [string]::IsNullOrEmpty("${{ github.event.inputs.version }}")) {
+ echo "version=${{ github.event.inputs.version }}" >> $env:GITHUB_OUTPUT
+ echo "version_full=${{ github.event.inputs.version }}" >> $env:GITHUB_OUTPUT
+ } else {
+ # For release event
+ echo "version=$($env:GITHUB_REF -replace 'refs/tags/', '')" >> $env:GITHUB_OUTPUT
+ echo "version_full=$($env:GITHUB_REF -replace 'refs/tags/', '')" >> $env:GITHUB_OUTPUT
+ }
+ shell: pwsh
+
+ - name: Download x64 zip
+ uses: robinraju/release-downloader@v1.12
+ with:
+ repository: ${{ github.repository }}
+ tag: ${{ steps.version.outputs.version_full }}
+ fileName: Telegram.zip
+ out-file-path: ./artifacts/x64/
+
+ - name: Download x86 zip
+ uses: robinraju/release-downloader@v1.12
+ with:
+ repository: ${{ github.repository }}
+ tag: ${{ steps.version.outputs.version_full }}
+ fileName: Telegram_x86.zip
+ out-file-path: ./artifacts/x86/
+
+ - name: Extract x64 zip
+ run: |
+ Expand-Archive -Path ./artifacts/x64/Telegram.zip -DestinationPath ./artifacts/x64/extracted
+
+ - name: Extract x86 zip
+ run: |
+ Expand-Archive -Path ./artifacts/x86/Telegram_x86.zip -DestinationPath ./artifacts/x86/extracted
+
+ - name: Install Inno Setup
+ run: |
+ choco install innosetup -y
+
+ - name: Prepare directories
+ run: |
+ New-Item -ItemType Directory -Path ./Telegram/build/release_x64 -Force
+ New-Item -ItemType Directory -Path ./Telegram/build/release_x86 -Force
+ Copy-Item -Path ./artifacts/x64/extracted/* -Destination ./Telegram/build/release_x64 -Recurse -Force
+ Copy-Item -Path ./artifacts/x86/extracted/* -Destination ./Telegram/build/release_x86 -Recurse -Force
+
+ - name: Get release ID by tag.
+ id: get_release
+ if: github.event_name == 'workflow_dispatch'
+ uses: cardinalby/git-get-release-action@master
+ env:
+ GITHUB_TOKEN: ${{ github.token }}
+ with:
+ tag: ${{ github.event.inputs.version }}
+ - name: Set upload URL for release event.
+ id: set_upload_url
+ if: github.event_name == 'release'
+ run: |
+ echo "upload_url=${{ github.event.release.upload_url }}" >> $env:GITHUB_OUTPUT
+
+ - name: Create x64 installer
+ id: create_x64
+ run: |
+ $cleanVersion = "${{ steps.version.outputs.version }}".TrimStart('v')
+ echo "Version: $cleanVersion."
+ iscc ./Telegram/build/setup.iss `
+ /dMyAppVersion=$cleanVersion `
+ /dMyAppVersionZero=$cleanVersion `
+ /dMyAppVersionFull=$cleanVersion `
+ /dMyBuildTarget="win64" `
+ /dReleasePath="../../artifacts/x64/extracted" `
+ /dSourcePath="../SourceFiles/"
+
+ # Find the output exe file
+ $exePath = Get-ChildItem -Path "." -Filter "tsetup-x64.$cleanVersion.exe" -Recurse | Select-Object -First 1 -ExpandProperty FullName
+
+ if ($exePath) {
+ echo "$exePath"
+ echo "output_file=$exePath" >> $env:GITHUB_OUTPUT
+ } else {
+ Write-Error "Output exe file not found"
+ exit 1
+ }
+
+ - name: Create x86 installer
+ id: create_x86
+ run: |
+ $cleanVersion = "${{ steps.version.outputs.version }}".TrimStart('v')
+ echo "Version: $cleanVersion."
+ iscc ./Telegram/build/setup.iss `
+ /dMyAppVersion=$cleanVersion `
+ /dMyAppVersionZero=$cleanVersion `
+ /dMyAppVersionFull=$cleanVersion `
+ /dMyBuildTarget="win32" `
+ /dReleasePath="../../artifacts/x86/extracted" `
+ /dSourcePath="../SourceFiles/"
+
+ # Find the output exe file
+ $exePath = Get-ChildItem -Path "." -Filter "tsetup.$cleanVersion.exe" -Recurse | Select-Object -First 1 -ExpandProperty FullName
+
+ if ($exePath) {
+ echo "$exePath"
+ echo "output_file=$exePath" >> $env:GITHUB_OUTPUT
+ } else {
+ Write-Error "Output exe file not found"
+ exit 1
+ }
+
+ - name: Upload x64 installer to release
+ uses: lovasoa/upload-release-asset@master
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ with:
+ upload_url: ${{ steps.get_release.outputs.upload_url || steps.set_upload_url.outputs.upload_url }}
+ asset_path: ${{ steps.create_x64.outputs.output_file }}
+ asset_name: Telegram Windows x64 Installer.exe
+ asset_content_type: application/octet-stream
+
+ - name: Upload x86 installer to release
+ uses: lovasoa/upload-release-asset@master
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ with:
+ upload_url: ${{ steps.get_release.outputs.upload_url || steps.set_upload_url.outputs.upload_url }}
+ asset_path: ${{ steps.create_x86.outputs.output_file }}
+ asset_name: Telegram Windows x32 Installer.exe
+ asset_content_type: application/octet-stream
diff --git a/.github/workflows/issue_closer.yml b/.github/workflows/issue_closer.yml
deleted file mode 100644
index 3554051655907..0000000000000
--- a/.github/workflows/issue_closer.yml
+++ /dev/null
@@ -1,14 +0,0 @@
-name: Issue closer.
-
-on:
- issues:
- types: opened
-
-jobs:
- comment:
- runs-on: ubuntu-slim
- steps:
- - name: Process an issue.
- uses: desktop-app/action_issue_closer@master
- with:
- token: ${{ secrets.GITHUB_TOKEN }}
diff --git a/.github/workflows/jekyll-gh-pages.yml b/.github/workflows/jekyll-gh-pages.yml
new file mode 100644
index 0000000000000..79f4d7b2c5bd5
--- /dev/null
+++ b/.github/workflows/jekyll-gh-pages.yml
@@ -0,0 +1,52 @@
+# Sample workflow for building and deploying a Jekyll site to GitHub Pages
+name: Deploy Jekyll with GitHub Pages dependencies preinstalled
+
+on:
+ # Runs on pushes targeting the default branch
+ push:
+ branches: ["dev"]
+
+ # Allows you to run this workflow manually from the Actions tab
+ workflow_dispatch:
+
+# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
+permissions:
+ contents: read
+ pages: write
+ id-token: write
+
+# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
+# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
+concurrency:
+ group: "pages"
+ cancel-in-progress: false
+
+jobs:
+ # Build job
+ build:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ - name: Setup Pages
+ uses: actions/configure-pages@v5
+ - name: Build with Jekyll
+ uses: actions/jekyll-build-pages@v1
+ with:
+ source: ./
+ destination: ./_site
+ jekyll_config: _config_github_pages.yml
+ - name: Upload artifact
+ uses: actions/upload-pages-artifact@v3
+
+ # Deployment job
+ deploy:
+ environment:
+ name: github-pages
+ url: ${{ steps.deployment.outputs.page_url }}
+ runs-on: ubuntu-latest
+ needs: build
+ steps:
+ - name: Deploy to GitHub Pages
+ id: deployment
+ uses: actions/deploy-pages@v4
diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml
index a1dbac713165b..c930be0ba847d 100644
--- a/.github/workflows/linux.yml
+++ b/.github/workflows/linux.yml
@@ -1,6 +1,16 @@
name: Linux.
on:
+ workflow_dispatch:
+ inputs:
+ version:
+ description: 'Version label (e.g., v5.15.3)'
+ required: false
+ type: string
+ release:
+ types: [published]
+ repository_dispatch:
+ types: ["Restart linux workflow."]
push:
# Pushes to the canary or private-ci branches run their own workflows.
branches-ignore:
@@ -62,11 +72,13 @@ jobs:
UPLOAD_ARTIFACT: "true"
ONLY_CACHE: "false"
IMAGE_TAG: tdesktop:centos_env
+ LEGACY_UPDATE: ${{ (github.event_name == 'release' || github.event_name == 'workflow_dispatch' || github.event_name == 'repository_dispatch') && 'true' || 'false' }}
steps:
- name: Clone.
- uses: actions/checkout@v7
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
+ persist-credentials: false
submodules: recursive
- name: First set up.
@@ -82,6 +94,8 @@ jobs:
echo "$DOCKERFILE" > Dockerfile
rm -rf __pycache__
+ sudo apt -y install wget 7zip unzip
+
- name: Free up some disk space.
uses: jlumbroso/free-disk-space@ceedf095f4ec1a097402bc6bd80831f2e1a6fde6
with:
@@ -89,11 +103,11 @@ jobs:
- name: Set up Docker Buildx.
id: setup-buildx
- uses: docker/setup-buildx-action@v4
+ uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4
- name: Libraries cache.
id: cache-libs
- uses: actions/cache@v6
+ uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
with:
path: |
${{ runner.temp }}/.buildx-cache
@@ -110,7 +124,7 @@ jobs:
skip-extraction: ${{ steps.cache-libs.outputs.cache-hit }}
- name: Libraries.
- uses: docker/build-push-action@v7
+ uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7
with:
context: Telegram/build/docker/centos_env
load: ${{ env.ONLY_CACHE == 'false' }}
@@ -126,12 +140,44 @@ jobs:
- name: Restore Telegram Desktop cache.
id: cache-tdesktop
if: env.ONLY_CACHE == 'false'
- uses: actions/cache/restore@v6
+ uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
with:
path: ${{ env.CCACHE_DIR }}
key: ${{ runner.OS }}-tdesktop-${{ matrix.defines || 'null' }}-${{ github.run_id }}
restore-keys: ${{ runner.OS }}-tdesktop-${{ matrix.defines || 'null' }}-
+ - name: Set up the Packer headers for CI.
+ if: env.LEGACY_UPDATE == 'false'
+ run: |
+ mkdir -p ../DesktopPrivate
+ printf 'const char *PrivateKey = "";\nconst char *PrivateBetaKey = "";\n' > ../DesktopPrivate/packer_private.h
+ printf '[[maybe_unused]] static const char *AlphaPrivateKey = "";\n' > ../DesktopPrivate/alpha_private.h
+
+ - name: Set up the legacy signing files.
+ if: env.LEGACY_UPDATE == 'true'
+ env:
+ DESKTOP_PRIVATE_BASE64: ${{ secrets.DESKTOP_PRIVATE_BASE64 }}
+ ALPHA_PRIVATE: ${{ secrets.ALPHA_PRIVATE }}
+ PACKER_PRIVATE: ${{ secrets.PACKER_PRIVATE }}
+ PACK_FILE: ${{ secrets.PACK_FILE }}
+ PACK_FILE_PASSWORD: ${{ secrets.PACK_FILE_PASSWORD }}
+ run: |
+ umask 077
+ cd "$GITHUB_WORKSPACE/.."
+ mkdir -p DesktopPrivate
+ if [ -n "$DESKTOP_PRIVATE_BASE64" ]; then
+ printf '%s' "$DESKTOP_PRIVATE_BASE64" | base64 --decode > desktop_private.zip
+ unzip -oq desktop_private.zip -d DesktopPrivate
+ rm desktop_private.zip
+ else
+ printf '#pragma once\n%s\n' "$ALPHA_PRIVATE" > DesktopPrivate/alpha_private.h
+ printf '#pragma once\n%s\n' "$PACKER_PRIVATE" > DesktopPrivate/packer_private.h
+ fi
+
+ wget "$PACK_FILE" -O p.7z
+ 7za x p.7z -p"$PACK_FILE_PASSWORD"
+ rm p.7z
+
- name: Telegram Desktop build.
if: env.ONLY_CACHE == 'false'
run: |
@@ -145,22 +191,24 @@ jobs:
fi
ccache -z
+ cache_options=()
+ if [ "$LEGACY_UPDATE" == "true" ]; then
+ cache_options=(-e CCACHE_DISABLE=1)
+ fi
docker run --rm \
-u $(id -u) \
- -v $PWD:/usr/src/tdesktop \
+ -v "$PWD":/usr/src/tdesktop \
+ -v "$PWD/../DesktopPrivate":/usr/src/DesktopPrivate:ro \
-v ${{ env.CCACHE_DIR }}:/var/cache/ccache \
-e CONFIG=Debug \
-e CCACHE_SLOPPINESS=pch_defines,time_macros \
+ "${cache_options[@]}" \
$IMAGE_TAG \
- env -u CCACHE_DISABLE /usr/src/tdesktop/Telegram/build/docker/centos_env/build.sh \
- -D CMAKE_CONFIGURATION_TYPES=Debug \
- -D CMAKE_C_FLAGS_DEBUG="-O0 -fpch-preprocess" \
- -D CMAKE_CXX_FLAGS_DEBUG="-O0 -fpch-preprocess" \
- -D CMAKE_COMPILE_WARNING_AS_ERROR=ON \
- -D TDESKTOP_API_TEST=ON \
- -D DESKTOP_APP_DISABLE_AUTOUPDATE=OFF \
- -D DESKTOP_APP_DISABLE_CRASH_REPORTS=OFF \
+ /usr/src/tdesktop/Telegram/build/docker/centos_env/build.sh \
+ -D TDESKTOP_API_ID=${{ secrets.API_ID }} \
+ -D TDESKTOP_API_HASH=${{ secrets.API_HASH }} \
+ -D DESKTOP_APP_SPECIAL_TARGET=linux \
$DEFINE
- name: Count ccache misses.
@@ -184,7 +232,7 @@ jobs:
env.ONLY_CACHE == 'false'
&& github.ref_name == github.event.repository.default_branch
&& fromJSON(steps.ccache-stats.outputs.misses) > 300
- uses: actions/cache/save@v6
+ uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
with:
path: ${{ env.CCACHE_DIR }}
key: ${{ steps.cache-tdesktop.outputs.cache-primary-key }}
@@ -192,7 +240,7 @@ jobs:
- name: Check.
if: env.ONLY_CACHE == 'false'
run: |
- filePath="out/Debug/Telegram"
+ filePath="out/MinSizeRel/Forkgram"
if test -f "$filePath"; then
echo "Build successfully done! :)"
@@ -203,16 +251,106 @@ jobs:
exit 1
fi
- - name: Move artifact.
- if: env.UPLOAD_ARTIFACT == 'true'
+ - name: Compress.
+ if: (github.event_name == 'release')
+ run: tar -cJvf Forkgram.tar.xz -C out/MinSizeRel Forkgram Updater TelegramHelpers/TelegramWidgetHelper
+
+ - name: Pack updater files.
+ if: env.LEGACY_UPDATE == 'true'
+ run: |
+ verPacker=$(awk '$1 == "AppVersion" { print $2 }' Telegram/build/version)
+ cd out/MinSizeRel
+ BEFORE=$(mktemp)
+ AFTER=$(mktemp)
+ ls -1 tlinuxupd* 2>/dev/null | sort > "$BEFORE" || true
+ ./Packer -path Forkgram -path Updater -path TelegramHelpers/TelegramWidgetHelper -version "$verPacker"
+ ls -1 tlinuxupd* 2>/dev/null | sort > "$AFTER" || true
+ UPDATE_FILE=$(comm -13 "$BEFORE" "$AFTER" | tail -n 1)
+ if [ -z "$UPDATE_FILE" ]; then
+ UPDATE_FILE=$(ls -1t tlinuxupd* | head -n 1)
+ fi
+ if [ -z "$UPDATE_FILE" ] || [ ! -f "$UPDATE_FILE" ]; then
+ echo "Packed update file was not generated."
+ exit 1
+ fi
+ echo "PACKED_UPDATE_FILE=$GITHUB_WORKSPACE/out/MinSizeRel/$UPDATE_FILE" >> $GITHUB_ENV
+ echo "PACKED_UPDATE_BASENAME=$UPDATE_FILE" >> $GITHUB_ENV
+ echo "VER_PACKER=$verPacker" >> $GITHUB_ENV
+
+ - name: Remove the legacy signing files.
+ if: always() && env.LEGACY_UPDATE == 'true'
+ run: rm -rf -- ../DesktopPrivate out/MinSizeRel/Packer
+
+ - name: Set up Python for the legacy uploader.
+ if: env.LEGACY_UPDATE == 'true'
+ uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6
+ with:
+ python-version: '3.12'
+
+ - name: Install the legacy uploader dependencies.
+ if: env.LEGACY_UPDATE == 'true'
run: |
- cd out/Debug
- mkdir artifact
- mv {Telegram,Updater} artifact/
- - uses: actions/upload-artifact@v7
- if: env.UPLOAD_ARTIFACT == 'true'
- name: Upload artifact.
+ python -m venv "$RUNNER_TEMP/telegram-venv"
+ python="$RUNNER_TEMP/telegram-venv/bin/python"
+ "$python" -m pip install --require-hashes -r .github/scripts/requirements-python-build.txt
+ "$python" -m pip install --require-hashes --no-build-isolation -r .github/scripts/requirements-legacy-uploader.txt
+
+ - name: Upload packed updater to Telegram channel.
+ if: env.LEGACY_UPDATE == 'true'
+ env:
+ UPDATER_UPLOAD_BASE64: ${{ secrets.UPDATER_UPLOAD_BASE64 }}
+ UPDATER_UPLOAD_BASE64_PART1: ${{ secrets.UPDATER_UPLOAD_BASE64_PART1 }}
+ UPDATER_UPLOAD_BASE64_PART2: ${{ secrets.UPDATER_UPLOAD_BASE64_PART2 }}
+ UPDATER_UPLOAD_BASE64_PART3: ${{ secrets.UPDATER_UPLOAD_BASE64_PART3 }}
+ run: |
+ MERGED_UPLOAD_BASE64="${UPDATER_UPLOAD_BASE64_PART1}${UPDATER_UPLOAD_BASE64_PART2}${UPDATER_UPLOAD_BASE64_PART3}"
+ if [ -z "${MERGED_UPLOAD_BASE64}" ]; then
+ MERGED_UPLOAD_BASE64="${UPDATER_UPLOAD_BASE64}"
+ fi
+
+ if [ -z "${MERGED_UPLOAD_BASE64}" ]; then
+ echo "UPDATER_UPLOAD_BASE64(_PART1/_PART2/_PART3) is empty, skip channel upload."
+ exit 0
+ fi
+
+ rm -rf updater_channel_upload
+ mkdir -p updater_channel_upload
+
+ printf "%s" "${MERGED_UPLOAD_BASE64}" | base64 --decode > updater_upload.raw
+ if unzip -tqq updater_upload.raw >/dev/null 2>&1; then
+ unzip -oq updater_upload.raw -d updater_channel_upload
+ elif tar -tzf updater_upload.raw >/dev/null 2>&1; then
+ tar -xzf updater_upload.raw -C updater_channel_upload
+ elif tar -tf updater_upload.raw >/dev/null 2>&1; then
+ tar -xf updater_upload.raw -C updater_channel_upload
+ else
+ echo "Unsupported upload bundle format: $(file -b updater_upload.raw)"
+ exit 1
+ fi
+
+ (
+ cd updater_channel_upload
+ 7za a -tzip -mx=0 ../updater_upload.zip . >/dev/null
+ )
+
+ SCRIPT_PATH=$(find updater_channel_upload -type f -name linux_pack_upl.py | head -n 1)
+ if [ -z "$SCRIPT_PATH" ]; then
+ echo "linux_pack_upl.py not found in UPDATER_UPLOAD_BASE64 bundle."
+ exit 1
+ fi
+
+ SCRIPT_DIR=$(dirname "$SCRIPT_PATH")
+ cp "$PACKED_UPDATE_FILE" "$SCRIPT_DIR/"
+ cp updater_upload.zip "$SCRIPT_DIR/"
+
+ cd "$SCRIPT_DIR"
+ "$RUNNER_TEMP/telegram-venv/bin/python" linux_pack_upl.py "tlinuxupd${VER_PACKER}"
+
+ - name: Upload.
+ if: (github.event_name == 'release')
+ uses: svenstaro/upload-release-action@b98a3b12e86552593f3e4e577ca8a62aa2f3f22b # 2.11.4
with:
- name: ${{ env.ARTIFACT_NAME }}
- path: out/Debug/artifact/
- retention-days: 1
+ repo_token: ${{ secrets.GITHUB_TOKEN }}
+ file: ./Forkgram.tar.xz
+ tag: ${{ github.event.release.tag_name }}
+ asset_name: Forkgram.tar.xz
diff --git a/.github/workflows/linux_release.yml b/.github/workflows/linux_release.yml
new file mode 100644
index 0000000000000..dce07cd71e96b
--- /dev/null
+++ b/.github/workflows/linux_release.yml
@@ -0,0 +1,396 @@
+name: Linux Release.
+
+on:
+ workflow_dispatch:
+ inputs:
+ only_cache:
+ description: 'Only build the container image and warm the cache.'
+ type: boolean
+ default: false
+ publish_release:
+ description: 'Publish a GitHub Release with the artifacts.'
+ type: boolean
+ default: false
+ telegram:
+ description: 'Publish update files to the Telegram channels (manual runs).'
+ type: choice
+ # 'off' must be quoted: YAML reads the bare word as boolean false, dropping it from the choices.
+ options: ['off', scheduled, testing, released]
+ default: 'off'
+ push:
+ tags:
+ - 'v*'
+ schedule:
+ # Keep the library cache from the 7-day eviction; centos_env builds every library from source.
+ - cron: '0 5 * * 1,4'
+
+permissions:
+ contents: read
+
+concurrency:
+ group: linux-release-${{ github.ref }}
+ cancel-in-progress: false
+
+jobs:
+
+ linux-release:
+ name: Linux x64 Release
+ runs-on: ubuntu-latest
+ timeout-minutes: 360
+
+ env:
+ IMAGE_TAG: tdesktop:centos_env
+ BUILD_CONFIG: MinSizeRel
+ UPD_PREFIX: td-update-linux-x64-
+ ASSET_PORTABLE: Forkgram.tar.xz
+ ONLY_CACHE: ${{ (github.event_name == 'schedule' || inputs.only_cache) && 'true' || 'false' }}
+
+ steps:
+ - name: Clone.
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ persist-credentials: false
+ submodules: recursive
+
+ - name: Read version.
+ run: |
+ awk 'NF { print $1"="$2 }' Telegram/build/version >> $GITHUB_ENV
+ source <(awk 'NF { print $1"="$2 }' Telegram/build/version)
+
+ if [ "$AlphaVersion" != "0" ]; then
+ echo "AppVersionStrFull=${AppVersionStr}_${AlphaVersion}" >> $GITHUB_ENV
+ elif [ "$BetaChannel" != "0" ]; then
+ echo "AppVersionStrFull=${AppVersionStr}.beta" >> $GITHUB_ENV
+ else
+ echo "AppVersionStrFull=${AppVersionStr}" >> $GITHUB_ENV
+ fi
+
+ # Packer's channel and the file name suffix, both from BetaChannel.
+ if [ "$BetaChannel" != "0" ]; then
+ echo "UPD_CHANNEL=beta" >> $GITHUB_ENV
+ echo "UPD_SUFFIX=-beta" >> $GITHUB_ENV
+ else
+ echo "UPD_CHANNEL=stable" >> $GITHUB_ENV
+ echo "UPD_SUFFIX=" >> $GITHUB_ENV
+ fi
+ echo "Building version $AppVersionStr ($AppVersion)."
+
+ - name: Free up some disk space.
+ uses: jlumbroso/free-disk-space@54081f138730dfa15788a46383842cd2f914a1be
+ with:
+ tool-cache: true
+
+ - name: Generate the Dockerfile.
+ run: |
+ set -e
+ curl -sSL https://install.python-poetry.org | python3 -
+ cd Telegram/build/docker/centos_env
+ poetry install
+
+ # The checked-in Dockerfile is itself the Jinja template, so redirecting
+ # into it truncates the input before the generator reads it.
+ DOCKERFILE=$(DEBUG= LTO= poetry run gen_dockerfile)
+ printf '%s\n' "$DOCKERFILE" > Dockerfile
+ rm -rf __pycache__
+
+ if [ "$(grep -c '^FROM' Dockerfile)" -lt 1 ]; then
+ echo "Generated Dockerfile has no FROM instruction:"
+ head -20 Dockerfile
+ exit 1
+ fi
+ echo "Generated Dockerfile: $(wc -l < Dockerfile) lines."
+
+ - name: Set up Docker Buildx.
+ id: setup-buildx
+ uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4
+
+ - name: Libraries cache.
+ id: cache-libs
+ uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
+ with:
+ path: |
+ ${{ runner.temp }}/.buildx-cache
+ ${{ runner.temp }}/.mount-cache
+ key: ${{ runner.OS }}-libs-${{ hashFiles('Telegram/build/docker/centos_env/**') }}
+ restore-keys: ${{ runner.OS }}-libs-
+
+ # Libraries build into BuildKit mount caches, which the layer cache above does not carry.
+ - name: Restore Docker cache mounts.
+ uses: reproducible-containers/buildkit-cache-dance@5422eac04292c961a382e0f584ea0f03ad9da723
+ with:
+ builder: ${{ steps.setup-buildx.outputs.name }}
+ cache-dir: ${{ runner.temp }}/.mount-cache
+ dockerfile: Telegram/build/docker/centos_env/Dockerfile
+ skip-extraction: ${{ steps.cache-libs.outputs.cache-hit }}
+
+ - name: Libraries.
+ uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7
+ with:
+ context: Telegram/build/docker/centos_env
+ load: ${{ env.ONLY_CACHE == 'false' }}
+ tags: ${{ env.IMAGE_TAG }}
+ cache-from: type=local,src=${{ runner.temp }}/.buildx-cache
+ cache-to: type=local,dest=${{ runner.temp }}/.buildx-cache-new,mode=max
+
+ - name: Move cache.
+ run: |
+ rm -rf ${{ runner.temp }}/.buildx-cache
+ mv ${{ runner.temp }}/.buildx-cache{-new,}
+
+ - name: Set up DesktopPrivate.
+ if: env.ONLY_CACHE == 'false'
+ env:
+ API_ID: ${{ secrets.TDESKTOP_API_ID }}
+ API_HASH: ${{ secrets.TDESKTOP_API_HASH }}
+ run: |
+ set -e
+ python3 - <<'PY'
+ import os, pathlib
+
+ private = pathlib.Path(os.environ['GITHUB_WORKSPACE']).parent / 'DesktopPrivate'
+ private.mkdir(parents=True, exist_ok=True)
+
+ # configure.py only regex-scans this one for the API credentials.
+ (private / 'custom_api_id.h').write_text(
+ 'static const int32 ApiId = %s;\n'
+ 'static const char *ApiHash = "%s";\n'
+ % (os.environ['API_ID'], os.environ['API_HASH']))
+
+ (private / 'packer_private.h').write_text(
+ 'const char *PrivateKey = "";\n'
+ 'const char *PrivateBetaKey = "";\n')
+ (private / 'alpha_private.h').write_text(
+ '[[maybe_unused]] static const char *AlphaPrivateKey = "";\n')
+ PY
+
+ ls -l $GITHUB_WORKSPACE/../DesktopPrivate
+
+ - name: Telegram Desktop build.
+ if: env.ONLY_CACHE == 'false'
+ run: |
+ set -e
+ docker run --rm \
+ -u $(id -u) \
+ -v $PWD:/usr/src/tdesktop \
+ -v $PWD/../DesktopPrivate:/usr/src/DesktopPrivate:ro \
+ -e CONFIG=$BUILD_CONFIG \
+ $IMAGE_TAG \
+ /usr/src/tdesktop/Telegram/build/docker/centos_env/build.sh \
+ -D TDESKTOP_API_ID=${{ secrets.TDESKTOP_API_ID }} \
+ -D TDESKTOP_API_HASH=${{ secrets.TDESKTOP_API_HASH }} \
+ -D DESKTOP_APP_SPECIAL_TARGET=linux
+
+ - name: Check.
+ if: env.ONLY_CACHE == 'false'
+ run: |
+ set -e
+ release="out/$BUILD_CONFIG"
+ for f in Forkgram Updater Packer TelegramHelpers/TelegramWidgetHelper; do
+ if [ ! -f "$release/$f" ]; then
+ echo "Build error: $release/$f does not exist."
+ exit 1
+ fi
+ done
+ file "$release/Forkgram"
+ echo "Forkgram: $(stat -c %s "$release/Forkgram") bytes."
+
+ # Before Packer, so the update carries the same stripped binary as the release asset.
+ - name: Strip, keeping MiniDebugInfo.
+ if: env.ONLY_CACHE == 'false'
+ run: |
+ set -e
+ Telegram/build/minidebug.sh out/$BUILD_CONFIG/Forkgram
+ echo "Stripped: $(stat -c %s out/$BUILD_CONFIG/Forkgram) bytes."
+
+ - name: Pack the update file.
+ if: env.ONLY_CACHE == 'false'
+ run: |
+ set -e
+ cd out/$BUILD_CONFIG
+ ./Packer -path Forkgram -path Updater -path TelegramHelpers/TelegramWidgetHelper -version "$AppVersion" \
+ -channel "$UPD_CHANNEL" \
+ -keys-loc "$GITHUB_WORKSPACE/Telegram/Resources/update" \
+ -emit-signing-input update-signing-input.bin
+
+ update="${UPD_PREFIX}${AppVersion}${UPD_SUFFIX}.unsigned"
+ if [ ! -f "$update" ]; then
+ echo "Packed update file $update was not produced."
+ exit 1
+ fi
+ echo "Produced $update ($(stat -c %s "$update") bytes)."
+
+ - name: Collect the artifacts.
+ if: env.ONLY_CACHE == 'false'
+ run: |
+ set -e
+ release="out/$BUILD_CONFIG"
+ mkdir -p deploy
+
+ tar -cJf "deploy/$ASSET_PORTABLE" -C "$release" Forkgram Updater TelegramHelpers/TelegramWidgetHelper
+
+ # The update file keeps its raw name: the Telegram job derives the platform from it.
+ cp "$release/${UPD_PREFIX}${AppVersion}${UPD_SUFFIX}.unsigned" deploy/
+
+ ls -l deploy
+
+ - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7
+ name: Upload the unsigned artifacts.
+ if: env.ONLY_CACHE == 'false'
+ with:
+ name: unsigned-linux
+ path: deploy/
+ if-no-files-found: error
+ retention-days: 7
+ compression-level: 0
+ overwrite: true
+
+ sign-release:
+ name: Sign the Linux update
+ needs: linux-release
+ if: github.event_name != 'schedule' && !inputs.only_cache
+ runs-on: ubuntu-latest
+ environment: desktop-update-signing
+ permissions:
+ contents: write
+
+ env:
+ ASSET_PORTABLE: Forkgram.tar.xz
+
+ steps:
+ - name: Check out the release signing tools.
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ persist-credentials: false
+ sparse-checkout: |
+ Telegram/build/sign_forkgram_update.py
+ Telegram/build/version
+ Telegram/Resources/update
+ sparse-checkout-cone-mode: false
+
+ - name: Download the unsigned release.
+ uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7
+ with:
+ name: unsigned-linux
+ path: deploy
+
+ - name: Read artifact version.
+ run: |
+ awk '
+ $1 == "AppVersionStr" { version = $2 }
+ $1 == "AlphaVersion" { alpha = $2 }
+ $1 == "BetaChannel" { beta = $2 }
+ END {
+ print "AppVersionStr=" version
+ print "BetaChannel=" beta
+ print "AppVersionStrFull=" version (alpha != "0" ? "_" alpha : (beta != "0" ? ".beta" : ""))
+ }
+ ' Telegram/build/version >> "$GITHUB_ENV"
+
+ - name: Sign the update file.
+ env:
+ UPDATE_LOCAL_KEY: ${{ secrets.UPDATE_LOCAL_KEY }}
+ run: >-
+ python3 -I Telegram/build/sign_forkgram_update.py deploy Telegram/build/version
+ Telegram/Resources/update linux-x64
+
+ - name: Upload the artifacts.
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7
+ with:
+ name: Telegram Linux Release ${{ env.AppVersionStrFull }}
+ path: deploy/
+ if-no-files-found: error
+ compression-level: 0
+ overwrite: true
+
+ - name: Publish the release.
+ if: inputs.publish_release || startsWith(github.ref, 'refs/tags/')
+ env:
+ # A fork refuses release creation even with contents: write, so it needs a
+ # RELEASE_TOKEN (repo scope) - which is why publish_release defaults to off.
+ GH_TOKEN: ${{ secrets.RELEASE_TOKEN || github.token }}
+ run: |
+ set -e
+ R="$GITHUB_REPOSITORY"
+
+ if [[ "$GITHUB_REF" == refs/tags/* ]]; then
+ TAG="${GITHUB_REF#refs/tags/}"
+ TARGET=()
+ else
+ TAG="v$AppVersionStr"
+ TARGET=(--target dev)
+ fi
+
+ # Create only if missing, else just add assets, so the Windows and macOS legs share one release.
+ if [ "$BetaChannel" != "0" ]; then
+ PRERELEASE=(--prerelease)
+ else
+ PRERELEASE=()
+ fi
+ if ! gh release view "$TAG" -R "$R" >/dev/null 2>&1; then
+ gh release create "$TAG" -R "$R" "${TARGET[@]}" "${PRERELEASE[@]}" \
+ --title "Forkgram $TAG" \
+ --notes "Forkgram $TAG" >/dev/null 2>&1 \
+ || gh release view "$TAG" -R "$R" >/dev/null
+ fi
+
+ gh release upload "$TAG" "deploy/$ASSET_PORTABLE" -R "$R" --clobber
+
+ publish-telegram:
+ name: Publish update files to Telegram
+ needs: sign-release
+ runs-on: ubuntu-latest
+ if: >-
+ needs.sign-release.result == 'success' &&
+ (startsWith(github.ref, 'refs/tags/') ||
+ (github.event_name == 'workflow_dispatch' && inputs.telegram != 'off'))
+ environment: telegram-publish
+ # The feed message is rewritten read-modify-write; the shared group name
+ # serialises this with the Windows workflow so neither loses its entry.
+ concurrency:
+ group: telegram-feed
+ cancel-in-progress: false
+ steps:
+ - name: Clone the uploader script.
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ persist-credentials: false
+ sparse-checkout: |
+ .github/scripts/publish_telegram.py
+ .github/scripts/requirements-telethon.txt
+ .github/scripts/requirements-python-build.txt
+ .github/data/logo_256_square.png
+ sparse-checkout-cone-mode: false
+
+ # Filtered: unfiltered this also pulls build-push-action's .dockerbuild
+ # record, which fails to extract and takes the job down with it.
+ - name: Download build artifacts.
+ uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7
+ with:
+ pattern: Telegram Linux Release *
+ path: artifacts
+
+ - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6
+ with:
+ python-version: "3.12"
+
+ - name: Install Telethon.
+ run: |
+ python -m venv "$RUNNER_TEMP/telegram-venv"
+ python="$RUNNER_TEMP/telegram-venv/bin/python"
+ "$python" -m pip install --require-hashes -r .github/scripts/requirements-python-build.txt
+ "$python" -m pip install --require-hashes --no-build-isolation -r .github/scripts/requirements-telethon.txt
+ echo "$RUNNER_TEMP/telegram-venv/bin" >> "$GITHUB_PATH"
+
+ - name: Publish.
+ env:
+ # api_id/api_hash aren't secret here (the session is) - Telegram's public open credentials.
+ TG_API_ID: "611335"
+ TG_API_HASH: "d524b414d21f4d37f08684c1df41ac9c"
+ TG_SESSION: ${{ secrets.TG_SESSION }}
+ TG_FEED_CHANNEL: ${{ secrets.TG_FEED_CHANNEL }}
+ TG_FILES_CHANNEL: ${{ secrets.TG_FILES_CHANNEL }}
+ ARTIFACTS_DIR: artifacts
+ # 'scheduled' sends for real but 360 days out - an invisible smoke test; delete those after.
+ TG_SCHEDULE_DAYS: ${{ (github.event_name == 'workflow_dispatch' && inputs.telegram == 'scheduled') && '360' || '0' }}
+ TG_ENTRY_KEY: ${{ (github.event_name == 'workflow_dispatch' && inputs.telegram == 'testing') && 'testing' || 'released' }}
+ run: python .github/scripts/publish_telegram.py
diff --git a/.github/workflows/lock.yml b/.github/workflows/lock.yml
deleted file mode 100644
index 7904e79591f79..0000000000000
--- a/.github/workflows/lock.yml
+++ /dev/null
@@ -1,15 +0,0 @@
-name: 'Lock Threads'
-
-on:
- schedule:
- - cron: '0 0 * * *'
-
-jobs:
- lock:
- runs-on: ubuntu-slim
- steps:
- - uses: dessant/lock-threads@v6
- with:
- github-token: ${{ github.token }}
- issue-inactive-days: 45
- pr-inactive-days: 45
diff --git a/.github/workflows/master_updater.yml b/.github/workflows/master_updater.yml
deleted file mode 100644
index fedc24f8e5d78..0000000000000
--- a/.github/workflows/master_updater.yml
+++ /dev/null
@@ -1,13 +0,0 @@
-name: Master branch updater.
-
-on:
- release:
- types: released
-
-jobs:
- User-agent:
- runs-on: ubuntu-slim
- steps:
- - uses: desktop-app/action_code_updater@master
- with:
- type: "dev-to-master"
diff --git a/.github/workflows/publish_channel.yml b/.github/workflows/publish_channel.yml
new file mode 100644
index 0000000000000..697b9178c5a25
--- /dev/null
+++ b/.github/workflows/publish_channel.yml
@@ -0,0 +1,107 @@
+name: Publish to the public channel.
+
+on:
+ workflow_dispatch:
+ inputs:
+ tag:
+ description: 'Release tag to take the asset from (empty = latest release).'
+ type: string
+ default: ''
+ dry_run:
+ description: 'Download and print the caption, but upload nothing.'
+ type: boolean
+ default: false
+ workflow_run:
+ workflows: ["Windows Release."]
+ types: [completed]
+
+permissions:
+ contents: read
+
+concurrency:
+ group: telegram-channel
+ cancel-in-progress: false
+
+jobs:
+
+ publish-channel:
+ name: Upload the portable build to the channel
+ runs-on: ubuntu-latest
+ if: >-
+ github.event_name == 'workflow_dispatch' ||
+ (github.event.workflow_run.conclusion == 'success' &&
+ github.event.workflow_run.event == 'push' &&
+ startsWith(github.event.workflow_run.head_branch, 'v'))
+ environment: telegram-publish
+
+ steps:
+ - name: Clone the uploader script.
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ persist-credentials: false
+ sparse-checkout: |
+ .github/scripts/publish_channel.py
+ .github/scripts/requirements-telethon.txt
+ .github/scripts/requirements-python-build.txt
+ .github/data/logo_256_square.png
+ sparse-checkout-cone-mode: false
+
+ - name: Download the asset.
+ env:
+ GH_TOKEN: ${{ github.token }}
+ ASSET_NAME: Telegram.zip
+ TAG_INPUT: ${{ inputs.tag }}
+ TAG_BUILT: ${{ github.event.workflow_run.head_branch }}
+ run: |
+ set -e
+ TAG="${TAG_INPUT:-$TAG_BUILT}"
+ if [ -z "$TAG" ]; then
+ TAG=$(gh release view -R "$GITHUB_REPOSITORY" --json tagName -q .tagName)
+ fi
+
+ # The caption links the tag as an upstream version, so refuse anything
+ # that is not a plain vX.Y.Z rather than posting a broken link.
+ if [[ ! "$TAG" =~ ^v[0-9]+(\.[0-9]+)+$ ]]; then
+ echo "Not a version tag: $TAG" >&2
+ exit 1
+ fi
+
+ # Betas carry a plain tag too, the way upstream tags its own, so the
+ # tag cannot say which this is - the prerelease flag can.
+ BETA=0
+ if [ "$(gh release view "$TAG" -R "$GITHUB_REPOSITORY" \
+ --json isPrerelease -q .isPrerelease)" = "true" ]; then
+ BETA=1
+ fi
+ VERSION="${TAG#v}"
+
+ mkdir -p deploy
+ gh release download "$TAG" -R "$GITHUB_REPOSITORY" \
+ -p "$ASSET_NAME" -D deploy
+ ls -l "deploy/$ASSET_NAME"
+
+ echo "ASSET_PATH=deploy/$ASSET_NAME" >> "$GITHUB_ENV"
+ echo "ASSET_VERSION=$VERSION" >> "$GITHUB_ENV"
+ echo "ASSET_BETA=$BETA" >> "$GITHUB_ENV"
+
+ - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6
+ with:
+ python-version: "3.12"
+
+ - name: Install Telethon.
+ run: |
+ python -m venv "$RUNNER_TEMP/telegram-venv"
+ python="$RUNNER_TEMP/telegram-venv/bin/python"
+ "$python" -m pip install --require-hashes -r .github/scripts/requirements-python-build.txt
+ "$python" -m pip install --require-hashes --no-build-isolation -r .github/scripts/requirements-telethon.txt
+ echo "$RUNNER_TEMP/telegram-venv/bin" >> "$GITHUB_PATH"
+
+ - name: Publish.
+ env:
+ TG_API_ID: "611335"
+ TG_API_HASH: "d524b414d21f4d37f08684c1df41ac9c"
+ TG_SESSION: ${{ secrets.TG_SESSION }}
+ TG_PUBLIC_CHANNEL: ${{ secrets.TG_PUBLIC_CHANNEL }}
+ TG_SCHEDULE_DAYS: "350"
+ TG_DRY_RUN: ${{ inputs.dry_run && '1' || '0' }}
+ run: python .github/scripts/publish_channel.py
diff --git a/.github/workflows/snap.yml b/.github/workflows/snap.yml
index f6f1332e8c0cd..20758f1c733ff 100644
--- a/.github/workflows/snap.yml
+++ b/.github/workflows/snap.yml
@@ -1,65 +1,22 @@
-name: Snap.
+name: Snap
on:
- push:
- # Pushes to the canary or private-ci branches run their own workflows.
- branches-ignore:
- - public-canary
- - private-canary
- - 'private-ci/**'
- - 'private-ci-*'
- - 'win7-gate-*'
- paths-ignore:
- - 'docs/**'
- - '**.md'
- - 'changelog.txt'
- - 'LEGAL'
- - 'LICENSE'
- - '.github/**'
- - '!.github/workflows/snap.yml'
- - 'Telegram/build/**'
- - 'Telegram/Resources/uwp/**'
- - 'Telegram/Resources/winrc/**'
- - 'Telegram/SourceFiles/platform/win/**'
- - 'Telegram/SourceFiles/platform/mac/**'
- - 'Telegram/Telegram/**'
- - 'Telegram/configure.bat'
- - 'Telegram/Telegram.plist'
- pull_request:
- paths-ignore:
- - 'docs/**'
- - '**.md'
- - 'changelog.txt'
- - 'LEGAL'
- - 'LICENSE'
- - '.github/**'
- - '!.github/workflows/snap.yml'
- - 'Telegram/build/**'
- - 'Telegram/Resources/uwp/**'
- - 'Telegram/Resources/winrc/**'
- - 'Telegram/SourceFiles/platform/win/**'
- - 'Telegram/SourceFiles/platform/mac/**'
- - 'Telegram/Telegram/**'
- - 'Telegram/configure.bat'
- - 'Telegram/Telegram.plist'
+ release:
+ types: [published]
+ workflow_dispatch:
jobs:
-
snap:
- name: Ubuntu
- runs-on: ${{ (github.event_name == 'pull_request' || startsWith(github.ref, 'refs/tags/') || github.ref == 'refs/heads/nightly') && 'depot-ubuntu-latest-16' || 'ubuntu-latest' }}
-
- env:
- UPLOAD_ARTIFACT: "true"
-
+ name: Build and publish snap
+ runs-on: ubuntu-latest
steps:
- - name: Clone.
+ - name: Checkout
uses: actions/checkout@v7
with:
fetch-depth: 0
submodules: recursive
- - name: First set up.
+ - name: Setup LXD
run: |
sudo iptables -P FORWARD ACCEPT
sudo snap install --classic snapcraft
@@ -67,29 +24,29 @@ jobs:
sudo lxd init --auto
sudo lxd waitready
- - name: Free up some disk space.
+ - name: Free up disk space
uses: samueldr/more-space-action@97048bd0df83fb05b5257887bdbaffc848887673
with:
enable-remove-default-apt-patterns: false
enable-lvm-span: true
lvm-span-mountpoint: /var/snap/lxd/common/lxd/storage-pools/default/containers
- - name: Telegram Desktop snap build.
+ - name: Build snap
run: sudo -u $USER snap run snapcraft --verbosity=debug
- - name: Move artifact.
- if: env.UPLOAD_ARTIFACT == 'true'
+ - name: Find snap artifact
run: |
- artifact_name=$(echo telegram-desktop_*.snap)
- echo "ARTIFACT_NAME=$artifact_name" >> $GITHUB_ENV
+ SNAP_FILE=$(echo forkgram_*.snap)
+ echo "SNAP_FILE=$SNAP_FILE" >> "$GITHUB_ENV"
- mkdir artifact
- mv $artifact_name artifact
-
- - uses: actions/upload-artifact@v7
- if: env.UPLOAD_ARTIFACT == 'true'
- name: Upload artifact.
+ - name: Upload artifact
+ uses: actions/upload-artifact@v7
with:
- name: ${{ env.ARTIFACT_NAME }}
- path: artifact
+ name: ${{ env.SNAP_FILE }}
+ path: ${{ env.SNAP_FILE }}
retention-days: 1
+
+ - name: Publish to Snap Store
+ env:
+ SNAPCRAFT_STORE_CREDENTIALS: ${{ secrets.SNAPCRAFT_STORE_CREDENTIALS }}
+ run: snapcraft upload "$SNAP_FILE" --release=stable
diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml
deleted file mode 100644
index 0d57eb7dbd9a9..0000000000000
--- a/.github/workflows/stale.yml
+++ /dev/null
@@ -1,25 +0,0 @@
-name: 'Close stale issues and PRs'
-on:
- schedule:
- - cron: '30 1 * * *'
-
-jobs:
- stale:
- runs-on: ubuntu-slim
- steps:
- - uses: actions/stale@v11
- with:
- stale-issue-message: |
- Hey there!
-
- This issue was inactive for a long time and will be automatically closed in 30 days if there isn't any further activity. We therefore assume that the user has lost interest or resolved the problem on their own.
-
- Don't worry though; if this is an error, let us know with a comment and we'll be happy to reopen the issue.
-
- Thanks!
- stale-issue-label: 'stale'
- exempt-issue-labels: 'enhancement'
- days-before-stale: 180
- days-before-close: 30
- days-before-pr-stale: -1
- operations-per-run: 1000
diff --git a/.github/workflows/user_agent_updater.yml b/.github/workflows/user_agent_updater.yml
deleted file mode 100644
index 1e3dae8182aef..0000000000000
--- a/.github/workflows/user_agent_updater.yml
+++ /dev/null
@@ -1,16 +0,0 @@
-name: User-agent updater.
-
-on:
- repository_dispatch:
- types: ["Restart user_agent_updater workflow."]
- schedule:
- # At 00:00 on day-of-month 1.
- - cron: "0 0 1 * *"
-
-jobs:
- User-agent:
- runs-on: ubuntu-latest
- steps:
- - uses: desktop-app/action_code_updater@master
- with:
- type: "user-agent"
diff --git a/.github/workflows/win.yml b/.github/workflows/win.yml
index 5012e14afd272..6ba1d66eeebf9 100644
--- a/.github/workflows/win.yml
+++ b/.github/workflows/win.yml
@@ -154,9 +154,25 @@ jobs:
id: cache-libs
uses: actions/cache@v6
with:
- path: ${{ env.LibrariesPath }}
- key: ${{ runner.OS }}-${{ matrix.arch }}-libs-${{ env.CACHE_KEY }}
- restore-keys: ${{ runner.OS }}-${{ matrix.arch }}-libs-
+ path: |
+ ${{ env.LibrariesPath }}\*
+ !${{ env.LibrariesPath }}\cache_keys
+ !${{ env.LibrariesPath }}\[qQ]t[_-]*
+ ${{ env.LibrariesPath }}\cache_keys\*
+ !${{ env.LibrariesPath }}\cache_keys\[qQ]t[_-]*
+ key: ${{ runner.OS }}-${{ matrix.arch }}-libs-v2-${{ env.CACHE_KEY }}
+ restore-keys: ${{ runner.OS }}-${{ matrix.arch }}-libs-v2-
+
+ - name: Qt cache.
+ id: cache-qt
+ uses: actions/cache@v6
+ with:
+ path: |
+ ${{ env.LibrariesPath }}\[qQ]t[_-]*
+ ${{ env.LibrariesPath }}\cache_keys\[qQ]t[_-]*
+ # New prefix: the old -qt- caches hold the dropped Qt 5 build.
+ key: ${{ runner.OS }}-${{ matrix.arch }}-qt-w7-${{ env.CACHE_KEY }}
+ restore-keys: ${{ runner.OS }}-${{ matrix.arch }}-qt-w7-
- name: Libraries.
run: |
@@ -209,7 +225,7 @@ jobs:
- name: Free up some disk space.
shell: bash
- run: bash "$TBUILD/$REPO_NAME/Telegram/build/prune_libraries.sh" "$LibrariesPath" tdesktop_rust/out -name '*.lib' -o -name '*.a' -o -name '*.exe' -o -name '*.h' -o -name '*.hpp' -o -name '*.inc' -o -name '*.cmake' -o -name '*.pc' -o -path '*/include/*' -o -path '*/objects-*' -o -path '*/cache_keys/*' -o -path '*/patches/*' -o -path '*/nv-codec-headers/*' -o -path '*/src/wallet_engine/*'
+ run: bash "$TBUILD/$REPO_NAME/Telegram/build/prune_libraries.sh" "$LibrariesPath" tdesktop_rust/out -name '*.lib' -o -name '*.a' -o -name '*.exe' -o -name '*.h' -o -name '*.hpp' -o -name '*.inc' -o -name '*.cmake' -o -name '*.pc' -o -path '*/include/*' -o -path '*/objects-*' -o -path '*/cache_keys/*' -o -path '*/patches/*' -o -path '*/qt6_windows7/*' -o -path '*/nv-codec-headers/*' -o -path '*/src/wallet_engine/*'
- name: Telegram Desktop build.
if: env.ONLY_CACHE == 'false'
diff --git a/.github/workflows/win7-gate.yml b/.github/workflows/win7-gate.yml
index 80df34f3c117d..5cfb3f766fb99 100644
--- a/.github/workflows/win7-gate.yml
+++ b/.github/workflows/win7-gate.yml
@@ -152,7 +152,7 @@ jobs:
- name: Free up some disk space.
shell: bash
- run: find $LibrariesPath '(' '(' ! '(' -name '*.lib' -o -name '*.a' -o -name '*.exe' -o -name '*.h' -o -name '*.hpp' -o -name '*.inc' -o -name '*.cmake' -o -name '*.pc' -o -path '*/include/*' -o -path '*/objects-*' -o -path '*/cache_keys/*' -o -path '*/patches/*' -o -path '*/nv-codec-headers/*' -o -path '*/tlottie/*' -o -path '*/tdesktop_rust/out/src/*' -o -path '*/wallet-engine/*' -o -path '*/tinyasr/*' -o -path '*/tinylid/*' -o -path '*/tmath/*' -o -path '*/tmarkdown/*' ')' -type f ')' -o -empty ')' -delete
+ run: find $LibrariesPath '(' '(' ! '(' -name '*.lib' -o -name '*.a' -o -name '*.exe' -o -name '*.h' -o -name '*.hpp' -o -name '*.inc' -o -name '*.cmake' -o -name '*.pc' -o -path '*/include/*' -o -path '*/objects-*' -o -path '*/cache_keys/*' -o -path '*/patches/*' -o -path '*/qt6_windows7/*' -o -path '*/nv-codec-headers/*' -o -path '*/tlottie/*' -o -path '*/tdesktop_rust/out/src/*' -o -path '*/wallet-engine/*' -o -path '*/tinyasr/*' -o -path '*/tinylid/*' -o -path '*/tmath/*' -o -path '*/tmarkdown/*' ')' -type f ')' -o -empty ')' -delete
- name: Save ThirdParty cache.
if: steps.cache-third-party.outputs.cache-hit != 'true'
diff --git a/.github/workflows/win_release.yml b/.github/workflows/win_release.yml
new file mode 100644
index 0000000000000..ea5f9fcc5d458
--- /dev/null
+++ b/.github/workflows/win_release.yml
@@ -0,0 +1,932 @@
+name: Windows Release.
+
+on:
+ workflow_dispatch:
+ inputs:
+ arch:
+ description: 'Which architectures to build.'
+ type: choice
+ options: [all, x64, x86, arm64]
+ default: all
+ only_cache:
+ description: 'Only prepare libraries and warm the cache.'
+ type: boolean
+ default: false
+ lto:
+ description: 'Enable LTO (official builds use it, links much slower).'
+ type: boolean
+ default: false
+ publish_release:
+ description: 'Publish a GitHub Release with the artifacts.'
+ type: boolean
+ default: false
+ telegram:
+ description: 'Publish update files to the Telegram channels (manual runs).'
+ type: choice
+ # 'off' must be quoted: YAML reads the bare word as boolean false, dropping it from the choices.
+ options: ['off', scheduled, testing, released]
+ default: 'off'
+ push:
+ tags:
+ - 'v*'
+ schedule:
+ # Keep the library and Qt caches from the 7-day eviction; rebuilds only what changed.
+ - cron: '0 3 * * 1,4'
+
+permissions:
+ contents: read
+
+concurrency:
+ group: win-release-${{ github.ref }}
+ cancel-in-progress: false
+
+jobs:
+
+ windows-release:
+ name: Windows ${{ matrix.arch }} Release
+ # ARM64 must build natively: prepare.py gives Qt no -qt-host-path, so Qt runs the moc/rcc/qmake it just built.
+ # This image already carries the v145 toolset and ARM64 ATL, so it needs no vs_buildtools step.
+ runs-on: ${{ matrix.arch == 'arm64' && 'windows-11-vs2026-arm' || 'windows-latest' }}
+ timeout-minutes: 360
+
+ strategy:
+ fail-fast: false
+ matrix:
+ arch: ${{ fromJSON((github.event_name == 'workflow_dispatch' && inputs.arch != 'all') && format('["{0}"]', inputs.arch) || '["x64","x86","arm64"]') }}
+
+ env:
+ PREPARE_PATH: "Telegram/build/prepare/prepare.py"
+ BUILD_TARGET: ${{ matrix.arch == 'x64' && 'win64' || matrix.arch == 'arm64' && 'winarm' || 'win' }}
+ MSVC_ARCH: ${{ matrix.arch == 'x64' && 'x64' || matrix.arch == 'arm64' && 'arm64' || 'x64_x86' }}
+ LIBS_SUBDIR: ${{ matrix.arch == 'x64' && '\win64' || '' }}
+ MODULES_ARCH: ${{ matrix.arch == 'x64' && 'x64' || matrix.arch == 'arm64' && 'arm64' || 'x86' }}
+ # prepare.py scopes the Windows 7 layer (YY-Thunks, qtbase backport, ANGLE) to the x86 targets; nothing below may ask for its outputs.
+ WIN7_LAYER: ${{ matrix.arch != 'arm64' && 'true' || '' }}
+ # prepare.py forces PlatformToolset=v145 for the winarm projects; let vcvars use the default toolset to match.
+ MSVC_TOOLSET: ${{ matrix.arch != 'arm64' && '14.44' || '' }}
+ ONLY_CACHE: ${{ (github.event_name == 'schedule' || inputs.only_cache) && 'true' || 'false' }}
+ ENABLE_LTO: ${{ inputs.lto && 'true' || 'false' }}
+
+ defaults:
+ run:
+ shell: cmd
+
+ steps:
+ # Qt 6 debug+release PDBs exhaust the image; drop toolchains this build never uses (keep Perl/Python).
+ - name: Free up runner disk space.
+ shell: pwsh
+ run: |
+ function Show-Free($label) {
+ Write-Host ("{0}: {1:N1} GB free" -f $label, ((Get-PSDrive C).Free / 1GB))
+ }
+ Show-Free 'before'
+
+ $targets = @(
+ 'C:\Android',
+ 'C:\Miniconda',
+ 'C:\Julia',
+ 'C:\Program Files\MongoDB',
+ 'C:\Program Files\MySQL',
+ 'C:\Program Files\PostgreSQL',
+ 'C:\Program Files\Amazon',
+ 'C:\Program Files\Microsoft SQL Server',
+ 'C:\Program Files (x86)\Microsoft SQL Server',
+ 'C:\Program Files (x86)\Google',
+ 'C:\Program Files\R',
+ 'C:\hostedtoolcache\windows\Java_Temurin-Hotspot_jdk',
+ 'C:\hostedtoolcache\windows\Ruby',
+ 'C:\hostedtoolcache\windows\go',
+ 'C:\hostedtoolcache\windows\node',
+ 'C:\hostedtoolcache\windows\PyPy',
+ 'C:\tools\kotlinc',
+ 'C:\SeleniumWebDrivers'
+ )
+ foreach ($target in $targets) {
+ if (Test-Path $target) {
+ Remove-Item -Recurse -Force $target -ErrorAction SilentlyContinue
+ Write-Host "removed $target"
+ }
+ }
+ Show-Free 'after'
+
+ # Two /MP2 compilers on heavy files exhaust 16 GB RAM (C1060).
+ - name: Extend the pagefile.
+ if: matrix.arch != 'arm64'
+ uses: al-cheb/configure-pagefile-action@86589fd789a4de3e62ba628dda2cb10027b66d67 # v1.3
+ with:
+ minimum-size: 16GB
+ maximum-size: 32GB
+ disk-root: 'C:'
+
+ # Build on D: (C: is too small); keep the symlink for actions/checkout and short Qt paths.
+ - name: Prepare directories.
+ run: |
+ if exist D:\ (
+ mkdir D:\TBuild\Libraries
+ mklink /d %GITHUB_WORKSPACE%\TBuild D:\TBuild
+ ) else (
+ mkdir %userprofile%\TBuild\Libraries
+ mklink /d %GITHUB_WORKSPACE%\TBuild %userprofile%\TBuild
+ )
+ echo TBUILD=%GITHUB_WORKSPACE%\TBuild>>%GITHUB_ENV%
+ echo LibrariesPath=%GITHUB_WORKSPACE%\TBuild\Libraries%LIBS_SUBDIR%>>%GITHUB_ENV%
+
+ # Check out into 'tdesktop' so %ROOT_DIR%\tdesktop\patches resolves the same in CI and locally.
+ - name: Set the build directory name.
+ shell: bash
+ run: echo "REPO_NAME=tdesktop" >> $GITHUB_ENV
+
+ - name: Clone.
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ persist-credentials: false
+ submodules: recursive
+ path: ${{ env.TBUILD }}\${{ env.REPO_NAME }}
+
+ - name: First set up.
+ shell: bash
+ run: |
+ DOCPATH=$TBUILD/$REPO_NAME/docs/building-win.md
+ SDK="$(grep "SDK version" $DOCPATH | sed -r 's/.*\*\*(.*)\*\* SDK version.*/\1/')"
+ echo "SDK=$SDK" >> $GITHUB_ENV
+
+ sed -i '/CMAKE_${lang}_FLAGS_DEBUG_INIT/s/${_Zi}//' "$PROGRAMFILES"/CMake/share/cmake*/Modules/Platform/Windows-MSVC.cmake
+
+ echo "$(sha256sum $TBUILD/$REPO_NAME/$PREPARE_PATH | awk '{ print $1 }')" >> CACHE_KEY.txt
+ echo "$SDK" >> CACHE_KEY.txt
+ # Release libraries are built too, so these caches must not collide with win.yml.
+ echo "release" >> CACHE_KEY.txt
+ echo "CACHE_KEY=$(sha256sum CACHE_KEY.txt | awk '{ print $1 }')" >> $GITHUB_ENV
+
+ echo "Configurate git for cherry-picks."
+ git config --global user.email "you@example.com"
+ git config --global user.name "Sample"
+
+ - name: Set link-time optimization flags.
+ shell: bash
+ run: |
+ if [ "$ENABLE_LTO" == "true" ]; then
+ echo "LTO_FLAG=-D DESKTOP_APP_ENABLE_LTO=ON" >> $GITHUB_ENV
+ else
+ echo "LTO_FLAG=" >> $GITHUB_ENV
+ fi
+
+ - uses: Eden-CI/msvc-dev-cmd@1bd71f95d6f3d1b2b3395b335cc63bcdc90cf223 # master
+ name: Native Tools Command Prompt.
+ with:
+ arch: ${{ env.MSVC_ARCH }}
+ sdk: ${{ env.SDK }}
+ toolset: ${{ env.MSVC_TOOLSET }}
+
+ # prepare.py reads its target off this one variable, and otherwise dies an hour in with a bare "run from Native Tools Command Prompt".
+ - name: Check the target architecture.
+ shell: bash
+ env:
+ EXPECTED: ${{ matrix.arch == 'x64' && 'x64' || matrix.arch == 'arm64' && 'arm64' || 'x86' }}
+ run: |
+ # Read it out of the environment, not as $Platform: Windows picks the name's case and bash is case sensitive.
+ actual=$(env | sed -n 's/^[Pp]latform=//p' | head -1)
+ echo "vcvars set Platform=$actual, prepare.py needs $EXPECTED"
+ [ "$actual" = "$EXPECTED" ] || {
+ echo "::error::wrong target architecture: ${actual:-}"
+ exit 1
+ }
+
+ - name: NuGet sources.
+ run: |
+ nuget sources Disable -Name "Microsoft Visual Studio Offline Packages"
+ nuget sources Add -Source https://api.nuget.org/v3/index.json & exit 0
+
+ # breakpad's dump_syms needs ATL at a legacy VC path Visual Studio dropped.
+ - name: Make ATL available.
+ shell: pwsh
+ run: |
+ $vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
+ $vs = & $vswhere -latest -products * -property installationPath
+ Write-Host "Visual Studio: $vs"
+
+ function Find-AtlRoot {
+ if ($env:VCToolsInstallDir) {
+ $preferred = Join-Path $env:VCToolsInstallDir 'atlmfc'
+ if (Test-Path (Join-Path $preferred 'include\atlbase.h')) { return $preferred }
+ }
+ $found = Get-ChildItem "$vs\VC\Tools\MSVC\*\atlmfc\include\atlbase.h" -ErrorAction SilentlyContinue |
+ Sort-Object FullName -Descending | Select-Object -First 1
+ if ($found) { return (Split-Path (Split-Path $found.FullName -Parent) -Parent) }
+ return $null
+ }
+
+ $atlRoot = Find-AtlRoot
+ if (-not $atlRoot) {
+ Write-Host 'ATL is not installed, adding the component.'
+ $installer = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vs_installer.exe"
+ $p = Start-Process -FilePath $installer -Wait -PassThru -ArgumentList `
+ 'modify', '--installPath', "`"$vs`"", `
+ '--add', 'Microsoft.VisualStudio.Component.VC.ATL', `
+ '--quiet', '--norestart', '--nocache'
+ if ($p.ExitCode -ne 0 -and $p.ExitCode -ne 3010) {
+ Write-Error "vs_installer failed with $($p.ExitCode)"; exit 1
+ }
+ $atlRoot = Find-AtlRoot
+ }
+ if (-not $atlRoot) { Write-Error 'atlbase.h still not found'; exit 1 }
+
+ Write-Host "ATL root: $atlRoot"
+
+ # Compiler finds ATL headers via /I, linker finds atls.lib via LibraryPath - link both.
+ $legacy = Join-Path $vs 'VC\atlmfc'
+ $toolset = Join-Path $env:VCToolsInstallDir 'atlmfc'
+ foreach ($link in @($legacy, $toolset)) {
+ if (Test-Path $link) {
+ Write-Host "$link already exists"
+ } else {
+ New-Item -ItemType Junction -Path $link -Target $atlRoot | Out-Null
+ Write-Host "Linked $link -> $atlRoot"
+ }
+ }
+
+ foreach ($probe in @(
+ (Join-Path $legacy 'include\atlbase.h'),
+ (Join-Path $legacy 'include\atlcomcli.h'),
+ (Join-Path $toolset 'lib\x64\atls.lib'))) {
+ if (-not (Test-Path $probe)) { Write-Error "unreachable: $probe"; exit 1 }
+ Write-Host "found $probe"
+ }
+
+ # actions/cache saves only on success; split restore/save to bank library progress on failure.
+ - name: ThirdParty cache.
+ id: cache-third-party
+ uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
+ with:
+ path: ${{ env.TBUILD }}\ThirdParty
+ key: ${{ runner.OS }}-${{ matrix.arch }}-third-party-${{ env.CACHE_KEY }}-${{ github.run_id }}
+ restore-keys: ${{ runner.OS }}-${{ matrix.arch }}-third-party-
+
+ - name: Libraries cache.
+ id: cache-libs
+ uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
+ with:
+ path: |
+ ${{ env.LibrariesPath }}\*
+ !${{ env.LibrariesPath }}\cache_keys
+ !${{ env.LibrariesPath }}\[qQ]t[_-]*
+ ${{ env.LibrariesPath }}\cache_keys\*
+ !${{ env.LibrariesPath }}\cache_keys\[qQ]t[_-]*
+ key: ${{ runner.OS }}-${{ matrix.arch }}-libs-rel-${{ env.CACHE_KEY }}-${{ github.run_id }}
+ restore-keys: ${{ runner.OS }}-${{ matrix.arch }}-libs-rel-
+
+ - name: Qt cache.
+ id: cache-qt
+ uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
+ with:
+ path: |
+ ${{ env.LibrariesPath }}\[qQ]t[_-]*
+ ${{ env.LibrariesPath }}\cache_keys\[qQ]t[_-]*
+ key: ${{ runner.OS }}-${{ matrix.arch }}-qt-rel-${{ env.CACHE_KEY }}-${{ github.run_id }}
+ restore-keys: ${{ runner.OS }}-${{ matrix.arch }}-qt-rel-
+
+ # A restored cache that lost an artifact still reads as built; drop its key to refetch.
+ - name: Heal stale cache keys.
+ shell: bash
+ run: |
+ [ -d "$LibrariesPath" ] || exit 0
+ drop() {
+ rm -f "$LibrariesPath"/cache_keys/$1
+ echo "$2, dropped the $1 cache key"
+ }
+ if [ -n "$WIN7_LAYER" ]; then
+ [ -f "$LibrariesPath/yy_thunks/objs/$MODULES_ARCH/YY_Thunks_for_Win7.lib" ] \
+ || drop yy_thunks "YY-Thunks library missing"
+ [ -f "$LibrariesPath/tg_angle/out/Release/tg_angle.lib" ] \
+ || drop tg_angle "ANGLE library missing"
+ fi
+ # prepare.py rebuilds a stage whose folder the sweep emptied, but
+ # nv-codec-headers keeps its headers, so the folder survives without
+ # the makefile the ffmpeg build script installs from. The .pc files
+ # it reads live in the shared prefix, which has no stage of its own.
+ [ -f "$LibrariesPath/nv-codec-headers/Makefile" ] \
+ || drop nv-codec-headers "nv-codec-headers makefile missing"
+ for manifest in tlottie/Cargo.toml wallet-engine/bindgen/cpp/bindgen/Cargo.toml \
+ tinyasr/Cargo.toml tinylid/Cargo.toml tmath/ffi/Cargo.toml tmarkdown/ffi/Cargo.toml; do
+ [ -f "$LibrariesPath/$manifest" ] \
+ || drop "${manifest%%/*}" "$manifest missing"
+ done
+ if [ -z "$(ls -A "$LibrariesPath/local/lib/pkgconfig" 2>/dev/null)" ]; then
+ for lib in dav1d openh264 opus libvpx; do
+ drop $lib "pkg-config files missing"
+ done
+ fi
+
+ - name: Libraries.
+ # No skip-release: a Release build needs Release libraries. Step timeout < job limit so cache saves still run.
+ timeout-minutes: 285
+ run: |
+ %TBUILD%\%REPO_NAME%\Telegram\build\prepare\win.bat silent
+
+ - name: Free up some disk space.
+ if: always()
+ shell: bash
+ run: |
+ [ -d "$LibrariesPath" ] || { echo "nothing to clean up"; exit 0; }
+ bash "$TBUILD/$REPO_NAME/Telegram/build/prune_libraries.sh" "$LibrariesPath" tdesktop_rust/out \
+ -name '*.lib' -o -name '*.a' -o -name '*.exe' -o -name '*.h' -o -name '*.hpp' -o -name '*.inc' -o -name '*.cmake' -o -name '*.pc' -o -path '*/include/*' -o -path '*/objects-*' -o -path '*/cache_keys/*' -o -path '*/patches/*' -o -path '*/qt6_windows7/*' -o -path '*/yy_thunks/*' -o -path '*/nv-codec-headers/*' -o -path '*/gas-preprocessor/*' -o -path '*/src/wallet_engine/*' || true
+
+ - name: Save ThirdParty cache.
+ if: always()
+ uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
+ with:
+ path: ${{ env.TBUILD }}\ThirdParty
+ key: ${{ runner.OS }}-${{ matrix.arch }}-third-party-${{ env.CACHE_KEY }}-${{ github.run_id }}
+
+ - name: Save libraries cache.
+ if: always()
+ uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
+ with:
+ path: |
+ ${{ env.LibrariesPath }}\*
+ !${{ env.LibrariesPath }}\cache_keys
+ !${{ env.LibrariesPath }}\[qQ]t[_-]*
+ ${{ env.LibrariesPath }}\cache_keys\*
+ !${{ env.LibrariesPath }}\cache_keys\[qQ]t[_-]*
+ key: ${{ runner.OS }}-${{ matrix.arch }}-libs-rel-${{ env.CACHE_KEY }}-${{ github.run_id }}
+
+ - name: Save Qt cache.
+ if: always()
+ uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
+ with:
+ path: |
+ ${{ env.LibrariesPath }}\[qQ]t[_-]*
+ ${{ env.LibrariesPath }}\cache_keys\[qQ]t[_-]*
+ key: ${{ runner.OS }}-${{ matrix.arch }}-qt-rel-${{ env.CACHE_KEY }}-${{ github.run_id }}
+
+ - name: Build tree cache.
+ if: env.ONLY_CACHE == 'false'
+ uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
+ with:
+ path: ${{ env.TBUILD }}\${{ env.REPO_NAME }}\out
+ key: ${{ runner.OS }}-${{ matrix.arch }}-out-rel-unsigned-${{ env.CACHE_KEY }}-${{ github.run_id }}
+ restore-keys: ${{ runner.OS }}-${{ matrix.arch }}-out-rel-unsigned-${{ env.CACHE_KEY }}-
+
+ - name: Set up DesktopPrivate.
+ if: env.ONLY_CACHE == 'false'
+ shell: bash
+ env:
+ API_ID: ${{ secrets.TDESKTOP_API_ID }}
+ API_HASH: ${{ secrets.TDESKTOP_API_HASH }}
+ run: |
+ set -e
+ python3 - <<'PY'
+ import os, pathlib
+
+ private = pathlib.Path(os.environ['TBUILD']) / 'DesktopPrivate'
+ private.mkdir(parents=True, exist_ok=True)
+
+ # configure.py only regex-scans this one for the API credentials.
+ (private / 'custom_api_id.h').write_text(
+ 'static const int32 ApiId = %s;\n'
+ 'static const char *ApiHash = "%s";\n'
+ % (os.environ['API_ID'], os.environ['API_HASH']))
+
+ (private / 'packer_private.h').write_text(
+ 'const char *PrivateKey = "";\n'
+ 'const char *PrivateBetaKey = "";\n')
+ (private / 'alpha_private.h').write_text(
+ '[[maybe_unused]] static const char *AlphaPrivateKey = "";\n')
+ PY
+
+ # Presence of this file makes run_cmake.py build Packer (DESKTOP_APP_SPECIAL_TARGET).
+ echo "$BUILD_TARGET" > $TBUILD/$REPO_NAME/Telegram/build/target
+
+ echo "DesktopPrivate contents:"
+ ls -l $TBUILD/DesktopPrivate
+
+ - name: Telegram Desktop build.
+ if: env.ONLY_CACHE == 'false'
+ env:
+ # Debug info made single files blow the memory limit; off, two compilers fit.
+ _CL_: /MP2
+ run: |
+ cd %TBUILD%\%REPO_NAME%\Telegram
+
+ rem Re-running cmake rewrites the .vcxproj files, and the fresh
+ rem timestamps make MSBuild rebuild everything - which throws away the
+ rem restored build tree. Reuse the tree when it was configured with the
+ rem same flags and against the same libraries, and record both so that
+ rem a change in either still reconfigures - a tree carries absolute
+ rem paths and link lines resolved against the libraries of its own run.
+ set "CFG_FLAGS=lto=%LTO_FLAG% target=%BUILD_TARGET% qt6win7=on nodebug=1 libs=%CACHE_KEY%"
+ set "CFG_MARKER=..\out\.ci_configure_flags"
+ set "REUSE_TREE=0"
+ if exist ..\out\CMakeCache.txt if exist "%CFG_MARKER%" (
+ for /f "usebackq delims=" %%a in ("%CFG_MARKER%") do (
+ if "%%a"=="%CFG_FLAGS%" set "REUSE_TREE=1"
+ )
+ )
+ if "%REUSE_TREE%"=="1" (
+ echo Reusing the configured build tree.
+ goto :build
+ )
+ echo Configuring the build tree.
+
+ call configure.bat ^
+ -D CMAKE_CONFIGURATION_TYPES=Release ^
+ -D DESKTOP_APP_DISABLE_AUTOUPDATE=OFF ^
+ -D DESKTOP_APP_DISABLE_CRASH_REPORTS=OFF ^
+ -D CMAKE_MSVC_DEBUG_INFORMATION_FORMAT= ^
+ %LTO_FLAG% || exit /b 1
+
+ > "%CFG_MARKER%" echo %CFG_FLAGS%
+
+ :build
+ cmake --build ..\out --config Release --target Telegram --parallel 2 || exit /b 1
+
+ - name: Save build tree cache.
+ if: always() && env.ONLY_CACHE == 'false'
+ uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
+ with:
+ path: ${{ env.TBUILD }}\${{ env.REPO_NAME }}\out
+ key: ${{ runner.OS }}-${{ matrix.arch }}-out-rel-unsigned-${{ env.CACHE_KEY }}-${{ github.run_id }}
+
+ - name: Prepare the Windows build artifacts.
+ if: env.ONLY_CACHE == 'false'
+ shell: pwsh
+ run: |
+ $release = "$env:TBUILD\$env:REPO_NAME\out\Release"
+ New-Item -ItemType Directory -Path windows-build | Out-Null
+ foreach ($name in @('Telegram.exe', 'Updater.exe')) {
+ Copy-Item -LiteralPath (Join-Path $release $name) -Destination windows-build
+ }
+ $helperDir = "modules\${env:MODULES_ARCH}"
+ New-Item -ItemType Directory -Path "windows-build\$helperDir" -Force | Out-Null
+ Copy-Item -LiteralPath "$release\$helperDir\TelegramWidgetHelper.exe" -Destination "windows-build\$helperDir"
+ if ($env:WIN7_LAYER) {
+ $modules = "modules\${env:MODULES_ARCH}\d3d"
+ New-Item -ItemType Directory -Path "windows-build\$modules" -Force | Out-Null
+ Copy-Item -LiteralPath "$release\$modules\d3dcompiler_47.dll" -Destination "windows-build\$modules"
+ }
+
+ - name: Upload the Windows build artifacts.
+ if: env.ONLY_CACHE == 'false'
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7
+ with:
+ name: windows-build-${{ matrix.arch }}
+ path: windows-build/
+ if-no-files-found: error
+ retention-days: 7
+ overwrite: true
+
+ - name: Upload the Windows Packer.
+ if: env.ONLY_CACHE == 'false'
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7
+ with:
+ name: windows-packer-${{ matrix.arch }}
+ path: ${{ env.TBUILD }}/${{ env.REPO_NAME }}/out/Release/Packer.exe
+ if-no-files-found: error
+ retention-days: 7
+ overwrite: true
+
+ codesign-windows:
+ name: Sign Windows binaries (${{ matrix.arch }})
+ needs: windows-release
+ if: github.event_name != 'schedule' && !inputs.only_cache
+ runs-on: ${{ matrix.arch == 'arm64' && 'windows-11-vs2026-arm' || 'windows-latest' }}
+ environment: desktop-windows-signing
+
+ strategy:
+ fail-fast: false
+ matrix:
+ arch: ${{ fromJSON((github.event_name == 'workflow_dispatch' && inputs.arch != 'all') && format('["{0}"]', inputs.arch) || '["x64","x86","arm64"]') }}
+
+ env:
+ TBUILD: ${{ github.workspace }}\TBuild
+ REPO_NAME: tdesktop
+ MODULES_ARCH: ${{ matrix.arch == 'x64' && 'x64' || matrix.arch == 'arm64' && 'arm64' || 'x86' }}
+ ISS_TARGET: ${{ matrix.arch == 'x64' && 'win64' || matrix.arch == 'arm64' && 'winarm' || 'win32' }}
+ SETUP_PREFIX: ${{ matrix.arch == 'x64' && 'tsetup-x64' || matrix.arch == 'arm64' && 'tsetup-arm64' || 'tsetup' }}
+
+ steps:
+ - name: Check out the packaging inputs.
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ persist-credentials: false
+ path: TBuild/tdesktop
+ sparse-checkout: |
+ Telegram/build/setup.iss
+ Telegram/build/version
+ Telegram/Resources/art/icon256.ico
+ sparse-checkout-cone-mode: false
+
+ - name: Download the Windows build artifacts.
+ uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7
+ with:
+ name: windows-build-${{ matrix.arch }}
+ path: TBuild/tdesktop/out/Release
+
+ - name: Read version.
+ shell: bash
+ run: |
+ awk 'NF { print $1"="$2 }' $TBUILD/$REPO_NAME/Telegram/build/version >> $GITHUB_ENV
+ source <(awk 'NF { print $1"="$2 }' $TBUILD/$REPO_NAME/Telegram/build/version)
+
+ if [ "$AlphaVersion" != "0" ]; then
+ echo "AppVersionStrFull=${AppVersionStr}_${AlphaVersion}" >> $GITHUB_ENV
+ elif [ "$BetaChannel" != "0" ]; then
+ echo "AppVersionStrFull=${AppVersionStr}.beta" >> $GITHUB_ENV
+ else
+ echo "AppVersionStrFull=${AppVersionStr}" >> $GITHUB_ENV
+ fi
+
+ - name: Set up the code signing certificate.
+ shell: pwsh
+ env:
+ WIN_CODESIGN_PFX: ${{ secrets.WIN_CODESIGN_PFX }}
+ run: |
+ $tool = Get-ChildItem "${env:ProgramFiles(x86)}\Windows Kits\10\bin\*\x64\signtool.exe" |
+ Sort-Object FullName -Descending | Select-Object -First 1
+ if (-not $tool) { Write-Error 'signtool.exe not found'; exit 1 }
+ echo "SIGNTOOL=$($tool.FullName)" >> $env:GITHUB_ENV
+ echo "Using $($tool.FullName)"
+
+ $pfx = Join-Path $env:RUNNER_TEMP 'codesign.pfx'
+ echo "CODESIGN_PFX=$pfx" >> $env:GITHUB_ENV
+ [IO.File]::WriteAllBytes($pfx, [Convert]::FromBase64String($env:WIN_CODESIGN_PFX))
+
+ - name: Sign the binaries.
+ shell: pwsh
+ env:
+ CODESIGN_PASSWORD: ${{ secrets.WIN_CODESIGN_PASSWORD }}
+ run: |
+ $release = "$env:TBUILD\$env:REPO_NAME\out\Release"
+ # Guard explicitly: an empty target list would make this step pass silently.
+ if (-not (Test-Path (Join-Path $release 'Telegram.exe'))) {
+ Write-Error "Telegram.exe is missing from $release"; exit 1
+ }
+ $helper = "modules\${env:MODULES_ARCH}\TelegramWidgetHelper.exe"
+ $targets = @('Telegram.exe', 'Updater.exe', $helper) |
+ ForEach-Object { Join-Path $release $_ }
+ foreach ($target in $targets) {
+ if (-not (Test-Path -LiteralPath $target)) { Write-Error "missing $target"; exit 1 }
+ }
+
+ foreach ($target in $targets) {
+ # Timestamping is what keeps a signature valid past certificate expiry.
+ & $env:SIGNTOOL sign /f $env:CODESIGN_PFX /p $env:CODESIGN_PASSWORD `
+ /fd SHA256 /tr http://timestamp.digicert.com /td SHA256 $target
+ if ($LASTEXITCODE -ne 0) {
+ Write-Host "Timestamping failed for $target, signing without a timestamp."
+ & $env:SIGNTOOL sign /f $env:CODESIGN_PFX /p $env:CODESIGN_PASSWORD /fd SHA256 $target
+ if ($LASTEXITCODE -ne 0) { exit 1 }
+ }
+ }
+ # Not verify /pa: a self-signed cert has no trusted chain; just check the signature is intact.
+ foreach ($target in $targets) {
+ $sig = Get-AuthenticodeSignature $target
+ $name = [IO.Path]::GetFileName($target)
+ if (-not $sig.SignerCertificate) { Write-Error "$name carries no signature"; exit 1 }
+ if ($sig.Status -in @('NotSigned', 'HashMismatch')) {
+ Write-Error "$name signature is broken: $($sig.Status)"; exit 1
+ }
+ Write-Host "$name -> $($sig.Status), signed by $($sig.SignerCertificate.Subject)"
+ }
+
+ - name: Create the installer.
+ shell: pwsh
+ env:
+ CODESIGN_PASSWORD: ${{ secrets.WIN_CODESIGN_PASSWORD }}
+ run: |
+ $release = "$env:TBUILD\$env:REPO_NAME\out\Release"
+ $iss = "$env:TBUILD\$env:REPO_NAME\Telegram\build\setup.iss"
+
+ $iscc = Get-ChildItem 'C:\Program Files*\Inno Setup*\ISCC.exe' -ErrorAction SilentlyContinue |
+ Sort-Object FullName -Descending | Select-Object -First 1
+ if (-not $iscc) { Write-Error 'ISCC.exe not found'; exit 1 }
+ echo "Using $($iscc.FullName)"
+
+ & $iscc.FullName `
+ "/dMyAppVersion=$env:AppVersionStrSmall" `
+ "/dMyAppVersionZero=$env:AppVersionStr" `
+ "/dMyAppVersionFull=$env:AppVersionStrFull" `
+ "/dReleasePath=$release" `
+ "/dMyBuildTarget=${env:ISS_TARGET}" `
+ $iss
+ if ($LASTEXITCODE -ne 0) { exit 1 }
+
+ $setup = Join-Path $release "${env:SETUP_PREFIX}.${env:AppVersionStrFull}.exe"
+ if (-not (Test-Path $setup)) { Write-Error "$setup was not produced"; exit 1 }
+ & $env:SIGNTOOL sign /f $env:CODESIGN_PFX /p $env:CODESIGN_PASSWORD /fd SHA256 $setup
+ if ($LASTEXITCODE -ne 0) { exit 1 }
+
+ - name: Remove the code signing certificate.
+ if: always() && env.CODESIGN_PFX != ''
+ shell: pwsh
+ run: Remove-Item -LiteralPath $env:CODESIGN_PFX -Force -ErrorAction Stop
+
+ - name: Upload the signed Windows binaries.
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7
+ with:
+ name: windows-signed-${{ matrix.arch }}
+ path: TBuild/tdesktop/out/Release/
+ if-no-files-found: error
+ retention-days: 7
+ overwrite: true
+
+ package-windows:
+ name: Package Windows (${{ matrix.arch }})
+ needs: codesign-windows
+ if: github.event_name != 'schedule' && !inputs.only_cache
+ runs-on: ${{ matrix.arch == 'arm64' && 'windows-11-vs2026-arm' || 'windows-latest' }}
+
+ strategy:
+ fail-fast: false
+ matrix:
+ arch: ${{ fromJSON((github.event_name == 'workflow_dispatch' && inputs.arch != 'all') && format('["{0}"]', inputs.arch) || '["x64","x86","arm64"]') }}
+
+ env:
+ TBUILD: ${{ github.workspace }}\TBuild
+ REPO_NAME: tdesktop
+ BUILD_TARGET: ${{ matrix.arch == 'x64' && 'win64' || matrix.arch == 'arm64' && 'winarm' || 'win' }}
+ UPD_PREFIX: ${{ matrix.arch == 'x64' && 'td-update-win-x64-' || matrix.arch == 'arm64' && 'td-update-win-arm-' || 'td-update-win-x86-' }}
+ SETUP_PREFIX: ${{ matrix.arch == 'x64' && 'tsetup-x64' || matrix.arch == 'arm64' && 'tsetup-arm64' || 'tsetup' }}
+ MODULES_ARCH: ${{ matrix.arch == 'x64' && 'x64' || matrix.arch == 'arm64' && 'arm64' || 'x86' }}
+ WIN7_LAYER: ${{ matrix.arch != 'arm64' && 'true' || '' }}
+ ASSET_INSTALLER: ${{ matrix.arch == 'x64' && 'Telegram.Windows.x64.Installer.exe' || matrix.arch == 'arm64' && 'Telegram.Windows.arm64.Installer.exe' || 'Telegram.Windows.x32.Installer.exe' }}
+ ASSET_PORTABLE: ${{ matrix.arch == 'x64' && 'Telegram.zip' || matrix.arch == 'arm64' && 'Telegram_arm64.zip' || 'Telegram_x86.zip' }}
+
+ steps:
+ - name: Check out the update manifest.
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ persist-credentials: false
+ path: TBuild/tdesktop
+ sparse-checkout: |
+ Telegram/build/version
+ Telegram/Resources/update
+ sparse-checkout-cone-mode: false
+
+ - name: Download the signed Windows binaries.
+ uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7
+ with:
+ name: windows-signed-${{ matrix.arch }}
+ path: TBuild/tdesktop/out/Release
+
+ - name: Download the Windows Packer.
+ uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7
+ with:
+ name: windows-packer-${{ matrix.arch }}
+ path: TBuild/tdesktop/out/Release
+
+ - name: Read version.
+ shell: bash
+ run: |
+ awk 'NF { print $1"="$2 }' $TBUILD/$REPO_NAME/Telegram/build/version >> $GITHUB_ENV
+ source <(awk 'NF { print $1"="$2 }' $TBUILD/$REPO_NAME/Telegram/build/version)
+
+ if [ "$AlphaVersion" != "0" ]; then
+ echo "AppVersionStrFull=${AppVersionStr}_${AlphaVersion}" >> $GITHUB_ENV
+ elif [ "$BetaChannel" != "0" ]; then
+ echo "AppVersionStrFull=${AppVersionStr}.beta" >> $GITHUB_ENV
+ else
+ echo "AppVersionStrFull=${AppVersionStr}" >> $GITHUB_ENV
+ fi
+
+ # Packer's channel and the file name suffix, both from BetaChannel.
+ if [ "$BetaChannel" != "0" ]; then
+ echo "UPD_CHANNEL=beta" >> $GITHUB_ENV
+ echo "UPD_SUFFIX=-beta" >> $GITHUB_ENV
+ else
+ echo "UPD_CHANNEL=stable" >> $GITHUB_ENV
+ echo "UPD_SUFFIX=" >> $GITHUB_ENV
+ fi
+ echo "Building version $AppVersionStr ($AppVersion)."
+
+ - name: Pack the update file.
+ shell: pwsh
+ run: |
+ $release = "$env:TBUILD\$env:REPO_NAME\out\Release"
+ Set-Location $release
+
+ # Not $args: that is an automatic variable in PowerShell.
+ $helper = "modules\${env:MODULES_ARCH}\TelegramWidgetHelper.exe"
+ $packerArgs = @('-version', $env:AppVersion, '-path', 'Telegram.exe', '-path', 'Updater.exe', '-path', $helper)
+ if ($env:WIN7_LAYER) {
+ $d3d = "modules\${env:MODULES_ARCH}\d3d\d3dcompiler_47.dll"
+ if (-not (Test-Path $d3d)) { Write-Error "missing $d3d for ANGLE"; exit 1 }
+ $packerArgs += @('-path', $d3d)
+ }
+ $packerArgs += @('-target', $env:BUILD_TARGET)
+ $packerArgs += @('-channel', $env:UPD_CHANNEL)
+ $packerArgs += @('-keys-loc', "$env:TBUILD\$env:REPO_NAME\Telegram\Resources\update")
+ $packerArgs += @('-emit-signing-input', 'update-signing-input.bin')
+
+ & .\Packer.exe @packerArgs
+ if ($LASTEXITCODE -ne 0) { exit 1 }
+
+ $update = "${env:UPD_PREFIX}${env:AppVersion}${env:UPD_SUFFIX}.unsigned"
+ if (-not (Test-Path $update)) { Write-Error "$update was not produced"; exit 1 }
+ echo "Produced $update ($((Get-Item $update).Length) bytes)"
+
+ - name: Collect the artifacts.
+ shell: pwsh
+ run: |
+ $release = "$env:TBUILD\$env:REPO_NAME\out\Release"
+ $deploy = Join-Path $env:GITHUB_WORKSPACE 'deploy'
+ $portableDir = Join-Path $deploy 'Telegram'
+ New-Item -ItemType Directory -Path $portableDir -Force | Out-Null
+
+ Copy-Item (Join-Path $release 'Telegram.exe') $portableDir
+ $helperDir = "modules\${env:MODULES_ARCH}"
+ New-Item -ItemType Directory -Path "$portableDir\$helperDir" -Force | Out-Null
+ Copy-Item -LiteralPath "$release\$helperDir\TelegramWidgetHelper.exe" -Destination "$portableDir\$helperDir"
+ if ($env:WIN7_LAYER) {
+ $d3d = Join-Path $release "modules\${env:MODULES_ARCH}\d3d\d3dcompiler_47.dll"
+ if (-not (Test-Path $d3d)) { Write-Error "missing $d3d for ANGLE"; exit 1 }
+ $modules = Join-Path $portableDir "modules\${env:MODULES_ARCH}\d3d"
+ New-Item -ItemType Directory -Path $modules -Force | Out-Null
+ Copy-Item $d3d $modules
+ }
+
+ Set-Location $deploy
+ & 7z a -mx9 $env:ASSET_PORTABLE Telegram\
+ if ($LASTEXITCODE -ne 0) { exit 1 }
+ & 7z t $env:ASSET_PORTABLE
+ if ($LASTEXITCODE -ne 0) { exit 1 }
+ Remove-Item -Recurse -Force $portableDir
+
+ # Installer gets the release name; the update file keeps its raw name for the Telegram job (Updater/PDB excluded).
+ $installer = Join-Path $release "${env:SETUP_PREFIX}.${env:AppVersionStrFull}.exe"
+ if (-not (Test-Path $installer)) { Write-Error "missing installer: $installer"; exit 1 }
+ Copy-Item $installer (Join-Path $deploy $env:ASSET_INSTALLER)
+
+ $update = Join-Path $release "${env:UPD_PREFIX}${env:AppVersion}${env:UPD_SUFFIX}.unsigned"
+ if (-not (Test-Path $update)) { Write-Error "missing update file: $update"; exit 1 }
+ Copy-Item $update $deploy
+
+ Get-ChildItem $deploy | Format-Table Name, Length
+
+ - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7
+ name: Upload the unsigned artifacts.
+ with:
+ name: unsigned-windows-${{ matrix.arch }}
+ path: deploy\
+ if-no-files-found: error
+ retention-days: 7
+ compression-level: 0
+ overwrite: true
+
+ sign-release:
+ name: Sign the Windows update (${{ matrix.arch }})
+ needs: package-windows
+ if: github.event_name != 'schedule' && !inputs.only_cache
+ runs-on: ubuntu-latest
+ environment: desktop-update-signing
+ permissions:
+ contents: write
+
+ strategy:
+ fail-fast: false
+ matrix:
+ arch: ${{ fromJSON((github.event_name == 'workflow_dispatch' && inputs.arch != 'all') && format('["{0}"]', inputs.arch) || '["x64","x86","arm64"]') }}
+
+ env:
+ ASSET_INSTALLER: ${{ matrix.arch == 'x64' && 'Telegram.Windows.x64.Installer.exe' || matrix.arch == 'arm64' && 'Telegram.Windows.arm64.Installer.exe' || 'Telegram.Windows.x32.Installer.exe' }}
+ ASSET_PORTABLE: ${{ matrix.arch == 'x64' && 'Telegram.zip' || matrix.arch == 'arm64' && 'Telegram_arm64.zip' || 'Telegram_x86.zip' }}
+
+ steps:
+ - name: Check out the release signing tools.
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ persist-credentials: false
+ sparse-checkout: |
+ Telegram/build/sign_forkgram_update.py
+ Telegram/build/version
+ Telegram/Resources/update
+ sparse-checkout-cone-mode: false
+
+ - name: Download the unsigned release.
+ uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7
+ with:
+ name: unsigned-windows-${{ matrix.arch }}
+ path: deploy
+
+ - name: Read artifact version.
+ run: |
+ awk '
+ $1 == "AppVersionStr" { version = $2 }
+ $1 == "AlphaVersion" { alpha = $2 }
+ $1 == "BetaChannel" { beta = $2 }
+ END {
+ print "AppVersionStr=" version
+ print "BetaChannel=" beta
+ print "AppVersionStrFull=" version (alpha != "0" ? "_" alpha : (beta != "0" ? ".beta" : ""))
+ }
+ ' Telegram/build/version >> "$GITHUB_ENV"
+
+ - name: Sign the update file.
+ env:
+ UPDATE_LOCAL_KEY: ${{ secrets.UPDATE_LOCAL_KEY }}
+ run: >-
+ python3 -I Telegram/build/sign_forkgram_update.py deploy Telegram/build/version
+ Telegram/Resources/update ${{ matrix.arch == 'arm64' && 'win-arm' || format('win-{0}', matrix.arch) }}
+
+ - name: Upload the artifacts.
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7
+ with:
+ name: Telegram ${{ matrix.arch }} Release ${{ env.AppVersionStrFull }}
+ path: deploy/
+ if-no-files-found: error
+ compression-level: 0
+ overwrite: true
+
+ - name: Publish the release.
+ if: inputs.publish_release || startsWith(github.ref, 'refs/tags/')
+ shell: bash
+ env:
+ # RELEASE_TOKEN (repo scope) overrides the workflow token if release creation is ever refused.
+ GH_TOKEN: ${{ secrets.RELEASE_TOKEN || github.token }}
+ run: |
+ set -e
+ R="$GITHUB_REPOSITORY"
+
+ if [[ "$GITHUB_REF" == refs/tags/* ]]; then
+ TAG="${GITHUB_REF#refs/tags/}"
+ TARGET=()
+ else
+ TAG="v$AppVersionStr"
+ TARGET=(--target dev)
+ fi
+
+ # Create only if missing, else just add assets, so the arch legs and the mac workflow share one release.
+ if [ "$BetaChannel" != "0" ]; then
+ PRERELEASE=(--prerelease)
+ else
+ PRERELEASE=()
+ fi
+ if ! gh release view "$TAG" -R "$R" >/dev/null 2>&1; then
+ gh release create "$TAG" -R "$R" "${TARGET[@]}" "${PRERELEASE[@]}" \
+ --title "Forkgram $TAG" \
+ --notes "Forkgram $TAG" >/dev/null 2>&1 \
+ || gh release view "$TAG" -R "$R" >/dev/null
+ fi
+
+ gh release upload "$TAG" \
+ "deploy/$ASSET_INSTALLER" \
+ "deploy/$ASSET_PORTABLE" \
+ -R "$R" --clobber
+
+ publish-telegram:
+ name: Publish update files to Telegram
+ needs: sign-release
+ runs-on: ubuntu-latest
+ if: >-
+ needs.sign-release.result == 'success' &&
+ (startsWith(github.ref, 'refs/tags/') ||
+ (github.event_name == 'workflow_dispatch' && inputs.telegram != 'off'))
+ environment: telegram-publish
+ # The feed message is rewritten read-modify-write; the shared group name
+ # serialises this with the Linux workflow so neither loses its entry.
+ concurrency:
+ group: telegram-feed
+ cancel-in-progress: false
+ steps:
+ - name: Clone the uploader script.
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ with:
+ persist-credentials: false
+ sparse-checkout: |
+ .github/scripts/publish_telegram.py
+ .github/scripts/requirements-telethon.txt
+ .github/scripts/requirements-python-build.txt
+ .github/data/logo_256_square.png
+ sparse-checkout-cone-mode: false
+
+ - name: Download build artifacts.
+ uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7
+ with:
+ pattern: Telegram * Release *
+ path: artifacts
+
+ - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6
+ with:
+ python-version: "3.12"
+
+ - name: Install Telethon.
+ run: |
+ python -m venv "$RUNNER_TEMP/telegram-venv"
+ python="$RUNNER_TEMP/telegram-venv/bin/python"
+ "$python" -m pip install --require-hashes -r .github/scripts/requirements-python-build.txt
+ "$python" -m pip install --require-hashes --no-build-isolation -r .github/scripts/requirements-telethon.txt
+ echo "$RUNNER_TEMP/telegram-venv/bin" >> "$GITHUB_PATH"
+
+ - name: Publish.
+ env:
+ # api_id/api_hash aren't secret here (the session is) - Telegram's public open credentials.
+ TG_API_ID: "611335"
+ TG_API_HASH: "d524b414d21f4d37f08684c1df41ac9c"
+ TG_SESSION: ${{ secrets.TG_SESSION }}
+ TG_FEED_CHANNEL: ${{ secrets.TG_FEED_CHANNEL }}
+ TG_FILES_CHANNEL: ${{ secrets.TG_FILES_CHANNEL }}
+ ARTIFACTS_DIR: artifacts
+ # 'scheduled' sends for real but 360 days out - an invisible smoke test; delete those after.
+ TG_SCHEDULE_DAYS: ${{ (github.event_name == 'workflow_dispatch' && inputs.telegram == 'scheduled') && '360' || '0' }}
+ TG_ENTRY_KEY: ${{ (github.event_name == 'workflow_dispatch' && inputs.telegram == 'testing') && 'testing' || 'released' }}
+ run: python .github/scripts/publish_telegram.py
diff --git a/.github/workflows/winget.yml b/.github/workflows/winget.yml
deleted file mode 100644
index 0ff2d50d8b12b..0000000000000
--- a/.github/workflows/winget.yml
+++ /dev/null
@@ -1,20 +0,0 @@
-name: Publish to WinGet
-on:
- release:
- types: [released, prereleased]
-jobs:
- publish:
- runs-on: windows-latest # action can only be run on windows
- steps:
- - if: github.event.action == 'released'
- uses: telegramdesktop/winget-releaser@main
- with:
- identifier: Telegram.TelegramDesktop
- installers-regex: 't(setup|portable).*(exe|zip)$'
- token: ${{ secrets.WINGET_TOKEN }}
- - if: github.event.action == 'prereleased'
- uses: telegramdesktop/winget-releaser@main
- with:
- identifier: Telegram.TelegramDesktop.Beta
- installers-regex: 't(setup|portable).*(exe|zip)$'
- token: ${{ secrets.WINGET_TOKEN }}
diff --git a/.gitmodules b/.gitmodules
index b0ffc4b3b0160..7c39f6dedaf1f 100644
--- a/.gitmodules
+++ b/.gitmodules
@@ -21,7 +21,7 @@
url = https://github.com/desktop-app/codegen.git
[submodule "Telegram/lib_ui"]
path = Telegram/lib_ui
- url = https://github.com/desktop-app/lib_ui.git
+ url = https://github.com/forkgram/lib_ui.git
[submodule "Telegram/lib_lottie"]
path = Telegram/lib_lottie
url = https://github.com/desktop-app/lib_lottie.git
@@ -91,6 +91,9 @@
[submodule "Telegram/ThirdParty/TooManyCooks"]
path = Telegram/ThirdParty/TooManyCooks
url = https://github.com/tzcnt/TooManyCooks.git
+[submodule "Telegram/ThirdParty/zbar"]
+ path = Telegram/ThirdParty/zbar
+ url = https://github.com/mchehab/zbar.git
[submodule "Telegram/ThirdParty/libcbor"]
path = Telegram/ThirdParty/libcbor
url = https://github.com/PJK/libcbor.git
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 59477e251bbfe..ed62f2e8c4d5f 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -8,6 +8,74 @@ cmake_minimum_required(VERSION 3.25...3.31)
set_property(GLOBAL PROPERTY USE_FOLDERS ON)
+# Apply local patches to submodules at configure time.
+# Filename prefix (split on '_') is matched against submodule directories,
+# trying the longest prefix first, both at the repo root and under Telegram/.
+file(GLOB _submodule_patches CONFIGURE_DEPENDS "${CMAKE_SOURCE_DIR}/patches/*.patch")
+foreach(_patch ${_submodule_patches})
+ get_filename_component(_patch_stem ${_patch} NAME_WE)
+ get_filename_component(_patch_name ${_patch} NAME)
+ string(REPLACE "_" ";" _parts ${_patch_stem})
+ list(LENGTH _parts _n)
+ set(_applied FALSE)
+ set(_already FALSE)
+ set(_matched "")
+ while(_n GREATER 0 AND NOT _applied AND NOT _already)
+ list(SUBLIST _parts 0 ${_n} _head)
+ string(REPLACE ";" "_" _candidate "${_head}")
+ foreach(_root "Telegram/" "")
+ set(_dir "${CMAKE_SOURCE_DIR}/${_root}${_candidate}")
+ if (IS_DIRECTORY ${_dir} AND EXISTS ${_dir}/.git)
+ if (NOT _matched)
+ set(_matched "${_root}${_candidate}")
+ endif()
+ execute_process(
+ COMMAND git apply --check ${_patch}
+ WORKING_DIRECTORY ${_dir}
+ RESULT_VARIABLE _check_result
+ OUTPUT_VARIABLE _check_output
+ ERROR_VARIABLE _check_output
+ )
+ if (_check_result EQUAL 0 AND NOT _check_output MATCHES "Skipped patch")
+ execute_process(
+ COMMAND git apply ${_patch}
+ WORKING_DIRECTORY ${_dir}
+ )
+ message(STATUS "Applied patch ${_patch_name} in ${_root}${_candidate}")
+ set(_applied TRUE)
+ break()
+ endif()
+ # Forward apply failed. Only a patch that reverses cleanly is
+ # already applied; anything else has rotted against a moved
+ # submodule and would otherwise be dropped without a trace.
+ execute_process(
+ COMMAND git apply --reverse --check ${_patch}
+ WORKING_DIRECTORY ${_dir}
+ RESULT_VARIABLE _reverse_result
+ OUTPUT_VARIABLE _reverse_output
+ ERROR_VARIABLE _reverse_output
+ )
+ if (_reverse_result EQUAL 0 AND NOT _reverse_output MATCHES "Skipped patch")
+ message(STATUS "Skipped patch ${_patch_name} (already applied in ${_root}${_candidate})")
+ set(_already TRUE)
+ break()
+ endif()
+ endif()
+ endforeach()
+ math(EXPR _n "${_n} - 1")
+ endwhile()
+ if (NOT _applied AND NOT _already)
+ if (_matched)
+ message(WARNING
+ "Patch ${_patch_name} no longer applies to ${_matched} and is not "
+ "already applied there. It is being ignored -- refresh it against "
+ "the current submodule or delete it.")
+ else()
+ message(STATUS "Skipped patch ${_patch_name} (no matching submodule)")
+ endif()
+ endif()
+endforeach()
+
include(cmake/validate_special_target.cmake)
include(cmake/version.cmake)
desktop_app_parse_version(Telegram/build/version)
@@ -64,4 +132,7 @@ set(desktop_app_skip_libs
)
add_subdirectory(cmake)
+if (APPLE AND NOT DESKTOP_APP_USE_PACKAGED)
+ target_link_libraries(external_ffmpeg INTERFACE desktop-app::external_iconv)
+endif()
add_subdirectory(Telegram)
diff --git a/README.md b/README.md
index a7abfeab3c984..7558431548acb 100644
--- a/README.md
+++ b/README.md
@@ -102,3 +102,72 @@ Version **1.8.15** was the last that supports older systems
CI infrastructure sponsored by [Depot](https://depot.dev) — fast GitHub Actions runners.
+[](https://github.com/Forkgram/tdesktop/releases)
+[](https://snapcraft.io/forkgram)
+[](https://aur.archlinux.org/packages/forkgram)
+[](https://community.chocolatey.org/packages/forkgram)
+[](https://scoop.sh/#/apps?q=forkgram)
+[](https://github.com/Forkgram/tdesktop/releases/latest)
+[](https://formulae.brew.sh/cask/forkgram)
+[](https://github.com/Forkgram/tdesktop/releases/latest)
+
+## Features:
+- Square avatars. *(Added XX.04.2017.)*
+Square tray icon. *(Updated 18.08.2018.)*
+
+- Opening any links with a custom URI Scheme. *(Added XX.04.2017 and updated 02.08.2019.)*
+
+- Checkmark "Delete for everyone" by default. *(Added XX.04.2017.)*
+
+
+- The fourth button in the title to "Always on top" window. (Windows only.) *(Added 16.05.2017.)*
+
+
+- Showing the full timestamp if the user was online more than 1 hour ago. *(Added 14.06.2017.)*
+
+
+- Hotkeys for the mediaview was usability improved. [**Cheatsheet**](#cheatsheet). *(Added 29.06.2017.)*
+
+- Experimental auto-submitting of the local passcode. *(Added 29.06.2017.)*
+
+
+- Showing date of forwarded messages in the title. *(Added 25.08.2017.)*
+
+
+- Button to go to the first message. *(Added 16.05.2018.)* ([Telegrate's](https://github.com/Sea-n/tdesktop) idea.)
+
+
+- Option to remove fading of audio when it's paused/played. *(Added 10.08.2018.)*
+
+- Ability to see thumbs of the executable files as well as for other files. *(Added 14.08.2018.)*
+
+- Ability to search a selected text via the context menu. *(Added 22.01.2019.)*
+
+- Ability to show the last seen time of the user in list of the dialogs. *(Added 31.01.2019.)*
+
+- Option to enable a display of all recently used stickers. *(Added 09.02.2019.)*
+
+- Auto-replacing of "..." with "…". *(Added 17.02.2019.)*
+
+- Ability to bind Ctrl+6-9 dialogs with Ctrl+Shift+6-9 shortcuts. *(Added 11.06.2019.)*
+
+- Ability to send files to Saved Messages without the forward header. *(Added 23.06.2019.)*
+
+- Forward messages without quoting the original sender via `Share` box. *(Added 25.06.2019.)*
+
+
+
+## Cheatsheet
+
+| Zoom in | Zoom out | Zoom reset | Old zoom in | Old zoom out | Old zoom reset |
+|----------------|-----------------|------------------|----------------|-----------------|------------------|
+| + | - | 0 | Ctrl`+`+ | Ctrl`+`- | Ctrl`+`0 |
+| Up arrow | Down arrow | * | Ctrl`+`] | Ctrl`+`_ | Middle button |
+| Scroll up | Scroll down | Middle button | Ctrl`+`= | Ctrl`+`Scroll down | |
+| ] | _ | | Ctrl`+`* | | |
+| = | | | Ctrl`+`Scroll up | | |
+
+You can scroll images by the wheel with pressed Ctrl.
+
+## Downloads:
+You can download binaries from the Releases or from my [Telegram channel Forkgram](https://t.me/forkgram).
diff --git a/Telegram/CMakeLists.txt b/Telegram/CMakeLists.txt
index f5d372ac4f21b..48874078e0e1d 100644
--- a/Telegram/CMakeLists.txt
+++ b/Telegram/CMakeLists.txt
@@ -49,6 +49,7 @@ include(cmake/td_ui.cmake)
include(cmake/td_webauthn.cmake)
include(cmake/telegram_apple_swift_runtime.cmake)
include(cmake/generate_appstream_changelog.cmake)
+include(cmake/td_forkgram.cmake)
if (DESKTOP_APP_TEST_APPS)
include(cmake/tests.cmake)
@@ -100,6 +101,7 @@ PRIVATE
tdesktop::td_scheme
tdesktop::td_tde2e
tdesktop::td_ui
+ tdesktop::td_forkgram
tdesktop::td_webauthn
desktop-app::lib_webrtc
desktop-app::lib_base
@@ -120,6 +122,7 @@ PRIVATE
desktop-app::external_qt_static_plugins
desktop-app::external_qt
desktop-app::external_qr_code_generator
+ desktop-app::external_zbar
desktop-app::external_crash_reports
desktop-app::external_auto_updates
desktop-app::external_openssl
@@ -140,6 +143,8 @@ nice_target_sources(Telegram ${src_loc}
PRIVATE
${style_files}
+ api/api_as_copy.cpp
+ api/api_as_copy.h
api/api_attached_stickers.cpp
api/api_attached_stickers.h
api/api_authorizations.cpp
@@ -677,6 +682,8 @@ PRIVATE
core/core_screenshot_protection.h
core/core_settings.cpp
core/core_settings.h
+ core/fork_settings.cpp
+ core/fork_settings.h
core/core_settings_proxy.cpp
core/core_settings_proxy.h
core/crash_report_window.cpp
@@ -1094,6 +1101,14 @@ PRIVATE
export/view/export_view_settings.h
export/view/export_view_top_bar.cpp
export/view/export_view_top_bar.h
+ forkgram/gpu_demo_renderer.cpp
+ forkgram/gpu_demo_renderer.h
+ forkgram/link_replacements.cpp
+ forkgram/link_replacements.h
+ forkgram/link_replacements_box.cpp
+ forkgram/link_replacements_box.h
+ forkgram/uri_menu.cpp
+ forkgram/uri_menu.h
history/admin_log/history_admin_log_filter.cpp
history/admin_log/history_admin_log_filter.h
history/admin_log/history_admin_log_inner.cpp
@@ -1266,6 +1281,8 @@ PRIVATE
history/view/history_view_contact_status.h
history/view/history_view_context_menu.cpp
history/view/history_view_context_menu.h
+ history/view/history_view_context_menu_fork.cpp
+ history/view/history_view_context_menu_fork.h
history/view/history_view_copy_selection.cpp
history/view/history_view_copy_selection.h
history/view/history_view_corner_buttons.cpp
@@ -1404,6 +1421,8 @@ PRIVATE
history/history_view_swipe_back_session.h
history/history_widget.cpp
history/history_widget.h
+ history/history_widget_extract_media_fork.cpp
+ history/history_widget_extract_media_fork.h
info/bot/earn/info_bot_earn_list.cpp
info/bot/earn/info_bot_earn_list.h
info/bot/earn/info_bot_earn_widget.cpp
@@ -1850,6 +1869,8 @@ PRIVATE
menu/menu_item_download_files.h
menu/menu_item_rate_transcribe_session.cpp
menu/menu_item_rate_transcribe_session.h
+ menu/menu_item_save_to_markdown.cpp
+ menu/menu_item_save_to_markdown.h
menu/menu_mark_as_read.cpp
menu/menu_mark_as_read.h
menu/menu_mute.cpp
@@ -1954,6 +1975,7 @@ PRIVATE
platform/linux/tray_linux.h
platform/linux/update_install_linux.cpp
platform/linux/update_install_linux.h
+ platform/linux/webauthn_linux.cpp
platform/linux/widget_descriptors_linux.cpp
platform/linux/widget_descriptors_linux.h
platform/linux/widget_helper_linux.cpp
@@ -1991,6 +2013,8 @@ PRIVATE
platform/mac/translate_provider_mac.mm
platform/mac/tray_mac.h
platform/mac/tray_mac.mm
+ platform/mac/webauthn_local_mac.h
+ platform/mac/webauthn_local_mac.mm
platform/mac/wallet_protection_mac.h
platform/mac/wallet_protection_mac.mm
platform/mac/webauthn_mac.mm
@@ -2059,6 +2083,8 @@ PRIVATE
platform/win/windows_autostart_task.h
platform/win/windows_taskbar_buttons.cpp
platform/win/windows_taskbar_buttons.h
+ platform/win/windows_gpu_info.cpp
+ platform/win/windows_gpu_info.h
platform/win/windows_toast_activator.cpp
platform/win/windows_toast_activator.h
platform/platform_file_utilities.cpp
@@ -2133,6 +2159,10 @@ PRIVATE
settings/sections/settings_business.h
settings/sections/settings_calls.cpp
settings/sections/settings_calls.h
+ settings/sections/settings_fork.cpp
+ settings/sections/settings_fork.h
+ settings/sections/settings_link_device.cpp
+ settings/sections/settings_link_device.h
settings/settings_codes.cpp
settings/settings_codes.h
settings/settings_common_session.h
@@ -2150,6 +2180,8 @@ PRIVATE
settings/settings_experimental.h
settings/sections/settings_folders.cpp
settings/sections/settings_folders.h
+ settings/sections/settings_fork.cpp
+ settings/sections/settings_fork.h
settings/sections/settings_global_ttl.cpp
settings/sections/settings_global_ttl.h
settings/sections/settings_information.cpp
@@ -2988,10 +3020,34 @@ if (WIN32)
"Copying d3dcompiler_47.dll for ANGLE."
VERBATIM
)
- # The loader reads the subsystem version as the minimal Windows.
target_link_options(Telegram PRIVATE /SUBSYSTEM:WINDOWS,6.01)
endif()
+ set(yy_thunks_lib "")
+ if (DESKTOP_APP_WIN7_BASELINE AND NOT DESKTOP_APP_WIN7_PROBE)
+ if (CMAKE_SIZEOF_VOID_P EQUAL 8)
+ set(yy_thunks_arch x64)
+ else()
+ set(yy_thunks_arch x86)
+ endif()
+ set(yy_thunks_candidate "${libs_loc}/yy_thunks/objs/${yy_thunks_arch}/YY_Thunks_for_Win7.lib")
+ if (NOT EXISTS "${yy_thunks_candidate}")
+ message(FATAL_ERROR "YY-Thunks library not found at ${yy_thunks_candidate}. Run Telegram/build/prepare/prepare.py to build it.")
+ endif()
+ message(STATUS "YY-Thunks: enabling Windows 7/8 compatibility via ${yy_thunks_candidate}")
+ set(yy_thunks_lib "${yy_thunks_candidate}")
+
+ # Three optional hooks are weak in a stock build, define defaults.
+ add_library(yy_thunks_defaults STATIC
+ ${src_loc}/_other/yy_thunks_defaults.cpp)
+ set_target_properties(yy_thunks_defaults PROPERTIES FOLDER "(external)")
+
+ # Whole archive: a plain link takes only already undefined symbols.
+ target_link_options(Telegram PRIVATE "/WHOLEARCHIVE:${yy_thunks_lib}")
+ target_link_libraries(Telegram PRIVATE yy_thunks_defaults)
+ target_compile_definitions(Telegram PRIVATE DESKTOP_APP_WIN7_BASELINE)
+ endif()
+
target_link_options(Telegram PRIVATE /PDBPAGESIZE:8192)
elseif (APPLE)
if (NOT DESKTOP_APP_USE_PACKAGED)
@@ -3114,6 +3170,9 @@ else()
endif()
set(bundle_entitlements "Telegram.entitlements")
set(output_name "Telegram")
+ if (LINUX OR APPLE)
+ set(output_name "Forkgram")
+ endif()
endif()
if (CMAKE_GENERATOR STREQUAL Xcode)
@@ -3166,6 +3225,10 @@ PRIVATE
G_LOG_DOMAIN="Telegram"
)
+if (APPLE)
+ target_compile_definitions(Telegram PRIVATE TDESKTOP_APP_BUNDLE_NAME="${output_name}.app")
+endif()
+
get_property(is_multi_config GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
if (APPLE
OR is_multi_config
@@ -3207,30 +3270,11 @@ if (MSVC)
else()
target_link_options(Telegram
PRIVATE
- /DELAYLOAD:API-MS-Win-Core-Console-l1-1-0.dll
- /DELAYLOAD:API-MS-Win-Core-Fibers-l2-1-0.dll
- /DELAYLOAD:API-MS-Win-Core-Fibers-l2-1-1.dll
- /DELAYLOAD:API-MS-Win-Core-File-l1-1-0.dll
- # Not delayed: WindowsApp.lib binds LoadLibraryExA here, and
- # __delayLoadHelper2 calls it to resolve delayed imports -- self-recurses.
- /DELAYLOAD:API-MS-Win-Core-Localization-l1-2-0.dll
- /DELAYLOAD:API-MS-Win-Core-Memory-l1-1-0.dll
- /DELAYLOAD:API-MS-Win-Core-Memory-l1-1-1.dll
- /DELAYLOAD:API-MS-Win-Core-ProcessThreads-l1-1-0.dll
- /DELAYLOAD:API-MS-Win-Core-Synch-l1-2-0.dll # Synchronization.lib
- /DELAYLOAD:API-MS-Win-Core-SysInfo-l1-1-0.dll
- # /DELAYLOAD:API-MS-Win-Core-Timezone-l1-1-0.dll
- /DELAYLOAD:API-MS-Win-Core-WinRT-l1-1-0.dll
- /DELAYLOAD:API-MS-Win-Core-WinRT-Error-l1-1-0.dll
- /DELAYLOAD:API-MS-Win-Core-WinRT-String-l1-1-0.dll
- /DELAYLOAD:API-MS-Win-Security-CryptoAPI-l1-1-0.dll
- # /DELAYLOAD:API-MS-Win-Shcore-Scaling-l1-1-1.dll # We shadowed GetDpiForMonitor
/DELAYLOAD:secur32.dll
/DELAYLOAD:winmm.dll
/DELAYLOAD:ws2_32.dll
/DELAYLOAD:user32.dll
/DELAYLOAD:gdi32.dll
- /DELAYLOAD:advapi32.dll
/DELAYLOAD:avrt.dll
/DELAYLOAD:shell32.dll
/DELAYLOAD:ole32.dll
@@ -3252,22 +3296,55 @@ if (MSVC)
/DELAYLOAD:wtsapi32.dll
/DELAYLOAD:propsys.dll
/DELAYLOAD:uiautomationcore.dll
- /DELAYLOAD:authz.dll
- /DELAYLOAD:comdlg32.dll
- /DELAYLOAD:dwrite.dll
- /DELAYLOAD:dxgi.dll
- /DELAYLOAD:d3d9.dll
- /DELAYLOAD:d3d11.dll
- /DELAYLOAD:d3d12.dll
- /DELAYLOAD:setupapi.dll
- /DELAYLOAD:winhttp.dll
/DELAYLOAD:icu.dll
)
- endif()
- if (NOT build_winarm)
- target_link_options(Telegram PRIVATE
- /DELAYLOAD:API-MS-Win-EventLog-Legacy-l1-1-0.dll
- )
+ # YY-Thunks covers imports bound at link time, not delayed ones.
+ if (NOT DESKTOP_APP_WIN7_BASELINE)
+ target_link_options(Telegram PRIVATE /DELAYLOAD:advapi32.dll)
+ endif()
+ if (QT_VERSION GREATER 6 AND NOT DESKTOP_APP_WIN7_BASELINE)
+ if (NOT build_winarm)
+ target_link_options(Telegram PRIVATE
+ /DELAYLOAD:API-MS-Win-EventLog-Legacy-l1-1-0.dll
+ )
+ endif()
+
+ target_link_options(Telegram
+ PRIVATE
+ /DELAYLOAD:API-MS-Win-Core-Console-l1-1-0.dll
+ /DELAYLOAD:API-MS-Win-Core-Fibers-l2-1-0.dll
+ /DELAYLOAD:API-MS-Win-Core-Fibers-l2-1-1.dll
+ /DELAYLOAD:API-MS-Win-Core-File-l1-1-0.dll
+ # Not delayed: WindowsApp.lib binds LoadLibraryExA here, and
+ # __delayLoadHelper2 calls it to resolve delayed imports -- self-recurses.
+ /DELAYLOAD:API-MS-Win-Core-Localization-l1-2-0.dll
+ /DELAYLOAD:API-MS-Win-Core-Memory-l1-1-0.dll
+ /DELAYLOAD:API-MS-Win-Core-Memory-l1-1-1.dll
+ /DELAYLOAD:API-MS-Win-Core-ProcessThreads-l1-1-0.dll
+ /DELAYLOAD:API-MS-Win-Core-Synch-l1-2-0.dll # Synchronization.lib
+ /DELAYLOAD:API-MS-Win-Core-SysInfo-l1-1-0.dll
+ # /DELAYLOAD:API-MS-Win-Core-Timezone-l1-1-0.dll
+ /DELAYLOAD:API-MS-Win-Core-WinRT-l1-1-0.dll
+ /DELAYLOAD:API-MS-Win-Core-WinRT-Error-l1-1-0.dll
+ /DELAYLOAD:API-MS-Win-Core-WinRT-String-l1-1-0.dll
+ /DELAYLOAD:API-MS-Win-Security-CryptoAPI-l1-1-0.dll
+ # /DELAYLOAD:API-MS-Win-Shcore-Scaling-l1-1-1.dll # We shadowed GetDpiForMonitor
+ )
+ endif()
+ if (QT_VERSION GREATER 6)
+ target_link_options(Telegram
+ PRIVATE
+ /DELAYLOAD:authz.dll # Authz.lib
+ /DELAYLOAD:comdlg32.dll
+ /DELAYLOAD:dwrite.dll # DWrite.lib
+ /DELAYLOAD:dxgi.dll # DXGI.lib
+ /DELAYLOAD:d3d9.dll # D3D9.lib
+ /DELAYLOAD:d3d11.dll # D3D11.lib
+ /DELAYLOAD:d3d12.dll # D3D12.lib
+ /DELAYLOAD:setupapi.dll # SetupAPI.lib
+ /DELAYLOAD:winhttp.dll
+ )
+ endif()
endif()
endif()
@@ -3320,19 +3397,24 @@ if (NOT DESKTOP_APP_DISABLE_AUTOUPDATE AND NOT build_macstore AND NOT build_wins
target_link_options(Updater
PRIVATE
/DELAYLOAD:user32.dll
- /DELAYLOAD:advapi32.dll
/DELAYLOAD:shell32.dll
/DELAYLOAD:ole32.dll
/DELAYLOAD:oleaut32.dll
/DELAYLOAD:shlwapi.dll
)
+ if (NOT DESKTOP_APP_WIN7_BASELINE)
+ target_link_options(Updater PRIVATE /DELAYLOAD:advapi32.dll)
+ endif()
else()
target_link_options(Updater PRIVATE -municode)
endif()
- if (DESKTOP_APP_WIN7_BASELINE)
- target_link_options(Updater PRIVATE /SUBSYSTEM:WINDOWS,6.01)
+ if (yy_thunks_lib)
+ target_link_options(Updater PRIVATE "/WHOLEARCHIVE:${yy_thunks_lib}" /SUBSYSTEM:WINDOWS,6.01)
+ target_link_libraries(Updater PRIVATE yy_thunks_defaults)
endif()
elseif (APPLE)
+ target_compile_definitions(Updater PRIVATE TDESKTOP_APP_BUNDLE_NAME="${output_name}.app")
+
# Keep the launch API available to macOS 10.13 release builds.
target_compile_options(Updater PRIVATE -Wno-error=deprecated-declarations)
add_custom_command(TARGET Updater
@@ -3370,10 +3452,9 @@ if (NOT DESKTOP_APP_DISABLE_AUTOUPDATE AND NOT build_macstore AND NOT build_wins
target_compile_definitions(Packer PRIVATE PACKER_USE_PACKAGED)
endif()
- if (WIN32 AND DESKTOP_APP_WIN7_BASELINE)
- # WindowsApp.lib is off the link line, WinRT stubs come from lib_base.
- target_link_libraries(Packer PRIVATE desktop-app::lib_base)
- target_link_options(Packer PRIVATE /SUBSYSTEM:CONSOLE,6.01)
+ if (WIN32 AND yy_thunks_lib)
+ target_link_options(Packer PRIVATE "/WHOLEARCHIVE:${yy_thunks_lib}" /SUBSYSTEM:CONSOLE,6.01)
+ target_link_libraries(Packer PRIVATE yy_thunks_defaults)
endif()
set_target_properties(Packer PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${output_folder})
@@ -3400,24 +3481,25 @@ if (LINUX AND DESKTOP_APP_USE_PACKAGED)
configure_file("../lib/xdg/org.telegram.desktop.metainfo.xml" "${CMAKE_CURRENT_BINARY_DIR}/org.telegram.desktop.metainfo.xml" @ONLY)
generate_appstream_changelog(Telegram "${CMAKE_SOURCE_DIR}/changelog.txt" "${CMAKE_CURRENT_BINARY_DIR}/org.telegram.desktop.metainfo.xml")
install(TARGETS Telegram RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" BUNDLE DESTINATION "${CMAKE_INSTALL_BINDIR}")
- install(FILES "Resources/art/icon16.png" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/16x16/apps" RENAME "org.telegram.desktop.png")
- install(FILES "Resources/art/icon16@2x.png" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/16x16@2/apps" RENAME "org.telegram.desktop.png")
- install(FILES "Resources/art/icon32.png" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/32x32/apps" RENAME "org.telegram.desktop.png")
- install(FILES "Resources/art/icon32@2x.png" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/32x32@2/apps" RENAME "org.telegram.desktop.png")
- install(FILES "Resources/art/icon48.png" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/48x48/apps" RENAME "org.telegram.desktop.png")
- install(FILES "Resources/art/icon48@2x.png" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/48x48@2/apps" RENAME "org.telegram.desktop.png")
- install(FILES "Resources/art/icon64.png" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/64x64/apps" RENAME "org.telegram.desktop.png")
- install(FILES "Resources/art/icon64@2x.png" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/64x64@2/apps" RENAME "org.telegram.desktop.png")
- install(FILES "Resources/art/icon128.png" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/128x128/apps" RENAME "org.telegram.desktop.png")
- install(FILES "Resources/art/icon128@2x.png" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/128x128@2/apps" RENAME "org.telegram.desktop.png")
- install(FILES "Resources/art/icon256.png" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/256x256/apps" RENAME "org.telegram.desktop.png")
- install(FILES "Resources/art/icon256@2x.png" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/256x256@2/apps" RENAME "org.telegram.desktop.png")
- install(FILES "Resources/art/icon512.png" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/512x512/apps" RENAME "org.telegram.desktop.png")
- install(FILES "Resources/art/icon512@2x.png" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/512x512@2/apps" RENAME "org.telegram.desktop.png")
- install(FILES "Resources/icons/tray_monochrome.svg" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/symbolic/apps" RENAME "org.telegram.desktop-symbolic.svg")
- install(FILES "Resources/icons/tray_monochrome_attention.svg" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/symbolic/apps" RENAME "org.telegram.desktop-attention-symbolic.svg")
- install(FILES "Resources/icons/tray_monochrome_mute.svg" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/symbolic/apps" RENAME "org.telegram.desktop-mute-symbolic.svg")
- install(FILES "../lib/xdg/org.telegram.desktop.desktop" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/applications")
- install(FILES "${CMAKE_CURRENT_BINARY_DIR}/org.telegram.desktop.service" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/dbus-1/services")
- install(FILES "${CMAKE_CURRENT_BINARY_DIR}/org.telegram.desktop.metainfo.xml" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/metainfo")
+ install(FILES "Resources/art/icon16.png" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/16x16/apps" RENAME "io.github.forkgram.tdesktop.png")
+ install(FILES "Resources/art/icon16@2x.png" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/16x16@2/apps" RENAME "io.github.forkgram.tdesktop.png")
+ install(FILES "Resources/art/icon32.png" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/32x32/apps" RENAME "io.github.forkgram.tdesktop.png")
+ install(FILES "Resources/art/icon32@2x.png" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/32x32@2/apps" RENAME "io.github.forkgram.tdesktop.png")
+ install(FILES "Resources/art/icon48.png" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/48x48/apps" RENAME "io.github.forkgram.tdesktop.png")
+ install(FILES "Resources/art/icon48@2x.png" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/48x48@2/apps" RENAME "io.github.forkgram.tdesktop.png")
+ install(FILES "Resources/art/icon64.png" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/64x64/apps" RENAME "io.github.forkgram.tdesktop.png")
+ install(FILES "Resources/art/icon64@2x.png" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/64x64@2/apps" RENAME "io.github.forkgram.tdesktop.png")
+ install(FILES "Resources/art/icon128.png" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/128x128/apps" RENAME "io.github.forkgram.tdesktop.png")
+ install(FILES "Resources/art/icon128@2x.png" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/128x128@2/apps" RENAME "io.github.forkgram.tdesktop.png")
+ install(FILES "Resources/art/icon256.png" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/256x256/apps" RENAME "io.github.forkgram.tdesktop.png")
+ install(FILES "Resources/art/icon256@2x.png" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/256x256@2/apps" RENAME "io.github.forkgram.tdesktop.png")
+ install(FILES "Resources/art/icon512.png" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/512x512/apps" RENAME "io.github.forkgram.tdesktop.png")
+ install(FILES "Resources/art/icon512@2x.png" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/512x512@2/apps" RENAME "io.github.forkgram.tdesktop.png")
+ install(FILES "Resources/icons/tray_monochrome.svg" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/symbolic/apps" RENAME "io.github.forkgram.tdesktop-symbolic.svg")
+ install(FILES "Resources/icons/tray_monochrome_attention.svg" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/symbolic/apps" RENAME "io.github.forkgram.tdesktop-attention-symbolic.svg")
+ install(FILES "Resources/icons/tray_monochrome_mute.svg" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/symbolic/apps" RENAME "io.github.forkgram.tdesktop-mute-symbolic.svg")
+ install(FILES "../lib/xdg/org.telegram.desktop.desktop" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/applications" RENAME "io.github.forkgram.tdesktop.desktop")
+ install(FILES "${CMAKE_CURRENT_BINARY_DIR}/org.telegram.desktop.service" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/dbus-1/services" RENAME "io.github.forkgram.tdesktop.service")
+ install(FILES "${CMAKE_CURRENT_BINARY_DIR}/org.telegram.desktop.metainfo.xml" DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/metainfo" RENAME "io.github.forkgram.tdesktop.metainfo.xml")
endif()
+
diff --git a/Telegram/Resources/art/favicon.ico b/Telegram/Resources/art/favicon.ico
new file mode 100644
index 0000000000000..3a0bdb167b570
Binary files /dev/null and b/Telegram/Resources/art/favicon.ico differ
diff --git a/Telegram/Resources/art/forkgram/logo_256.png b/Telegram/Resources/art/forkgram/logo_256.png
new file mode 100644
index 0000000000000..26d94fe32d7ac
Binary files /dev/null and b/Telegram/Resources/art/forkgram/logo_256.png differ
diff --git a/Telegram/Resources/art/forkgram/logo_256_no_margin.png b/Telegram/Resources/art/forkgram/logo_256_no_margin.png
new file mode 100644
index 0000000000000..26d94fe32d7ac
Binary files /dev/null and b/Telegram/Resources/art/forkgram/logo_256_no_margin.png differ
diff --git a/Telegram/Resources/art/icon128.png b/Telegram/Resources/art/icon128.png
index fc96863ef6faf..fca6ac86dbb99 100644
Binary files a/Telegram/Resources/art/icon128.png and b/Telegram/Resources/art/icon128.png differ
diff --git a/Telegram/Resources/art/icon128@2x.png b/Telegram/Resources/art/icon128@2x.png
index 7943dd19df4fb..26d94fe32d7ac 100644
Binary files a/Telegram/Resources/art/icon128@2x.png and b/Telegram/Resources/art/icon128@2x.png differ
diff --git a/Telegram/Resources/art/icon16.png b/Telegram/Resources/art/icon16.png
index 561369d2b2688..fb0e6a70ccfc4 100644
Binary files a/Telegram/Resources/art/icon16.png and b/Telegram/Resources/art/icon16.png differ
diff --git a/Telegram/Resources/art/icon16@2x.png b/Telegram/Resources/art/icon16@2x.png
index f220a885bbb2c..2e82163ec5c58 100644
Binary files a/Telegram/Resources/art/icon16@2x.png and b/Telegram/Resources/art/icon16@2x.png differ
diff --git a/Telegram/Resources/art/icon256.ico b/Telegram/Resources/art/icon256.ico
index 8c71faaf6d5e9..3a0bdb167b570 100644
Binary files a/Telegram/Resources/art/icon256.ico and b/Telegram/Resources/art/icon256.ico differ
diff --git a/Telegram/Resources/art/icon256.png b/Telegram/Resources/art/icon256.png
index 8c4abee16dec0..26d94fe32d7ac 100644
Binary files a/Telegram/Resources/art/icon256.png and b/Telegram/Resources/art/icon256.png differ
diff --git a/Telegram/Resources/art/icon256@2x.png b/Telegram/Resources/art/icon256@2x.png
index d096c2bd0ac1b..6a18109334c87 100644
Binary files a/Telegram/Resources/art/icon256@2x.png and b/Telegram/Resources/art/icon256@2x.png differ
diff --git a/Telegram/Resources/art/icon32.png b/Telegram/Resources/art/icon32.png
index cff636894428e..2e82163ec5c58 100644
Binary files a/Telegram/Resources/art/icon32.png and b/Telegram/Resources/art/icon32.png differ
diff --git a/Telegram/Resources/art/icon32@2x.png b/Telegram/Resources/art/icon32@2x.png
index 22b468746a286..b8cff00ecc09f 100644
Binary files a/Telegram/Resources/art/icon32@2x.png and b/Telegram/Resources/art/icon32@2x.png differ
diff --git a/Telegram/Resources/art/icon48.png b/Telegram/Resources/art/icon48.png
index a8299b182123b..1c5dc1f7698cc 100644
Binary files a/Telegram/Resources/art/icon48.png and b/Telegram/Resources/art/icon48.png differ
diff --git a/Telegram/Resources/art/icon48@2x.png b/Telegram/Resources/art/icon48@2x.png
index 69b69d86a5e26..e0bcd19ebbd2f 100644
Binary files a/Telegram/Resources/art/icon48@2x.png and b/Telegram/Resources/art/icon48@2x.png differ
diff --git a/Telegram/Resources/art/icon512.png b/Telegram/Resources/art/icon512.png
index cdf2fdab5d276..6a18109334c87 100644
Binary files a/Telegram/Resources/art/icon512.png and b/Telegram/Resources/art/icon512.png differ
diff --git a/Telegram/Resources/art/icon512@2x.png b/Telegram/Resources/art/icon512@2x.png
index 7c1560fe6312e..dc81b8b1f06a3 100644
Binary files a/Telegram/Resources/art/icon512@2x.png and b/Telegram/Resources/art/icon512@2x.png differ
diff --git a/Telegram/Resources/art/icon64.png b/Telegram/Resources/art/icon64.png
index b201e31ee0327..b8cff00ecc09f 100644
Binary files a/Telegram/Resources/art/icon64.png and b/Telegram/Resources/art/icon64.png differ
diff --git a/Telegram/Resources/art/icon64@2x.png b/Telegram/Resources/art/icon64@2x.png
index 61924d136cbf4..fca6ac86dbb99 100644
Binary files a/Telegram/Resources/art/icon64@2x.png and b/Telegram/Resources/art/icon64@2x.png differ
diff --git a/Telegram/Resources/art/logo_256_square.png b/Telegram/Resources/art/logo_256_square.png
new file mode 100644
index 0000000000000..dbc4ac7ac66a6
Binary files /dev/null and b/Telegram/Resources/art/logo_256_square.png differ
diff --git a/Telegram/Resources/bot_webview_shell_html/page.js b/Telegram/Resources/bot_webview_shell_html/page.js
index b7100fb30f28d..c72f3371b1020 100644
--- a/Telegram/Resources/bot_webview_shell_html/page.js
+++ b/Telegram/Resources/bot_webview_shell_html/page.js
@@ -274,6 +274,15 @@
setMetric('--fullscreen-control-gap', data.fullscreenControlGap);
}
+ function applyTitle(data) {
+ const visibleTitle = (data && data.title) || '';
+ title.textContent = visibleTitle;
+ document.title = (data && data.nativeTitle)
+ || (data && data.windowTitle)
+ || visibleTitle
+ || 'Telegram';
+ }
+
function hexByte(value) {
const text = Math.max(
0,
@@ -943,8 +952,7 @@
applyMetrics(data && data.metrics);
applyColors(data && data.colors);
applyChrome(data || {});
- title.textContent = (data && data.title) || '';
- document.title = (data && data.windowTitle) || 'Telegram';
+ applyTitle(data);
sameOrigin = !!(data && data.sameOrigin);
frameUrl = (data && data.url) || 'about:blank';
frameOrigin = sameOrigin ? originFromUrl(frameUrl) : '';
@@ -968,8 +976,7 @@
if (!isNativeToken(token)) {
return;
}
- title.textContent = (data && data.title) || '';
- document.title = (data && data.windowTitle) || 'Telegram';
+ applyTitle(data);
},
setChrome: function(data, token) {
if (!isNativeToken(token)) {
diff --git a/Telegram/Resources/icons/intro_plane_trace.png b/Telegram/Resources/icons/intro_plane_trace.png
index 172485c2f2073..1e28bec9e5e62 100644
Binary files a/Telegram/Resources/icons/intro_plane_trace.png and b/Telegram/Resources/icons/intro_plane_trace.png differ
diff --git a/Telegram/Resources/icons/intro_plane_trace@2x.png b/Telegram/Resources/icons/intro_plane_trace@2x.png
index 9d16a3197b428..2fe4ceeb65031 100644
Binary files a/Telegram/Resources/icons/intro_plane_trace@2x.png and b/Telegram/Resources/icons/intro_plane_trace@2x.png differ
diff --git a/Telegram/Resources/icons/intro_plane_trace@3x.png b/Telegram/Resources/icons/intro_plane_trace@3x.png
index 9eb0636766556..b7fd697c31057 100644
Binary files a/Telegram/Resources/icons/intro_plane_trace@3x.png and b/Telegram/Resources/icons/intro_plane_trace@3x.png differ
diff --git a/Telegram/Resources/icons/settings/settings_fork.svg b/Telegram/Resources/icons/settings/settings_fork.svg
new file mode 100644
index 0000000000000..1f0f57f4f13c0
--- /dev/null
+++ b/Telegram/Resources/icons/settings/settings_fork.svg
@@ -0,0 +1,5 @@
+
diff --git a/Telegram/Resources/langs/lang.strings b/Telegram/Resources/langs/lang.strings
index f9c7dc273f60d..fb16dac32a091 100644
--- a/Telegram/Resources/langs/lang.strings
+++ b/Telegram/Resources/langs/lang.strings
@@ -394,6 +394,9 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
"lng_pinned_hide_all_sure" = "Do you want to hide the pinned message bar? It will stay hidden until a new message is pinned.";
"lng_pinned_hide_all_hide" = "Hide";
+"lng_binded" = "Dialog was binded.";
+"lng_unbinded" = "Dialog was unbinded.";
+
"lng_edit_media_album_error" = "This file cannot be saved as a part of an album.";
"lng_edit_media_invalid_file" = "Sorry, no way to use this file.";
"lng_iv_editor_media_invalid_file" = "Sorry, this file can only be added as a file here.";
@@ -562,6 +565,76 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
"lng_settings_section_info" = "Info";
+// Fork settings.
+"lng_settings_section_fork" = "Fork Settings";
+"lng_settings_square_avatats" = "Square avatars";
+"lng_settings_audio_fade" = "Audio fade";
+"lng_settings_uri_scheme" = "Open links with custom URI Scheme";
+"lng_settings_uri_scheme_box_title" = "Custom URI Scheme";
+"lng_settings_uri_scheme_field_label" = "Example: potplayer://.";
+"lng_settings_last_seen_in_dialogs" = "Show last seen time in list of dialogs";
+"lng_settings_search_engine" = "Add a 'Search Selected Text' to Context Menu";
+"lng_settings_search_engine_box_title" = "URL of Search Engine";
+"lng_settings_search_engine_field_label" = "URL must contain '%q'";
+"lng_settings_show_all_recent_stickers" = "Show all Recently used Stickers";
+"lng_settings_use_black_tray_icon" = "Use black tray icon";
+"lng_settings_use_original_tray_icon" = "Use original tray icon";
+"lng_settings_auto_submit_passcode" = "Auto-submit local passcode";
+"lng_settings_emoji_on_click" = "Disable emoji popup display on hovering";
+"lng_settings_remember_media_menu" = "Add 'Remember' to menu for media";
+"lng_settings_hide_all_chats_tab" = "Hide 'All Chats' tab";
+"lng_settings_disable_global_search" = "Disable global search";
+"lng_settings_forward_and_remove" = "Button to forward and remove";
+"lng_settings_auto_copy_login_codes" = "Auto-copy incoming login codes";
+"lng_settings_hide_archived_stories" = "Hide archived stories";
+"lng_settings_hide_from_blocked_users" = "Hide messages from blocked users";
+"lng_settings_skip_share_from_bot" = "Skip share box from app bots";
+"lng_settings_additional_buttons_web_bot" = "Display additional buttons for app bots";
+
+"lng_fork_extract_media_from_preview" = "Send media from link preview as attachment";
+
+"lng_fork_link_replacements" = "Replace links on paste";
+"lng_fork_link_replacements_about" = "Links you paste into a message are rewritten by the rules below. Useful for services whose previews Telegram cannot render.";
+"lng_fork_link_replacements_rules" = "Replacement rules";
+"lng_fork_link_replacements_rules_about" = "Each rule is a regular expression and the text that replaces a match. Use $1 to insert a captured group.";
+"lng_fork_link_replacements_add" = "Add rule";
+"lng_fork_link_replacements_edit" = "Edit rule";
+"lng_fork_link_replacements_find" = "Find";
+"lng_fork_link_replacements_replace" = "Replace with";
+"lng_fork_link_replacements_invalid" = "Invalid expression";
+"lng_fork_link_replacements_reset" = "Reset";
+"lng_fork_link_replaced" = "Link replaced";
+"lng_fork_link_replaced_undo" = "Undo";
+
+"lng_settings_custom_sticker_size" = "Custom Sticker Size";
+"lng_settings_sticker_size_label" = "Allowed values are between 50 and 256.";
+
+"lng_settings_markdown_clipboard_text" = "Clipboard text for 'Save to markdown file'";
+"lng_settings_markdown_clipboard_text_box_title" = "Clipboard text for 'Save to markdown file'";
+"lng_settings_markdown_clipboard_text_label" = "Use '%q' as a placeholder for the path to the saved markdown file. Leave empty to copy the path itself.";
+"lng_settings_markdown_clipboard_text_placeholder" = "Text to copy on save";
+
+// Link Device (QR login).
+"lng_settings_link_device" = "Link Device";
+"lng_settings_link_device_privacy" = "Your camera feed stays on your device. No video data is sent over the network — QR codes are scanned locally.";
+"lng_settings_link_device_start" = "Open Camera";
+"lng_settings_link_device_scanning" = "Point camera at the QR code shown on the device you want to log in.";
+"lng_settings_link_device_success" = "Device linked successfully!";
+"lng_settings_link_device_error" = "Could not link device: {error}";
+"lng_settings_link_device_confirm" = "Do you want to link this device to your account?";
+"lng_settings_link_device_stop" = "Stop Camera";
+"lng_settings_link_device_clipboard" = "Scan QR from Clipboard";
+
+"lng_context_open_uri_link" = "Open Link with URI Scheme";
+
+"lng_context_search_selected" = "Search Selected Text";
+
+"lng_info_id_label" = "ID";
+"lng_profile_copy_id" = "Copy ID";
+"lng_info_id_topic_label" = "Topic ID";
+"lng_info_id_topic_value_label" = "{id}. Created at: {date}";
+//
+
"lng_settings_section_notify" = "Notifications and Sounds";
"lng_settings_show_from" = "Show notifications from";
"lng_settings_notify_all" = "All accounts";
@@ -1297,6 +1370,10 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
"lng_proxy_auto_switch_timeout#one" = "{count} s";
"lng_proxy_auto_switch_timeout#other" = "{count} s";
"lng_proxy_about" = "Proxy servers may be helpful in accessing Telegram if there is no connection in a specific region.";
+"lng_proxy_websocket" = "Connect through a WebSocket relay";
+"lng_proxy_websocket_domain" = "Relay domain (optional)";
+"lng_proxy_websocket_http2" = "Media multiplexing (HTTP/2)";
+"lng_proxy_websocket_about" = "Wraps the connection in ordinary HTTPS to a Cloudflare-fronted relay, which can get through where a direct connection is blocked. Leave the domain empty to use the automatic public relay list. Those relays are run by third parties and rotate often, so for a reliable connection enter the domain of a Cloudflare worker of your own.";
"lng_proxy_add" = "Add proxy";
"lng_proxy_share" = "Share";
"lng_proxy_online" = "online";
@@ -1432,6 +1509,18 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
"lng_passkey_cable_no_bluetooth" = "Bluetooth is unavailable. Turn on Bluetooth to sign in with a phone.";
"lng_passkey_cable_error" = "Couldn't connect to your phone.\nPlease try again.";
+"lng_fork_passkeys_button_local" = "Add Passkey (Local Only)";
+"lng_fork_passkeys_none_button_local" = "Create Passkey (Local Only)";
+"lng_fork_passkeys_intro_local" = "Log in using passkey (Local Only)";
+"lng_fork_passkeys_local_about" = "**Local Only** passkeys are created and stored by Forkgram itself, in the Secure Enclave or your login keychain. They are never synced to iCloud or to a password manager, so they work only on this computer.";
+"lng_fork_passkeys_local_short" = "Your passkey stays on this Mac only and is never synced anywhere.";
+"lng_fork_passkeys_created" = "Passkey created and stored on this Mac.";
+"lng_fork_passkeys_create_error" = "Couldn't create a local passkey on this Mac.";
+"lng_fork_passkeys_create_reason" = "create a passkey stored only on this Mac";
+"lng_fork_passkeys_login_reason" = "log in with a passkey stored on this Mac";
+"lng_fork_passkeys_choose_title" = "Choose a passkey";
+"lng_fork_passkeys_choose_about" = "Several passkeys are stored on this Mac. Pick the one you want to log in with.";
+
"lng_settings_quick_dialog_action_title" = "Chat list quick action";
"lng_settings_quick_dialog_action_about" = "Choose the action you want to perform when you middle-click or swipe in the chat list.";
"lng_settings_quick_dialog_action_both" = "Swipe and Middle-click";
@@ -1696,6 +1785,8 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
"lng_mute_menu_sound_off" = "Disable sound";
"lng_mute_menu_sound_select" = "Select tone";
"lng_mute_box_title" = "Mute notifications for...";
+"lng_mute_all" = "Mute all";
+"lng_mute_all_sure" = "Are you sure you want to mute all chats in this folder?";
"lng_preview_loading" = "Getting Link Info...";
"lng_preview_cant" = "Could not generate preview for this link.";
@@ -5653,7 +5744,12 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
"lng_context_save_images_selected" = "Save Selected";
"lng_context_save_documents_selected" = "Download Selected";
"lng_context_save_html" = "Save as HTML";
+"lng_context_save_to_markdown_selected" = "Save to markdown file";
+"lng_context_save_to_markdown_done" = "Markdown saved. Path copied to clipboard.";
"lng_context_clear_selection" = "Clear Selection";
+"lng_context_to_save_messages" = "To Saved Messages";
+"lng_context_group_items" = "Group Selected";
+
"lng_context_seen_loading" = "Loading...";
"lng_context_seen_text#one" = "{count} Seen";
"lng_context_seen_text#other" = "{count} Seen";
@@ -6028,6 +6124,8 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
"lng_share_message_to_many_chats#other" = "Message forwarded to **{count} chats**.";
"lng_share_messages_to_many_chats#one" = "Messages forwarded to **{count} chat**.";
"lng_share_messages_to_many_chats#other" = "Messages forwarded to **{count} chats**.";
+"lng_share_as_copy" = "As copy";
+"lng_share_as_copy_no_text" = "No text";
"lng_contact_phone" = "Phone Number";
"lng_contact_link_invalid" = "This link is invalid or has expired.";
@@ -6150,7 +6248,7 @@ https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
"lng_upload_show_file" = "Show file";
"lng_about_version" = "version {version}";
-"lng_about_text1" = "Official free messaging app based on {api_link}\nfor speed and security.";
+"lng_about_text1" = "Unofficial free messaging app based on {api_link}\nfor speed and security.";
"lng_about_text1_api" = "Telegram API";
"lng_about_text2" = "This software is licensed under {gpl_link} version 3.\nSource code is available on {github_link}.";
"lng_about_text3" = "Visit the {faq_link} for more info.";
diff --git a/Telegram/Resources/qrc/telegram.qrc b/Telegram/Resources/qrc/telegram.qrc
new file mode 100644
index 0000000000000..e69de29bb2d1d
diff --git a/Telegram/Resources/qrc/telegram/telegram.qrc b/Telegram/Resources/qrc/telegram/telegram.qrc
index 95921b15c68fe..bf0bb7786709b 100644
--- a/Telegram/Resources/qrc/telegram/telegram.qrc
+++ b/Telegram/Resources/qrc/telegram/telegram.qrc
@@ -6,7 +6,10 @@
../../art/business_logo.png../../art/affiliate_logo.png../../art/logo_256.png
+ ../../art/logo_256_square.png../../art/logo_256_no_margin.png
+ ../../art/forkgram/logo_256.png
+ ../../art/forkgram/logo_256_no_margin.png../../art/themeimage.jpg../../art/round_placeholder.jpg../../art/cocoon.webp
diff --git a/Telegram/Resources/update/manifest.min.json b/Telegram/Resources/update/manifest.min.json
index c7e2beb0fa258..40213facb35a9 100644
--- a/Telegram/Resources/update/manifest.min.json
+++ b/Telegram/Resources/update/manifest.min.json
@@ -1 +1 @@
-{"format":1,"manifest_version":2,"issued":1787184000,"expires":1826668800,"keys":[{"id":"rl-2026b","alg":"Ed25519","x":"C8sDZ7G_3-v5DPKBjqcU6hCNFJjC1z8ggFcCyoVLtC0"},{"id":"rc-2026a","alg":"ES256","crv":"P-256","x":"STnSOvgTXqkfM-TelsKMG6UVPHIuoB23vf5ckVKu-JU","y":"yejET3nS79sqDDT0LeH4ZfcnNc-X36DotOAtdrOashM"},{"id":"cp-2026a","alg":"ES256","crv":"P-256","x":"Nn5D71VdtoaXuCAdLBixdeMbLpy8ApzZMfp8iMtqE9Q","y":"K6K_enSIa5KChVV1oAC7Bxfkr9t3RTR_iQAR9Ls21yc","expires":1821398400},{"id":"cx-2026a","alg":"ES256","crv":"P-256","x":"gsX8hFpkokAvvHqFhZ65D2cv0zLfDVpS60961hho6PM","y":"SrAhvdW1waKh_81Imyoc0Pa3e-2HsNZXC9qeRY4Mbn8","expires":1821398400}],"channels":{"stable":[["rl-2026b"],["rc-2026a"]],"beta":[["rl-2026b"],["rc-2026a"]],"canary-public":[["cp-2026a"]],"canary-private":[["cx-2026a"]]},"revoked":["rl-2026a"]}
\ No newline at end of file
+{"format":1,"manifest_version":1,"issued":1788586528,"keys":[{"id":"fg-2026a","alg":"Ed25519","x":"HXLtYQ03CThmyPGpLk5JZTwgcYcz75gvelzR-QhZ_gg"}],"channels":{"stable":[["fg-2026a"]],"beta":[["fg-2026a"]]},"revoked":[]}
\ No newline at end of file
diff --git a/Telegram/Resources/update/manifest.sig b/Telegram/Resources/update/manifest.sig
index 614df02dd3e2e..336a3bdabfd3e 100644
Binary files a/Telegram/Resources/update/manifest.sig and b/Telegram/Resources/update/manifest.sig differ
diff --git a/Telegram/Resources/update/root-public.pem b/Telegram/Resources/update/root-public.pem
index a5028f6d605fc..d0f8dd05a58c1 100644
--- a/Telegram/Resources/update/root-public.pem
+++ b/Telegram/Resources/update/root-public.pem
@@ -1,3 +1,3 @@
-----BEGIN PUBLIC KEY-----
-MCowBQYDK2VwAyEARgB8IFZWA08OzifsbPQ3SRdGbON2ecPVsMm1Qo7QNR0=
+MCowBQYDK2VwAyEAGejdOFLuPk0+mb/Ctt1/v1dhs7+8xrBeCgfq+4oSS2A=
-----END PUBLIC KEY-----
diff --git a/Telegram/Resources/winrc/Telegram.rc b/Telegram/Resources/winrc/Telegram.rc
index 25b1df7c42a9f..729a78dbe120b 100644
--- a/Telegram/Resources/winrc/Telegram.rc
+++ b/Telegram/Resources/winrc/Telegram.rc
@@ -60,7 +60,7 @@ BEGIN
BEGIN
BLOCK "040904b0"
BEGIN
- VALUE "CompanyName", "Telegram FZ-LLC"
+ VALUE "CompanyName", ""
VALUE "FileDescription", "Telegram Desktop"
VALUE "FileVersion", "7.5.1.0"
VALUE "LegalCopyright", "Copyright (C) 2014-2026"
diff --git a/Telegram/Resources/winrc/Updater.rc b/Telegram/Resources/winrc/Updater.rc
index d92bb0dabc896..ed86bcb03e25c 100644
--- a/Telegram/Resources/winrc/Updater.rc
+++ b/Telegram/Resources/winrc/Updater.rc
@@ -51,7 +51,7 @@ BEGIN
BEGIN
BLOCK "040904b0"
BEGIN
- VALUE "CompanyName", "Telegram FZ-LLC"
+ VALUE "CompanyName", ""
VALUE "FileDescription", "Telegram Desktop Updater"
VALUE "FileVersion", "7.5.1.0"
VALUE "LegalCopyright", "Copyright (C) 2014-2026"
diff --git a/Telegram/SourceFiles/_other/packer.cpp b/Telegram/SourceFiles/_other/packer.cpp
index 75195c9d2a9dd..7e500020f1bcf 100644
--- a/Telegram/SourceFiles/_other/packer.cpp
+++ b/Telegram/SourceFiles/_other/packer.cpp
@@ -31,9 +31,9 @@ Core::Updates::Target V2Target;
const char *PublicKey = "\
-----BEGIN RSA PUBLIC KEY-----\n\
-MIGJAoGBAMA4ViQrjkPZ9xj0lrer3r23JvxOnrtE8nI69XLGSr+sRERz9YnUptnU\n\
-BZpkIfKaRcl6XzNJiN28cVwO1Ui5JSa814UAiDHzWUqCaXUiUEQ6NmNTneiGx2sQ\n\
-+9PKKlb8mmr3BB9A45ZNwLT6G9AK3+qkZLHojeSA+m84/a6GP4svAgMBAAE=\n\
+MIGJAoGBAKsnBsqNhHwWrCK1KQweYxXAkLNAmPI4Q1x2MXspQvZ+qcIoOzLppvjs\n\
+ci6swYGMGreT1qmdlPTqBlCYbpfX8uD3qcVA6IYVGtyk1U4xu2kNRabALW0pQiuj\n\
++GknJCPf+ajdlsfTMtRuEh76a+uDF2hfkItBLLcx4SKlNifBdSQbAgMBAAE=\n\
-----END RSA PUBLIC KEY-----\
";
@@ -989,7 +989,7 @@ int main(int argc, char *argv[])
cout << "Bad signature length: " << siglen << "\n";
return -1;
}
-
+ /*
cout << "Checking signature..\n";
RSA *pbKey = [] {
const auto bio = makeBIO(
@@ -1011,6 +1011,7 @@ int main(int argc, char *argv[])
}
cout << "Signature verified!\n";
RSA_free(pbKey);
+ */
#ifdef Q_OS_WIN
QString outName((targetwinarm ? QString("tarm64upd%1") : targetwin64 ? QString("tx64upd%1") : QString("tupdate%1")).arg(AlphaVersion ? AlphaVersion : version));
#elif defined Q_OS_MACOS
@@ -1035,6 +1036,7 @@ int main(int argc, char *argv[])
}
QString countAlphaVersionSignature(quint64 version) { // duplicated in autoupdater.cpp
+ /*
QByteArray cAlphaPrivateKey(AlphaPrivateKey);
if (cAlphaPrivateKey.isEmpty()) {
cout << "Error: Trying to count alpha version signature without alpha private key!\n";
@@ -1082,4 +1084,6 @@ QString countAlphaVersionSignature(quint64 version) { // duplicated in autoupdat
signature = signature.toBase64(QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals);
signature = signature.replace('-', '8').replace('_', 'B');
return QString::fromUtf8(signature.mid(19, 32));
+ */
+ return "0";
}
diff --git a/Telegram/SourceFiles/_other/updater_linux.cpp b/Telegram/SourceFiles/_other/updater_linux.cpp
index 5ae2b644708e4..c350d9667a273 100644
--- a/Telegram/SourceFiles/_other/updater_linux.cpp
+++ b/Telegram/SourceFiles/_other/updater_linux.cpp
@@ -295,7 +295,7 @@ bool update() {
writeLog("Error: bad update, has Updater! '%s' equal '%s'", tofname.c_str(), updaterName.c_str());
delFolder();
return false;
- } else if (equal(tofname, exePath + "Telegram") && exeName != "Telegram") {
+ } else if (equal(tofname, exePath + "Forkgram") && exeName != "Forkgram") {
string fullBinaryPath = exePath + exeName;
writeLog("Target binary found: '%s', changing to '%s'", tofname.c_str(), fullBinaryPath.c_str());
tofname = fullBinaryPath;
@@ -425,7 +425,7 @@ int main(int argc, char *argv[]) {
}
}
if (exeName.empty() || exeName.find('/') != string::npos) {
- exeName = "Telegram";
+ exeName = "Forkgram";
}
openLog();
@@ -542,7 +542,7 @@ int main(int argc, char *argv[]) {
return 1;
}
- writeLog("Executed Telegram, closing log and quitting..");
+ writeLog("Executed Forkgram, closing log and quitting..");
}
closeLog();
diff --git a/Telegram/SourceFiles/_other/updater_osx.m b/Telegram/SourceFiles/_other/updater_osx.m
index 6951a153629a7..53fc50901f779 100644
--- a/Telegram/SourceFiles/_other/updater_osx.m
+++ b/Telegram/SourceFiles/_other/updater_osx.m
@@ -8,7 +8,7 @@
#import
#include
-NSString *appName = @"Telegram.app";
+NSString *appName = @TDESKTOP_APP_BUNDLE_NAME;
NSString *appDir = nil;
NSString *workDir = nil;
@@ -55,8 +55,9 @@ void RemoveQuarantineAttribute(NSString *path) {
}
void RemoveQuarantineFromBundle(NSString *path) {
+ NSString *executable = [appName stringByDeletingPathExtension];
RemoveQuarantineAttribute(path);
- RemoveQuarantineAttribute([path stringByAppendingString:@"/Contents/MacOS/Telegram"]);
+ RemoveQuarantineAttribute([path stringByAppendingFormat:@"/Contents/MacOS/%@", executable]);
RemoveQuarantineAttribute([path stringByAppendingString:@"/Contents/Helpers/crashpad_handler"]);
RemoveQuarantineAttribute([path stringByAppendingString:@"/Contents/Helpers/TelegramWidgetHelper"]);
RemoveQuarantineAttribute([path stringByAppendingString:@"/Contents/Frameworks/Updater"]);
diff --git a/Telegram/SourceFiles/_other/updater_win.cpp b/Telegram/SourceFiles/_other/updater_win.cpp
index 0fa37bdaece8d..8ee462c75ae08 100644
--- a/Telegram/SourceFiles/_other/updater_win.cpp
+++ b/Telegram/SourceFiles/_other/updater_win.cpp
@@ -469,7 +469,7 @@ void updateRegistry() {
RegSetValueEx(rkey, L"DisplayVersion", 0, REG_SZ, (const BYTE*)versionStr, ((versionLen / 2) + 1) * sizeof(WCHAR));
wsprintf(nameStr, L"Telegram Desktop");
RegSetValueEx(rkey, L"DisplayName", 0, REG_SZ, (const BYTE*)nameStr, (wcslen(nameStr) + 1) * sizeof(WCHAR));
- wsprintf(publisherStr, L"Telegram FZ-LLC");
+ wsprintf(publisherStr, L"");
RegSetValueEx(rkey, L"Publisher", 0, REG_SZ, (const BYTE*)publisherStr, (wcslen(publisherStr) + 1) * sizeof(WCHAR));
wsprintf(icongroupStr, L"Telegram Desktop");
RegSetValueEx(rkey, L"Inno Setup: Icon Group", 0, REG_SZ, (const BYTE*)icongroupStr, (wcslen(icongroupStr) + 1) * sizeof(WCHAR));
diff --git a/Telegram/SourceFiles/_other/yy_thunks_defaults.cpp b/Telegram/SourceFiles/_other/yy_thunks_defaults.cpp
new file mode 100644
index 0000000000000..c8d512c9d4c77
--- /dev/null
+++ b/Telegram/SourceFiles/_other/yy_thunks_defaults.cpp
@@ -0,0 +1,34 @@
+/*
+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
+
+// YY-Thunks makes these hooks weak with closed tool we skip, so define defaults.
+extern "C" {
+
+// Keep the DLL preloading that a stock YY-Thunks build has enabled.
+BOOL __YY_Thunks_Disable_Rreload_Dlls = FALSE;
+
+// Const at namespace scope is internal linkage, so declare extern first.
+extern HMODULE (__fastcall * const __pfnYY_Thunks_CustomLoadLibrary)(
+ const wchar_t *moduleName,
+ DWORD flags);
+HMODULE (__fastcall * const __pfnYY_Thunks_CustomLoadLibrary)(
+ const wchar_t *moduleName,
+ DWORD flags) = nullptr;
+
+// No custom entry point, so the original CRT startup is used.
+extern BOOL (WINAPI * const __pfnDllMainCRTStartupForYY_Thunks)(
+ HINSTANCE instance,
+ DWORD reason,
+ LPVOID reserved);
+BOOL (WINAPI * const __pfnDllMainCRTStartupForYY_Thunks)(
+ HINSTANCE instance,
+ DWORD reason,
+ LPVOID reserved) = nullptr;
+
+} // extern "C"
diff --git a/Telegram/SourceFiles/api/api_as_copy.cpp b/Telegram/SourceFiles/api/api_as_copy.cpp
new file mode 100644
index 0000000000000..44460adbaebd6
--- /dev/null
+++ b/Telegram/SourceFiles/api/api_as_copy.cpp
@@ -0,0 +1,257 @@
+/*
+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 "api/api_as_copy.h"
+
+#include "api/api_common.h"
+#include "api/api_sending.h"
+#include "api/api_text_entities.h"
+#include "apiwrap.h"
+#include "base/random.h"
+#include "base/unixtime.h"
+#include "chat_helpers/message_field.h"
+#include "data/data_channel.h"
+#include "data/data_document.h"
+#include "data/data_drafts.h"
+#include "data/data_histories.h"
+#include "data/data_photo.h"
+#include "data/data_session.h"
+#include "history/history.h"
+#include "history/history_item.h"
+#include "main/main_session.h"
+
+namespace Api::AsCopy {
+namespace {
+
+MTPInputSingleMedia PrepareAlbumItemMedia(
+ not_null item,
+ const MTPInputMedia &media,
+ uint64 randomId,
+ bool emptyText,
+ TextWithTags comment) {
+ auto commentEntities = TextWithEntities {
+ comment.text,
+ TextUtilities::ConvertTextTagsToEntities(comment.tags)
+ };
+
+ auto caption = item->originalText();
+ TextUtilities::Trim(caption);
+ auto sentEntities = Api::EntitiesToMTP(
+ &item->history()->session(),
+ emptyText ? commentEntities.entities : caption.entities,
+ Api::ConvertOption::SkipLocal);
+ const auto flags = !sentEntities.v.isEmpty()
+ ? MTPDinputSingleMedia::Flag::f_entities
+ : MTPDinputSingleMedia::Flag(0);
+
+ return MTP_inputSingleMedia(
+ MTP_flags(flags),
+ media,
+ MTP_long(randomId),
+ MTP_string(emptyText ? commentEntities.text : caption.text),
+ sentEntities);
+}
+
+MTPinputMedia InputMediaFromItem(not_null i) {
+ if (const auto document = i->media()->document()) {
+ return MTP_inputMediaDocument(
+ MTP_flags(MTPDinputMediaDocument::Flag(0)),
+ document->mtpInput(),
+ document->goodThumbnailPhoto()
+ ? document->goodThumbnailPhoto()->mtpInput()
+ : MTPInputPhoto(),
+ MTP_int(0),
+ MTP_int(0),
+ MTPstring());
+ } else if (const auto photo = i->media()->photo()) {
+ return MTP_inputMediaPhoto(
+ MTP_flags(MTPDinputMediaPhoto::Flag(0)),
+ photo->mtpInput(),
+ MTP_int(0),
+ MTPInputDocument());
+ } else {
+ return MTP_inputMediaEmpty();
+ }
+}
+
+FullReplyTo ReplyToIdFromDraft(not_null peer) {
+ const auto history = peer->owner().history(peer);
+ const auto replyTo = [&]() -> FullReplyTo {
+ if (const auto localDraft = history->localDraft(0, 0)) {
+ return localDraft->reply;
+ } else if (const auto cloudDraft = history->cloudDraft(0, 0)) {
+ return cloudDraft->reply;
+ } else {
+ return {};
+ }
+ }();
+ if (replyTo) {
+ history->clearCloudDraft(0, 0);
+ history->clearLocalDraft(0, 0);
+ peer->session().api().request(
+ MTPmessages_SaveDraft(
+ MTP_flags(MTPmessages_SaveDraft::Flags(0)),
+ MTP_inputReplyToStory(MTP_inputPeerEmpty(), MTPint()),
+ history->peer->input(),
+ MTPstring(),
+ MTPVector(),
+ MTP_inputMediaEmpty(),
+ MTP_long(0),
+ SuggestToMTP({}),
+ MTPInputRichMessage()
+ )).send();
+ }
+ return replyTo;
+}
+
+} // namespace
+
+void SendAlbumFromItems(
+ HistoryItemsList items,
+ ToSend &&toSend,
+ bool andDelete) {
+ if (items.empty()) {
+ return;
+ }
+ const auto history = items.front()->history();
+ const auto ids = history->owner().itemsToIds(items);
+ auto medias = QVector();
+ for (const auto &i : items) {
+ medias.push_back(PrepareAlbumItemMedia(
+ i,
+ InputMediaFromItem(i),
+ base::RandomValue(),
+ toSend.emptyText,
+ medias.empty() ? toSend.comment : TextWithTags()));
+ }
+ auto &api = history->owner().session().api();
+
+ for (const auto &peer : toSend.peers) {
+ const auto replyTo = ReplyToIdFromDraft(peer);
+
+ const auto flags = MTPmessages_SendMultiMedia::Flags(0)
+ | (replyTo
+ ? MTPmessages_SendMultiMedia::Flag::f_reply_to
+ : MTPmessages_SendMultiMedia::Flag(0))
+ | (toSend.silent
+ ? MTPmessages_SendMultiMedia::Flag::f_silent
+ : MTPmessages_SendMultiMedia::Flag(0))
+ | (toSend.scheduled
+ ? MTPmessages_SendMultiMedia::Flag::f_schedule_date
+ : MTPmessages_SendMultiMedia::Flag(0));
+ api.request(MTPmessages_SendMultiMedia(
+ MTP_flags(flags),
+ peer->input(),
+ ReplyToForMTP(history, replyTo),
+ MTP_vector(medias),
+ MTP_int(toSend.scheduled),
+ MTP_inputPeerEmpty(),
+ MTPInputQuickReplyShortcut(),
+ MTP_long(0),
+ MTP_long(0)
+ )).done([=](const MTPUpdates &result) {
+ history->owner().session().api().applyUpdates(result);
+
+ if (andDelete) {
+ history->owner().histories().deleteMessages(ids, true);
+ history->owner().sendHistoryChangeNotifications();
+ }
+ }).fail([=](const MTP::Error &error) {
+ }).send();
+ }
+}
+
+void GuardedSendExistingAlbumFromItem(
+ not_null item,
+ Api::AsCopy::ToSend &&toSend) {
+ if (!item->groupId()) {
+ return;
+ }
+ const auto items = item->history()->owner().groups().find(item)->items;
+ UpdateFileRef(
+ items,
+ [=] { SendAlbumFromItems(items, base::duplicate(toSend), false); },
+ [](QString){});
+}
+
+void SendExistingMediaFromItem(
+ not_null item,
+ Api::AsCopy::ToSend &&toSend) {
+ for (const auto &peer : toSend.peers) {
+ const auto history = peer->owner().history(peer);
+ auto message = MessageToSend(SendAction{ history });
+ if (!item->media()) {
+ message.textWithTags = PrepareEditText(item);
+ history->session().api().sendMessage(std::move(message));
+ continue;
+ }
+ message.textWithTags = toSend.emptyText
+ ? toSend.comment
+ : PrepareEditText(item);
+ message.action.options.silent = toSend.silent;
+ message.action.options.scheduled = toSend.scheduled;
+ message.action.replyTo = ReplyToIdFromDraft(peer);
+ if (const auto document = item->media()->document()) {
+ Api::SendExistingDocument(
+ std::move(message),
+ document,
+ item->fullId());
+ } else if (const auto photo = item->media()->photo()) {
+ Api::SendExistingPhoto(std::move(message), photo, item->fullId());
+ }
+ }
+}
+
+void UpdateFileRef(
+ HistoryItemsList list,
+ Fn success,
+ Fn fail) {
+ if (list.empty()) {
+ return;
+ }
+ const auto history = list.front()->history();
+ auto inputMessages = ranges::views::all(
+ list
+ ) | ranges::views::transform([&](const auto &item) {
+ return MTP_inputMessageID(MTP_int(item->id));
+ }) | ranges::to>();
+ const auto receive = [=](const MTPmessages_Messages &result) {
+ result.match([&](const MTPDmessages_messagesNotModified &) {
+ fail("MTPDmessages_messagesNotModified");
+ }, [&](const auto &d) {
+ auto good = true;
+ for (const auto &tlMessage : d.vmessages().v) {
+ tlMessage.match([&](const MTPDmessage &d) {
+ history->session().data().updateExistingMessage(d);
+ }, [&](const auto &) {
+ good = false;
+ fail("MTPDmessageService or MTPDmessageEmpty");
+ });
+ }
+ if (good) {
+ success();
+ }
+ });
+ };
+ const auto receiveError = [=](auto error) {
+ fail("Get Message error: " + error.type());
+ };
+ if (const auto channel = history->peer->asChannel()) {
+ history->session().api().request(
+ MTPchannels_GetMessages(
+ channel->inputChannel(),
+ MTP_vector(std::move(inputMessages)))
+ ).done(receive).fail(receiveError).send();
+ } else {
+ history->session().api().request(
+ MTPmessages_GetMessages(
+ MTP_vector(std::move(inputMessages)))
+ ).done(receive).fail(receiveError).send();
+ }
+}
+
+} // namespace Api::AsCopy
diff --git a/Telegram/SourceFiles/api/api_as_copy.h b/Telegram/SourceFiles/api/api_as_copy.h
new file mode 100644
index 0000000000000..3850dd11e01d5
--- /dev/null
+++ b/Telegram/SourceFiles/api/api_as_copy.h
@@ -0,0 +1,40 @@
+/*
+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
+
+class HistoryItem;
+class PeerData;
+struct TextWithTags;
+
+namespace Api::AsCopy {
+
+struct ToSend {
+ std::vector> peers;
+ TextWithTags comment;
+ bool emptyText = false;
+ bool silent = false;
+ TimeId scheduled = 0;
+};
+
+void GuardedSendExistingAlbumFromItem(
+ not_null item,
+ ToSend &&toSend);
+
+void SendExistingMediaFromItem(not_null item, ToSend &&toSend);
+
+void SendAlbumFromItems(
+ HistoryItemsList items,
+ ToSend &&toSend,
+ bool andDelete);
+
+void UpdateFileRef(
+ HistoryItemsList list,
+ Fn success,
+ Fn fail);
+
+} // namespace Api::AsCopy
diff --git a/Telegram/SourceFiles/api/api_editing.cpp b/Telegram/SourceFiles/api/api_editing.cpp
index 885fe985fb0f9..62da508527f93 100644
--- a/Telegram/SourceFiles/api/api_editing.cpp
+++ b/Telegram/SourceFiles/api/api_editing.cpp
@@ -820,4 +820,17 @@ void EditTodoList(
MTP_inputMediaTodo(TodoListDataToMTP(&data)));
}
+namespace Fork {
+
+void EditMessageMedia(
+ not_null item,
+ Api::SendOptions options,
+ MTPInputMedia media,
+ Fn fail) {
+ EditMessage(item, options, []{}, fail, media);
+ // EditMessageWithUploadedMedia(item, options, media, fail);
+}
+
+} // namespace Fork
+
} // namespace Api
diff --git a/Telegram/SourceFiles/api/api_editing.h b/Telegram/SourceFiles/api/api_editing.h
index 51f3b5494493e..2462b3a015dfd 100644
--- a/Telegram/SourceFiles/api/api_editing.h
+++ b/Telegram/SourceFiles/api/api_editing.h
@@ -73,4 +73,15 @@ void EditTodoList(
Fn done,
Fn fail);
+
+namespace Fork {
+
+void EditMessageMedia(
+ not_null item,
+ Api::SendOptions options,
+ MTPInputMedia media,
+ Fn fail);
+
+} // namespace Fork
+
} // namespace Api
diff --git a/Telegram/SourceFiles/api/api_sending.cpp b/Telegram/SourceFiles/api/api_sending.cpp
index 79d184beaf625..085c68769b035 100644
--- a/Telegram/SourceFiles/api/api_sending.cpp
+++ b/Telegram/SourceFiles/api/api_sending.cpp
@@ -689,6 +689,52 @@ void SendMusicSelectionBatch(
} // namespace
+void SendExistingDocument(
+ MessageToSend &&message,
+ not_null document,
+ Data::FileOrigin origin) {
+ const auto inputMedia = [=] {
+ return MTP_inputMediaDocument(
+ MTP_flags(0),
+ document->mtpInput(),
+ document->goodThumbnailPhoto()
+ ? document->goodThumbnailPhoto()->mtpInput()
+ : MTPInputPhoto(),
+ MTPint(),
+ MTPint(), // ttl_seconds
+ MTPstring()); // query
+ };
+ SendExistingMedia(
+ std::move(message),
+ document,
+ inputMedia,
+ origin,
+ std::nullopt);
+
+ if (document->sticker()) {
+ document->owner().stickers().incrementSticker(document);
+ }
+}
+
+void SendExistingPhoto(
+ MessageToSend &&message,
+ not_null photo,
+ Data::FileOrigin origin) {
+ const auto inputMedia = [=] {
+ return MTP_inputMediaPhoto(
+ MTP_flags(0),
+ photo->mtpInput(),
+ MTPint(),
+ MTPInputDocument());
+ };
+ SendExistingMedia(
+ std::move(message),
+ photo,
+ inputMedia,
+ origin,
+ std::nullopt);
+}
+
void SendExistingDocument(
MessageToSend &&message,
not_null document,
diff --git a/Telegram/SourceFiles/api/api_sending.h b/Telegram/SourceFiles/api/api_sending.h
index b6f3c51fc2229..795a89af00250 100644
--- a/Telegram/SourceFiles/api/api_sending.h
+++ b/Telegram/SourceFiles/api/api_sending.h
@@ -46,6 +46,16 @@ void SendExistingPhoto(
not_null photo,
std::optional localMessageId = std::nullopt);
+void SendExistingDocument(
+ MessageToSend &&message,
+ not_null document,
+ Data::FileOrigin origin);
+
+void SendExistingPhoto(
+ MessageToSend &&message,
+ not_null photo,
+ Data::FileOrigin origin);
+
bool SendDice(MessageToSend &message);
// We can't create Data::LocationPoint() and use it
diff --git a/Telegram/SourceFiles/apiwrap.cpp b/Telegram/SourceFiles/apiwrap.cpp
index 62d44b1fcdfb4..d5fa75998172a 100644
--- a/Telegram/SourceFiles/apiwrap.cpp
+++ b/Telegram/SourceFiles/apiwrap.cpp
@@ -4238,6 +4238,31 @@ FullMsgId ApiWrap::forwardMessages(
uint64(0),
std::move(buildMessage),
[=](const MTPUpdates &result, const MTP::Response &) {
+ { // Delete after forward.
+ auto toDelete = MessageIdsList();
+ for (const auto &id : ids) {
+ const auto it = ranges::find_if(_deleteAfterForward, [&](const FullMsgId &m) {
+ return m.msg.bare == id.v && forwardFrom->id == m.peer;
+ });
+ if (it != _deleteAfterForward.end()) {
+ toDelete.push_back(*it);
+ _deleteAfterForward.erase(it);
+ }
+ }
+ const auto count = toDelete.size();
+ if (count > 0) {
+ _session->data().histories().deleteMessages(
+ toDelete,
+ true);
+ if (const auto w = Core::App().activeWindow()) {
+ if (const auto c = w->sessionController()) {
+ c->uiShow()->showToast((count > 1)
+ ? (u"Delete %1 messages."_q.arg(count))
+ : (u"Delete %1 message."_q.arg(count)));
+ }
+ }
+ }
+ }
if (!scheduled) {
_session->api().updates().checkForSentToScheduled(
result);
diff --git a/Telegram/SourceFiles/apiwrap.h b/Telegram/SourceFiles/apiwrap.h
index 76bf12baecb3d..c430ca4340915 100644
--- a/Telegram/SourceFiles/apiwrap.h
+++ b/Telegram/SourceFiles/apiwrap.h
@@ -480,6 +480,10 @@ class ApiWrap final : public MTP::Sender {
void registerStatsRequest(MTP::DcId dcId, mtpRequestId id);
void unregisterStatsRequest(MTP::DcId dcId, mtpRequestId id);
+ void rememberToDeleteAfterForward(MessageIdsList ids) {
+ _deleteAfterForward.insert(_deleteAfterForward.end(), ids.begin(), ids.end());
+ }
+
[[nodiscard]] Api::Authorizations &authorizations();
[[nodiscard]] Api::AttachedStickers &attachedStickers();
[[nodiscard]] Api::BlockedPeers &blockedPeers();
@@ -906,6 +910,8 @@ class ApiWrap final : public MTP::Sender {
const std::unique_ptr _shareThemes;
const std::unique_ptr _botInfoLocalizations;
+ MessageIdsList _deleteAfterForward;
+
mtpRequestId _wallPaperRequestId = 0;
QString _wallPaperSlug;
Fn _wallPaperDone;
diff --git a/Telegram/SourceFiles/boxes/about_box.cpp b/Telegram/SourceFiles/boxes/about_box.cpp
index 59934a6b0414c..331535c7476a3 100644
--- a/Telegram/SourceFiles/boxes/about_box.cpp
+++ b/Telegram/SourceFiles/boxes/about_box.cpp
@@ -37,6 +37,8 @@ For license and copyright information please follow this link:
namespace {
rpl::producer Text1() {
+ return rpl::single({
+ .text = "Forkgram based on the Telegram Desktop." });
return tr::lng_about_text1(
lt_api_link,
tr::lng_about_text1_api(tr::url(u"https://core.telegram.org/api"_q)),
@@ -66,7 +68,7 @@ rpl::producer Text3() {
} // namespace
void AboutBox(not_null box) {
- box->setTitle(u"Telegram Desktop"_q);
+ box->setTitle(rpl::single(QString(AppNameF.utf8())));
auto layout = box->verticalLayout();
diff --git a/Telegram/SourceFiles/boxes/confirm_box.cpp b/Telegram/SourceFiles/boxes/confirm_box.cpp
new file mode 100644
index 0000000000000..e69de29bb2d1d
diff --git a/Telegram/SourceFiles/boxes/connection_box.cpp b/Telegram/SourceFiles/boxes/connection_box.cpp
index fb04e6027b14e..6bdcc9c5fda38 100644
--- a/Telegram/SourceFiles/boxes/connection_box.cpp
+++ b/Telegram/SourceFiles/boxes/connection_box.cpp
@@ -7,8 +7,9 @@ For license and copyright information please follow this link:
*/
#include "boxes/connection_box.h"
-#include "base/qt/qt_key_modifiers.h"
#include "base/call_delayed.h"
+#include "base/options.h"
+#include "base/qt/qt_key_modifiers.h"
#include "base/qthelp_regex.h"
#include "base/qthelp_url.h"
#include "base/weak_ptr.h"
@@ -23,6 +24,7 @@ For license and copyright information please follow this link:
#include "mtproto/facade.h"
#include "mtproto/mtproto_config.h"
#include "mtproto/proxy_check.h"
+#include "mtproto/websocket_relays.h"
#include "qr/qr_generate.h"
#include "settings/settings_common.h"
#include "storage/localstorage.h"
@@ -713,6 +715,10 @@ class ProxiesBox : public Ui::BoxContent {
not_null _controller;
Core::SettingsProxy &_settings;
QPointer _tryIPv6;
+ QPointer _webSocket;
+ QPointer> _webSocketOptions;
+ QPointer _webSocketDomain;
+ QPointer _webSocketMedia;
std::shared_ptr> _proxySettings;
QPointer> _proxyRotation;
QPointer> _proxyRotationOptions;
@@ -1355,6 +1361,49 @@ void ProxiesBox::setupContent() {
tr::lng_connection_try_ipv6(tr::now),
_settings.tryIPv6()),
st::proxyTryIPv6Padding);
+ _webSocket = inner->add(
+ object_ptr(
+ inner,
+ tr::lng_proxy_websocket(tr::now),
+ base::options::value(MTP::kOptionWebSocketTransport)),
+ st::proxyTryIPv6Padding);
+ _webSocketOptions = inner->add(
+ object_ptr>(
+ inner,
+ object_ptr(inner)));
+ const auto webSocketInner = _webSocketOptions->entity();
+ const auto domainRow = webSocketInner->add(
+ object_ptr(
+ webSocketInner,
+ st::connectionHostInputField.heightMin),
+ st::proxyEditInputPadding);
+ _webSocketDomain = Ui::CreateChild(
+ domainRow,
+ st::connectionHostInputField,
+ tr::lng_proxy_websocket_domain(),
+ base::options::value(MTP::kOptionWebSocketDomain));
+ domainRow->widthValue(
+ ) | rpl::on_next([=](int width) {
+ _webSocketDomain->resize(width, _webSocketDomain->height());
+ _webSocketDomain->moveToLeft(0, 0);
+ }, domainRow->lifetime());
+ _webSocketMedia = webSocketInner->add(
+ object_ptr(
+ webSocketInner,
+ tr::lng_proxy_websocket_http2(tr::now),
+ base::options::value(
+ MTP::kOptionWebSocketMediaMultiplexing)),
+ st::proxyTryIPv6Padding);
+ webSocketInner->add(
+ object_ptr(
+ webSocketInner,
+ tr::lng_proxy_websocket_about(tr::now),
+ st::boxDividerLabel),
+ st::proxyAboutPadding);
+ _webSocketOptions->toggle(
+ base::options::value(MTP::kOptionWebSocketTransport),
+ anim::type::instant);
+
_proxySettings
= std::make_shared>(
_settings.settings());
@@ -1448,6 +1497,29 @@ void ProxiesBox::setupContent() {
_controller->setTryIPv6(checked);
}, _tryIPv6->lifetime());
+ const auto applyWebSocketDomain = [=] {
+ _controller->setWebSocketDomain(
+ _webSocketDomain->getLastText().trimmed());
+ };
+ _webSocket->checkedChanges(
+ ) | rpl::on_next([=](bool checked) {
+ _webSocketOptions->toggle(checked, anim::type::normal);
+ _controller->setWebSocketTransport(checked);
+ }, _webSocket->lifetime());
+ _webSocketMedia->checkedChanges(
+ ) | rpl::on_next([=](bool checked) {
+ _controller->setWebSocketMediaMultiplexing(checked);
+ }, _webSocketMedia->lifetime());
+
+ connect(
+ _webSocketDomain.data(),
+ &Ui::MaskedInputField::blurred,
+ applyWebSocketDomain);
+ connect(
+ _webSocketDomain.data(),
+ &Ui::MaskedInputField::submitted,
+ applyWebSocketDomain);
+
_controller->proxySettingsValue(
) | rpl::on_next([=](ProxyData::Settings value) {
_proxySettings->setValue(value);
@@ -2907,6 +2979,46 @@ void ProxiesBoxController::setTryIPv6(bool enabled) {
saveDelayed();
}
+void ProxiesBoxController::setWebSocketTransport(bool enabled) {
+ auto &option = base::options::lookup(
+ MTP::kOptionWebSocketTransport);
+ if (option.value() == enabled) {
+ return;
+ }
+ option.set(enabled);
+ Core::App().refreshGlobalProxy();
+ _account->mtp().restart();
+ _settings.connectionTypeChangesNotify();
+}
+
+void ProxiesBoxController::setWebSocketDomain(const QString &domain) {
+ auto &option = base::options::lookup(
+ MTP::kOptionWebSocketDomain);
+ if (option.value() == domain) {
+ return;
+ }
+ option.set(domain);
+ Core::App().refreshGlobalProxy();
+ if (base::options::value(MTP::kOptionWebSocketTransport)) {
+ _account->mtp().restart();
+ _settings.connectionTypeChangesNotify();
+ }
+}
+
+void ProxiesBoxController::setWebSocketMediaMultiplexing(bool enabled) {
+ auto &option = base::options::lookup(
+ MTP::kOptionWebSocketMediaMultiplexing);
+ if (option.value() == enabled) {
+ return;
+ }
+ option.set(enabled);
+ Core::App().refreshGlobalProxy();
+ if (base::options::value(MTP::kOptionWebSocketTransport)) {
+ _account->mtp().restart();
+ _settings.connectionTypeChangesNotify();
+ }
+}
+
void ProxiesBoxController::saveDelayed() {
Core::App().proxyRotationSettingsChanged();
_saveTimer.callOnce(kSaveSettingsDelayedTimeout);
diff --git a/Telegram/SourceFiles/boxes/connection_box.h b/Telegram/SourceFiles/boxes/connection_box.h
index 40e69d4d9bf39..2f7818a9582c5 100644
--- a/Telegram/SourceFiles/boxes/connection_box.h
+++ b/Telegram/SourceFiles/boxes/connection_box.h
@@ -95,6 +95,9 @@ class ProxiesBoxController {
void setProxyRotationEnabled(bool enabled);
void setProxyRotationTimeout(int value);
void setTryIPv6(bool enabled);
+ void setWebSocketTransport(bool enabled);
+ void setWebSocketDomain(const QString &domain);
+ void setWebSocketMediaMultiplexing(bool enabled);
rpl::producer proxySettingsValue() const;
[[nodiscard]] bool contains(const ProxyData &proxy) const;
diff --git a/Telegram/SourceFiles/boxes/delete_messages_box.cpp b/Telegram/SourceFiles/boxes/delete_messages_box.cpp
index d75a176f52d4f..e61f86d1e0524 100644
--- a/Telegram/SourceFiles/boxes/delete_messages_box.cpp
+++ b/Telegram/SourceFiles/boxes/delete_messages_box.cpp
@@ -160,7 +160,7 @@ void DeleteMessagesBox::prepare() {
_revoke.create(
this,
revoke->checkbox,
- false,
+ true,
st::defaultBoxCheckbox);
appendDetails(std::move(revoke->description));
if (!peer->isUser() && !_wipeHistoryJustClear) {
diff --git a/Telegram/SourceFiles/boxes/edit_caption_box.cpp b/Telegram/SourceFiles/boxes/edit_caption_box.cpp
index 04ef598b440dd..3e4470a1dd354 100644
--- a/Telegram/SourceFiles/boxes/edit_caption_box.cpp
+++ b/Telegram/SourceFiles/boxes/edit_caption_box.cpp
@@ -37,6 +37,7 @@ For license and copyright information please follow this link:
#include "editor/photo_editor_layer_widget.h"
#include "history/view/controls/history_view_compose_ai_button.h"
#include "history/history.h"
+#include "forkgram/link_replacements.h"
#include "history/history_drag_area.h"
#include "history/history_item.h"
#include "lang/lang_keys.h"
@@ -619,7 +620,7 @@ void EditCaptionBox::setupField() {
) | rpl::on_next([=] {
captionResized();
}, _field->lifetime());
- _field->setMimeDataHook([=](
+ _field->setMimeDataHook(Forkgram::LinkReplacements::WrappedMimeHook([=](
not_null data,
Ui::InputField::MimeAction action) {
if (action == Ui::InputField::MimeAction::Check) {
@@ -633,7 +634,7 @@ void EditCaptionBox::setupField() {
return fileFromClipboard(data);
}
Unexpected("Action in MimeData hook.");
- });
+ }, _field.get()));
_aiButton = Ui::SetupCaptionAiButton({
.parent = this,
@@ -1088,7 +1089,9 @@ void EditCaptionBox::setupEmojiPanel() {
};
_emojiFilter.reset(base::install_event_filter(container, filterCallback));
+ if (!Core::App().settings().fork().emojiPopupOnClick()) {
_emojiToggle->installEventFilter(_emojiPanel);
+ }
_emojiToggle->addClickHandler([=] {
_emojiPanel->toggleAnimated();
});
diff --git a/Telegram/SourceFiles/boxes/moderate_messages_box.cpp b/Telegram/SourceFiles/boxes/moderate_messages_box.cpp
index 52c843222cd6b..a610308467349 100644
--- a/Telegram/SourceFiles/boxes/moderate_messages_box.cpp
+++ b/Telegram/SourceFiles/boxes/moderate_messages_box.cpp
@@ -461,6 +461,7 @@ void CreateModerateMessagesBox(
const auto &items = entry.items;
const auto reaction = entry.reaction;
Expects(!items.empty() || reaction.has_value());
+ box->setLayerAnimationDuration(kModerateMessagesBoxAnimationDuration);
box->setLayerAnimationDuration(kModerateMessagesBoxAnimationDuration);
diff --git a/Telegram/SourceFiles/boxes/peers/edit_peer_invite_link.cpp b/Telegram/SourceFiles/boxes/peers/edit_peer_invite_link.cpp
index 02a7b683066f9..d1f0b27a22443 100644
--- a/Telegram/SourceFiles/boxes/peers/edit_peer_invite_link.cpp
+++ b/Telegram/SourceFiles/boxes/peers/edit_peer_invite_link.cpp
@@ -1474,6 +1474,7 @@ object_ptr ShareInviteLinkBox(
.countMessagesCallback = std::move(countMessagesCallback),
.submitCallback = std::move(submitCallback),
.filterCallback = std::move(filterCallback),
+ .asCopyCallback = nullptr,
.moneyRestrictionError = ShareMessageMoneyRestrictionError(),
});
*box = base::make_weak(object.data());
diff --git a/Telegram/SourceFiles/boxes/send_files_box.cpp b/Telegram/SourceFiles/boxes/send_files_box.cpp
index 01132879dbe0a..c2b012b263e7d 100644
--- a/Telegram/SourceFiles/boxes/send_files_box.cpp
+++ b/Telegram/SourceFiles/boxes/send_files_box.cpp
@@ -53,6 +53,7 @@ For license and copyright information please follow this link:
#include "storage/localstorage.h"
#include "storage/storage_folder_archive.h"
#include "storage/storage_media_prepare.h"
+#include "forkgram/link_replacements.h"
#include "ui/boxes/time_picker_box.h"
#include "ui/chat/attach/attach_album_preview.h"
#include "ui/chat/attach/attach_single_file_preview.h"
@@ -2218,6 +2219,16 @@ void SendFilesBox::setupSendWayControls() {
== _sendWay.current().sendImagesAsPhotos()))
? Core::App().settings().sendFilesWay().sendImagesAsPhotos()
: _sendWay.current().sendImagesAsPhotos();
+
+ if ((_list.files.size() == 1)
+ && _list.files.front().path.endsWith(".ogg")) {
+ _sendAsVoice.create(
+ this,
+ u"Send first as Voice"_q,
+ false,
+ _st.files.checkbox,
+ _st.files.check);
+ }
_groupFiles.create(
this,
tr::lng_send_grouped(tr::now),
@@ -2387,7 +2398,7 @@ void SendFilesBox::setupCaption() {
requestToTakeTextWithTags();
closeBox();
}, _caption->lifetime());
- _caption->setMimeDataHook([=](
+ _caption->setMimeDataHook(Forkgram::LinkReplacements::WrappedMimeHook([=](
not_null data,
Ui::InputField::MimeAction action) {
if (action == Ui::InputField::MimeAction::Check) {
@@ -2396,7 +2407,7 @@ void SendFilesBox::setupCaption() {
return addFiles(data);
}
Unexpected("action in MimeData hook.");
- });
+ }, _caption.data()));
updateCaptionVisibility();
setupEmojiPanel();
@@ -2550,7 +2561,9 @@ void SendFilesBox::setupEmojiPanel() {
_emojiToggle.create(this, _st.files.emoji);
_emojiToggle->setVisible(!_caption->isHidden());
+ if (!Core::App().settings().fork().emojiPopupOnClick()) {
_emojiToggle->installEventFilter(_emojiPanel);
+ }
_emojiToggle->addClickHandler([=] {
_emojiPanel->toggleAnimated();
});
@@ -2727,11 +2740,12 @@ void SendFilesBox::updateBoxSize() {
footerHeight += st::boxPhotoCaptionSkip + _caption->height();
}
footerHeight += _replyHeaderHeight.current();
- const auto pairs = std::array, 4>{ {
+ const auto pairs = std::array, 5>{ {
{ _groupFiles.data(), st::boxPhotoCompressedSkip },
{ _sendImagesAsPhotos.data(), st::boxPhotoCompressedSkip },
{ _wayRemember.data(), st::boxPhotoCompressedSkip },
{ _hintLabel.data(), st::editMediaLabelMargins.top() },
+ { _sendAsVoice.data(), st::boxPhotoCompressedSkip },
} };
for (const auto &pair : pairs) {
const auto pointer = pair.first;
@@ -2801,11 +2815,12 @@ void SendFilesBox::updateControlsGeometry() {
_aiButton->raise();
}
}
- const auto pairs = std::array, 4>{ {
+ const auto pairs = std::array, 5>{ {
{ _hintLabel.data(), st::editMediaLabelMargins.top() },
{ _groupFiles.data(), st::boxPhotoCompressedSkip },
{ _sendImagesAsPhotos.data(), st::boxPhotoCompressedSkip },
{ _wayRemember.data(), st::boxPhotoCompressedSkip },
+ { _sendAsVoice.data(), st::boxPhotoCompressedSkip },
} };
for (const auto &pair : ranges::views::reverse(pairs)) {
const auto pointer = pair.first;
@@ -2915,7 +2930,7 @@ void SendFilesBox::send(
return;
}
- const auto way = _sendWay.current();
+ auto way = _sendWay.current();
if (ranges::any_of(_list.files, &Ui::PreparedFile::sendAsVoice)) {
if ((_limits & SendFilesAllow::OnlyOne)
&& !_list.canBeSentInSlowmode()) {
@@ -2983,6 +2998,9 @@ void SendFilesBox::send(
Assert(_list.filesToProcess.empty());
+ if (_sendAsVoice && _sendAsVoice->checked()) {
+ way.asVoice = true;
+ }
auto groupsWay = way;
if (ranges::any_of(_list.files, &Ui::PreparedFile::ttlSeconds)) {
groupsWay.setGroupFiles(false);
diff --git a/Telegram/SourceFiles/boxes/send_files_box.h b/Telegram/SourceFiles/boxes/send_files_box.h
index a3cd8da10d8c5..d5a87d0977ed8 100644
--- a/Telegram/SourceFiles/boxes/send_files_box.h
+++ b/Telegram/SourceFiles/boxes/send_files_box.h
@@ -359,6 +359,7 @@ class SendFilesBox : public Ui::BoxContent {
object_ptr _groupFiles = { nullptr };
object_ptr _sendImagesAsPhotos = { nullptr };
object_ptr _wayRemember = { nullptr };
+ object_ptr _sendAsVoice = { nullptr };
object_ptr _hintLabel = { nullptr };
rpl::variable _sendWay = Ui::SendFilesWay();
diff --git a/Telegram/SourceFiles/boxes/share_box.cpp b/Telegram/SourceFiles/boxes/share_box.cpp
index ad27521088583..b7884663c8939 100644
--- a/Telegram/SourceFiles/boxes/share_box.cpp
+++ b/Telegram/SourceFiles/boxes/share_box.cpp
@@ -9,6 +9,8 @@ For license and copyright information please follow this link:
#include "api/api_premium.h"
#include "apiwrap.h"
+#include "api/api_sending.h"
+#include "api/api_as_copy.h"
#include "base/call_delayed.h"
#include "base/qthelp_url.h"
#include "base/random.h"
@@ -49,6 +51,7 @@ For license and copyright information please follow this link:
#include "menu/menu_check_item.h"
#include "menu/menu_send.h"
#include "settings/sections/settings_premium.h"
+#include "base/qt/qt_key_modifiers.h"
#include "storage/localimageloader.h"
#include "storage/storage_account.h"
#include "storage/storage_media_prepare.h"
@@ -69,6 +72,7 @@ For license and copyright information please follow this link:
#include "ui/ui_utility.h"
#include "window/window_session_controller.h"
+#include "window/window_controller.h"
#include "styles/style_boxes.h"
#include "styles/style_calls.h"
#include "styles/style_chat_helpers.h"
@@ -736,6 +740,22 @@ void ShareBox::showMenu(not_null parent) {
}
void ShareBox::createButtons() {
+ const auto asCopyShare = [=](bool emptyText, TimeId scheduled) {
+ if (!_descriptor.asCopyCallback) {
+ return;
+ }
+ const auto selected = _inner->selected();
+ _descriptor.asCopyCallback(
+ ranges::views::all(
+ selected
+ ) | ranges::views::transform(
+ &Data::Thread::peer
+ ) | ranges::to_vector,
+ _comment->entity()->getTextWithAppliedMarkdown(),
+ emptyText,
+ scheduled);
+ closeBox();
+ };
clearButtons();
if (_topics && !_topics->community()) {
addButton(tr::lng_create_group_back(), [=] { _topics->dismiss(); });
@@ -760,6 +780,21 @@ void ShareBox::createButtons() {
send->setText(PaidSendButtonText(
_starsToSend.value(),
tr::lng_share_confirm()));
+ addButton(tr::lng_share_as_copy(), [=] { asCopyShare(false, 0); });
+ addButton(tr::lng_share_as_copy_no_text(), [=] { asCopyShare(true, 0); });
+ addTopButton(st::historyScheduledToggle, [=] {
+ const auto window = Core::App().findWindow(this);
+ const auto controller = window ? window->sessionController() : nullptr;
+ if (!controller) {
+ return;
+ }
+ uiShow()->show(
+ HistoryView::PrepareScheduleBox(
+ this,
+ controller->uiShow(),
+ SendMenu::Details(),
+ [=](Api::SendOptions options) { asCopyShare(false, options.scheduled); }));
+ });
} else if (_descriptor.copyCallback) {
addButton(_copyLinkText.value(), [=] { copyLink(); });
}
@@ -1676,7 +1711,11 @@ void ShareBox::Inner::paintStoryRepost(Painter &p) {
});
p.setPen(Qt::NoPen);
p.setBrush(gradient);
- p.drawEllipse(circleRect);
+ if (style::SquareUserpics()) {
+ p.drawRect(circleRect);
+ } else {
+ p.drawEllipse(circleRect);
+ }
if (_storyRepostLottie) {
_storyRepostLottie->paintInCenter(p, circleRect);
@@ -2408,6 +2447,40 @@ void FastShareMessage(
}
};
+ auto asCopyCallback = [=, msgIds = owner->itemOrItsGroup(item)](
+ std::vector> &&result,
+ TextWithTags &&comment,
+ bool emptyText,
+ TimeId scheduled) {
+ auto toSend = Api::AsCopy::ToSend{
+ .peers = std::move(result),
+ .comment = std::move(comment),
+ .emptyText = emptyText,
+ .silent = QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier),
+ .scheduled = scheduled,
+ };
+ const auto toast = (toSend.silent && toSend.scheduled)
+ ? u"Silently scheduled."_q
+ : toSend.silent
+ ? u"Silently."_q
+ : toSend.scheduled
+ ? u"Scheduled."_q
+ : QString();
+ if (!toast.isEmpty()) {
+ show->showToast(toast);
+ }
+ if (item->groupId()) {
+ Api::AsCopy::GuardedSendExistingAlbumFromItem(item, std::move(toSend));
+ } else if (const auto i = history->owner().message(msgIds[0])) {
+ Api::AsCopy::UpdateFileRef(
+ { i },
+ [=, toSend = std::move(toSend)] {
+ Api::AsCopy::SendExistingMediaFromItem(i, base::duplicate(toSend));
+ },
+ [=](QString a) { show->showToast(a); });
+ }
+ };
+
const auto requiredRight = item->requiredSendRight();
const auto requiresInline = item->requiresSendInlineRight();
auto filterCallback = [=](not_null thread) {
@@ -2435,6 +2508,7 @@ void FastShareMessage(
history,
msgIds),
.filterCallback = std::move(filterCallback),
+ .asCopyCallback = std::move(asCopyCallback),
.st = st,
.forwardOptions = {
.sendersCount = ItemsForwardSendersCount(items),
diff --git a/Telegram/SourceFiles/boxes/share_box.h b/Telegram/SourceFiles/boxes/share_box.h
index 0826541ea24f1..3d0fa8c9a6704 100644
--- a/Telegram/SourceFiles/boxes/share_box.h
+++ b/Telegram/SourceFiles/boxes/share_box.h
@@ -111,6 +111,11 @@ class ShareBox final : public Ui::BoxContent {
TextWithTags&&,
Api::SendOptions,
Data::ForwardOptions)>;
+ using AsCopyCallback = Fn>&&,
+ TextWithTags&&,
+ bool emptyText,
+ TimeId scheduled)>;
using FilterCallback = Fn)>;
[[nodiscard]] static auto DefaultForwardCountMessages(
@@ -128,6 +133,7 @@ class ShareBox final : public Ui::BoxContent {
CountMessagesCallback countMessagesCallback;
SubmitCallback submitCallback;
FilterCallback filterCallback;
+ AsCopyCallback asCopyCallback;
Fn repostStoryCallback;
object_ptr bottomWidget = { nullptr };
rpl::producer copyLinkText;
diff --git a/Telegram/SourceFiles/calls/calls.style b/Telegram/SourceFiles/calls/calls.style
index 2f5883b097f29..316d00c4568a3 100644
--- a/Telegram/SourceFiles/calls/calls.style
+++ b/Telegram/SourceFiles/calls/calls.style
@@ -587,6 +587,16 @@ callTitle: WindowTitle(defaultWindowTitle) {
}
closeIconActive: callTitleCloseIcon;
closeIconActiveOver: callTitleCloseIconOver;
+
+ // Dummy values.
+ top: IconButton(callTitleButton) {
+ }
+ topIconActive: callTitleMinimizeIcon;
+ topIconActiveOver: callTitleMinimizeIcon;
+ top2Icon: callTitleMinimizeIcon;
+ top2IconOver: callTitleMinimizeIcon;
+ top2IconActive: callTitleMinimizeIcon;
+ top2IconActiveOver: callTitleMinimizeIcon;
}
callTitleShadowRight: icon {{ "calls/calls_shadow_controls", windowShadowFg }};
callTitleShadowLeft: icon {{ "calls/calls_shadow_controls-flip_horizontal", windowShadowFg }};
@@ -1311,6 +1321,16 @@ groupCallTitle: WindowTitle(defaultWindowTitle) {
}
closeIconActive: groupCallTitleCloseIcon;
closeIconActiveOver: groupCallTitleCloseIconOver;
+
+ // Dummy values.
+ top: IconButton(callTitleButton) {
+ }
+ topIconActive: callTitleMinimizeIcon;
+ topIconActiveOver: callTitleMinimizeIcon;
+ top2Icon: callTitleMinimizeIcon;
+ top2IconOver: callTitleMinimizeIcon;
+ top2IconActive: callTitleMinimizeIcon;
+ top2IconActiveOver: callTitleMinimizeIcon;
}
groupCallPinOnTop: IconButton(groupCallMenuToggle) {
icon: icon{{ "calls/navbar_pin", groupCallMemberNotJoinedStatus }};
diff --git a/Telegram/SourceFiles/calls/calls_window.cpp b/Telegram/SourceFiles/calls/calls_window.cpp
index 3277fdf1a989e..caa515e98dc5e 100644
--- a/Telegram/SourceFiles/calls/calls_window.cpp
+++ b/Telegram/SourceFiles/calls/calls_window.cpp
@@ -95,6 +95,21 @@ Window::Window()
_controlsTop.value()))
#endif // !Q_OS_MACOS
{
+#ifdef Q_OS_WIN
+ // RpWindow on Windows goes through Platform::WindowHelper, which
+ // owns its own TitleWidget that normally replaces the native frame.
+ // The call window adds SeparateTitleControls on top of the body, so
+ // without stripping the helper's title bar we end up rendering two
+ // stacked title rows. Opt out of the helper's internal Frameless
+ // flag management (on pre-Win8 it ties Qt::FramelessWindowHint to
+ // the TitleWidget's visibility: hidden title => native frame, which
+ // is the opposite of what we want), then hide the helper title and
+ // drive FramelessWindowHint explicitly - final state: frameless,
+ // helper title hidden, separate controls as the only title bar.
+ window()->setManualFramelessOwned(true);
+ window()->setNativeFrame(true);
+ window()->setWindowFlag(Qt::FramelessWindowHint);
+#endif // Q_OS_WIN
_layerBg->setStyleOverrides(&st::groupCallBox, &st::groupCallLayerBox);
_layerBg->setHideByBackgroundClick(true);
}
diff --git a/Telegram/SourceFiles/calls/group/calls_group_call.cpp b/Telegram/SourceFiles/calls/group/calls_group_call.cpp
index 0f3c31dc98803..df2ec6af8cf70 100644
--- a/Telegram/SourceFiles/calls/group/calls_group_call.cpp
+++ b/Telegram/SourceFiles/calls/group/calls_group_call.cpp
@@ -587,6 +587,11 @@ GroupCall::GroupCall(
}
void GroupCall::processConferenceStart(StartConferenceInfo conference) {
+#ifdef DESKTOP_APP_DISABLE_WEBVIEW2
+ // Win7 debug: skip conference start to avoid crash in
+ // rpl::event_stream null consumer / GroupCall initialization.
+ return;
+#endif // DESKTOP_APP_DISABLE_WEBVIEW2
if (!conference.videoCapture) {
return;
}
diff --git a/Telegram/SourceFiles/chat_helpers/chat_helpers.style b/Telegram/SourceFiles/chat_helpers/chat_helpers.style
index 85d0ea422542b..2443ae93d1249 100644
--- a/Telegram/SourceFiles/chat_helpers/chat_helpers.style
+++ b/Telegram/SourceFiles/chat_helpers/chat_helpers.style
@@ -1203,6 +1203,13 @@ historyPinnedShowAll: IconButton(historyReplyCancel) {
icon: icon {{ "pinned_show_all", historyReplyCancelFg }};
iconOver: icon {{ "pinned_show_all", historyReplyCancelFgOver }};
}
+historyForkExtractMediaIcon: icon {{ "chat/input_replace", historyReplyCancelFg }};
+historyForkExtractMediaIconOver: icon {{ "chat/input_replace", historyReplyCancelFgOver }};
+historyForkExtractMediaActiveIcon: icon {{ "chat/input_replace", windowActiveTextFg }};
+historyForkExtractMedia: IconButton(historyReplyCancel) {
+ icon: historyForkExtractMediaIcon;
+ iconOver: historyForkExtractMediaIconOver;
+}
sendFilesReplyIconPosition: point(11px, 7px);
sendFilesReplyCancelSize: 24px;
sendFilesReplyCancel: IconButton(editMediaButton) {
diff --git a/Telegram/SourceFiles/chat_helpers/message_field.cpp b/Telegram/SourceFiles/chat_helpers/message_field.cpp
index 6617322e7e1c9..a48c666f55c2b 100644
--- a/Telegram/SourceFiles/chat_helpers/message_field.cpp
+++ b/Telegram/SourceFiles/chat_helpers/message_field.cpp
@@ -22,10 +22,11 @@ For license and copyright information please follow this link:
#include "data/data_session.h"
#include "data/data_user.h"
#include "history/view/controls/compose_controls_common.h"
+#include "forkgram/link_replacements.h"
+#include "history/history_widget.h"
#include "history/history.h" // History::session
#include "history/history_item.h" // HistoryItem::originalText
#include "history/history_item_helpers.h" // DropDisallowedCustomEmoji
-#include "history/history_widget.h"
#include "info/profile/info_profile_icon.h"
#include "lang/lang_keys.h"
#include "lottie/lottie_icon.h"
@@ -757,6 +758,27 @@ void InitSpellchecker(
field.get(),
Core::App().settings().spellcheckerEnabledValue(),
menuItem);
+
+ // Add wrong keyboard layout fixer.
+ base::install_event_filter(field.get(), [=](not_null e) {
+ if (e->type() != QEvent::KeyPress) {
+ return base::EventFilterResult::Continue;
+ }
+ const auto k = static_cast(e.get());
+ const auto rightBracket = (k->key() == Qt::Key_BracketRight)
+ || (k->key() == 1066);
+ if (rightBracket
+ && k->modifiers().testFlag(Qt::ControlModifier)) {
+ const auto text = field->getLastText();
+ const auto translatedString = rusKeyboardLayoutSwitch(text);
+ if (text != translatedString) {
+ field->setTextWithTags(
+ { translatedString, TextWithTags::Tags() });
+ return base::EventFilterResult::Cancel;
+ }
+ }
+ return base::EventFilterResult::Continue;
+ });
}
bool HasSendText(not_null field) {
@@ -1710,7 +1732,7 @@ void FrozenInfoBox(
Ui::InputField::MimeDataHook WrappedMessageFieldMimeHook(
Ui::InputField::MimeDataHook original,
not_null field) {
- return [field, originalHook = std::move(original)](
+ auto hook = [field, originalHook = std::move(original)](
not_null data,
Ui::InputField::MimeAction action) {
if (data->hasFormat(u"application/x-telegram-input-field"_q)) {
@@ -1724,6 +1746,9 @@ Ui::InputField::MimeDataHook WrappedMessageFieldMimeHook(
}
return originalHook ? originalHook(data, action) : false;
};
+ return Forkgram::LinkReplacements::WrappedMimeHook(
+ std::move(hook),
+ field);
}
bool PasteAsPlainTextRequested() {
diff --git a/Telegram/SourceFiles/chat_helpers/stickers_list_widget.cpp b/Telegram/SourceFiles/chat_helpers/stickers_list_widget.cpp
index 309e32d0e6af5..3fe6678430935 100644
--- a/Telegram/SourceFiles/chat_helpers/stickers_list_widget.cpp
+++ b/Telegram/SourceFiles/chat_helpers/stickers_list_widget.cpp
@@ -10,14 +10,14 @@ For license and copyright information please follow this link:
#include "api/api_premium.h"
#include "api/api_toggling_media.h" // Api::ToggleFavedSticker
#include "apiwrap.h"
-#include "base/platform/base_platform_info.h"
+#include "core/core_settings.h"
#include "base/options.h"
-#include "base/random.h"
#include "base/timer_rpl.h"
+#include "base/platform/base_platform_info.h"
+#include "base/random.h"
#include "boxes/share_box.h"
#include "boxes/sticker_set_box.h"
#include "boxes/stickers_box.h"
-#include "boxes/stickers_box.h"
#include "chat_helpers/stickers_list_footer.h"
#include "chat_helpers/stickers_lottie.h"
#include "core/application.h"
@@ -3814,7 +3814,7 @@ auto StickersListWidget::collectRecentStickers() -> std::vector {
auto add = [&](not_null document, bool custom) {
if (result.size() >= kRecentDisplayLimit
- && !OptionUnlimitedRecentStickers.value()) {
+ && (!OptionUnlimitedRecentStickers.value() || !Core::App().settings().fork().allRecentStickers())) {
return;
}
const auto i = ranges::find(result, document, &Sticker::document);
diff --git a/Telegram/SourceFiles/core/application.cpp b/Telegram/SourceFiles/core/application.cpp
index ac895b29ae71e..d7117999dd1ff 100644
--- a/Telegram/SourceFiles/core/application.cpp
+++ b/Telegram/SourceFiles/core/application.cpp
@@ -71,6 +71,7 @@ For license and copyright information please follow this link:
#include "mtproto/mtproto_dc_options.h"
#include "mtproto/mtproto_config.h"
#include "mtproto/web_proxy/web_proxy_transport.h"
+#include "mtproto/websocket_relays.h"
#include "speech/speech_catalog.h"
#include "media/audio/media_audio_track.h"
#include "media/player/media_player_instance.h"
@@ -451,16 +452,15 @@ void Application::run() {
}
}, _lifetime);
- DEBUG_LOG(("Application Info: window created..."));
-
startDomain();
+ style::SetSquareUserpics(settings().fork().squareUserpics());
+
startTray();
_lastActivePrimaryWindow->firstShow();
startMediaView();
- DEBUG_LOG(("Application Info: showing."));
_lastActivePrimaryWindow->finishFirstShow();
if (!_lastActivePrimaryWindow->locked() && cStartToSettings()) {
@@ -563,7 +563,6 @@ void Application::showOpenGLCrashNotification() {
void Application::startDomain() {
const auto state = _domain->start(QByteArray());
if (state != Storage::StartResult::IncorrectPasscodeLegacy) {
- // In case of non-legacy passcoded app all global settings are ready.
startSettingsAndBackground();
}
if (state != Storage::StartResult::Success) {
@@ -2116,6 +2115,11 @@ void Application::refreshGlobalProxy() {
MTP::WebProxy::Transport::Deactivate();
}
Sandbox::Instance().refreshGlobalProxy();
+
+ auto &relays = MTP::WebSocketRelays::Instance();
+ relays.applyConfig();
+
+ relays.refresh();
}
void QuitAttempt() {
diff --git a/Telegram/SourceFiles/core/core_settings.cpp b/Telegram/SourceFiles/core/core_settings.cpp
index a37fc6f5b0b85..c72e1735b6256 100644
--- a/Telegram/SourceFiles/core/core_settings.cpp
+++ b/Telegram/SourceFiles/core/core_settings.cpp
@@ -418,6 +418,20 @@ QByteArray Settings::serialize() const {
+ Serialize::stringSize(translateToCode)
+ sizeof(qint32); // _sendSilentByDefault
+ // Fork Settings.
+ size += sizeof(qint32);
+ size += sizeof(qint32);
+ size += sizeof(qint32);
+ size += sizeof(qint32);
+ size += Serialize::stringSize(QString());
+ size += Serialize::stringSize(QString());
+ size += sizeof(qint32);
+ size += sizeof(qint32);
+ size += sizeof(qint32);
+ size += sizeof(qint32);
+ size += sizeof(qint32);
+ //
+
auto result = QByteArray();
result.reserve(size);
{
@@ -462,6 +476,19 @@ QByteArray Settings::serialize() const {
<< qint32(_largeEmoji.current() ? 1 : 0)
<< qint32(_replaceEmoji.current() ? 1 : 0)
<< qint32(_suggestEmoji ? 1 : 0)
+ // Fork Settings.
+ << qint32(0)
+ << qint32(0)
+ << qint32(0)
+ << qint32(0)
+ << QString()
+ << QString()
+ << qint32(0)
+ << qint32(0)
+ << qint32(0)
+ << qint32(0)
+ << qint32(0)
+ //
<< qint32(_suggestStickersByEmoji ? 1 : 0)
<< qint32(_spellcheckerEnabled.current() ? 1 : 0)
<< qint32(SerializePlaybackSpeed(_videoPlaybackSpeed))
@@ -619,6 +646,19 @@ void Settings::addFromSerialized(
QDataStream stream(serialized);
stream.setVersion(QDataStream::Qt_5_1);
+ // Old.
+ qint32 squareUserpics = 0;
+ qint32 audioFade = 0;
+ qint32 askUriScheme = 0;
+ qint32 lastSeenInDialogs = 0;
+ QString uriScheme = {};
+ QString searchEngineUrl = {};
+ qint32 searchEngine = 0;
+ qint32 allRecentStickers = 0;
+ qint32 customStickerSize = 0;
+ qint32 useBlackTrayIcon = 0;
+ qint32 useOriginalTrayIcon = 0;
+
QByteArray themesAccentColors;
qint32 adaptiveForWide = _adaptiveForWide.current() ? 1 : 0;
qint32 moderateModeEnabled = _moderateModeEnabled ? 1 : 0;
@@ -799,6 +839,19 @@ void Settings::addFromSerialized(
>> largeEmoji
>> replaceEmoji
>> suggestEmoji
+ // Old Fork Settings.
+ >> squareUserpics
+ >> audioFade
+ >> askUriScheme
+ >> lastSeenInDialogs
+ >> uriScheme
+ >> searchEngineUrl
+ >> searchEngine
+ >> allRecentStickers
+ >> customStickerSize
+ >> useBlackTrayIcon
+ >> useOriginalTrayIcon
+ //
>> suggestStickersByEmoji
>> spellcheckerEnabled
>> videoPlaybackSpeed
@@ -1310,6 +1363,20 @@ void Settings::addFromSerialized(
}
_autoDownloadDictionaries = (autoDownloadDictionaries == 1);
_mainMenuAccountsShown = (mainMenuAccountsShown == 1);
+
+ // Old.
+ _forkSettings.setSquareUserpics(squareUserpics == 1);
+ _forkSettings.setAudioFade(audioFade == 1);
+ _forkSettings.setAskUriScheme(askUriScheme == 1);
+ _forkSettings.setLastSeenInDialogs(lastSeenInDialogs == 1);
+ _forkSettings.setUriScheme(uriScheme);
+ _forkSettings.setSearchEngineUrl(searchEngineUrl);
+ _forkSettings.setSearchEngine(searchEngine == 1);
+ _forkSettings.setAllRecentStickers(allRecentStickers == 1);
+ _forkSettings.setCustomStickerSize(customStickerSize);
+ _forkSettings.setUseBlackTrayIcon(useBlackTrayIcon == 1);
+ _forkSettings.setUseOriginalTrayIcon(useOriginalTrayIcon == 1);
+
_tabbedSelectorSectionEnabled = (tabbedSelectorSectionEnabled == 1);
auto uncheckedColumn = static_cast(floatPlayerColumn);
switch (uncheckedColumn) {
@@ -1844,6 +1911,8 @@ void Settings::setLegacyEmojiVariants(QMap data) {
}
void Settings::resetOnLastLogout() {
+ _forkSettings.resetOnLastLogout();
+
_adaptiveForWide = true;
_moderateModeEnabled = false;
diff --git a/Telegram/SourceFiles/core/core_settings.h b/Telegram/SourceFiles/core/core_settings.h
index da3a87f3cefef..44d567ae949e4 100644
--- a/Telegram/SourceFiles/core/core_settings.h
+++ b/Telegram/SourceFiles/core/core_settings.h
@@ -16,6 +16,8 @@ For license and copyright information please follow this link:
#include "base/flags.h"
#include "emoji.h"
+#include "core/fork_settings.h"
+
enum class RectPart;
struct LanguageId;
@@ -138,6 +140,10 @@ class Settings final {
Settings();
~Settings();
+ [[nodiscard]] ForkSettings &fork() {
+ return _forkSettings;
+ }
+
[[nodiscard]] rpl::producer<> saveDelayedRequests() const {
return _saveDelayed.events();
}
@@ -1067,6 +1073,8 @@ class Settings final {
[[nodiscard]] std::optional readPrefGeneric(
std::string_view key);
+ ForkSettings _forkSettings;
+
static constexpr auto kDefaultThirdColumnWidth = 0;
static constexpr auto kDefaultDialogsWidthRatio = 5. / 14;
static constexpr auto kDefaultBigDialogsWidthRatio = 0.275;
diff --git a/Telegram/SourceFiles/core/deep_links/deep_links_settings.cpp b/Telegram/SourceFiles/core/deep_links/deep_links_settings.cpp
index 6750b8405e629..851cfa2b57977 100644
--- a/Telegram/SourceFiles/core/deep_links/deep_links_settings.cpp
+++ b/Telegram/SourceFiles/core/deep_links/deep_links_settings.cpp
@@ -47,6 +47,7 @@ For license and copyright information please follow this link:
#include "settings/sections/settings_calls.h"
#include "settings/sections/settings_chat.h"
#include "settings/sections/settings_passkeys.h"
+#include "settings/sections/settings_fork.h"
#include "data/components/passkeys.h"
#include "calls/calls_box_controller.h"
#include "settings/sections/settings_credits.h"
diff --git a/Telegram/SourceFiles/core/fork_settings.cpp b/Telegram/SourceFiles/core/fork_settings.cpp
new file mode 100644
index 0000000000000..10066c912c7bf
--- /dev/null
+++ b/Telegram/SourceFiles/core/fork_settings.cpp
@@ -0,0 +1,283 @@
+/*
+Author: 23rd.
+*/
+#include "core/fork_settings.h"
+
+#include "storage/serialize_common.h"
+
+namespace Core {
+
+namespace {
+
+constexpr auto kDefaultStickerSize = 256;
+
+bool StaticHideFromBlockedUsers = false;
+
+} // namespace
+
+ForkSettings::ForkSettings() {
+}
+
+bool ForkSettings::HideFromBlockedUsers() {
+ return StaticHideFromBlockedUsers;
+}
+
+QByteArray ForkSettings::serialize() const {
+
+ auto size = sizeof(qint32) * 4
+ + Serialize::stringSize(_uriScheme)
+ + Serialize::stringSize(_searchEngineUrl)
+ + sizeof(qint32) * 13
+ + sizeof(qint32) * 2
+ + Serialize::stringSize(_botsPlatforms);
+
+ auto result = QByteArray();
+ result.reserve(size);
+ {
+ QDataStream stream(&result, QIODevice::WriteOnly);
+ stream.setVersion(QDataStream::Qt_5_1);
+ stream
+ << qint32(_squareUserpics ? 1 : 0)
+ << qint32(_audioFade ? 1 : 0)
+ << qint32(_askUriScheme ? 1 : 0)
+ << qint32(_lastSeenInDialogs ? 1 : 0)
+ << _uriScheme
+ << _searchEngineUrl
+ << qint32(_searchEngine ? 1 : 0)
+ << qint32(_allRecentStickers ? 1 : 0)
+ << qint32(_customStickerSize)
+ << qint32(_useBlackTrayIcon ? 1 : 0)
+ << qint32(_useOriginalTrayIcon ? 1 : 0)
+ << qint32(_autoSubmitPasscode ? 1 : 0)
+ << qint32(_emojiPopupOnClick ? 1 : 0)
+ << qint32(0) // Vacant slot (was _mentionByNameDisabled).
+ << qint32(0) // Vacant slot (was _primaryUnmutedMessages).
+ << qint32(_addToMenuRememberMedia ? 1 : 0)
+ << qint32(_hideAllChatsTab ? 1 : 0)
+ << qint32(_globalSearchDisabled ? 1 : 0)
+ << qint32(_thirdButtonTopBar ? 1 : 0)
+ << qint32(_skipShareFromBot ? 1 : 0)
+ << qint32(_copyLoginCode ? 1 : 0)
+ << qint32(_additionalButtonsWebBot ? 1 : 0)
+ << _botsPlatforms
+ << qint32(_archivedStoriesAreHidden ? 1 : 0)
+ << qint32(_hideFromBlockedUsers ? 1 : 0)
+ ;
+ }
+ return result;
+}
+
+void ForkSettings::addFromSerialized(const QByteArray &serialized) {
+ if (serialized.isEmpty()) {
+ return;
+ }
+
+ QDataStream stream(serialized);
+ stream.setVersion(QDataStream::Qt_5_1);
+
+ qint32 squareUserpics = _squareUserpics;
+ qint32 audioFade = _audioFade;
+ qint32 askUriScheme = _askUriScheme;
+ qint32 lastSeenInDialogs = _lastSeenInDialogs;
+ QString uriScheme = _uriScheme;
+ QString searchEngineUrl = _searchEngineUrl;
+ qint32 searchEngine = _searchEngine;
+ qint32 allRecentStickers = _allRecentStickers;
+ qint32 customStickerSize = _customStickerSize;
+ qint32 useBlackTrayIcon = _useBlackTrayIcon;
+ qint32 useOriginalTrayIcon = _useOriginalTrayIcon;
+ qint32 autoSubmitPasscode = _autoSubmitPasscode;
+ qint32 emojiPopupOnClick = _emojiPopupOnClick;
+ qint32 mentionByNameDisabled = 0; // Vacant slot.
+ qint32 primaryUnmutedMessages = 0; // Vacant slot.
+ qint32 addToMenuRememberMedia = _addToMenuRememberMedia;
+ qint32 hideAllChatsTab = _hideAllChatsTab;
+ qint32 globalSearchDisabled = _globalSearchDisabled;
+ qint32 thirdButtonTopBar = _thirdButtonTopBar;
+ qint32 skipShareFromBot = _skipShareFromBot;
+ qint32 copyLoginCode = _copyLoginCode;
+ qint32 additionalButtonsWebBot = _additionalButtonsWebBot;
+ qint32 archivedStoriesAreHidden = _archivedStoriesAreHidden;
+ qint32 hideFromBlockedUsers = _hideFromBlockedUsers;
+ QString botsPlatforms = _botsPlatforms;
+
+ if (!stream.atEnd()) {
+ stream
+ >> squareUserpics
+ >> audioFade
+ >> askUriScheme
+ >> lastSeenInDialogs
+ >> uriScheme
+ >> searchEngineUrl
+ >> searchEngine
+ >> allRecentStickers
+ >> customStickerSize
+ >> useBlackTrayIcon
+ >> useOriginalTrayIcon
+ >> autoSubmitPasscode
+ >> emojiPopupOnClick
+ >> mentionByNameDisabled
+ >> primaryUnmutedMessages
+ ;
+ }
+ if (!stream.atEnd()) {
+ stream >> addToMenuRememberMedia;
+ }
+ if (!stream.atEnd()) {
+ stream >> hideAllChatsTab;
+ }
+ if (!stream.atEnd()) {
+ stream >> globalSearchDisabled;
+ }
+ if (!stream.atEnd()) {
+ stream >> thirdButtonTopBar;
+ }
+ if (!stream.atEnd()) {
+ stream >> skipShareFromBot;
+ }
+ if (!stream.atEnd()) {
+ stream >> copyLoginCode;
+ }
+ if (!stream.atEnd()) {
+ stream >> additionalButtonsWebBot;
+ }
+ if (!stream.atEnd()) {
+ stream >> botsPlatforms;
+ }
+ if (!stream.atEnd()) {
+ stream >> archivedStoriesAreHidden;
+ }
+ if (!stream.atEnd()) {
+ stream >> hideFromBlockedUsers;
+ }
+ if (stream.status() != QDataStream::Ok) {
+ LOG(("App Error: "
+ "Bad data for Core::ForkSettings::constructFromSerialized()"));
+ return;
+ }
+ _squareUserpics = (squareUserpics == 1);
+ _audioFade = (audioFade == 1);
+ _askUriScheme = (askUriScheme == 1);
+ _lastSeenInDialogs = (lastSeenInDialogs == 1);
+ _uriScheme = std::move(uriScheme);
+ _searchEngineUrl = std::move(searchEngineUrl);
+ _searchEngine = (searchEngine == 1);
+ _allRecentStickers = (allRecentStickers == 1);
+ _customStickerSize = customStickerSize
+ ? std::clamp(customStickerSize, 50, kDefaultStickerSize)
+ : kDefaultStickerSize;
+ _useBlackTrayIcon = (useBlackTrayIcon == 1);
+ _useOriginalTrayIcon = (useOriginalTrayIcon == 1);
+ _autoSubmitPasscode = (autoSubmitPasscode == 1);
+ _emojiPopupOnClick = (emojiPopupOnClick == 1);
+ (void)mentionByNameDisabled; // Vacant slot.
+ (void)primaryUnmutedMessages; // Vacant slot.
+ _addToMenuRememberMedia = (addToMenuRememberMedia == 1);
+ _hideAllChatsTab = (hideAllChatsTab == 1);
+ _globalSearchDisabled = (globalSearchDisabled == 1);
+ _thirdButtonTopBar = (thirdButtonTopBar == 1);
+ _skipShareFromBot = (skipShareFromBot == 1);
+ _copyLoginCode = (copyLoginCode == 1);
+ _additionalButtonsWebBot = (additionalButtonsWebBot == 1);
+ _archivedStoriesAreHidden = (archivedStoriesAreHidden == 1);
+ setHideFromBlockedUsers(hideFromBlockedUsers == 1);
+ _botsPlatforms = std::move(botsPlatforms);
+}
+
+void ForkSettings::resetOnLastLogout() {
+ _squareUserpics = false;
+ _audioFade = true;
+ _askUriScheme = false;
+ _uriScheme = QString();
+ _lastSeenInDialogs = false;
+ _searchEngineUrl = qsl("https://dgg.gg/%q");
+ _searchEngine = false;
+ _allRecentStickers = true;
+ _customStickerSize = kDefaultStickerSize;
+ _useOriginalTrayIcon = false;
+ _autoSubmitPasscode = false;
+ _emojiPopupOnClick = false;
+ _addToMenuRememberMedia = false;
+ _hideAllChatsTab = false;
+ _globalSearchDisabled = false;
+ _thirdButtonTopBar = false;
+ _skipShareFromBot = false;
+ _copyLoginCode = false;
+ _additionalButtonsWebBot = false;
+ _archivedStoriesAreHidden = false;
+ setHideFromBlockedUsers(false);
+ _botsPlatforms = QString();
+}
+
+[[nodiscard]] bool ForkSettings::addToMenuRememberMedia() const {
+ return _addToMenuRememberMedia;
+}
+void ForkSettings::setAddToMenuRememberMedia(bool newValue) {
+ _addToMenuRememberMedia = newValue;
+}
+
+[[nodiscard]] bool ForkSettings::hideAllChatsTab() const {
+ return _hideAllChatsTab;
+}
+void ForkSettings::setHideAllChatsTab(bool newValue) {
+ _hideAllChatsTab = newValue;
+}
+
+[[nodiscard]] bool ForkSettings::globalSearchDisabled() const {
+ return _globalSearchDisabled;
+}
+void ForkSettings::setGlobalSearchDisabled(bool newValue) {
+ _globalSearchDisabled = newValue;
+}
+
+[[nodiscard]] bool ForkSettings::thirdButtonTopBar() const {
+ return _thirdButtonTopBar;
+}
+void ForkSettings::setThirdButtonTopBar(bool newValue) {
+ _thirdButtonTopBar = newValue;
+}
+
+[[nodiscard]] bool ForkSettings::skipShareFromBot() const {
+ return _skipShareFromBot;
+}
+void ForkSettings::setSkipShareFromBot(bool newValue) {
+ _skipShareFromBot = newValue;
+}
+
+[[nodiscard]] bool ForkSettings::copyLoginCode() const {
+ return _copyLoginCode;
+}
+void ForkSettings::setCopyLoginCode(bool newValue) {
+ _copyLoginCode = newValue;
+}
+
+[[nodiscard]] bool ForkSettings::additionalButtonsWebBot() const {
+ return _additionalButtonsWebBot;
+}
+void ForkSettings::setAdditionalButtonsWebBot(bool newValue) {
+ _additionalButtonsWebBot = newValue;
+}
+
+[[nodiscard]] QString ForkSettings::botsPlatforms() const {
+ return _botsPlatforms;
+}
+void ForkSettings::setBotsPlatforms(QString newValue) {
+ _botsPlatforms = std::move(newValue);
+}
+
+[[nodiscard]] bool ForkSettings::archivedStoriesAreHidden() const {
+ return _archivedStoriesAreHidden;
+}
+void ForkSettings::setArchivedStoriesAreHidden(bool newValue) {
+ _archivedStoriesAreHidden = newValue;
+}
+
+[[nodiscard]] bool ForkSettings::hideFromBlockedUsers() const {
+ return _hideFromBlockedUsers;
+}
+void ForkSettings::setHideFromBlockedUsers(bool newValue) {
+ StaticHideFromBlockedUsers = newValue;
+ _hideFromBlockedUsers = newValue;
+}
+
+} // namespace Core
diff --git a/Telegram/SourceFiles/core/fork_settings.h b/Telegram/SourceFiles/core/fork_settings.h
new file mode 100644
index 0000000000000..9b5ef1d3c11e4
--- /dev/null
+++ b/Telegram/SourceFiles/core/fork_settings.h
@@ -0,0 +1,156 @@
+/*
+Author: 23rd.
+*/
+#pragma once
+
+namespace Core {
+
+class ForkSettings final {
+public:
+ ForkSettings();
+
+ [[nodiscard]] static bool HideFromBlockedUsers();
+
+ [[nodiscard]] QByteArray serialize() const;
+ void addFromSerialized(const QByteArray &serialized);
+
+ void resetOnLastLogout();
+
+ [[nodiscard]] bool squareUserpics() const {
+ return _squareUserpics;
+ }
+ void setSquareUserpics(bool newValue) {
+ _squareUserpics = newValue;
+ }
+ [[nodiscard]] bool audioFade() const {
+ return _audioFade;
+ }
+ void setAudioFade(bool newValue) {
+ _audioFade = newValue;
+ }
+ [[nodiscard]] bool askUriScheme() const {
+ return _askUriScheme;
+ }
+ void setAskUriScheme(bool newValue) {
+ _askUriScheme = newValue;
+ }
+ [[nodiscard]] QString uriScheme() const {
+ return _uriScheme;
+ }
+ void setUriScheme(QString newValue) {
+ _uriScheme = newValue;
+ }
+ [[nodiscard]] bool lastSeenInDialogs() const {
+ return _lastSeenInDialogs;
+ }
+ void setLastSeenInDialogs(bool newValue) {
+ _lastSeenInDialogs = newValue;
+ }
+ [[nodiscard]] QString searchEngineUrl() const {
+ return _searchEngineUrl;
+ }
+ void setSearchEngineUrl(QString newValue) {
+ _searchEngineUrl = newValue;
+ }
+ [[nodiscard]] bool searchEngine() const {
+ return _searchEngine;
+ }
+ void setSearchEngine(bool newValue) {
+ _searchEngine = newValue;
+ }
+ [[nodiscard]] bool allRecentStickers() const {
+ return _allRecentStickers;
+ }
+ void setAllRecentStickers(bool newValue) {
+ _allRecentStickers = newValue;
+ }
+ [[nodiscard]] int customStickerSize() const {
+ return _customStickerSize;
+ }
+ void setCustomStickerSize(int newValue) {
+ _customStickerSize = newValue;
+ }
+ [[nodiscard]] bool useBlackTrayIcon() const {
+ return _useBlackTrayIcon;
+ }
+ void setUseBlackTrayIcon(bool newValue) {
+ _useBlackTrayIcon = newValue;
+ }
+ [[nodiscard]] bool useOriginalTrayIcon() const {
+ return _useOriginalTrayIcon;
+ }
+ void setUseOriginalTrayIcon(bool newValue) {
+ _useOriginalTrayIcon = newValue;
+ }
+ [[nodiscard]] bool autoSubmitPasscode() const {
+ return _autoSubmitPasscode;
+ }
+ void setAutoSubmitPasscode(bool newValue) {
+ _autoSubmitPasscode = newValue;
+ }
+ [[nodiscard]] bool emojiPopupOnClick() const {
+ return _emojiPopupOnClick;
+ }
+ void setEmojiPopupOnClick(bool newValue) {
+ _emojiPopupOnClick = newValue;
+ }
+ [[nodiscard]] bool addToMenuRememberMedia() const;
+ void setAddToMenuRememberMedia(bool newValue);
+
+ [[nodiscard]] bool hideAllChatsTab() const;
+ void setHideAllChatsTab(bool newValue);
+
+ [[nodiscard]] bool globalSearchDisabled() const;
+ void setGlobalSearchDisabled(bool newValue);
+
+ [[nodiscard]] bool thirdButtonTopBar() const;
+ void setThirdButtonTopBar(bool newValue);
+
+ [[nodiscard]] bool skipShareFromBot() const;
+ void setSkipShareFromBot(bool newValue);
+
+ [[nodiscard]] bool additionalButtonsWebBot() const;
+ void setAdditionalButtonsWebBot(bool newValue);
+
+ [[nodiscard]] bool copyLoginCode() const;
+ void setCopyLoginCode(bool);
+
+ // "bot_id1:platform1|bot_id2:platform2"
+ [[nodiscard]] QString botsPlatforms() const;
+ void setBotsPlatforms(QString);
+
+ [[nodiscard]] bool archivedStoriesAreHidden() const;
+ void setArchivedStoriesAreHidden(bool newValue);
+
+ [[nodiscard]] bool hideFromBlockedUsers() const;
+ void setHideFromBlockedUsers(bool newValue);
+
+private:
+ bool _squareUserpics = false;
+ bool _audioFade = true;
+ bool _askUriScheme = false;
+ bool _lastSeenInDialogs = false;
+ QString _uriScheme;
+ QString _searchEngineUrl = u"https://dgg.gg/%q"_q;
+ bool _searchEngine = false;
+ bool _allRecentStickers = true;
+ int _customStickerSize = 256;
+ bool _useBlackTrayIcon = false;
+ bool _useOriginalTrayIcon = false;
+ bool _autoSubmitPasscode = false;
+ bool _emojiPopupOnClick = false;
+ bool _addToMenuRememberMedia = false;
+ bool _hideAllChatsTab = false;
+ bool _globalSearchDisabled = false;
+ bool _thirdButtonTopBar = false;
+ bool _skipShareFromBot = false;
+ bool _copyLoginCode = false;
+ bool _additionalButtonsWebBot = false;
+ QString _botsPlatforms;
+ bool _archivedStoriesAreHidden = false;
+ bool _hideFromBlockedUsers = false;
+
+};
+
+} // namespace Core
+
diff --git a/Telegram/SourceFiles/core/launcher.cpp b/Telegram/SourceFiles/core/launcher.cpp
index 368395062de8e..7729114b941af 100644
--- a/Telegram/SourceFiles/core/launcher.cpp
+++ b/Telegram/SourceFiles/core/launcher.cpp
@@ -340,7 +340,7 @@ void Launcher::init() {
prepareSettings();
initQtMessageLogging();
- QApplication::setApplicationName(u"TelegramDesktop"_q);
+ QApplication::setApplicationName(u"ForkgramDesktop"_q);
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
// fallback session management is useless for tdesktop since it doesn't have
diff --git a/Telegram/SourceFiles/core/update_checker.cpp b/Telegram/SourceFiles/core/update_checker.cpp
index 1c6c0d7e44a3b..3493a8e3b3da5 100644
--- a/Telegram/SourceFiles/core/update_checker.cpp
+++ b/Telegram/SourceFiles/core/update_checker.cpp
@@ -748,8 +748,8 @@ rpl::lifetime &Checker::lifetime() {
return _lifetime;
}
-HttpChecker::HttpChecker(bool testing) : Checker(testing) {
-}
+// HttpChecker::HttpChecker(bool testing) : Checker(testing) {
+// }
void HttpChecker::start() {
const auto updaterVersion = Platform::AutoUpdateVersion();
@@ -1060,8 +1060,8 @@ void MtpChecker::start() {
startCanary();
return;
}
- const auto updaterVersion = Platform::AutoUpdateVersion();
- const auto feed = "tdhbcfeed"
+ const auto updaterVersion = 1;//Platform::AutoUpdateVersion();
+ const auto feed = "frkgrmfeed"
+ (updaterVersion > 1 ? QString::number(updaterVersion) : QString());
MTP::ResolveChannel(&_mtp, feed, [=](
const MTPInputChannel &channel) {
@@ -1813,15 +1813,9 @@ void Updater::start(bool forceWait) {
}
#endif // !Q_OS_WIN && !Q_OS_MACOS
} else if (sendRequest) {
- if (BuildIsCanary) {
- // Canary builds discover updates only through their own MTP
- // channels, the v1 HTTP feed serves other channels.
- startImplementation(&_httpImplementation, nullptr);
- } else {
- startImplementation(
- &_httpImplementation,
- std::make_unique(_testing));
- }
+ //startImplementation(
+ // &_httpImplementation,
+ // std::make_unique(_testing));
startImplementation(
&_mtpImplementation,
std::make_unique(
@@ -2130,7 +2124,7 @@ namespace {
QFileInfo updater(cWorkingDir() + u"tupdates/temp/Updater.exe"_q);
#elif defined Q_OS_MACOS // Q_OS_WIN
QString curUpdater = (cExeDir() + cExeName() + u"/Contents/Frameworks/Updater"_q);
- QFileInfo updater(cWorkingDir() + u"tupdates/temp/Telegram.app/Contents/Frameworks/Updater"_q);
+ QFileInfo updater(cWorkingDir() + u"tupdates/temp/" TDESKTOP_APP_BUNDLE_NAME "/Contents/Frameworks/Updater"_q);
#else // Q_OS_MACOS
QString curUpdater = (cExeDir() + u"Updater"_q);
QFileInfo updater(cWorkingDir() + u"tupdates/temp/Updater"_q);
@@ -2353,9 +2347,9 @@ void UpdateApplication() {
return "https://itunes.apple.com/ae/app/telegram-desktop/id946399090";
#else // OS_WIN_STORE || OS_MAC_STORE
if (KSandbox::isFlatpak()) {
- return "https://flathub.org/apps/details/org.telegram.desktop";
+ return "https://flathub.org/apps/details/io.github.forkgram.tdesktop";
} else if (KSandbox::isSnap()) {
- return "https://snapcraft.io/telegram-desktop";
+ return "https://snapcraft.io/forkgram";
}
return "https://desktop.telegram.org";
#endif // OS_WIN_STORE || OS_MAC_STORE
diff --git a/Telegram/SourceFiles/core/version.h b/Telegram/SourceFiles/core/version.h
index dcc42bbabeba0..4ed25ba7a9151 100644
--- a/Telegram/SourceFiles/core/version.h
+++ b/Telegram/SourceFiles/core/version.h
@@ -9,6 +9,8 @@ For license and copyright information please follow this link:
#include "base/const_string.h"
+constexpr auto AppNameF = "Forkgram Desktop"_cs;
+
#define TDESKTOP_REQUESTED_ALPHA_VERSION (0ULL)
#ifdef TDESKTOP_ALLOW_CLOSED_ALPHA
diff --git a/Telegram/SourceFiles/data/components/passkeys.cpp b/Telegram/SourceFiles/data/components/passkeys.cpp
index 5f376d3a11382..9081dcfb9d092 100644
--- a/Telegram/SourceFiles/data/components/passkeys.cpp
+++ b/Telegram/SourceFiles/data/components/passkeys.cpp
@@ -12,6 +12,7 @@ For license and copyright information please follow this link:
#include "main/main_app_config.h"
#include "main/main_session.h"
#include "mtproto/mtproto_auth_key.h"
+#include "mtproto/mtproto_response.h"
#include "platform/platform_webauthn.h"
namespace Data {
@@ -38,7 +39,8 @@ Passkeys::Passkeys(not_null session)
Passkeys::~Passkeys() = default;
void Passkeys::initRegistration(
- Fn done) {
+ Fn done,
+ Fn fail) {
if (_pendingRegistration
&& (crl::now() - _pendingRegistrationTime
< crl::time(_pendingRegistration->timeout))) {
@@ -55,6 +57,12 @@ void Passkeys::initRegistration(
= std::make_unique(*p);
_pendingRegistrationTime = crl::now();
done(*p);
+ } else if (fail) {
+ fail(u"PASSKEY_OPTIONS_INVALID"_q);
+ }
+ }).fail([=](const MTP::Error &error) {
+ if (fail && !MTP::IgnoreError(error)) {
+ fail(error.type());
}
}).send();
}
@@ -88,6 +96,7 @@ void Passkeys::deletePasskey(
_session->api().request(MTPaccount_DeletePasskey(
MTP_string(id)
)).done([=] {
+ Platform::WebAuthn::RemoveKeyLocalOnly(id);
_lastRequestTime = 0;
_listKnown = false;
loadList();
@@ -140,8 +149,14 @@ bool Passkeys::canRegister() const {
return Platform::WebAuthn::IsSupported() && _passkeys.size() < max;
}
+bool Passkeys::canRegisterLocalOnly() const {
+ const auto max = _session->appConfig().passkeysAccountPasskeysMax();
+ return Platform::WebAuthn::LocalOnlySupported() && _passkeys.size() < max;
+}
+
bool Passkeys::possible() const {
- return _session->appConfig().settingsDisplayPasskeys();
+ return _session->appConfig().settingsDisplayPasskeys()
+ || Platform::WebAuthn::LocalOnlySupported();
}
void InitPasskeyLogin(
diff --git a/Telegram/SourceFiles/data/components/passkeys.h b/Telegram/SourceFiles/data/components/passkeys.h
index 668f26fe34bb2..ee1899afcdc12 100644
--- a/Telegram/SourceFiles/data/components/passkeys.h
+++ b/Telegram/SourceFiles/data/components/passkeys.h
@@ -39,7 +39,9 @@ class Passkeys final {
explicit Passkeys(not_null session);
~Passkeys();
- void initRegistration(Fn done);
+ void initRegistration(
+ Fn done,
+ Fn fail = nullptr);
void registerPasskey(
const Platform::WebAuthn::RegisterResult &result,
Fn done);
@@ -51,6 +53,7 @@ class Passkeys final {
[[nodiscard]] const std::vector &list() const;
[[nodiscard]] bool listKnown() const;
[[nodiscard]] bool canRegister() const;
+ [[nodiscard]] bool canRegisterLocalOnly() const;
[[nodiscard]] bool possible() const;
private:
diff --git a/Telegram/SourceFiles/data/data_folder.cpp b/Telegram/SourceFiles/data/data_folder.cpp
index 35797b1af42c0..83534c606a801 100644
--- a/Telegram/SourceFiles/data/data_folder.cpp
+++ b/Telegram/SourceFiles/data/data_folder.cpp
@@ -17,10 +17,12 @@ For license and copyright information please follow this link:
#include "history/history.h"
#include "history/history_item.h"
#include "lang/lang_keys.h"
+#include "storage/storage_facade.h"
+#include "core/application.h"
+#include "core/core_settings.h"
#include "main/main_account.h"
#include "main/main_session.h"
#include "mtproto/mtproto_config.h"
-#include "storage/storage_facade.h"
#include "ui/text/text_options.h"
#include "ui/text/text_utilities.h"
#include "ui/painter.h"
@@ -274,7 +276,9 @@ void Folder::paintUserpic(
p.setBrush(overrideBg ? *overrideBg : st::historyPeerArchiveUserpicBg);
{
auto hq = PainterHighQualityEnabler(p);
- p.drawEllipse(x, y, size, size);
+ Core::App().settings().fork().squareUserpics()
+ ? p.drawRect(x, y, size, size)
+ : p.drawEllipse(x, y, size, size);
}
if (size == st::defaultDialogRow.photoSize) {
const auto rect = QRect{ x, y, size, size };
diff --git a/Telegram/SourceFiles/data/data_peer.cpp b/Telegram/SourceFiles/data/data_peer.cpp
index d443f26ff1bf3..ebe73dbd3e748 100644
--- a/Telegram/SourceFiles/data/data_peer.cpp
+++ b/Telegram/SourceFiles/data/data_peer.cpp
@@ -414,6 +414,9 @@ void PeerData::setUserpicPhoto(const MTPPhoto &data) {
}
QImage *PeerData::userpicCloudImage(Ui::PeerUserpicView &view) const {
+ if (isBlocked()) {
+ return nullptr;
+ }
if (!_userpic.isCurrentView(view.cloud)) {
if (!_userpic.empty()) {
view.cloud = _userpic.createView();
@@ -556,6 +559,9 @@ bool PeerData::userpicPhotoUnknown() const {
}
PhotoId PeerData::userpicPhotoId() const {
+ if (isBlocked()) {
+ return 0;
+ }
return userpicPhotoUnknown() ? 0 : _userpicPhotoId;
}
diff --git a/Telegram/SourceFiles/data/data_peer_values.cpp b/Telegram/SourceFiles/data/data_peer_values.cpp
index e89caaddf671b..1632fa80d4c21 100644
--- a/Telegram/SourceFiles/data/data_peer_values.cpp
+++ b/Telegram/SourceFiles/data/data_peer_values.cpp
@@ -531,6 +531,15 @@ QString OnlineTextFull(not_null user, TimeId now) {
const auto till = user->lastseen().onlineTill();
const auto onlineFull = base::unixtime::parse(till);
const auto nowFull = base::unixtime::parse(now);
+
+ //check minutes
+ int32 minutes = (now - user->lastseen().onlineTill()) / 60;
+ if (!minutes) {
+ return tr::lng_status_lastseen_now(tr::now);
+ } else if (minutes < 60) {
+ return tr::lng_status_lastseen_minutes(tr::now, lt_count, minutes);
+ }
+
const auto locale = QLocale();
if (onlineFull.date() == nowFull.date()) {
const auto onlineTime = locale.toString(onlineFull.time(), QLocale::ShortFormat);
diff --git a/Telegram/SourceFiles/dialogs/dialogs_entry.cpp b/Telegram/SourceFiles/dialogs/dialogs_entry.cpp
index 2a47f889e2813..680d80f6fb5a9 100644
--- a/Telegram/SourceFiles/dialogs/dialogs_entry.cpp
+++ b/Telegram/SourceFiles/dialogs/dialogs_entry.cpp
@@ -28,8 +28,11 @@ For license and copyright information please follow this link:
#include "ui/text/text_options.h"
#include "ui/ui_utility.h"
+#include "history/history_unread_things.h"
#include "styles/style_dialogs.h" // st::dialogsTextWidthMin
+#include "core/fork_settings.h"
+
namespace Dialogs {
namespace {
@@ -248,7 +251,20 @@ int Entry::lookupPinnedIndex(FilterId filterId) const {
uint64 Entry::computeSortPosition(FilterId filterId) const {
const auto index = lookupPinnedIndex(filterId);
- return index ? PinnedDialogPos(index) : _sortKeyByDate;
+ if (index) {
+ return PinnedDialogPos(index);
+ } else if (owner().dialogsUnreadOnTop()) {
+ if (const auto history = asHistory()) {
+ const auto hasMention = history->unreadMentions().has();
+ const auto hasUnread = (history->unreadCount() > 0) || hasMention;
+ if (!history->isForum()
+ && ((!history->muted() && hasUnread) || hasMention)) {
+ // Keep such chats right below the pinned dialogs.
+ return PinnedDialogPos(30);
+ }
+ }
+ }
+ return _sortKeyByDate;
}
bool Entry::hasUnreadUnmutedForSort() const {
diff --git a/Telegram/SourceFiles/dialogs/dialogs_inner_widget.cpp b/Telegram/SourceFiles/dialogs/dialogs_inner_widget.cpp
index 6a29da00d3a9c..15e4507fc78f1 100644
--- a/Telegram/SourceFiles/dialogs/dialogs_inner_widget.cpp
+++ b/Telegram/SourceFiles/dialogs/dialogs_inner_widget.cpp
@@ -22,6 +22,7 @@ For license and copyright information please follow this link:
#include "boxes/delete_messages_box.h"
#include "boxes/peer_list_box.h"
#include "core/application.h"
+#include "core/core_settings.h"
#include "core/click_handler_types.h"
#include "core/file_utilities.h"
#include "core/shortcuts.h"
@@ -5203,6 +5204,9 @@ void InnerWidget::peerSearchReceived(Api::PeerSearchResult result) {
for (const auto &peer : result.my) {
appendToFiltered(peer->owner().history(peer));
}
+ if (Core::App().settings().fork().globalSearchDisabled()) {
+ return refresh();
+ }
const auto inlist = [&](not_null peer) {
if (const auto history = peer->owner().historyLoaded(peer)) {
// Skip existing chats.
diff --git a/Telegram/SourceFiles/dialogs/dialogs_row.cpp b/Telegram/SourceFiles/dialogs/dialogs_row.cpp
index f98faa666f00f..9a6fe3604d620 100644
--- a/Telegram/SourceFiles/dialogs/dialogs_row.cpp
+++ b/Telegram/SourceFiles/dialogs/dialogs_row.cpp
@@ -424,6 +424,10 @@ const style::DialogRow &Row::ComputeSt(
void Row::recountHeight(float64 narrowRatio, FilterId filterId) {
const auto &st = ComputeSt(_id.entry(), filterId);
+ if (_id.history() && _id.history()->isTopPromoted()) {
+ _height = 1;
+ return;
+ }
_height = ((&st == &st::defaultDialogRow) || !_id.history())
? st::defaultDialogRow.height
: anim::interpolate(
diff --git a/Telegram/SourceFiles/dialogs/dialogs_widget.cpp b/Telegram/SourceFiles/dialogs/dialogs_widget.cpp
index 4cfd48db2d51b..7c47f6dfbdea7 100644
--- a/Telegram/SourceFiles/dialogs/dialogs_widget.cpp
+++ b/Telegram/SourceFiles/dialogs/dialogs_widget.cpp
@@ -10,15 +10,17 @@ For license and copyright information please follow this link:
#include "api/api_authorizations.h"
#include "api/api_chat_filters.h"
#include "apiwrap.h"
-#include "base/qt/qt_key_modifiers.h"
+#include "core/application.h"
+#include "core/fork_settings.h"
+
#include "base/call_delayed.h"
+#include "base/qt/qt_key_modifiers.h"
#include "base/options.h"
#include "boxes/peers/community_box.h"
#include "boxes/peers/community_pending_requests_box.h"
#include "boxes/peers/edit_peer_requests_box.h"
#include "boxes/choose_filter_box.h"
#include "chat_helpers/message_field.h"
-#include "core/application.h"
#include "core/click_handler_types.h"
#include "core/shortcuts.h"
#include "core/update_checker.h"
@@ -1542,6 +1544,21 @@ void Widget::setupMainMenuToggle() {
_mainMenu.toggle->setClickedCallback([=] { showMainMenu(); });
_mainMenu.toggle->setIsMenuButton(true);
_mainMenu.toggle->setAccessibleName(tr::lng_main_menu(tr::now));
+ _mainMenu.toggle->setAcceptBoth();
+ const auto window = controller();
+ _mainMenu.toggle->addClickHandler([=](Qt::MouseButton button) {
+ if (button == Qt::LeftButton) {
+ showMainMenu();
+ } else if (button == Qt::MiddleButton) {
+ const auto folder = session().data().folderLoaded(
+ Data::Folder::kId);
+ if (folder && !folder->chatsList()->empty()) {
+ controller()->openFolder(folder);
+ }
+ } else if (button == Qt::RightButton) {
+ window->showPeerHistory(window->session().user());
+ }
+ });
rpl::single(rpl::empty) | rpl::then(
controller()->filtersMenuChanged()
@@ -2849,6 +2866,9 @@ void Widget::updateStoriesVisibility(anim::type animated) {
|| (widthAnimation && _openedFolder)
|| _childList
|| _stories->empty()
+ || (Core::App().settings().fork().archivedStoriesAreHidden()
+ ? !!_openedFolder
+ : false)
|| (pulledDown && hiddenAnimated);
const auto hidden = hiddenInstant || hiddenAnimated;
const auto changed = (_stories->toggledHidden() != hidden);
@@ -4948,6 +4968,8 @@ void Widget::keyPressEvent(QKeyEvent *e) {
}
_postponeProcessSearchFocusChange = false;
processSearchFocusChange();
+ } else if (e->key() == Qt::Key_F10) {
+ showMainMenu();
} else {
e->ignore();
}
diff --git a/Telegram/SourceFiles/dialogs/ui/dialogs_layout.cpp b/Telegram/SourceFiles/dialogs/ui/dialogs_layout.cpp
index 7e8e333b3ad8f..58f3a4858fa48 100644
--- a/Telegram/SourceFiles/dialogs/ui/dialogs_layout.cpp
+++ b/Telegram/SourceFiles/dialogs/ui/dialogs_layout.cpp
@@ -47,6 +47,8 @@ For license and copyright information please follow this link:
#include "ui/unread_badge_paint.h"
#include "ui/unread_counter_format.h"
+#include "core/application.h"
+#include "core/core_settings.h"
#include "styles/style_dialogs.h"
#include "styles/style_dialogs_layout.h"
#include "styles/style_widgets.h"
@@ -101,6 +103,11 @@ void PaintRowTopRight(
: context.selected
? st::dialogsDateFgOver
: st::dialogsDateFg);
+
+ if (text == tr::lng_status_online(tr::now)) {
+ p.setPen(st::contactsStatusFgOnline);
+ }
+
p.drawText(
rectForName.left() + rectForName.width() + st::dialogsDateSkip,
rectForName.top() + st::semiboldFont->height - st::normalFont->descent,
@@ -893,6 +900,20 @@ void PaintRow(
rectForName.setWidth(rectForName.width() - st::dialogsSendStateSkip);
sendStateIcon->paint(p, rectForName.topLeft() + QPoint(rectForName.width(), 0), context.width);
}
+ if (from) {
+ if (from->isUser() && Core::App().settings().fork().lastSeenInDialogs()) {
+ auto lastSeen = Data::OnlineText(from->asUser(), base::unixtime::now());
+ static QSet ignoredStrings {
+ tr::lng_status_recently(tr::now),
+ tr::lng_status_bot(tr::now),
+ tr::lng_status_service_notifications(tr::now),
+ tr::lng_status_support(tr::now),
+ };
+ if (!ignoredStrings.contains(lastSeen)) {
+ PaintRowTopRight(p, lastSeen, rectForName, context);
+ }
+ }
+ }
p.setFont(st::semiboldFont);
const auto paintPeerBadge = [&](int rowNameWidth) {
diff --git a/Telegram/SourceFiles/dialogs/ui/dialogs_stories_list.cpp b/Telegram/SourceFiles/dialogs/ui/dialogs_stories_list.cpp
index fbc7ef27bbc3b..bf5029dbafc45 100644
--- a/Telegram/SourceFiles/dialogs/ui/dialogs_stories_list.cpp
+++ b/Telegram/SourceFiles/dialogs/ui/dialogs_stories_list.cpp
@@ -748,7 +748,11 @@ void List::paint(
p.setPen(QPen(gradient, line));
}
p.setBrush(Qt::NoBrush);
+ if (style::SquareUserpics()) {
+ p.drawRect(outer);
+ } else {
p.drawEllipse(outer);
+ }
} else {
validateSegments(itemFull, gradient, line, true);
Ui::PaintOutlineSegments(
@@ -793,7 +797,11 @@ void List::paint(
p.setCompositionMode(QPainter::CompositionMode_Source);
p.setPen(Qt::NoPen);
p.setBrush(st::transparent);
+ if (style::SquareUserpics()) {
+ p.drawRect(rect);
+ } else {
p.drawEllipse(rect);
+ }
p.setCompositionMode(QPainter::CompositionMode_SourceOver);
}
if (hasReadLine) {
diff --git a/Telegram/SourceFiles/dialogs/ui/dialogs_suggestions.cpp b/Telegram/SourceFiles/dialogs/ui/dialogs_suggestions.cpp
index c6ea1897fb88d..303ade0dfd65e 100644
--- a/Telegram/SourceFiles/dialogs/ui/dialogs_suggestions.cpp
+++ b/Telegram/SourceFiles/dialogs/ui/dialogs_suggestions.cpp
@@ -16,6 +16,7 @@ For license and copyright information please follow this link:
#include "boxes/choose_filter_box.h"
#include "boxes/peer_list_box.h"
#include "core/application.h"
+#include "core/local_url_handlers.h"
#include "core/ui_integration.h"
#include "data/components/recent_peers.h"
#include "data/components/top_peers.h"
@@ -47,6 +48,7 @@ For license and copyright information please follow this link:
#include "main/main_session.h"
#include "settings/sections/settings_premium.h"
#include "settings/settings_common.h"
+#include "ui/basic_click_handlers.h"
#include "settings/settings_credits_graphics.h"
#include "storage/storage_shared_media.h"
#include "ui/boxes/confirm_box.h"
@@ -70,6 +72,7 @@ For license and copyright information please follow this link:
#include "ui/delayed_activation.h"
#include "ui/dynamic_thumbnails.h"
#include "ui/painter.h"
+#include "ui/rect.h"
#include "ui/search_field_controller.h"
#include "ui/ui_utility.h"
#include "ui/unread_badge_paint.h"
@@ -1739,6 +1742,8 @@ Suggestions::Suggestions(
_recentApps.get(),
false))
, _searchQueryTimer([=] { applySearchQuery(); }) {
+
+ setupLocalUrlButton();
setupTabs();
setupChats();
setupChannels();
@@ -1757,6 +1762,49 @@ Suggestions::~Suggestions() {
}
}
+void Suggestions::setupLocalUrlButton() {
+ const auto urlFromClipboard = [=] {
+ const auto maybeUrl = QGuiApplication::clipboard()->text();
+ const auto local = Core::TryConvertUrlToLocal(maybeUrl);
+
+ const auto protocol = u"tg://"_q;
+ if (local.startsWith(protocol)) {
+ return local;
+ }
+ return QString();
+ };
+ const auto url = urlFromClipboard();
+ if (url.isEmpty()) {
+ return;
+ }
+ const auto &st = st::defaultSettingsButton;
+ _localUrlButton = base::unique_qptr(
+ Ui::CreateSimpleSettingsButton(this, st.ripple, st.textBg));
+ _localUrlButton->resize(width(), st.height + rect::m::sum::v(st.padding));
+ const auto text = lifetime().make_state(
+ st::semiboldTextStyle,
+ tr::lng_animated_emoji_saved_open(tr::now) + QChar(' ') + url);
+ _localUrlButton->paintRequest() | rpl::on_next([=] {
+ auto p = QPainter(_localUrlButton.get());
+ const auto r = _localUrlButton->rect();
+ const auto left = st::searchedBarPosition.x();
+ p.setPen(st::windowBgActive);
+ text->draw(p, {
+ .position = QPoint(left, (r.height() - text->minHeight()) / 2),
+ .outerWidth = (r.width() - left),
+ .availableWidth = (r.width() - left),
+ .elisionLines = 1,
+ });
+ }, _localUrlButton->lifetime());
+ widthValue() | rpl::on_next([=](int width) {
+ _localUrlButton->resizeToWidth(width);
+ }, _localUrlButton->lifetime());
+ _localUrlButton->setClickedCallback([=] {
+ const auto current = urlFromClipboard();
+ UrlClickHandler::Open(current.isEmpty() ? url : current);
+ });
+}
+
void Suggestions::setupTabs() {
_tabsScroll->setCustomWheelProcess([=](not_null e) {
const auto pixelDelta = e->pixelDelta();
@@ -1796,14 +1844,15 @@ void Suggestions::setupTabs() {
const auto shadow = Ui::CreateChild(this);
shadow->lower();
- _tabsScroll->move(0, 0);
- _tabs->move(0, 0);
+ const auto localY = _localUrlButton ? _localUrlButton->height() : 0;
+ _tabsScroll->move(0, localY);
+ _tabs->move(0, localY);
rpl::combine(
widthValue(),
- _tabs->heightValue()
- ) | rpl::on_next([=](int width, int height) {
+ _tabs->geometryValue()
+ ) | rpl::on_next([=](int width, const QRect &r) {
const auto line = st::lineWidth;
- shadow->setGeometry(0, height - line, width, line);
+ shadow->setGeometry(0, rect::bottom(r) - line, width, line);
}, shadow->lifetime());
shadow->showOn(_tabsScroll->shownValue());
@@ -3154,6 +3203,9 @@ void Suggestions::startShownAnimation(bool shown, Fn finish) {
resize(now, height());
}
}
+ if (_localUrlButton) {
+ _localUrlButton->hide();
+ }
_tabsScroll->hide();
_chatsScroll->hide();
_channelsScroll->hide();
@@ -3177,6 +3229,9 @@ void Suggestions::finishShow() {
_cachedRecent = QRect();
_dirtyChatRows = QRegion();
+ if (_localUrlButton) {
+ _localUrlButton->show();
+ }
_tabsScroll->show();
const auto key = _key.current();
_chatsScroll->setVisible(!_tabsOnly && key == Key{ Tab::Chats });
@@ -3269,9 +3324,12 @@ void Suggestions::resizeEvent(QResizeEvent *e) {
void Suggestions::updateControlsGeometry() {
const auto w = std::max(width(), st::columnMinimalWidthLeft);
_tabs->fitWidthToSections();
-
- const auto tabs = _tabs->height();
- _tabsScroll->setGeometry(0, 0, w, tabs);
+ if (_localUrlButton) {
+ _localUrlButton->resizeToWidth(w);
+ _tabs->move(_tabs->x(), rect::bottom(_localUrlButton.get()));
+ }
+ const auto tabs = rect::bottom(_tabs.get());
+ _tabsScroll->setGeometry(0, _tabs->y(), w, _tabs->height());
if (_tabsOnly) {
return;
}
diff --git a/Telegram/SourceFiles/dialogs/ui/dialogs_suggestions.h b/Telegram/SourceFiles/dialogs/ui/dialogs_suggestions.h
index 27c1b663f371f..54c4d7bb50697 100644
--- a/Telegram/SourceFiles/dialogs/ui/dialogs_suggestions.h
+++ b/Telegram/SourceFiles/dialogs/ui/dialogs_suggestions.h
@@ -43,6 +43,7 @@ struct SwipeHandlerFinishData;
} // namespace Ui::Controls
namespace Ui {
+class AbstractButton;
class BoxContent;
class SearchFieldController;
class ScrollArea;
@@ -198,6 +199,7 @@ class Suggestions final : public Ui::RpWidget {
void paintEvent(QPaintEvent *e) override;
void resizeEvent(QResizeEvent *e) override;
+ void setupLocalUrlButton();
void setupTabs();
void setupChats();
void setupChannels();
@@ -297,6 +299,7 @@ class Suggestions final : public Ui::RpWidget {
const not_null _controller;
+ base::unique_qptr _localUrlButton;
const std::unique_ptr _tabsScroll;
const not_null _tabs;
Ui::Animations::Simple _tabsScrollAnimation;
diff --git a/Telegram/SourceFiles/forkgram/gpu_demo_renderer.cpp b/Telegram/SourceFiles/forkgram/gpu_demo_renderer.cpp
new file mode 100644
index 0000000000000..06e4fd805f045
--- /dev/null
+++ b/Telegram/SourceFiles/forkgram/gpu_demo_renderer.cpp
@@ -0,0 +1,207 @@
+/*
+This file is part of Forkgram Desktop,
+the unofficial Telegram desktop client.
+
+For license and copyright information please follow this link:
+https://github.com/nicegram/nicegram-desktop/blob/master/LEGAL
+*/
+#include "forkgram/gpu_demo_renderer.h"
+
+#if QT_VERSION >= QT_VERSION_CHECK(6, 7, 0)
+
+#include "ui/rhi/rhi_shader.h"
+#include "ui/rp_widget.h"
+#include "ui/painter.h"
+#include "styles/style_basic.h"
+
+#include
+#include
+
+namespace Forkgram {
+namespace {
+
+struct DemoUniforms {
+ float viewport[2];
+ float time;
+ float _pad;
+};
+static_assert(sizeof(DemoUniforms) % 16 == 0);
+
+[[nodiscard]] QShader LoadShader(const QString &name) {
+ return Ui::Rhi::ShaderFromFile(
+ u":/shaders/"_q + name + u".qsb"_q);
+}
+
+} // namespace
+
+GpuDemoRenderer::GpuDemoRenderer() {
+ _elapsed.start();
+}
+
+GpuDemoRenderer::~GpuDemoRenderer() {
+ releaseResources();
+}
+
+void GpuDemoRenderer::initialize(
+ QRhi *rhi,
+ QRhiRenderTarget *rt,
+ QRhiCommandBuffer *cb) {
+ if (_initialized && _rhi == rhi) {
+ return;
+ }
+ releaseResources();
+
+ _rhi = rhi;
+
+ constexpr auto kVertexSize = 4 * sizeof(float);
+ constexpr auto kQuadVertices = 4;
+
+ _vertexBuffer = rhi->newBuffer(
+ QRhiBuffer::Dynamic,
+ QRhiBuffer::VertexBuffer,
+ kQuadVertices * kVertexSize);
+ _vertexBuffer->create();
+
+ _uniformBuffer = rhi->newBuffer(
+ QRhiBuffer::Dynamic,
+ QRhiBuffer::UniformBuffer,
+ sizeof(DemoUniforms));
+ _uniformBuffer->create();
+
+ _srb = rhi->newShaderResourceBindings();
+ _srb->setBindings({
+ QRhiShaderResourceBinding::uniformBuffer(
+ 0,
+ QRhiShaderResourceBinding::VertexStage
+ | QRhiShaderResourceBinding::FragmentStage,
+ _uniformBuffer),
+ });
+ _srb->create();
+
+ const auto rpDesc = rt->renderPassDescriptor();
+ const auto vertShader = LoadShader(u"demo.vert"_q);
+ const auto fragShader = LoadShader(u"demo.frag"_q);
+
+ _pipeline = rhi->newGraphicsPipeline();
+ _pipeline->setShaderStages({
+ { QRhiShaderStage::Vertex, vertShader },
+ { QRhiShaderStage::Fragment, fragShader },
+ });
+
+ QRhiVertexInputLayout inputLayout;
+ inputLayout.setBindings({
+ { quint32(kVertexSize) },
+ });
+ inputLayout.setAttributes({
+ { 0, 0, QRhiVertexInputAttribute::Float2, 0 },
+ { 0, 1, QRhiVertexInputAttribute::Float2, 2 * sizeof(float) },
+ });
+ _pipeline->setVertexInputLayout(inputLayout);
+ _pipeline->setTopology(QRhiGraphicsPipeline::TriangleStrip);
+ _pipeline->setShaderResourceBindings(_srb);
+ _pipeline->setRenderPassDescriptor(rpDesc);
+ _pipeline->create();
+
+ _initialized = true;
+
+ LOG(("[GPU_DEMO] backend=%1 device=%2")
+ .arg(rhi->backendName())
+ .arg(rhi->driverInfo().deviceName));
+}
+
+void GpuDemoRenderer::render(
+ QRhi *rhi,
+ QRhiRenderTarget *rt,
+ QRhiCommandBuffer *cb) {
+ _rhi = rhi;
+
+ const auto size = rt->pixelSize();
+ const auto factor = style::DevicePixelRatio();
+ const auto w = float(size.width() / factor);
+ const auto h = float(size.height() / factor);
+ const auto t = float(_elapsed.elapsed()) / 1000.0f;
+
+ const float vertices[] = {
+ 0.f, 0.f, 0.f, 0.f,
+ w, 0.f, 1.f, 0.f,
+ 0.f, h, 0.f, 1.f,
+ w, h, 1.f, 1.f,
+ };
+
+ DemoUniforms uniforms;
+ uniforms.viewport[0] = w;
+ uniforms.viewport[1] = h;
+ uniforms.time = t;
+ uniforms._pad = 0.f;
+
+ auto *rub = rhi->nextResourceUpdateBatch();
+ rub->updateDynamicBuffer(_vertexBuffer, 0, sizeof(vertices), vertices);
+ rub->updateDynamicBuffer(
+ _uniformBuffer, 0, sizeof(uniforms), &uniforms);
+
+ const auto bg = QColor(0, 0, 0, 255);
+ cb->beginPass(rt, bg, { 1.0f, 0 }, rub);
+
+ cb->setGraphicsPipeline(_pipeline);
+ cb->setShaderResources(_srb);
+ cb->setViewport({
+ 0, 0,
+ float(size.width()),
+ float(size.height()) });
+
+ const QRhiCommandBuffer::VertexInput vbufBinding(_vertexBuffer, 0);
+ cb->setVertexInput(0, 1, &vbufBinding);
+ cb->draw(4);
+
+ cb->endPass();
+}
+
+void GpuDemoRenderer::releaseResources() {
+ delete _pipeline;
+ _pipeline = nullptr;
+ delete _srb;
+ _srb = nullptr;
+ delete _uniformBuffer;
+ _uniformBuffer = nullptr;
+ delete _vertexBuffer;
+ _vertexBuffer = nullptr;
+ _initialized = false;
+}
+
+void GpuDemoRenderer::paintFallback(
+ Painter &p,
+ const QRegion &clip,
+ Ui::GL::Backend backend) {
+ p.fillRect(clip.boundingRect(), QColor(40, 40, 60));
+ p.setPen(Qt::white);
+ p.drawText(
+ clip.boundingRect(),
+ Qt::AlignCenter,
+ u"GPU Demo (QRhi not available)"_q);
+}
+
+Ui::GL::ChosenRenderer ChooseDemoRenderer() {
+ return {
+ .renderer = std::make_unique(),
+ .backend = Ui::GL::Backend::QRhi,
+ };
+}
+
+std::unique_ptr CreateGpuDemoWidget(
+ QWidget *parent) {
+ auto surface = Ui::GL::CreateSurface(parent, ChooseDemoRenderer());
+ if (const auto widget = surface->rpWidget()) {
+ const auto raw = widget;
+ auto *timer = new QTimer(raw);
+ timer->setInterval(16);
+ QObject::connect(timer, &QTimer::timeout, raw, [raw] {
+ raw->update();
+ });
+ timer->start();
+ }
+ return surface;
+}
+
+} // namespace Forkgram
+
+#endif // Qt >= 6.7
diff --git a/Telegram/SourceFiles/forkgram/gpu_demo_renderer.h b/Telegram/SourceFiles/forkgram/gpu_demo_renderer.h
new file mode 100644
index 0000000000000..460e3f2fcd7de
--- /dev/null
+++ b/Telegram/SourceFiles/forkgram/gpu_demo_renderer.h
@@ -0,0 +1,79 @@
+/*
+This file is part of Forkgram Desktop,
+the unofficial Telegram desktop client.
+
+For license and copyright information please follow this link:
+https://github.com/nicegram/nicegram-desktop/blob/master/LEGAL
+*/
+#pragma once
+
+#include "ui/rhi/rhi_renderer.h"
+#include "ui/gl/gl_surface.h"
+
+#include
+
+#if QT_VERSION >= QT_VERSION_CHECK(6, 7, 0)
+
+class QRhi;
+class QRhiBuffer;
+class QRhiSampler;
+class QRhiGraphicsPipeline;
+class QRhiShaderResourceBindings;
+
+namespace Ui {
+class RpWidgetWrap;
+class RpWidget;
+} // namespace Ui
+
+namespace Forkgram {
+
+class GpuDemoRenderer final
+ : public Ui::GL::Renderer
+ , public Ui::Rhi::Renderer {
+public:
+ GpuDemoRenderer();
+ ~GpuDemoRenderer();
+
+ void initialize(
+ QRhi *rhi,
+ QRhiRenderTarget *rt,
+ QRhiCommandBuffer *cb) override;
+ void render(
+ QRhi *rhi,
+ QRhiRenderTarget *rt,
+ QRhiCommandBuffer *cb) override;
+ void releaseResources() override;
+
+ QColor rhiClearColor() override {
+ return QColor(0, 0, 0, 255);
+ }
+
+ std::optional clearColor() override {
+ return QColor(0, 0, 0, 255);
+ }
+
+ void paintFallback(
+ Painter &p,
+ const QRegion &clip,
+ Ui::GL::Backend backend) override;
+
+private:
+ QRhi *_rhi = nullptr;
+ QRhiBuffer *_vertexBuffer = nullptr;
+ QRhiBuffer *_uniformBuffer = nullptr;
+ QRhiGraphicsPipeline *_pipeline = nullptr;
+ QRhiShaderResourceBindings *_srb = nullptr;
+
+ QElapsedTimer _elapsed;
+ bool _initialized = false;
+
+};
+
+[[nodiscard]] Ui::GL::ChosenRenderer ChooseDemoRenderer();
+
+[[nodiscard]] std::unique_ptr CreateGpuDemoWidget(
+ QWidget *parent);
+
+} // namespace Forkgram
+
+#endif // Qt >= 6.7
diff --git a/Telegram/SourceFiles/forkgram/link_replacements.cpp b/Telegram/SourceFiles/forkgram/link_replacements.cpp
new file mode 100644
index 0000000000000..0f8cad1fec7f4
--- /dev/null
+++ b/Telegram/SourceFiles/forkgram/link_replacements.cpp
@@ -0,0 +1,312 @@
+/*
+Author: 23rd.
+*/
+
+#include "forkgram/link_replacements.h"
+
+#include "chat_helpers/rich_paste_toast.h"
+#include "core/application.h"
+#include "core/core_settings.h"
+#include "lang/lang_keys.h"
+#include "ui/text/text_utilities.h"
+#include "ui/toast/toast.h"
+#include "ui/widgets/buttons.h"
+#include "ui/qt_object_factory.h"
+
+#include "styles/style_chat.h"
+
+namespace Forkgram::LinkReplacements {
+namespace {
+
+constexpr auto kEnabledKey = "fork_replace_links_on_paste";
+constexpr auto kRulesKey = "fork_link_replacement_rules";
+constexpr auto kSerializeVersion = 1;
+constexpr auto kMaxTextLength = 10000;
+constexpr auto kMaxRules = 100;
+constexpr auto kToastDuration = 5 * crl::time(1000);
+
+[[nodiscard]] rpl::event_stream<> &ChangesStream() {
+ static auto result = rpl::event_stream<>();
+ return result;
+}
+
+[[nodiscard]] QString Expand(
+ const QRegularExpressionMatch &match,
+ const QString &replacement) {
+ const auto size = int(replacement.size());
+ auto result = QString();
+ result.reserve(size);
+ for (auto i = 0; i != size;) {
+ const auto ch = replacement[i];
+ if ((ch == '\\') && (i + 1 != size)) {
+ result.append(replacement[i + 1]);
+ i += 2;
+ } else if ((ch == '$')
+ && (i + 1 != size)
+ && replacement[i + 1].isDigit()) {
+ const auto group = replacement[i + 1].digitValue();
+ if (group <= match.lastCapturedIndex()) {
+ result.append(match.captured(group));
+ }
+ i += 2;
+ } else {
+ result.append(ch);
+ ++i;
+ }
+ }
+ return result;
+}
+
+[[nodiscard]] int Apply(TextWithTags &text, int from, int till) {
+ if (till - from > kMaxTextLength) {
+ return -1;
+ }
+ struct Edit {
+ int from = 0;
+ int till = 0;
+ QString with;
+ };
+ auto changed = false;
+ for (const auto &rule : Load()) {
+ const auto regex = QRegularExpression(rule.pattern);
+ if (!rule.enabled || !regex.isValid()) {
+ continue;
+ }
+ auto edits = std::vector();
+ auto i = regex.globalMatch(text.text.mid(from, till - from));
+ while (i.hasNext()) {
+ const auto match = i.next();
+ if (match.capturedEnd() > match.capturedStart()) {
+ edits.push_back({
+ int(match.capturedStart()),
+ int(match.capturedEnd()),
+ Expand(match, rule.replacement),
+ });
+ }
+ }
+ for (auto j = edits.crbegin(); j != edits.crend(); ++j) {
+ text = ChatHelpers::TextWithTagsReplaced(
+ text,
+ from + j->from,
+ from + j->till,
+ { j->with });
+ till += int(j->with.size()) - (j->till - j->from);
+ changed = true;
+ }
+ }
+ return changed ? till : -1;
+}
+
+void ShowUndoToast(
+ not_null field,
+ TextWithTags replaced,
+ Fn undo) {
+ const auto weakField = base::make_weak(field);
+ const auto intact = [=] {
+ const auto strong = weakField.get();
+ return strong && (strong->getTextWithTags() == replaced);
+ };
+ const auto button = tr::lng_fork_link_replaced_undo(tr::now);
+ const auto st = std::make_shared(st::historyPremiumToast);
+ st->padding.setRight(
+ st::historyPremiumViewSet.style.font->width(button)
+ - st::historyPremiumViewSet.width);
+ const auto weak = Ui::Toast::Show(field->window(), Ui::Toast::Config{
+ .text = tr::lng_fork_link_replaced(tr::now, tr::marked),
+ .st = st.get(),
+ .acceptinput = true,
+ .duration = kToastDuration,
+ });
+ const auto strong = weak.get();
+ if (!strong) {
+ return;
+ }
+ const auto widget = strong->widget();
+ widget->lifetime().add([st] {});
+ field->changes() | rpl::filter([=] {
+ return !intact();
+ }) | rpl::on_next([=] {
+ if (const auto strong = weak.get()) {
+ strong->hideAnimated();
+ }
+ }, widget->lifetime());
+ const auto activate = Ui::CreateChild(
+ widget.get(),
+ rpl::single(button),
+ st::historyPremiumViewSet);
+ activate->show();
+ activate->setClickedCallback([=] {
+ if (const auto strong = weak.get()) {
+ strong->hideAnimated();
+ }
+ if (intact()) {
+ undo();
+ }
+ });
+ rpl::combine(
+ widget->sizeValue(),
+ activate->sizeValue()
+ ) | rpl::on_next([=](QSize outer, QSize inner) {
+ activate->moveToRight(
+ 0,
+ (outer.height() - inner.height()) / 2,
+ outer.width());
+ }, widget->lifetime());
+}
+
+void ScheduleReplace(not_null field) {
+ const auto was = field->getTextWithTags();
+ const auto cursor = field->textCursor();
+ const auto from = std::min(cursor.position(), cursor.anchor());
+ crl::on_main(field, [=] {
+ const auto pastedTill = int(field->textCursor().position());
+ const auto pasted = field->getTextWithTags();
+ if ((pastedTill <= from) || (pasted == was)) {
+ return;
+ }
+ auto updated = pasted;
+ const auto till = Apply(updated, from, pastedTill);
+ if (till < 0) {
+ return;
+ }
+ field->setTextWithTags(updated);
+ field->setCursorPosition(till);
+ ShowUndoToast(field, field->getTextWithTags(), [=] {
+ field->setTextWithTags(pasted);
+ field->setCursorPosition(pastedTill);
+ });
+ });
+}
+
+} // namespace
+
+bool Enabled() {
+ return Core::App().settings().readPref(kEnabledKey, true);
+}
+
+void SetEnabled(bool enabled) {
+ Core::App().settings().writePref(kEnabledKey, enabled);
+ Core::App().saveSettingsDelayed();
+ ChangesStream().fire({});
+}
+
+std::vector Default() {
+ return {
+ {
+ u"https?://(?:www\\.)?(?:twitter|x)\\.com/"_q,
+ u"https://fixupx.com/"_q,
+ },
+ {
+ u"https?://(?:www\\.)?instagram\\.com/"_q,
+ u"https://kkinstagram.com/"_q,
+ },
+ {
+ u"https?://(?:www\\.|vm\\.|vt\\.)?tiktok\\.com/"_q,
+ u"https://vxtiktok.com/"_q,
+ },
+ {
+ u"https?://(?:www\\.|old\\.)?reddit\\.com/"_q,
+ u"https://rxddit.com/"_q,
+ },
+ {
+ u"https?://(?:www\\.)?bsky\\.app/"_q,
+ u"https://fxbsky.app/"_q,
+ },
+ {
+ u"https?://(?:www\\.)?pixiv\\.net/(?:en/)?artworks/"_q,
+ u"https://phixiv.net/artworks/"_q,
+ },
+ };
+}
+
+std::vector Load() {
+ const auto stored = Core::App().settings().readPref(kRulesKey);
+ if (stored.isEmpty()) {
+ return Default();
+ }
+ auto stream = QDataStream(stored);
+ stream.setVersion(QDataStream::Qt_5_1);
+ auto version = qint32();
+ auto count = qint32();
+ stream >> version >> count;
+ if ((stream.status() != QDataStream::Ok)
+ || (version != kSerializeVersion)
+ || (count < 0)
+ || (count > kMaxRules)) {
+ return Default();
+ }
+ auto result = std::vector();
+ result.reserve(count);
+ for (auto i = 0; i != count; ++i) {
+ auto pattern = QString();
+ auto replacement = QString();
+ auto enabled = qint32();
+ stream >> pattern >> replacement >> enabled;
+ if (stream.status() != QDataStream::Ok) {
+ return Default();
+ } else if (!pattern.isEmpty()) {
+ result.push_back({ pattern, replacement, (enabled == 1) });
+ }
+ }
+ return result;
+}
+
+void Save(const std::vector &rules) {
+ const auto count = int(std::min(rules.size(), size_t(kMaxRules)));
+ auto data = QByteArray();
+ {
+ auto stream = QDataStream(&data, QIODevice::WriteOnly);
+ stream.setVersion(QDataStream::Qt_5_1);
+ stream << qint32(kSerializeVersion) << qint32(count);
+ for (auto i = 0; i != count; ++i) {
+ const auto &rule = rules[i];
+ stream
+ << rule.pattern
+ << rule.replacement
+ << qint32(rule.enabled ? 1 : 0);
+ }
+ }
+ Core::App().settings().writePref(kRulesKey, data);
+ Core::App().saveSettingsDelayed();
+ ChangesStream().fire({});
+}
+
+void Reset() {
+ Core::App().settings().clearPref(kRulesKey);
+ Core::App().saveSettingsDelayed();
+ ChangesStream().fire({});
+}
+
+bool ValidPattern(const QString &pattern) {
+ return !pattern.isEmpty() && QRegularExpression(pattern).isValid();
+}
+
+int EnabledCount() {
+ const auto rules = Load();
+ return int(ranges::count_if(rules, [](const Rule &rule) {
+ return rule.enabled && ValidPattern(rule.pattern);
+ }));
+}
+
+rpl::producer<> Changes() {
+ return ChangesStream().events();
+}
+
+Ui::InputField::MimeDataHook WrappedMimeHook(
+ Ui::InputField::MimeDataHook original,
+ not_null field) {
+ return [=, original = std::move(original)](
+ not_null data,
+ Ui::InputField::MimeAction action) {
+ if (original && original(data, action)) {
+ return true;
+ } else if ((action == Ui::InputField::MimeAction::Insert)
+ && Enabled()
+ && data->hasText()) {
+ ScheduleReplace(field);
+ }
+ return false;
+ };
+}
+
+} // namespace Forkgram::LinkReplacements
diff --git a/Telegram/SourceFiles/forkgram/link_replacements.h b/Telegram/SourceFiles/forkgram/link_replacements.h
new file mode 100644
index 0000000000000..a59bddf52a142
--- /dev/null
+++ b/Telegram/SourceFiles/forkgram/link_replacements.h
@@ -0,0 +1,32 @@
+/*
+Author: 23rd.
+*/
+#pragma once
+
+#include "ui/widgets/fields/input_field.h"
+
+namespace Forkgram::LinkReplacements {
+
+struct Rule {
+ QString pattern;
+ QString replacement;
+ bool enabled = true;
+};
+
+[[nodiscard]] bool Enabled();
+void SetEnabled(bool enabled);
+
+[[nodiscard]] std::vector Default();
+[[nodiscard]] std::vector Load();
+void Save(const std::vector &rules);
+void Reset();
+
+[[nodiscard]] bool ValidPattern(const QString &pattern);
+[[nodiscard]] int EnabledCount();
+[[nodiscard]] rpl::producer<> Changes();
+
+[[nodiscard]] Ui::InputField::MimeDataHook WrappedMimeHook(
+ Ui::InputField::MimeDataHook original,
+ not_null field);
+
+} // namespace Forkgram::LinkReplacements
diff --git a/Telegram/SourceFiles/forkgram/link_replacements_box.cpp b/Telegram/SourceFiles/forkgram/link_replacements_box.cpp
new file mode 100644
index 0000000000000..7708ef3d5bdf5
--- /dev/null
+++ b/Telegram/SourceFiles/forkgram/link_replacements_box.cpp
@@ -0,0 +1,237 @@
+/*
+Author: 23rd.
+*/
+
+#include "forkgram/link_replacements_box.h"
+
+#include "forkgram/link_replacements.h"
+#include "lang/lang_keys.h"
+#include "settings/settings_common.h"
+#include "ui/layers/generic_box.h"
+#include "ui/widgets/fields/input_field.h"
+#include "ui/widgets/buttons.h"
+#include "ui/widgets/checkbox.h"
+#include "ui/widgets/labels.h"
+#include "ui/wrap/vertical_layout.h"
+#include "ui/vertical_list.h"
+
+#include "styles/style_boxes.h"
+#include "styles/style_layers.h"
+#include "styles/style_settings.h"
+
+namespace Forkgram {
+namespace {
+
+using Rule = LinkReplacements::Rule;
+
+void EditRuleBox(
+ not_null box,
+ Rule rule,
+ Fn save,
+ Fn remove) {
+ box->setTitle(remove
+ ? tr::lng_fork_link_replacements_edit()
+ : tr::lng_fork_link_replacements_add());
+
+ const auto pattern = box->addRow(
+ object_ptr(
+ box,
+ st::defaultInputField,
+ tr::lng_fork_link_replacements_find(),
+ rule.pattern),
+ st::markdownLinkFieldPadding);
+ const auto replacement = box->addRow(
+ object_ptr(
+ box,
+ st::defaultInputField,
+ tr::lng_fork_link_replacements_replace(),
+ rule.replacement),
+ st::markdownLinkFieldPadding);
+
+ const auto submit = [=] {
+ const auto now = pattern->getLastText().trimmed();
+ if (!LinkReplacements::ValidPattern(now)) {
+ pattern->showError();
+ return;
+ }
+ save({ now, replacement->getLastText(), rule.enabled });
+ box->closeBox();
+ };
+ pattern->submits() | rpl::on_next([=] {
+ replacement->setFocus();
+ }, pattern->lifetime());
+ replacement->submits() | rpl::on_next([=] {
+ submit();
+ }, replacement->lifetime());
+
+ box->setFocusCallback([=] {
+ pattern->setFocusFast();
+ });
+
+ box->addButton(tr::lng_settings_save(), submit);
+ box->addButton(tr::lng_cancel(), [=] {
+ box->closeBox();
+ });
+ if (remove) {
+ box->addLeftButton(tr::lng_box_delete(), [=] {
+ remove();
+ box->closeBox();
+ });
+ }
+}
+
+} // namespace
+
+void LinkReplacementsBox(not_null box) {
+ box->setTitle(tr::lng_fork_link_replacements());
+ box->setWidth(st::boxWideWidth);
+
+ struct State {
+ std::vector rules;
+ Ui::VerticalLayout *wrap = nullptr;
+ Fn refresh;
+ };
+ const auto state = box->lifetime().make_state();
+ state->rules = LinkReplacements::Load();
+
+ const auto container = box->verticalLayout();
+ const auto enabled = container->add(
+ object_ptr(
+ container,
+ tr::lng_fork_link_replacements(),
+ st::settingsButtonNoIcon)
+ )->toggleOn(rpl::single(LinkReplacements::Enabled()));
+ enabled->toggledChanges(
+ ) | rpl::on_next([=](bool value) {
+ LinkReplacements::SetEnabled(value);
+ }, enabled->lifetime());
+
+ Ui::AddSkip(container);
+ Ui::AddDividerText(container, tr::lng_fork_link_replacements_about());
+ Ui::AddSkip(container);
+ Ui::AddSubsectionTitle(
+ container,
+ tr::lng_fork_link_replacements_rules());
+
+ state->wrap = container->add(object_ptr(container));
+
+ const auto add = Settings::AddButtonWithIcon(
+ container,
+ tr::lng_fork_link_replacements_add(),
+ st::settingsButtonActive,
+ {
+ &st::settingsIconAdd,
+ Settings::IconType::Round,
+ &st::windowBgActive,
+ });
+
+ Ui::AddSkip(container);
+ Ui::AddDividerText(
+ container,
+ tr::lng_fork_link_replacements_rules_about());
+
+ const auto save = [=] {
+ LinkReplacements::Save(state->rules);
+ state->refresh();
+ };
+ const auto addRow = [=](not_null inner, int i) {
+ const auto &rule = state->rules[i];
+ const auto valid = LinkReplacements::ValidPattern(rule.pattern);
+ const auto &titlePadding = st::settingsForkRuleTitlePadding;
+ const auto &aboutPadding = st::settingsForkRuleAboutPadding;
+ const auto row = Ui::CreateChild(
+ inner.get(),
+ rpl::single(QString()),
+ st::settingsButtonNoIcon);
+ const auto title = inner->add(
+ object_ptr(
+ inner,
+ rule.pattern,
+ st::settingsExperimentalTitle),
+ titlePadding);
+ const auto about = inner->add(
+ object_ptr(
+ inner,
+ (valid
+ ? (u"→ "_q + rule.replacement)
+ : tr::lng_fork_link_replacements_invalid(tr::now)),
+ st::settingsExperimentalAbout),
+ aboutPadding);
+ if (!valid) {
+ about->setTextColorOverride(st::attentionButtonFg->c);
+ }
+ title->setAttribute(Qt::WA_TransparentForMouseEvents);
+ about->setAttribute(Qt::WA_TransparentForMouseEvents);
+ rpl::combine(
+ inner->widthValue(),
+ title->heightValue(),
+ about->heightValue()
+ ) | rpl::on_next([=](int width, int titleHeight, int aboutHeight) {
+ row->resize(width, titlePadding.top()
+ + titleHeight
+ + titlePadding.bottom()
+ + aboutPadding.top()
+ + aboutHeight
+ + aboutPadding.bottom());
+ }, row->lifetime());
+ title->topValue(
+ ) | rpl::on_next([=](int top) {
+ row->moveToLeft(0, top - titlePadding.top());
+ }, row->lifetime());
+ row->show();
+ row->setClickedCallback([=] {
+ box->uiShow()->showBox(Box(
+ EditRuleBox,
+ state->rules[i],
+ crl::guard(box, [=](Rule updated) {
+ state->rules[i] = updated;
+ save();
+ }),
+ crl::guard(box, [=] {
+ state->rules.erase(begin(state->rules) + i);
+ save();
+ })));
+ });
+ const auto [toggle, checkView] = Settings::AddSeparatedToggle(
+ row,
+ st::settingsButtonNoIcon,
+ rule.enabled);
+ toggle->clicks() | rpl::on_next([=] {
+ const auto checked = !checkView->checked();
+ checkView->setChecked(checked, anim::type::normal);
+ state->rules[i].enabled = checked;
+ LinkReplacements::Save(state->rules);
+ }, toggle->lifetime());
+ };
+ state->refresh = [=] {
+ state->wrap->clear();
+ const auto inner = state->wrap->add(
+ object_ptr(state->wrap));
+ for (auto i = 0; i != int(state->rules.size()); ++i) {
+ addRow(inner, i);
+ }
+ };
+ state->refresh();
+
+ add->setClickedCallback([=] {
+ box->uiShow()->showBox(Box(
+ EditRuleBox,
+ Rule(),
+ crl::guard(box, [=](Rule created) {
+ state->rules.push_back(created);
+ save();
+ }),
+ Fn()));
+ });
+
+ box->addButton(tr::lng_close(), [=] {
+ box->closeBox();
+ });
+ box->addLeftButton(tr::lng_fork_link_replacements_reset(), [=] {
+ LinkReplacements::Reset();
+ state->rules = LinkReplacements::Load();
+ state->refresh();
+ });
+}
+
+} // namespace Forkgram
diff --git a/Telegram/SourceFiles/forkgram/link_replacements_box.h b/Telegram/SourceFiles/forkgram/link_replacements_box.h
new file mode 100644
index 0000000000000..5f70000051232
--- /dev/null
+++ b/Telegram/SourceFiles/forkgram/link_replacements_box.h
@@ -0,0 +1,14 @@
+/*
+Author: 23rd.
+*/
+#pragma once
+
+namespace Ui {
+class GenericBox;
+} // namespace Ui
+
+namespace Forkgram {
+
+void LinkReplacementsBox(not_null box);
+
+} // namespace Forkgram
diff --git a/Telegram/SourceFiles/forkgram/uri_menu.cpp b/Telegram/SourceFiles/forkgram/uri_menu.cpp
new file mode 100644
index 0000000000000..ad89a14e3be16
--- /dev/null
+++ b/Telegram/SourceFiles/forkgram/uri_menu.cpp
@@ -0,0 +1,29 @@
+/*
+Author: 23rd.
+*/
+
+#include "forkgram/uri_menu.h"
+
+#include "forkgram/uri_open.h"
+#include "core/application.h"
+#include "core/core_settings.h"
+#include "lang/lang_keys.h"
+#include "ui/widgets/popup_menu.h"
+
+namespace Forkgram {
+
+void FillUrlWithCustomUri(
+ not_null menu,
+ const QString &url) {
+ if (!Core::App().settings().fork().askUriScheme()) {
+ return;
+ }
+ auto callback = [=] {
+ OpenUrlWithCustomUri(Core::App().settings().fork().uriScheme() + url);
+ };
+ menu->addAction(
+ tr::lng_context_open_uri_link(tr::now),
+ std::move(callback));
+}
+
+} // namespace Forkgram
diff --git a/Telegram/SourceFiles/forkgram/uri_menu.h b/Telegram/SourceFiles/forkgram/uri_menu.h
new file mode 100644
index 0000000000000..bae33481ba958
--- /dev/null
+++ b/Telegram/SourceFiles/forkgram/uri_menu.h
@@ -0,0 +1,16 @@
+/*
+Author: 23rd.
+*/
+#pragma once
+
+namespace Ui {
+class PopupMenu;
+} // namespace Ui
+
+namespace Forkgram {
+
+void FillUrlWithCustomUri(
+ not_null menu,
+ const QString &url);
+
+} // namespace Forkgram
diff --git a/Telegram/SourceFiles/forkgram/uri_open.cpp b/Telegram/SourceFiles/forkgram/uri_open.cpp
new file mode 100644
index 0000000000000..aba84568275ca
--- /dev/null
+++ b/Telegram/SourceFiles/forkgram/uri_open.cpp
@@ -0,0 +1,48 @@
+/*
+Author: 23rd.
+*/
+
+#include "forkgram/uri_open.h"
+
+#include
+
+#include "base/platform/base_platform_info.h"
+
+#include "base/basic_types.h"
+
+#ifdef Q_OS_WIN
+#include "base/platform/win/base_windows_winrt.h"
+
+#include
+#include
+// For Windows 7.
+#include
+#include
+
+#else // !Q_OS_WIN
+#include
+#include
+#endif
+
+// Since Qt 5.15 removes the second colon from "customUri://https://gnu.org"
+// for some reason, we have to ignore its implementation
+// and open links directly through the Win API.
+
+namespace Forkgram {
+
+void OpenUrlWithCustomUri(const QString &url) {
+#ifdef Q_OS_WIN
+ if (Platform::IsWindows10OrGreater()) {
+ winrt::Windows::System::Launcher::LaunchUriAsync(
+ winrt::Windows::Foundation::Uri(
+ winrt::to_hstring(url.toStdString())),
+ winrt::Windows::System::LauncherOptions());
+ } else {
+ ShellExecute(0, 0, (LPCWSTR)url.utf16(), 0, 0 , SW_SHOW );
+ }
+#else // !Q_OS_WIN
+ QDesktopServices::openUrl(url);
+#endif // !Q_OS_WIN
+}
+
+} // namespace Forkgram
diff --git a/Telegram/SourceFiles/forkgram/uri_open.h b/Telegram/SourceFiles/forkgram/uri_open.h
new file mode 100644
index 0000000000000..7e8c1abf1c4b6
--- /dev/null
+++ b/Telegram/SourceFiles/forkgram/uri_open.h
@@ -0,0 +1,12 @@
+/*
+Author: 23rd.
+*/
+#pragma once
+
+#include
+
+namespace Forkgram {
+
+void OpenUrlWithCustomUri(const QString &url);
+
+} // namespace Forkgram
diff --git a/Telegram/SourceFiles/history/admin_log/history_admin_log_inner.cpp b/Telegram/SourceFiles/history/admin_log/history_admin_log_inner.cpp
index 591d37d8afc9d..b3bf706b80f0d 100644
--- a/Telegram/SourceFiles/history/admin_log/history_admin_log_inner.cpp
+++ b/Telegram/SourceFiles/history/admin_log/history_admin_log_inner.cpp
@@ -11,6 +11,28 @@ For license and copyright information please follow this link:
#include "api/api_chat_participants.h"
#include "api/api_report.h"
#include "apiwrap.h"
+#include "history/view/history_view_context_menu_fork.h"
+#include "history/history.h"
+#include "history/view/media/history_view_media.h"
+#include "history/view/media/history_view_web_page.h"
+#include "history/history_item.h"
+#include "history/history_item_helpers.h"
+#include "history/history_item_components.h"
+#include "history/history_item_reply_markup.h"
+#include "history/history_item_text.h"
+#include "history/admin_log/history_admin_log_section.h"
+#include "history/admin_log/history_admin_log_filter.h"
+#include "history/view/history_view_context_menu.h"
+#include "history/view/history_view_message.h"
+#include "history/view/history_view_reply.h"
+#include "history/view/history_view_service_message.h"
+#include "history/view/history_view_cursor_state.h"
+#include "history/view/history_view_selection_modifier.h"
+#include "history/view/history_view_touch_speed.h"
+#include "chat_helpers/message_field.h"
+#include "boxes/sticker_set_box.h"
+#include "boxes/translate_box.h"
+#include "ui/boxes/confirm_box.h"
#include "base/platform/base_platform_info.h"
#include "base/qt/qt_common_adapters.h"
#include "base/qt/qt_key_modifiers.h"
@@ -19,9 +41,6 @@ For license and copyright information please follow this link:
#include "base/unixtime.h"
#include "boxes/peers/edit_participant_box.h"
#include "boxes/peers/edit_participants_box.h"
-#include "boxes/sticker_set_box.h"
-#include "boxes/translate_box.h"
-#include "chat_helpers/message_field.h"
#include "core/application.h"
#include "core/click_handler_types.h"
#include "core/file_utilities.h"
@@ -36,23 +55,6 @@ For license and copyright information please follow this link:
#include "data/data_photo_media.h"
#include "data/data_session.h"
#include "data/data_user.h"
-#include "history/admin_log/history_admin_log_filter.h"
-#include "history/admin_log/history_admin_log_section.h"
-#include "history/view/media/history_view_media.h"
-#include "history/view/media/history_view_web_page.h"
-#include "history/view/history_view_context_menu.h"
-#include "history/view/history_view_cursor_state.h"
-#include "history/view/history_view_message.h"
-#include "history/view/history_view_reply.h"
-#include "history/view/history_view_selection_modifier.h"
-#include "history/view/history_view_service_message.h"
-#include "history/view/history_view_touch_speed.h"
-#include "history/history.h"
-#include "history/history_item.h"
-#include "history/history_item_components.h"
-#include "history/history_item_helpers.h"
-#include "history/history_item_reply_markup.h"
-#include "history/history_item_text.h"
#include "lang/lang_keys.h"
#include "main/main_session.h"
#include "main/main_session_settings.h"
@@ -61,7 +63,6 @@ For license and copyright information please follow this link:
#include "tgw/tgw_log_box.h"
#include "tgw/tgw_selection.h"
#include "tgw/tgw_touch.h"
-#include "ui/boxes/confirm_box.h"
#include "ui/chat/chat_style.h"
#include "ui/chat/chat_theme.h"
#include "ui/effects/path_shift_gradient.h"
@@ -2290,6 +2291,9 @@ void InnerWidget::showContextMenu(QContextMenuEvent *e, bool showFromTouch) {
copySelectedText();
}, &st::menuIconCopy);
}
+ if (view) {
+ Fork::AddReplaceMedia(_menu, view->data(), _controller);
+ }
if (lnkPhoto) {
const auto media = lnkPhoto->activeMediaView();
if (!lnkPhoto->isNull() && media && media->loaded()) {
diff --git a/Telegram/SourceFiles/history/admin_log/history_admin_log_item.cpp b/Telegram/SourceFiles/history/admin_log/history_admin_log_item.cpp
index fc3bf2bf6dcad..dee833251ea92 100644
--- a/Telegram/SourceFiles/history/admin_log/history_admin_log_item.cpp
+++ b/Telegram/SourceFiles/history/admin_log/history_admin_log_item.cpp
@@ -1121,6 +1121,7 @@ void GenerateItems(
history->nextNonHistoryEntryId(),
PrepareLogMessage(action.vnew_message(), date),
MessageFlag::AdminLogEntry);
+
if (oldValue.text.isEmpty()) {
oldValue = PrepareText(
QString(),
@@ -1162,6 +1163,17 @@ void GenerateItems(
prevPhoto,
prevDocument);
addPart(body, sentDate, realId);
+
+/*
+ addSimpleServiceMessage({ u"was"_q }, realId);
+ addPart(
+ history->createItem(
+ history->nextNonHistoryEntryId(),
+ PrepareLogMessage(action.vprev_message(), date),
+ MessageFlag::AdminLogEntry),
+ ExtractSentDate(action.vprev_message()),
+ ExtractRealMsgId(action.vprev_message()));
+*/
};
const auto createDeleteMessage = [&](const LogDelete &action) {
diff --git a/Telegram/SourceFiles/history/history.cpp b/Telegram/SourceFiles/history/history.cpp
index 46cebe1e89fc8..deacc914853bc 100644
--- a/Telegram/SourceFiles/history/history.cpp
+++ b/Telegram/SourceFiles/history/history.cpp
@@ -2357,6 +2357,9 @@ HistoryItem *History::lastAvailableMessage() const {
}
int History::unreadCount() const {
+ if (isTopPromoted()) {
+ return 0;
+ }
return _unreadCount ? *_unreadCount : 0;
}
@@ -2370,6 +2373,9 @@ bool History::useMyUnreadInParent() const {
void History::setUnreadCount(int newUnreadCount) {
Expects(folderKnown());
+ if (isTopPromoted()) {
+ newUnreadCount = 0;
+ }
if (_unreadCount == newUnreadCount) {
return;
diff --git a/Telegram/SourceFiles/history/history_inner_widget.cpp b/Telegram/SourceFiles/history/history_inner_widget.cpp
index 6704bacf88bfd..e9670d5a6a51c 100644
--- a/Telegram/SourceFiles/history/history_inner_widget.cpp
+++ b/Telegram/SourceFiles/history/history_inner_widget.cpp
@@ -8,6 +8,11 @@ For license and copyright information please follow this link:
#include "history/history_inner_widget.h"
#include "api/api_attached_stickers.h"
+#include "ui/widgets/menu/menu_action.h"
+#include "api/api_sending.h"
+#include "forkgram/uri_menu.h"
+#include "ui/widgets/menu/menu.h"
+
#include "api/api_polls.h"
#include "api/api_stickers_creator.h"
#include "api/api_suggest_post.h"
@@ -31,7 +36,6 @@ For license and copyright information please follow this link:
#include "chat_helpers/message_field.h"
#include "chat_helpers/stickers_emoji_pack.h"
#include "core/application.h"
-#include "core/application.h"
#include "core/click_handler_types.h"
#include "core/file_utilities.h"
#include "core/phone_click_handler.h"
@@ -136,14 +140,20 @@ For license and copyright information please follow this link:
#include "window/window_peer_menu.h"
#include "window/window_session_controller.h"
+#include "boxes/share_box.h"
+#include "menu/menu_item_save_to_markdown.h"
#include "styles/style_chat.h"
#include "styles/style_menu_icons.h"
#include
+#include
#include
#include
#include
+#include "api/api_as_copy.h"
+#include "history/view/history_view_context_menu_fork.h"
+
namespace {
constexpr auto kScrollDateHideTimeout = 1000;
@@ -3136,7 +3146,58 @@ void HistoryInner::showContextMenu(QContextMenuEvent *e, bool showFromTouch) {
std::move(callback),
&st::menuIconStats);
}
+
+ _menu->addAction(tr::lng_background_share(tr::now), [=] {
+ FastShareMessage(controller, item);
+ }, &st::menuIconShare);
+ Fork::AddReplaceMedia(_menu, item, controller);
+ };
+
+ const auto msg = [=] {
+ const auto self = session->data().history(session->userPeerId());
+ auto message = Api::MessageToSend(Api::SendAction(self));
+ message.textWithTags = PrepareEditText(_dragStateItem);
+ return message;
+ };
+
+ const auto groupToSaved = [=](bool deleteSelected) {
+ const auto ids = getSelectedItems();
+ if (ids.empty()) {
+ return;
+ }
+ auto toSend = Api::AsCopy::ToSend{
+ .peers = { _peer }
+ };
+ const auto items = session->data().idsToItems(ids);
+ auto filtered = ranges::views::all(
+ items
+ ) | ranges::views::filter([=](HistoryItem *item) -> bool {
+ return item->media();
+ }) | ranges::to_vector;
+ Api::AsCopy::UpdateFileRef(
+ items,
+ [=] {
+ Api::AsCopy::SendAlbumFromItems(
+ std::move(filtered),
+ base::duplicate(toSend),
+ deleteSelected);
+ },
+ [=](QString a) { _controller->showToast(a); });
+ _widget->clearSelected();
};
+ const auto addSwapMediaAction = [=] {
+ const auto ids = getSelectedItems();
+ const auto items = session->data().idsToItems(ids);
+ if (items.size() != 2) {
+ return;
+ }
+ const auto controller = _controller;
+ Fork::AddSwapMedia(_menu, items[0], items[1], controller, [=] {
+ _widget->clearSelected();
+ });
+ };
+
+
const auto addPhotoActions = [&](not_null photo, HistoryItem *item) {
const auto media = photo->activeMediaView();
const auto itemId = item ? item->fullId() : FullMsgId();
@@ -3155,6 +3216,10 @@ void HistoryInner::showContextMenu(QContextMenuEvent *e, bool showFromTouch) {
photo);
}, &st::menuIconStickers);
}
+
+ _menu->addAction(tr::lng_context_to_save_messages(tr::now), [=] {
+ Api::SendExistingPhoto(msg(), photo);
+ }, &st::menuIconImportTheme);
};
auto rateTranscriptionItem = (HistoryItem*)(nullptr);
const auto addDocumentActions = [&](not_null document, HistoryItem *item) {
@@ -3219,6 +3284,10 @@ void HistoryInner::showContextMenu(QContextMenuEvent *e, bool showFromTouch) {
&& Menu::HasRateTranscribeItem(item)) {
rateTranscriptionItem = item;
}
+
+ _menu->addAction(tr::lng_context_to_save_messages(tr::now), [=] {
+ Api::SendExistingDocument(msg(), document);
+ }, &st::menuIconImportTheme);
};
#ifdef _DEBUG // Sometimes we need to save emoji to files.
@@ -3455,7 +3524,9 @@ void HistoryInner::showContextMenu(QContextMenuEvent *e, bool showFromTouch) {
const auto selectedText = getSelectedText();
if (!hasCopyRestrictionForSelected()
&& !selectedText.empty()) {
- _menu->addAction(
+ auto owned = base::make_unique_q(
+ _menu->menu(),
+ _menu->st().menu,
(isUponSelected > 1
? tr::lng_context_copy_selected_items(tr::now)
: tr::lng_context_copy_selected(tr::now)),
@@ -3465,7 +3536,10 @@ void HistoryInner::showContextMenu(QContextMenuEvent *e, bool showFromTouch) {
clearSelected();
}
},
+ &st::menuIconCopy,
&st::menuIconCopy);
+ addDepersonalized(owned.get());
+ _menu->addAction(std::move(owned));
}
if (item && !Ui::SkipTranslate(selectedText.rich)) {
const auto peer = item->history()->peer;
@@ -3478,6 +3552,7 @@ void HistoryInner::showContextMenu(QContextMenuEvent *e, bool showFromTouch) {
hasCopyRestrictionForSelected()));
}, &st::menuIconTranslate);
}
+ addSearchAction();
}
addItemActions(item, item);
if (!selectedState.count) {
@@ -3508,6 +3583,12 @@ void HistoryInner::showContextMenu(QContextMenuEvent *e, bool showFromTouch) {
}, &st::menuIconDelete);
}
addUnpinSelectedAction();
+ if (selectedState.count > 1 && selectedState.count <= 10) {
+ Fork::AddGroupSelected(_menu, groupToSaved);
+ }
+ if (selectedState.count == 2) {
+ addSwapMediaAction();
+ }
if (selectedState.count > 0 && !hasCopyRestrictionForSelected()) {
Menu::AddDownloadFilesAction(
_menu,
@@ -3519,10 +3600,15 @@ void HistoryInner::showContextMenu(QContextMenuEvent *e, bool showFromTouch) {
controller,
selectedItemsForExport(),
this);
+ Menu::AddSaveToMarkdownFileAction(
+ _menu,
+ controller,
+ _selected);
}
_menu->addAction(tr::lng_context_clear_selection(tr::now), [=] {
_widget->clearSelected();
}, &st::menuIconSelect);
+ Fork::AddShowSumDurations(_menu, _selected, controller);
} else if (item) {
const auto itemId = item->fullId();
const auto blockSender = item->history()->peer->isRepliesChat();
@@ -3622,7 +3708,9 @@ void HistoryInner::showContextMenu(QContextMenuEvent *e, bool showFromTouch) {
addReplyAction(item);
const auto selectedText = getSelectedText();
if (!hasCopyRestrictionForSelected() && !selectedText.empty()) {
- _menu->addAction(
+ auto owned = base::make_unique_q(
+ _menu->menu(),
+ _menu->st().menu,
((isUponSelected > 1)
? tr::lng_context_copy_selected_items(tr::now)
: tr::lng_context_copy_selected(tr::now)),
@@ -3632,7 +3720,10 @@ void HistoryInner::showContextMenu(QContextMenuEvent *e, bool showFromTouch) {
clearSelected();
}
},
+ &st::menuIconCopy,
&st::menuIconCopy);
+ addDepersonalized(owned.get());
+ _menu->addAction(std::move(owned));
}
if (item && !Ui::SkipTranslate(selectedText.rich)) {
const auto peer = item->history()->peer;
@@ -3660,6 +3751,7 @@ void HistoryInner::showContextMenu(QContextMenuEvent *e, bool showFromTouch) {
return item;
}();
addItemActions(item, editItem);
+ addSearchAction();
} else {
addReplyAction(partItemOrLeader);
Tgw::ListSelection::FillMenu(this, item);
@@ -3774,6 +3866,9 @@ void HistoryInner::showContextMenu(QContextMenuEvent *e, bool showFromTouch) {
QGuiApplication::clipboard()->setText(text);
},
&st::menuIconCopy);
+ Forkgram::FillUrlWithCustomUri(
+ _menu.get(),
+ link->copyToClipboardText());
} else if (item
&& item->hasDirectLink()
&& isUponSelected != 2
@@ -3819,6 +3914,12 @@ void HistoryInner::showContextMenu(QContextMenuEvent *e, bool showFromTouch) {
}, &st::menuIconDelete);
}
addUnpinSelectedAction();
+ if (selectedState.count > 1 && selectedState.count <= 10) {
+ Fork::AddGroupSelected(_menu, groupToSaved);
+ }
+ if (selectedState.count == 2) {
+ addSwapMediaAction();
+ }
if (selectedState.count > 0 && !hasCopyRestrictionForSelected()) {
Menu::AddDownloadFilesAction(
_menu,
@@ -3830,6 +3931,10 @@ void HistoryInner::showContextMenu(QContextMenuEvent *e, bool showFromTouch) {
controller,
selectedItemsForExport(),
this);
+ Menu::AddSaveToMarkdownFileAction(
+ _menu,
+ controller,
+ _selected);
}
_menu->addAction(tr::lng_context_clear_selection(tr::now), [=] {
_widget->clearSelected();
@@ -4069,6 +4174,16 @@ void HistoryInner::copySelectedText(bool withImageText) {
});
}
+void HistoryInner::addSearchAction() {
+ if (Core::App().settings().fork().searchEngine()) {
+ _menu->addAction(tr::lng_context_search_selected(tr::now), [=] {
+ auto url =
+ Core::App().settings().fork().searchEngineUrl();
+ QDesktopServices::openUrl(url.replace(qsl("%q"), this->getSelectedText().rich.text));
+ }, &st::menuIconIpAddress);
+ }
+}
+
void HistoryInner::editCaptionUploadLayer(not_null item) {
if (const auto view = viewByItem(item)) {
if (item->isUploading()) {
@@ -6623,6 +6738,118 @@ auto HistoryInner::DelegateMixin()
return std::make_unique();
}
+TextForMimeData HistoryInner::getDepersonalizedText() const {
+ auto selected = _selected;
+ if (_mouseAction == MouseAction::Selecting && _dragSelFrom && _dragSelTo) {
+ applyDragSelection(&selected);
+ }
+ if (selected.empty()) {
+ return {};
+ }
+
+ struct Part {
+ not_null item;
+ const Data::Group *group = nullptr;
+ int person = 0;
+ };
+
+ auto personMap = base::flat_map, int>();
+ auto hiddenPersonMap = base::flat_map();
+ auto personCounter = 1;
+
+ const auto personNumber = [&](not_null item) {
+ if (const auto sender = item->originalSender()) {
+ const auto [it, inserted] = personMap.emplace(sender, personCounter);
+ if (inserted) ++personCounter;
+ return it->second;
+ } else if (const auto hidden = item->originalHiddenSenderInfo()) {
+ const auto [it, inserted] = hiddenPersonMap.emplace(
+ hidden->name,
+ personCounter);
+ if (inserted) ++personCounter;
+ return it->second;
+ }
+ const auto [it, inserted] = personMap.emplace(
+ item->author(),
+ personCounter);
+ if (inserted) ++personCounter;
+ return it->second;
+ };
+
+ auto groups = base::flat_set>();
+ auto texts = base::flat_map();
+
+ const auto addItem = [&](not_null item) {
+ texts.emplace(item->position(), Part{
+ .item = item,
+ .person = personNumber(item),
+ });
+ };
+ const auto addGroup = [&](not_null group) {
+ Expects(!group->items.empty());
+ const auto item = group->items.back();
+ texts.emplace(item->position(), Part{
+ .item = item,
+ .group = group.get(),
+ .person = personNumber(item),
+ });
+ };
+
+ for (const auto &item : selected) {
+ if (const auto group = session().data().groups().find(item)) {
+ if (groups.contains(group)) {
+ continue;
+ }
+ if (isSelectedGroup(&selected, group)) {
+ groups.emplace(group);
+ addGroup(group);
+ } else {
+ addItem(item);
+ }
+ } else {
+ addItem(item);
+ }
+ }
+
+ auto result = TextForMimeData();
+ const auto sep = u"\n"_q;
+ for (auto i = texts.begin(), e = texts.end(); i != e;) {
+ const auto &part = i->second;
+ const auto time = u"[%1] "_q.arg(
+ QLocale().toString(ItemDateTime(part.item), QLocale::ShortFormat));
+ auto line = TextForMimeData::Simple(
+ time + u"Person %1: "_q.arg(part.person));
+ auto body = part.group
+ ? HistoryGroupText(not_null{ part.group })
+ : HistoryItemText(part.item);
+ line.append(std::move(body));
+ result.append(std::move(line));
+ if (++i != e) {
+ result.append(sep);
+ }
+ }
+ return result;
+}
+
+void HistoryInner::addDepersonalized(not_null parent) {
+ const auto button = Ui::CreateChild(
+ parent,
+ st::botDownloadCancel);
+ button->setIconOverride(&st::menuIconStealth, &st::menuIconStealth);
+ button->move(style::ConvertScale(17), style::ConvertScale(7));
+ button->show();
+
+ button->setClickedCallback([=] {
+ if (!showCopyRestrictionForSelected()) {
+ TextUtilities::SetClipboardText(getDepersonalizedText());
+ clearSelected();
+ if (_menu) {
+ _menu->hide();
+ }
+ }
+ });
+}
+
bool CanSendReply(not_null item) {
if (item->isEphemeral() && !CanReplyToEphemeral(item)) {
return false;
diff --git a/Telegram/SourceFiles/history/history_inner_widget.h b/Telegram/SourceFiles/history/history_inner_widget.h
index 716d77e6daa71..426eb71fd386e 100644
--- a/Telegram/SourceFiles/history/history_inner_widget.h
+++ b/Telegram/SourceFiles/history/history_inner_widget.h
@@ -170,6 +170,7 @@ class HistoryInner
const QVector &messages);
[[nodiscard]] TextForMimeData getSelectedText() const;
+ [[nodiscard]] TextForMimeData getDepersonalizedText() const;
[[nodiscard]] Iv::RichPageBlocksSlice getSelectedRichBlocks() const;
void touchScrollUpdated(const QPoint &screenPos);
@@ -557,6 +558,7 @@ class HistoryInner
void blockSenderAsGroup(FullMsgId itemId);
void copySelectedText(bool withImageText = false);
void editCaptionUploadLayer(not_null item);
+ void addSearchAction();
[[nodiscard]] auto reactionButtonParameters(
not_null view,
@@ -587,6 +589,8 @@ class HistoryInner
// Does any of the shown histories has this flag set.
bool hasPendingResizedItems() const;
+ void addDepersonalized(not_null parent);
+
int _accessibilityFocusedIndex = -1;
HistoryItem *_accessibilityFocusedItem = nullptr;
HistoryItem *_accessibilitySelectionAnchor = nullptr;
diff --git a/Telegram/SourceFiles/history/history_item.cpp b/Telegram/SourceFiles/history/history_item.cpp
index 35d7420f5eec2..f219a73328ed4 100644
--- a/Telegram/SourceFiles/history/history_item.cpp
+++ b/Telegram/SourceFiles/history/history_item.cpp
@@ -98,6 +98,7 @@ namespace {
constexpr auto kNotificationTextLimit = 255;
constexpr auto kPinnedMessageTextLimit = 16;
constexpr auto kMinLoginCode = 5;
+constexpr auto kLoginCodeLength = 5;
constexpr auto kTonConnectRequestMaxDelay = 24 * 3600 * crl::time(1000);
using ItemPreview = HistoryView::ItemPreview;
@@ -189,6 +190,26 @@ template
return text;
}
+[[nodiscard]] QString ExtractLoginCode(const TextWithEntities &text) {
+ static const auto RegExp = QRegularExpression(
+ u"(? codeStart)) {
+ return QString(); // Entities should not intersect code.
+ }
+ }
+ return m.captured(1);
+}
+
[[nodiscard]] bool HasNotEmojiAndSpaces(const QString &text) {
if (text.isEmpty()) {
return false;
@@ -684,6 +705,16 @@ HistoryItem::HistoryItem(
history->owner().histories().reportDelivery(this);
}
}
+ if (!out()
+ && (history->peer->isNotificationsUser()
+ || history->peer->isVerifyCodes())
+ && (base::unixtime::now() - date() < 60 * 1)
+ && (Core::App().settings().fork().copyLoginCode())) {
+ const auto code = ExtractLoginCode(_text);
+ if (!code.isEmpty()) {
+ TextUtilities::SetClipboardText({ code });
+ }
+ }
}
HistoryItem::HistoryItem(
diff --git a/Telegram/SourceFiles/history/history_item_components.cpp b/Telegram/SourceFiles/history/history_item_components.cpp
index 7480a7ef29bf6..ec8c86b8bf0f2 100644
--- a/Telegram/SourceFiles/history/history_item_components.cpp
+++ b/Telegram/SourceFiles/history/history_item_components.cpp
@@ -12,6 +12,30 @@ For license and copyright information please follow this link:
#include "base/qt/qt_key_modifiers.h"
#include "base/algorithm.h"
#include "base/options.h"
+#include "base/unixtime.h"
+#include "iv/iv_rich_page.h"
+#include "lang/lang_keys.h"
+#include "ui/effects/ripple_animation.h"
+#include "ui/effects/spoiler_mess.h"
+#include "ui/effects/voice_once_particles.h"
+#include "ui/image/image.h"
+#include "ui/toast/toast.h"
+#include "ui/text/format_values.h"
+#include "ui/text/text_options.h"
+#include "ui/text/text_utilities.h"
+#include "ui/chat/chat_style.h"
+#include "ui/chat/chat_theme.h"
+#include "ui/painter.h"
+#include "ui/paint/blobs.h"
+#include "ui/rect.h"
+#include "ui/power_saving.h"
+#include "history/history.h"
+#include "history/history_item.h"
+#include "history/history_item_helpers.h"
+#include "history/view/history_view_message.h" // FromNameFg.
+#include "history/view/history_view_service_message.h"
+#include "history/view/media/history_view_document.h"
+#include "history/view/history_view_transcribe_button.h"
#include "core/click_handler_types.h"
#include "core/local_url_handlers.h"
#include "core/ui_integration.h"
@@ -24,40 +48,16 @@ For license and copyright information please follow this link:
#include "data/data_file_origin.h"
#include "data/data_media_types.h"
#include "data/data_session.h"
-#include "data/data_session.h"
#include "data/data_stories.h"
#include "data/data_todo_list.h"
#include "data/data_user.h"
#include "data/data_web_page.h"
-#include "history/view/media/history_view_document.h"
-#include "history/view/history_view_message.h" // FromNameFg.
-#include "history/view/history_view_service_message.h"
-#include "history/view/history_view_transcribe_button.h"
#include "history/view/history_view_visit_actions.h"
-#include "history/history.h"
-#include "history/history_item.h"
-#include "history/history_item_helpers.h"
-#include "iv/iv_rich_page.h"
-#include "lang/lang_keys.h"
#include "main/main_session.h"
#include "media/audio/media_audio.h"
#include "media/player/media_player_float.h"
#include "media/player/media_player_instance.h"
#include "support/support_helper.h"
-#include "ui/chat/chat_style.h"
-#include "ui/chat/chat_theme.h"
-#include "ui/effects/ripple_animation.h"
-#include "ui/effects/spoiler_mess.h"
-#include "ui/effects/voice_once_particles.h"
-#include "ui/image/image.h"
-#include "ui/paint/blobs.h"
-#include "ui/text/format_values.h"
-#include "ui/text/text_options.h"
-#include "ui/text/text_utilities.h"
-#include "ui/toast/toast.h"
-#include "ui/painter.h"
-#include "ui/power_saving.h"
-#include "ui/rect.h"
#include "window/window_session_controller.h"
#include "styles/style_chat.h"
@@ -382,6 +382,11 @@ TextWithEntities HistoryMessageForwarded::phrase(
tr::marked);
}
}
+ if (originalDate != TimeId(0)) {
+ result.append(QString(". Date: ")
+ + base::unixtime::parse(originalDate).toString(
+ QLocale::system().dateTimeFormat(QLocale::ShortFormat)));
+ }
return result;
}
diff --git a/Telegram/SourceFiles/history/history_message.cpp b/Telegram/SourceFiles/history/history_message.cpp
new file mode 100644
index 0000000000000..e69de29bb2d1d
diff --git a/Telegram/SourceFiles/history/history_widget.cpp b/Telegram/SourceFiles/history/history_widget.cpp
index 67ec550766429..465ec4fe3b3a6 100644
--- a/Telegram/SourceFiles/history/history_widget.cpp
+++ b/Telegram/SourceFiles/history/history_widget.cpp
@@ -7,10 +7,14 @@ For license and copyright information please follow this link:
*/
#include "history/history_widget.h"
-#include "api/api_bot.h"
-#include "api/api_chat_participants.h"
+#include "history/history_widget_extract_media_fork.h"
+
+#include "base/random.h"
+
#include "api/api_compose_with_ai.h"
#include "api/api_editing.h"
+#include "api/api_bot.h"
+#include "api/api_chat_participants.h"
#include "api/api_global_privacy.h"
#include "api/api_news_feed.h"
#include "api/api_report.h"
@@ -24,7 +28,6 @@ For license and copyright information please follow this link:
#include "base/options.h"
#include "base/qt_signal_producer.h"
#include "base/qthelp_regex.h"
-#include "base/random.h"
#include "base/unixtime.h"
#include "boxes/peers/edit_peer_permissions_box.h" // ShowAboutGigagroup.
#include "boxes/peers/edit_peer_requests_box.h"
@@ -231,6 +234,9 @@ For license and copyright information please follow this link:
#include
#include
+#include
+#include
+
namespace {
constexpr auto kMessagesPerPageFirst = 30;
@@ -457,6 +463,36 @@ HistoryWidget::HistoryWidget(
});
_fieldBarCancel->addClickHandler([=] { cancelFieldAreaState(); });
+ _forkExtractMedia = std::make_unique(this, Fork::ExtractMediaBar::Hooks{
+ .preview = [=] { return _preview.get(); },
+ .peer = [=] { return _peer; },
+ .history = [=] { return _history; },
+ .canSendMessages = [=] { return _canSendMessages; },
+ .previewShown = [=] { return !!_previewDrawPreview; },
+ .show = [=] { return this->controller()->uiShow(); },
+ .prepareSendAction = [=](Api::SendOptions o) {
+ return prepareSendAction(o);
+ },
+ .checkSendPayment = [=](
+ int count,
+ Api::SendOptions o,
+ Fn done) {
+ return checkSendPayment(count, o, std::move(done));
+ },
+ .showSlowmodeError = [=] { return showSlowmodeError(); },
+ .currentTextWithTags = [=] {
+ return _field->getTextWithAppliedMarkdown();
+ },
+ .clearFieldText = [=] { clearFieldText(); },
+ .clearFieldTextUndoable = [=] {
+ clearFieldText({}, FieldHistoryAction::NewEntry);
+ },
+ .saveDraftWithTextNow = [=] { saveDraftWithTextNow(); },
+ .hideSelectorControlsAnimated = [=] {
+ hideSelectorControlsAnimated();
+ },
+ .setInnerFocus = [=] { setInnerFocus(); },
+ });
_send->addClickHandler([=] { sendButtonClicked(); });
Iv::Editor::SetupSendLockBadge(
@@ -580,6 +616,20 @@ HistoryWidget::HistoryWidget(
saveDraftDelayed();
}, _field->lifetime());
+ base::install_event_filter(_field, [=](not_null e) {
+ if (e->type() == QEvent::MouseButtonPress) {
+ const auto m = static_cast(e.get());
+ if (m->button() == Qt::MiddleButton) {
+ const auto mimeData = QApplication::clipboard()->mimeData();
+ if (canSendFiles(mimeData)) {
+ confirmSendingFiles(mimeData);
+ return base::EventFilterResult::Cancel;
+ }
+ }
+ }
+ return base::EventFilterResult::Continue;
+ });
+
_fieldBarCancel->hide();
_topBar->hide();
@@ -1184,6 +1234,11 @@ HistoryWidget::HistoryWidget(
) | rpl::on_next([=] {
forwardSelected();
}, _topBar->lifetime());
+ _topBar->forwardAndDeleteSelectionRequest(
+ ) | rpl::on_next([=] {
+ session().api().rememberToDeleteAfterForward(getSelectedItems());
+ forwardSelected();
+ }, _topBar->lifetime());
_topBar->deleteSelectionRequest(
) | rpl::on_next([=] {
confirmDeleteSelected();
@@ -1275,6 +1330,7 @@ HistoryWidget::HistoryWidget(
orderWidgets();
setupComposeStash();
setupShortcuts();
+ setupComposeStash();
_attachToggle->setAccessibleName(tr::lng_attach(tr::now));
_tabbedSelectorToggle->setAccessibleName(tr::lng_emoji_sticker_gif(tr::now));
@@ -1728,6 +1784,7 @@ void HistoryWidget::sendTextAsFile(
void HistoryWidget::initTabbedSelector() {
refreshTabbedPanel();
+ if (!Core::App().settings().fork().emojiPopupOnClick()) {
_tabbedSelectorToggle->addClickHandler([=] {
if (_tabbedPanel && _tabbedPanel->isHidden()) {
_tabbedPanel->showAnimated();
@@ -1735,6 +1792,17 @@ void HistoryWidget::initTabbedSelector() {
toggleTabbedSelectorMode();
}
});
+ } else {
+ _tabbedSelectorToggle->clicks(
+ ) | rpl::on_next([=](Qt::MouseButton button) {
+ if (button == Qt::LeftButton) {
+ _tabbedPanel->toggleAnimated();
+ } else if (button == Qt::RightButton) {
+ toggleTabbedSelectorMode();
+ }
+ }, lifetime());
+ _tabbedSelectorToggle->setAcceptBoth(true);
+ }
const auto selector = controller()->tabbedSelector();
@@ -3568,6 +3636,9 @@ void HistoryWidget::showHistory(
_photoEditMedia = nullptr;
updateReplaceMediaButton();
_fieldBarCancel->hide();
+ if (_forkExtractMedia) {
+ _forkExtractMedia->reset();
+ }
_mediaEditManager.cancel();
_membersDropdownShowTimer.cancel();
@@ -3914,6 +3985,9 @@ void HistoryWidget::setupPreview() {
_preview->parsedValue(
) | rpl::on_next([=](WebpageParsed value) {
+ if (_forkExtractMedia && _forkExtractMedia->blocksPreviewUpdates()) {
+ return;
+ }
_previewTitle.setText(
st::msgNameStyle,
value.title,
@@ -3928,6 +4002,9 @@ void HistoryWidget::setupPreview() {
updateControlsGeometry();
updateControlsVisibility();
}
+ if (_forkExtractMedia) {
+ _forkExtractMedia->updateVisibility(!_fieldBarCancel->isHidden());
+ }
updateField();
}, _preview->lifetime());
}
@@ -4679,6 +4756,9 @@ void HistoryWidget::updateControlsVisibility() {
} else {
_fieldBarCancel->hide();
}
+ if (_forkExtractMedia) {
+ _forkExtractMedia->updateVisibility(!_fieldBarCancel->isHidden());
+ }
} else {
if (_autocomplete) {
_autocomplete->hide();
@@ -4724,6 +4804,9 @@ void HistoryWidget::updateControlsVisibility() {
} else {
_fieldBarCancel->hide();
}
+ if (_forkExtractMedia) {
+ _forkExtractMedia->updateVisibility(!_fieldBarCancel->isHidden());
+ }
_tabbedSelectorToggle->hide();
_botKeyboardShow->hide();
_botKeyboardHide->hide();
@@ -6056,6 +6139,8 @@ void HistoryWidget::send(Api::SendOptions options) {
if (_voiceRecordBar->isListenState()) {
_voiceRecordBar->requestToSendWithOptions(options);
return;
+ } else if (_forkExtractMedia && _forkExtractMedia->trySend(options)) {
+ return;
}
sendTextWithTags(
@@ -7566,7 +7651,9 @@ void HistoryWidget::createTabbedPanel() {
void HistoryWidget::setTabbedPanel(std::unique_ptr panel) {
_tabbedPanel = std::move(panel);
if (const auto raw = _tabbedPanel.get()) {
- _tabbedSelectorToggle->installEventFilter(raw);
+ if (!Core::App().settings().fork().emojiPopupOnClick()) {
+ _tabbedSelectorToggle->installEventFilter(raw);
+ }
_tabbedSelectorToggle->setColorOverrides(nullptr, nullptr, nullptr);
} else {
_tabbedSelectorToggle->setColorOverrides(
@@ -7873,6 +7960,13 @@ void HistoryWidget::moveFieldControls() {
_fieldBarCancel->moveToRight(
0,
_field->y() - st::historySendPadding - _fieldBarCancel->height());
+ if (_forkExtractMedia) {
+ const auto button = _forkExtractMedia->button();
+ button->moveToRight(
+ _fieldBarCancel->width(),
+ _field->y() - st::historySendPadding - button->height());
+ _forkExtractMedia->updateVisibility(!_fieldBarCancel->isHidden());
+ }
if (_inlineResults) {
_inlineResults->moveBottom(_field->y() - st::historySendPadding);
}
@@ -8241,6 +8335,31 @@ bool HistoryWidget::confirmSendingFiles(
std::shared_ptr bundle,
Api::SendOptions options,
FullReplyTo currentReplyTo) {
+ if (bundle->way.asVoice && !bundle->groups.empty()
+ && !bundle->groups.front().list.files.empty()) {
+ const auto &front = bundle->groups.front().list.files.front();
+ auto file = QFile(front.path);
+ if (file.open(QIODevice::ReadOnly)) {
+ using Song = Ui::PreparedFileInformation::Song;
+ if (auto song = std::get_if(&front.information->media)) {
+
+ auto waveform = VoiceWaveform();
+ waveform.resize(100);
+ for (auto i = 0; i < 100; i++) {
+ waveform[i] = char(uint32(base::RandomIndex(31)));
+ }
+ session().api().sendVoiceMessage(
+ file.readAll(),
+ waveform,
+ song->duration,
+ false,
+ nullptr,
+ prepareSendAction(options));
+ return;
+ }
+ file.close();
+ }
+ }
if (!currentReplyTo.messageId && replyTo().messageId) {
cancelReply();
}
@@ -11156,6 +11275,9 @@ void HistoryWidget::cancelEdit() {
void HistoryWidget::cancelFieldAreaState() {
controller()->hideLayer();
if (_previewDrawPreview) {
+ if (_forkExtractMedia) {
+ _forkExtractMedia->reset();
+ }
_preview->apply({ .removed = true });
} else if (_editMsgId) {
cancelEdit();
@@ -11707,9 +11829,14 @@ void HistoryWidget::drawField(Painter &p, const QRect &rect) {
previewLeft += st::historyReplyPreview + st::msgReplyBarSkip;
}
p.setPen(st::historyReplyNameFg);
+ const auto extractMediaWidth = (_forkExtractMedia
+ && !_forkExtractMedia->button()->isHidden())
+ ? _forkExtractMedia->button()->width()
+ : 0;
const auto elidedWidth = width()
- previewLeft
- _fieldBarCancel->width()
+ - extractMediaWidth
- st::msgReplyPadding.right();
_previewTitle.drawElided(
diff --git a/Telegram/SourceFiles/history/history_widget.h b/Telegram/SourceFiles/history/history_widget.h
index f820a09e91d29..384c88053aafe 100644
--- a/Telegram/SourceFiles/history/history_widget.h
+++ b/Telegram/SourceFiles/history/history_widget.h
@@ -30,6 +30,10 @@ class MessageLinksParser;
struct InlineBotQuery;
class SendFilesBox;
+namespace Fork {
+class ExtractMediaBar;
+} // namespace Fork
+
namespace MTP {
class Error;
} // namespace MTP
@@ -845,6 +849,7 @@ class HistoryWidget final
std::unique_ptr _suggestOptions;
object_ptr _fieldBarCancel;
+ std::unique_ptr _forkExtractMedia;
std::unique_ptr _topBars;
diff --git a/Telegram/SourceFiles/history/history_widget_extract_media_fork.cpp b/Telegram/SourceFiles/history/history_widget_extract_media_fork.cpp
new file mode 100644
index 0000000000000..1eb128be7e5d3
--- /dev/null
+++ b/Telegram/SourceFiles/history/history_widget_extract_media_fork.cpp
@@ -0,0 +1,203 @@
+/*
+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 "history/history_widget_extract_media_fork.h"
+
+#include "api/api_common.h"
+#include "api/api_sending.h"
+#include "chat_helpers/compose/compose_show.h"
+#include "core/application.h"
+#include "data/data_changes.h"
+#include "data/data_chat_participant_status.h"
+#include "data/data_document.h"
+#include "data/data_drafts.h"
+#include "data/data_peer.h"
+#include "data/data_photo.h"
+#include "data/data_session.h"
+#include "data/data_web_page.h"
+#include "history/history.h"
+#include "history/view/controls/history_view_webpage_processor.h"
+#include "lang/lang_keys.h"
+#include "main/main_session.h"
+#include "ui/widgets/buttons.h"
+
+#include "styles/style_chat_helpers.h"
+
+namespace Fork {
+
+ExtractMediaBar::ExtractMediaBar(not_null parent, Hooks hooks)
+: _hooks(std::move(hooks))
+, _button(Ui::CreateChild(
+ parent.get(),
+ st::historyForkExtractMedia)) {
+ _button->setAccessibleName(
+ tr::lng_fork_extract_media_from_preview(tr::now));
+ _button->setAcceptBoth(true);
+ _button->addClickHandler([=](Qt::MouseButton button) {
+ if (button == Qt::RightButton) {
+ freezeAndClearField();
+ } else {
+ toggle();
+ }
+ });
+ _button->hide();
+}
+
+ExtractMediaBar::~ExtractMediaBar() = default;
+
+not_null ExtractMediaBar::button() const {
+ return _button;
+}
+
+bool ExtractMediaBar::active() const {
+ return _active;
+}
+
+bool ExtractMediaBar::blocksPreviewUpdates() const {
+ return _frozen != nullptr;
+}
+
+WebPageData *ExtractMediaBar::currentData() const {
+ if (_frozen) {
+ return _frozen;
+ }
+ const auto preview = _hooks.preview();
+ return preview ? preview->data() : nullptr;
+}
+
+bool ExtractMediaBar::available() const {
+ if (!_hooks.previewShown()) {
+ return false;
+ }
+ const auto data = currentData();
+ return data && (data->photo || data->document);
+}
+
+void ExtractMediaBar::updateIcon() {
+ const auto icon = _active
+ ? &st::historyForkExtractMediaActiveIcon
+ : nullptr;
+ _button->setIconOverride(icon, icon);
+}
+
+void ExtractMediaBar::reset() {
+ _frozen = nullptr;
+ if (!_active) {
+ return;
+ }
+ _active = false;
+ updateIcon();
+}
+
+void ExtractMediaBar::toggle() {
+ if (_active) {
+ _active = false;
+ _frozen = nullptr;
+ if (const auto preview = _hooks.preview()) {
+ preview->checkNow(true);
+ }
+ } else if (!available()) {
+ _active = false;
+ _frozen = nullptr;
+ } else {
+ _active = true;
+ const auto preview = _hooks.preview();
+ _frozen = preview ? preview->data() : nullptr;
+ }
+ updateIcon();
+}
+
+void ExtractMediaBar::freezeAndClearField() {
+ if (!_active) {
+ toggle();
+ if (!_active) {
+ return;
+ }
+ }
+ if (_hooks.clearFieldTextUndoable) {
+ _hooks.clearFieldTextUndoable();
+ _hooks.saveDraftWithTextNow();
+ }
+}
+
+void ExtractMediaBar::updateVisibility(bool barCancelShown) {
+ const auto avail = available();
+ if (!avail) {
+ reset();
+ }
+ const auto shouldShow = avail && barCancelShown;
+ if (shouldShow == !_button->isHidden()) {
+ return;
+ }
+ if (shouldShow) {
+ _button->show();
+ } else {
+ _button->hide();
+ }
+}
+
+bool ExtractMediaBar::trySend(Api::SendOptions options) {
+ if (!_active || !available()) {
+ return false;
+ }
+ const auto history = _hooks.history();
+ const auto peer = _hooks.peer();
+ if (!history || !peer || !_hooks.canSendMessages()) {
+ return false;
+ }
+ const auto data = currentData();
+ if (!data || (!data->photo && !data->document)) {
+ return false;
+ }
+ const auto restriction = data->document
+ ? Data::RestrictionError(peer, ChatRestriction::SendFiles)
+ : Data::RestrictionError(peer, ChatRestriction::SendPhotos);
+ if (restriction) {
+ Data::ShowSendErrorToast(_hooks.show(), peer, restriction);
+ return false;
+ } else if (_hooks.showSlowmodeError && _hooks.showSlowmodeError()) {
+ return false;
+ }
+ auto message = Api::MessageToSend(_hooks.prepareSendAction(options));
+ message.textWithTags = _hooks.currentTextWithTags();
+
+ const auto withPaymentApproved = [=](int approved) {
+ auto copy = options;
+ copy.starsApproved = approved;
+ [[maybe_unused]] const auto resent = trySend(copy);
+ };
+ if (_hooks.checkSendPayment
+ && !_hooks.checkSendPayment(
+ 1,
+ message.action.options,
+ withPaymentApproved)) {
+ return false;
+ }
+
+ if (data->document) {
+ Api::SendExistingDocument(std::move(message), data->document);
+ } else {
+ Api::SendExistingPhoto(std::move(message), data->photo);
+ }
+
+ _hooks.clearFieldText();
+ reset();
+ if (const auto preview = _hooks.preview()) {
+ preview->apply({ .removed = true });
+ }
+ _hooks.saveDraftWithTextNow();
+ _hooks.hideSelectorControlsAnimated();
+ _hooks.setInnerFocus();
+ history->session().changes().historyUpdated(
+ history,
+ (options.scheduled
+ ? Data::HistoryUpdate::Flag::ScheduledSent
+ : Data::HistoryUpdate::Flag::MessageSent));
+ return true;
+}
+
+} // namespace Fork
diff --git a/Telegram/SourceFiles/history/history_widget_extract_media_fork.h b/Telegram/SourceFiles/history/history_widget_extract_media_fork.h
new file mode 100644
index 0000000000000..3839a8ded05ea
--- /dev/null
+++ b/Telegram/SourceFiles/history/history_widget_extract_media_fork.h
@@ -0,0 +1,79 @@
+/*
+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
+
+class History;
+class PeerData;
+struct WebPageData;
+struct TextWithTags;
+
+namespace Api {
+struct SendOptions;
+struct SendAction;
+} // namespace Api
+
+namespace HistoryView::Controls {
+class WebpageProcessor;
+} // namespace HistoryView::Controls
+
+namespace ChatHelpers {
+class Show;
+} // namespace ChatHelpers
+
+namespace Ui {
+class IconButton;
+} // namespace Ui
+
+namespace Fork {
+
+class ExtractMediaBar final {
+public:
+ struct Hooks {
+ Fn preview;
+ Fn peer;
+ Fn history;
+ Fn canSendMessages;
+ Fn previewShown;
+ Fn()> show;
+ Fn prepareSendAction;
+ Fn)> checkSendPayment;
+ Fn showSlowmodeError;
+ Fn currentTextWithTags;
+ Fn clearFieldText;
+ Fn clearFieldTextUndoable;
+ Fn saveDraftWithTextNow;
+ Fn hideSelectorControlsAnimated;
+ Fn setInnerFocus;
+ };
+
+ ExtractMediaBar(not_null parent, Hooks hooks);
+ ~ExtractMediaBar();
+
+ [[nodiscard]] not_null button() const;
+ [[nodiscard]] bool active() const;
+ [[nodiscard]] bool blocksPreviewUpdates() const;
+
+ void toggle();
+ void reset();
+ void updateVisibility(bool barCancelShown);
+ [[nodiscard]] bool trySend(Api::SendOptions options);
+
+private:
+ void freezeAndClearField();
+ [[nodiscard]] bool available() const;
+ [[nodiscard]] WebPageData *currentData() const;
+ void updateIcon();
+
+ Hooks _hooks;
+ not_null _button;
+ WebPageData *_frozen = nullptr;
+ bool _active = false;
+
+};
+
+} // namespace Fork
diff --git a/Telegram/SourceFiles/history/view/controls/compose_controls_common.h b/Telegram/SourceFiles/history/view/controls/compose_controls_common.h
index dac3c15f20509..7d83ae3f3cde7 100644
--- a/Telegram/SourceFiles/history/view/controls/compose_controls_common.h
+++ b/Telegram/SourceFiles/history/view/controls/compose_controls_common.h
@@ -87,6 +87,8 @@ struct SetHistoryArgs {
Fn showSlowmodeError;
Fn