-
-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathDiscordRPforVSPackage.cs
204 lines (171 loc) · 9.91 KB
/
DiscordRPforVSPackage.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
namespace DiscordRPforVS
{
using DiscordRPC;
using DiscordRPforVS.Properties;
using EnvDTE;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
[ProvideAutoLoad(UIContextGuids80.NoSolution, PackageAutoLoadFlags.BackgroundLoad)]
[ProvideAutoLoad(UIContextGuids80.SolutionExists, PackageAutoLoadFlags.BackgroundLoad)]
[InstalledProductRegistration("#110", "#112", "1.0", IconResourceID = 400, LanguageIndependentName = "Discord Rich Presence")]
[Guid("ab4abbbf-2c58-4fb3-8d6f-651811a796aa")]
[ProvideMenuResource("Menus.ctmenu", 1)]
[ProvideBindingPath]
public sealed class DiscordRPforVSPackage : AsyncPackage, IDisposable
{
internal static DTE ide;
private Boolean InitializedTimestamp;
private Timestamps CurrentTimestamps;
private Timestamps InitialTimestamps;
private readonly DiscordRpcClient Discord = new DiscordRpcClient("551675228691103796", logger: new DiscordLogger());
private readonly RichPresence Presence = new RichPresence();
private readonly Assets Assets = new Assets();
private String versionString;
private String versionImageKey;
public static Settings Settings { get; set; } = Settings.Default;
protected override async System.Threading.Tasks.Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
{
try
{
await this.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
Settings.Upgrade();
// Writes the language used to the global variable
Settings.translates = Settings.Default.useEnglishLanguage ? "en-US" : CultureInfo.CurrentCulture.ToString();
Settings.Default.Save();
ide = GetGlobalService(typeof(SDTE)) as DTE;
ide.Events.WindowEvents.WindowActivated += this.WindowActivated;
ide.Events.SolutionEvents.BeforeClosing += this.SolutionBeforeClosing;
String ideVersion = ide.Version.Split(new Char[1] { '.' })[0];
this.versionString = $"Visual Studio {Constants.IdeVersions[Int32.Parse(ideVersion, CultureInfo.InvariantCulture)]}";
this.versionImageKey = $"dev{ideVersion}";
await SettingsCommand.InitializeAsync(this).ConfigureAwait(true);
if (!this.Discord.IsInitialized && !this.Discord.IsDisposed)
if (!this.Discord.Initialize())
ActivityLog.LogError("DiscordRPforVS", $"{Translates.LogError(Settings.Default.translates)}");
if (Settings.loadOnStartup)
await this.UpdatePresenceAsync(ide.ActiveDocument).ConfigureAwait(true);
await base.InitializeAsync(cancellationToken, progress).ConfigureAwait(true);
}
catch (OperationCanceledException exc)
{
ActivityLog.LogError(exc.Source, exc.Message);
}
}
/// <summary>
/// Handles closing a solution
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "VSTHRD100:Avoid async void methods")]
private async void SolutionBeforeClosing() => await this.UpdatePresenceAsync(null).ConfigureAwait(true);
/// <summary>
/// Handles switching between windows
/// </summary>
/// <param name="windowActivated">The window switched to</param>
/// <param name="lastWindow">The windows switched from</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "VSTHRD100:Avoid async void methods")]
private async void WindowActivated(Window windowActivated, Window lastWindow)
{
await this.JoinableTaskFactory.SwitchToMainThreadAsync();
if (!this.Discord.IsInitialized && !this.Discord.IsDisposed)
if (!this.Discord.Initialize())
ActivityLog.LogError("DiscordRPforVS", $"{Translates.LogError(Settings.Default.translates)}");
if (windowActivated.Document != null)
await this.UpdatePresenceAsync(windowActivated.Document).ConfigureAwait(true);
}
/// <summary>
/// Updates the Presence with the document
/// </summary>
/// <param name="document"></param>
/// <param name="overrideTimestampReset"></param>
/// <returns></returns>
public async System.Threading.Tasks.Task UpdatePresenceAsync(Document document, Boolean overrideTimestampReset = false)
{
try
{
await this.JoinableTaskFactory.SwitchToMainThreadAsync();
if (!Settings.enabled)
{
if (!this.Discord.IsInitialized && !this.Discord.IsDisposed)
if (!this.Discord.Initialize())
ActivityLog.LogError("DiscordRPforVS", $"{Translates.LogError(Settings.Default.translates)}");
this.Discord.ClearPresence();
return;
}
this.Presence.Details = this.Presence.State = this.Assets.LargeImageKey = this.Assets.LargeImageText = this.Assets.SmallImageKey = this.Assets.SmallImageText = String.Empty;
if (Settings.secretMode)
{
this.Presence.Details = Translates.PresenceDetails(Settings.Default.translates);
this.Presence.State = Translates.PresenceState(Settings.Default.translates);
this.Assets.LargeImageKey = this.versionImageKey;
this.Assets.LargeImageText = this.versionString;
this.Assets.SmallImageKey = this.Assets.SmallImageText = "";
goto finish;
}
this.Presence.Details = this.Presence.State = "";
String[] language = Array.Empty<String>();
if (document != null)
{
String filename = Path.GetFileName(path: document.FullName).ToUpperInvariant(), ext = Path.GetExtension(filename);
List<KeyValuePair<String[], String[]>> list = Constants.Languages.Where(lang => Array.IndexOf(lang.Key, filename) > -1 || Array.IndexOf(lang.Key, ext) > -1).ToList();
language = list.Count > 0 ? list[0].Value : Array.Empty<String>();
}
Boolean supported = language.Length > 0;
this.Assets.LargeImageKey = Settings.largeLanguage ? supported ? language[0] : "text" : this.versionImageKey;
this.Assets.LargeImageText = Settings.largeLanguage ? supported ? language[1] + " " + Translates.File(Settings.Default.translates) : Translates.UnrecognizedExtension(Settings.Default.translates) : this.versionString;
this.Assets.SmallImageKey = Settings.largeLanguage ? this.versionImageKey : supported ? language[0] : "text";
this.Assets.SmallImageText = Settings.largeLanguage ? this.versionString : supported ? language[1] + " " + Translates.File(Settings.Default.translates) : Translates.UnrecognizedExtension(Settings.Default.translates);
if (Settings.showFileName)
this.Presence.Details = !(document is null) ? Path.GetFileName(document.FullName) : Translates.NoFile(Settings.Default.translates);
if (Settings.showSolutionName)
{
Boolean idling = ide.Solution is null || String.IsNullOrEmpty(ide.Solution.FullName);
this.Presence.State = idling ? Translates.Idling(Settings.Default.translates) : $"{Translates.Developing(Settings.Default.translates)} {Path.GetFileNameWithoutExtension(ide.Solution.FileName)}";
if (idling)
{
this.Assets.LargeImageKey = this.versionImageKey;
this.Assets.LargeImageText = this.versionString;
this.Assets.SmallImageKey = this.Assets.SmallImageText = "";
}
}
if (Settings.showTimestamp && document != null)
{
if (!this.InitializedTimestamp)
{
this.InitialTimestamps = this.Presence.Timestamps = new Timestamps() { Start = DateTime.UtcNow };
this.InitializedTimestamp = true;
}
if (Settings.resetTimestamp && !overrideTimestampReset)
this.Presence.Timestamps = new Timestamps() { Start = DateTime.UtcNow };
else if (Settings.resetTimestamp && overrideTimestampReset)
this.Presence.Timestamps = this.CurrentTimestamps;
else if (!Settings.resetTimestamp && !overrideTimestampReset)
this.Presence.Timestamps = this.InitialTimestamps;
this.CurrentTimestamps = this.Presence.Timestamps;
}
finish:;
this.Presence.Assets = this.Assets;
if (!this.Discord.IsInitialized && !this.Discord.IsDisposed)
if (!this.Discord.Initialize())
ActivityLog.LogError("DiscordRPforVS", Translates.LogError(Settings.Default.translates));
this.Discord.SetPresence(this.Presence);
}
catch (ArgumentException e)
{
ActivityLog.LogError(e.Source, e.Message);
}
}
protected override void Dispose(Boolean disposing)
{
Dispose();
base.Dispose(disposing);
}
public void Dispose() => this.Discord.Dispose();
}
}