Skip to content

Commit

Permalink
init
Browse files Browse the repository at this point in the history
  • Loading branch information
grandsilence committed Jan 21, 2020
1 parent ca62ce7 commit e49e701
Show file tree
Hide file tree
Showing 11 changed files with 315 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
bin/
obj/
/packages/
.idea/
.vs/
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Telegram Desktop (Windows) Font Patcher

Replace Segoe UI and Open Sans to Arial / Tahoma when DirectWrite disabled.

It's slow but working. If you have a time make it faster on c++.
25 changes: 25 additions & 0 deletions TelegramFontPatcher.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.27428.2015
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TelegramFontPatcher", "TelegramFontPatcher\TelegramFontPatcher.csproj", "{D2DDBFA4-1082-4DFE-8512-3C9220237270}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{D2DDBFA4-1082-4DFE-8512-3C9220237270}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D2DDBFA4-1082-4DFE-8512-3C9220237270}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D2DDBFA4-1082-4DFE-8512-3C9220237270}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D2DDBFA4-1082-4DFE-8512-3C9220237270}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {92756B5D-F0B2-490B-93B5-45A1B038DBDE}
EndGlobalSection
EndGlobal
2 changes: 2 additions & 0 deletions TelegramFontPatcher.sln.DotSettings.user
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:Int64 x:Key="/Default/Environment/SearchAndNavigation/DefaultOccurrencesGroupingIndex/@EntryValue">0</s:Int64></wpf:ResourceDictionary>
6 changes: 6 additions & 0 deletions TelegramFontPatcher/App.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2" />
</startup>
</configuration>
71 changes: 71 additions & 0 deletions TelegramFontPatcher/BinaryUtility.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

//using System.Linq;

namespace TelegramFontPatcher
{
public static class BinaryUtility
{
public static IEnumerable<byte> GetByteStream(BinaryReader reader)
{
const int bufferSize = 1024;
byte[] buffer;
do
{
buffer = reader.ReadBytes(bufferSize);
foreach (var d in buffer) { yield return d; }
} while (bufferSize == buffer.Length);
}

public static void Replace(BinaryReader reader, BinaryWriter writer, IEnumerable<Tuple<byte[], byte[]>> searchAndReplace)
{
foreach (byte d in Replace(GetByteStream(reader), searchAndReplace))
writer.Write(d);
}

private static IEnumerable<byte> Replace(IEnumerable<byte> source, IEnumerable<Tuple<byte[], byte[]>> searchAndReplace)
{
var result = source;
foreach (var tuple in searchAndReplace)
result = Replace(result, tuple.Item1, tuple.Item2);

return result;
}

private static IEnumerable<byte> Replace(IEnumerable<byte> input, IEnumerable<byte> from, IEnumerable<byte> to)
{
using var fromEnumerator = from.GetEnumerator();
fromEnumerator.MoveNext();
int match = 0;
foreach (var data in input)
{
if (data == fromEnumerator.Current)
{
match++;
if (fromEnumerator.MoveNext()) { continue; }
foreach (byte d in to) { yield return d; }
match = 0;
fromEnumerator.Reset();
fromEnumerator.MoveNext();
continue;
}
if (0 != match)
{
foreach (byte d in from.Take(match)) { yield return d; }
match = 0;
fromEnumerator.Reset();
fromEnumerator.MoveNext();
}
yield return data;
}

if (0 != match)
{
foreach (byte d in from.Take(match)) { yield return d; }
}
}
}
}
23 changes: 23 additions & 0 deletions TelegramFontPatcher/PatternList.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Text;

namespace TelegramFontPatcher
{
internal class PatternList : List<Tuple<byte[], byte[]>>
{
public PatternList(string newFont, IEnumerable<string> oldFonts)
{
foreach (string oldFont in oldFonts)
{
Add(oldFont, newFont, Encoding.ASCII);
Add(oldFont, newFont, Encoding.Unicode);
}
}

private void Add(string oldFont, string newFont, Encoding encoding)
{
Add(new Tuple<byte[], byte[]>(oldFont.RawBytes(encoding, oldFont.Length), newFont.RawBytes(encoding, oldFont.Length)));
}
}
}
78 changes: 78 additions & 0 deletions TelegramFontPatcher/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;

namespace TelegramFontPatcher
{
internal class Program
{
private const string ProcName = "Telegram";
private const string ExeName = ProcName + ".exe";

private static void Error(string message)
{
Console.WriteLine($"ERROR: {message}");
Console.ReadLine();
Environment.Exit(1);
}

private static void Main(string[] args)
{
Console.Title = $"Telegram Font Patcher {Assembly.GetExecutingAssembly().GetName().Version}";
Console.WriteLine(Console.Title + Environment.NewLine);

var processes = Process.GetProcessesByName("Telegram");
if (processes.Length == 0)
Error(ExeName + " not found");

// Backup original Telegram.exe
try
{
var proc = processes[0];
var path = proc.MainModule.FileName;

proc.Kill();
proc.WaitForExit();

File.Copy(path, path + ".bak", true);
Console.WriteLine("INFO: Backup saved");

Console.WriteLine($"NOTICE: Trying to patch {ExeName}...");

var patternsRegular = new PatternList("Arial", new[] {
"Segoe UI", "Segoe UI Semibold",
"Open Sans", "Open Sans Semibold",
"DAOpenSansRegular",
"DAOpenSansRegularItalic",
"DAOpenSansBold",
"DAOpenSansBoldItalic",
"DAOpenSansSemibold",
"DAOpenSansSemiboldItalic"
});

string patchedName = path + ".patched";
if (File.Exists(patchedName))
File.Delete(patchedName);

Console.WriteLine("Patching...");

using (var reader = new BinaryReader(new FileStream(ExeName, FileMode.Open)))
using (var writer = new BinaryWriter(new FileStream(patchedName, FileMode.Create)))
{
BinaryUtility.Replace(reader, writer, patternsRegular);
}

File.Delete(path);
File.Move(patchedName, path);

Process.Start(path);
}
catch (Exception ex)
{
Error(ex.Message);
}
}
}
}

35 changes: 35 additions & 0 deletions TelegramFontPatcher/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using System.Reflection;
using System.Runtime.InteropServices;

// Общие сведения об этой сборке предоставляются следующим набором
// набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
// связанные со сборкой.
[assembly: AssemblyTitle("Telegram Patcher 2020")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Telegram Font Patcher 2020")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
// COM, задайте атрибуту ComVisible значение TRUE для этого типа.
[assembly: ComVisible(false)]

// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
[assembly: Guid("d2ddbfa4-1082-4dfe-8512-3c9220237270")]

// Сведения о версии сборки состоят из следующих четырех значений:
//
// Основной номер версии
// Дополнительный номер версии
// Номер сборки
// Редакция
//
// Можно задать все значения или принять номер сборки и номер редакции по умолчанию.
// используя "*", как показано ниже:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
15 changes: 15 additions & 0 deletions TelegramFontPatcher/StringExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using System.Text;

namespace TelegramFontPatcher
{
internal static class StringExtensions
{
public static byte[] RawBytes(this string self, Encoding encoding, int length)
{
var result = new byte[encoding.GetMaxByteCount(length)];
encoding.GetBytes(self, 0, self.Length, result, 0);

return result;
}
}
}
50 changes: 50 additions & 0 deletions TelegramFontPatcher/TelegramFontPatcher.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{D2DDBFA4-1082-4DFE-8512-3C9220237270}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>TelegramFontPatcher</RootNamespace>
<AssemblyName>TelegramFontPatcher</AssemblyName>
<TargetFrameworkVersion>v4.6.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<LangVersion>8</LangVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Compile Include="BinaryUtility.cs" />
<Compile Include="PatternList.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="StringExtensions.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

0 comments on commit e49e701

Please sign in to comment.