1
0
mirror of https://github.com/chylex/TweetDuck.git synced 2025-09-14 10:32:10 +02:00

Compare commits

...

31 Commits
1.15.2 ... 1.16

Author SHA1 Message Date
65d56b336b Release 1.16 2018-08-17 20:09:15 +02:00
7836d61173 Rewrite hovered column/tweet detection again to improve consistency & performance 2018-08-17 16:13:09 +02:00
898437720b Refactor and optimize the plugin configuration file 2018-08-17 11:09:07 +02:00
d9a80d1085 Make it easier to modify custom values for column width and font size 2018-08-17 08:09:28 +02:00
ab3d8b0ae2 Load edit-design plugin configuration dialog lazily 2018-08-17 07:53:43 +02:00
b865074c32 Mark DMs as read when replying to them 2018-08-17 07:02:22 +02:00
2b8ca77c0d Add a safeguard and a TODO to DM notification fix 2018-08-16 20:36:12 +02:00
fa8b4e1e7f Remove broken feature that showed missed notifications after reload 2018-08-16 20:33:31 +02:00
a310c5bcc1 Fix a broken workaround for DM notifications not showing if the convo is open 2018-08-16 19:53:48 +02:00
b5dccd6b91 Merge branch 'master' of https://github.com/chylex/TweetDuck 2018-08-15 15:55:23 +02:00
c2bcb39b38 Fix broken hover color on column filter icons 2018-08-15 15:55:02 +02:00
4515add0a0 Update README.md 2018-08-12 16:06:38 +02:00
5b6aaec48c Reorganize installer batch files 2018-08-12 15:56:14 +02:00
810e56ca31 Update CefSharp to 67 (pre01) 2018-08-12 15:36:48 +02:00
5bcc8ac2e0 Remove ITweetDeckBrowser 2018-08-10 03:18:26 +02:00
f5bfb35867 Add a notification script to the debug plugin for testing 2018-08-10 03:14:39 +02:00
9088b8cd07 Finish refactoring context menu structures & fix bugs from previous commits 2018-08-10 00:58:44 +02:00
a7d90dc708 Allow RT & Add to List/Collection dialogs to be smaller
Closes #236
2018-08-09 20:20:08 +02:00
5968b57a01 Add account context menu items to follow notifications 2018-08-09 20:07:51 +02:00
94946a9ed6 Refactor context menu link handling 2018-08-09 19:55:53 +02:00
561aec5ef0 Refactor highlighted column/tweet variables 2018-08-09 18:13:45 +02:00
e31696d843 Update README.md 2018-07-31 14:30:05 +02:00
8b33fd2002 Update README.md 2018-07-31 14:23:25 +02:00
064e43750f Rewrite PostBuild into F# with optional compilation for performance 2018-07-31 12:48:07 +02:00
29d2f4f681 Why the fuck is Copy-Item file exclusion not working 2018-07-31 03:01:15 +02:00
c11b40b94a Tweak appearance of list-related notifications 2018-07-31 02:33:51 +02:00
e874e1d798 Refactor StringBuilder usage 2018-07-30 01:58:23 +02:00
01244ec632 Replace td-example-notification attribute with .td-example body class 2018-07-30 01:49:38 +02:00
671657e2b0 Remove user & system config properties from Program class & fix field visibility 2018-07-29 10:16:29 +02:00
dff7278e2e Refactor zoom config events & fix notification zoom not updating when outside TweetDeck 2018-07-29 09:41:52 +02:00
0881328636 Release 1.15.2 2018-07-27 22:13:16 +02:00
59 changed files with 1056 additions and 814 deletions

View File

@@ -10,21 +10,25 @@ namespace TweetDuck.Configuration{
sealed class ConfigManager{ sealed class ConfigManager{
public UserConfig User { get; } public UserConfig User { get; }
public SystemConfig System { get; } public SystemConfig System { get; }
public PluginConfig Plugins { get; }
public event EventHandler ProgramRestartRequested; public event EventHandler ProgramRestartRequested;
private readonly FileConfigInstance<UserConfig> infoUser; private readonly FileConfigInstance<UserConfig> infoUser;
private readonly FileConfigInstance<SystemConfig> infoSystem; private readonly FileConfigInstance<SystemConfig> infoSystem;
private readonly PluginConfigInstance infoPlugins;
private readonly IConfigInstance<BaseConfig>[] infoList; private readonly IConfigInstance<BaseConfig>[] infoList;
public ConfigManager(){ public ConfigManager(){
User = new UserConfig(this); User = new UserConfig(this);
System = new SystemConfig(this); System = new SystemConfig(this);
Plugins = new PluginConfig(this);
infoList = new IConfigInstance<BaseConfig>[]{ infoList = new IConfigInstance<BaseConfig>[]{
infoUser = new FileConfigInstance<UserConfig>(Program.UserConfigFilePath, User, "program options"), infoUser = new FileConfigInstance<UserConfig>(Program.UserConfigFilePath, User, "program options"),
infoSystem = new FileConfigInstance<SystemConfig>(Program.SystemConfigFilePath, System, "system options") infoSystem = new FileConfigInstance<SystemConfig>(Program.SystemConfigFilePath, System, "system options"),
infoPlugins = new PluginConfigInstance(Program.PluginConfigFilePath, Plugins)
}; };
// TODO refactor further // TODO refactor further
@@ -51,16 +55,19 @@ namespace TweetDuck.Configuration{
public void LoadAll(){ public void LoadAll(){
infoUser.Load(); infoUser.Load();
infoSystem.Load(); infoSystem.Load();
infoPlugins.Load();
} }
public void SaveAll(){ public void SaveAll(){
infoUser.Save(); infoUser.Save();
infoSystem.Save(); infoSystem.Save();
infoPlugins.Save();
} }
public void ReloadAll(){ public void ReloadAll(){
infoUser.Reload(); infoUser.Reload();
infoSystem.Reload(); infoSystem.Reload();
infoPlugins.Reload();
} }
private void TriggerProgramRestartRequested(){ private void TriggerProgramRestartRequested(){

View File

@@ -0,0 +1,69 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace TweetDuck.Configuration.Instance{
class PluginConfigInstance : IConfigInstance<PluginConfig>{
public PluginConfig Instance { get; }
private readonly string filename;
public PluginConfigInstance(string filename, PluginConfig instance){
this.filename = filename;
this.Instance = instance;
}
public void Load(){
try{
using(StreamReader reader = new StreamReader(new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read), Encoding.UTF8)){
string line = reader.ReadLine();
if (line == "#Disabled"){
HashSet<string> newDisabled = new HashSet<string>();
while((line = reader.ReadLine()) != null){
newDisabled.Add(line);
}
Instance.ReloadSilently(newDisabled);
}
}
}catch(FileNotFoundException){
}catch(DirectoryNotFoundException){
}catch(Exception e){
Program.Reporter.HandleException("Plugin Configuration Error", "Could not read the plugin configuration file. If you continue, the list of disabled plugins will be reset to default.", true, e);
}
}
public void Save(){
try{
using(StreamWriter writer = new StreamWriter(new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.None), Encoding.UTF8)){
writer.WriteLine("#Disabled");
foreach(string identifier in Instance.DisabledPlugins){
writer.WriteLine(identifier);
}
}
}catch(Exception e){
Program.Reporter.HandleException("Plugin Configuration Error", "Could not save the plugin configuration file.", true, e);
}
}
public void Reload(){
Load();
}
public void Reset(){
try{
File.Delete(filename);
Instance.ReloadSilently(Instance.ConstructWithDefaults<PluginConfig>().DisabledPlugins);
}catch(Exception e){
Program.Reporter.HandleException("Plugin Configuration Error", "Could not delete the plugin configuration file.", true, e);
return;
}
Reload();
}
}
}

View File

@@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using TweetDuck.Plugins;
using TweetDuck.Plugins.Events;
namespace TweetDuck.Configuration{
sealed class PluginConfig : ConfigManager.BaseConfig, IPluginConfig{
private static readonly string[] DefaultDisabled = {
"official/clear-columns",
"official/reply-account"
};
// CONFIGURATION
public IEnumerable<string> DisabledPlugins => disabled;
public event EventHandler<PluginChangedStateEventArgs> PluginChangedState;
public void SetEnabled(Plugin plugin, bool enabled){
if ((enabled && disabled.Remove(plugin.Identifier)) || (!enabled && disabled.Add(plugin.Identifier))){
PluginChangedState?.Invoke(this, new PluginChangedStateEventArgs(plugin, enabled));
Save();
}
}
public bool IsEnabled(Plugin plugin){
return !disabled.Contains(plugin.Identifier);
}
public void ReloadSilently(IEnumerable<string> newDisabled){
disabled.Clear();
disabled.UnionWith(newDisabled);
}
private readonly HashSet<string> disabled = new HashSet<string>(DefaultDisabled);
// END OF CONFIG
public PluginConfig(ConfigManager configManager) : base(configManager){}
protected override ConfigManager.BaseConfig ConstructWithDefaults(ConfigManager configManager){
return new PluginConfig(configManager);
}
}
}

View File

@@ -23,9 +23,9 @@ namespace TweetDuck.Configuration{
public bool BestImageQuality { get; set; } = true; public bool BestImageQuality { get; set; } = true;
public bool EnableAnimatedImages { get; set; } = true; public bool EnableAnimatedImages { get; set; } = true;
public bool _enableSmoothScrolling = true; private bool _enableSmoothScrolling = true;
public bool _enableTouchAdjustment = false; private bool _enableTouchAdjustment = false;
public string _customCefArgs = null; private string _customCefArgs = null;
public string BrowserPath { get; set; } = null; public string BrowserPath { get; set; } = null;
public bool IgnoreTrackingUrlWarning { get; set; } = false; public bool IgnoreTrackingUrlWarning { get; set; } = false;

View File

@@ -1,4 +1,5 @@
using System.Text; using System.Text;
using TweetDuck.Configuration;
namespace TweetDuck.Core.Bridge{ namespace TweetDuck.Core.Bridge{
static class PropertyBridge{ static class PropertyBridge{
@@ -10,20 +11,21 @@ namespace TweetDuck.Core.Bridge{
string Bool(bool value) => value ? "true;" : "false;"; string Bool(bool value) => value ? "true;" : "false;";
string Str(string value) => '"'+value+"\";"; string Str(string value) => '"'+value+"\";";
StringBuilder build = new StringBuilder().Append("(function(x){"); UserConfig config = Program.Config.User;
StringBuilder build = new StringBuilder(128).Append("(function(x){");
build.Append("x.expandLinksOnHover=").Append(Bool(Program.UserConfig.ExpandLinksOnHover)); build.Append("x.expandLinksOnHover=").Append(Bool(config.ExpandLinksOnHover));
if (environment == Environment.Browser){ if (environment == Environment.Browser){
build.Append("x.openSearchInFirstColumn=").Append(Bool(Program.UserConfig.OpenSearchInFirstColumn)); build.Append("x.openSearchInFirstColumn=").Append(Bool(config.OpenSearchInFirstColumn));
build.Append("x.keepLikeFollowDialogsOpen=").Append(Bool(Program.UserConfig.KeepLikeFollowDialogsOpen)); build.Append("x.keepLikeFollowDialogsOpen=").Append(Bool(config.KeepLikeFollowDialogsOpen));
build.Append("x.muteNotifications=").Append(Bool(Program.UserConfig.MuteNotifications)); build.Append("x.muteNotifications=").Append(Bool(config.MuteNotifications));
build.Append("x.notificationMediaPreviews=").Append(Bool(Program.UserConfig.NotificationMediaPreviews)); build.Append("x.notificationMediaPreviews=").Append(Bool(config.NotificationMediaPreviews));
build.Append("x.translationTarget=").Append(Str(Program.UserConfig.TranslationTarget)); build.Append("x.translationTarget=").Append(Str(config.TranslationTarget));
} }
if (environment == Environment.Notification){ if (environment == Environment.Notification){
build.Append("x.skipOnLinkClick=").Append(Bool(Program.UserConfig.NotificationSkipOnLinkClick)); build.Append("x.skipOnLinkClick=").Append(Bool(config.NotificationSkipOnLinkClick));
} }
return build.Append("})(window.$TDX=window.$TDX||{})").ToString(); return build.Append("})(window.$TDX=window.$TDX||{})").ToString();

View File

@@ -1,13 +1,9 @@
using System.Collections.Generic; using System.Windows.Forms;
using System.Text;
using System.Windows.Forms;
using CefSharp;
using TweetDuck.Core.Controls; using TweetDuck.Core.Controls;
using TweetDuck.Core.Management; using TweetDuck.Core.Management;
using TweetDuck.Core.Notification; using TweetDuck.Core.Notification;
using TweetDuck.Core.Other; using TweetDuck.Core.Other;
using TweetDuck.Core.Utils; using TweetDuck.Core.Utils;
using TweetDuck.Resources;
namespace TweetDuck.Core.Bridge{ namespace TweetDuck.Core.Bridge{
class TweetDeckBridge{ class TweetDeckBridge{
@@ -15,25 +11,10 @@ namespace TweetDuck.Core.Bridge{
public static string NotificationHeadLayout { get; private set; } public static string NotificationHeadLayout { get; private set; }
public static readonly ContextInfo ContextInfo = new ContextInfo(); public static readonly ContextInfo ContextInfo = new ContextInfo();
private static readonly Dictionary<string, string> SessionData = new Dictionary<string, string>(2);
public static void ResetStaticProperties(){ public static void ResetStaticProperties(){
FontSize = NotificationHeadLayout = null; FontSize = NotificationHeadLayout = null;
} }
public static void RestoreSessionData(IFrame frame){
if (SessionData.Count > 0){
StringBuilder build = new StringBuilder().Append("window.TD_SESSION={");
foreach(KeyValuePair<string, string> kvp in SessionData){
build.Append(kvp.Key).Append(":'").Append(kvp.Value.Replace("'", "\\'")).Append("',");
}
ScriptLoader.ExecuteScript(frame, build.Append("}").ToString(), "gen:session");
SessionData.Clear();
}
}
private readonly FormBrowser form; private readonly FormBrowser form;
private readonly FormNotificationMain notification; private readonly FormNotificationMain notification;
@@ -79,12 +60,6 @@ namespace TweetDuck.Core.Bridge{
public void DisplayTooltip(string text){ public void DisplayTooltip(string text){
form.InvokeAsyncSafe(() => form.DisplayTooltip(text)); form.InvokeAsyncSafe(() => form.DisplayTooltip(text));
} }
public void SetSessionData(string key, string value){
form.InvokeSafe(() => { // do not use InvokeAsyncSafe, return only after invocation
SessionData.Add(key, value);
});
}
} }
// Notification only // Notification only

View File

@@ -14,13 +14,12 @@ using TweetDuck.Core.Other.Analytics;
using TweetDuck.Core.Other.Settings.Dialogs; using TweetDuck.Core.Other.Settings.Dialogs;
using TweetDuck.Core.Utils; using TweetDuck.Core.Utils;
using TweetDuck.Plugins; using TweetDuck.Plugins;
using TweetDuck.Plugins.Enums;
using TweetDuck.Plugins.Events; using TweetDuck.Plugins.Events;
using TweetDuck.Updates; using TweetDuck.Updates;
namespace TweetDuck.Core{ namespace TweetDuck.Core{
sealed partial class FormBrowser : Form, AnalyticsFile.IProvider{ sealed partial class FormBrowser : Form, AnalyticsFile.IProvider{
private static UserConfig Config => Program.UserConfig; private static UserConfig Config => Program.Config.User;
public bool IsWaiting{ public bool IsWaiting{
set{ set{
@@ -63,7 +62,7 @@ namespace TweetDuck.Core{
Text = Program.BrandName; Text = Program.BrandName;
this.plugins = new PluginManager(Program.PluginPath, Program.PluginConfigFilePath); this.plugins = new PluginManager(Program.Config.Plugins, Program.PluginPath);
this.plugins.Reloaded += plugins_Reloaded; this.plugins.Reloaded += plugins_Reloaded;
this.plugins.Executed += plugins_Executed; this.plugins.Executed += plugins_Executed;
this.plugins.Reload(); this.plugins.Reload();
@@ -79,11 +78,9 @@ namespace TweetDuck.Core{
this.updateBridge.UpdateDelayed += updateBridge_UpdateDelayed; this.updateBridge.UpdateDelayed += updateBridge_UpdateDelayed;
this.updateBridge.UpdateDismissed += updateBridge_UpdateDismissed; this.updateBridge.UpdateDismissed += updateBridge_UpdateDismissed;
this.browser = new TweetDeckBrowser(this, new TweetDeckBridge.Browser(this, notification), updateBridge); this.browser = new TweetDeckBrowser(this, plugins, new TweetDeckBridge.Browser(this, notification), updateBridge);
this.contextMenu = ContextMenuBrowser.CreateMenu(this); this.contextMenu = ContextMenuBrowser.CreateMenu(this);
this.plugins.Register(browser, PluginEnvironment.Browser, this, true);
Controls.Add(new MenuStrip{ Visible = false }); // fixes Alt freezing the program in Win 10 Anniversary Update Controls.Add(new MenuStrip{ Visible = false }); // fixes Alt freezing the program in Win 10 Anniversary Update
Disposed += (sender, args) => { Disposed += (sender, args) => {

View File

@@ -6,6 +6,7 @@ using CefSharp;
using TweetDuck.Core.Controls; using TweetDuck.Core.Controls;
using TweetDuck.Core.Utils; using TweetDuck.Core.Utils;
using System.Linq; using System.Linq;
using TweetDuck.Configuration;
using TweetDuck.Core.Bridge; using TweetDuck.Core.Bridge;
using TweetDuck.Core.Management; using TweetDuck.Core.Management;
using TweetDuck.Core.Notification; using TweetDuck.Core.Notification;
@@ -15,7 +16,9 @@ using TweetDuck.Resources;
namespace TweetDuck.Core.Handling{ namespace TweetDuck.Core.Handling{
abstract class ContextMenuBase : IContextMenuHandler{ abstract class ContextMenuBase : IContextMenuHandler{
private static TwitterUtils.ImageQuality ImageQuality => Program.UserConfig.TwitterImageQuality; protected static UserConfig Config => Program.Config.User;
private static TwitterUtils.ImageQuality ImageQuality => Config.TwitterImageQuality;
private const CefMenuCommand MenuOpenLinkUrl = (CefMenuCommand)26500; private const CefMenuCommand MenuOpenLinkUrl = (CefMenuCommand)26500;
private const CefMenuCommand MenuCopyLinkUrl = (CefMenuCommand)26501; private const CefMenuCommand MenuCopyLinkUrl = (CefMenuCommand)26501;
@@ -29,8 +32,7 @@ namespace TweetDuck.Core.Handling{
private const CefMenuCommand MenuReadApplyROT13 = (CefMenuCommand)26509; private const CefMenuCommand MenuReadApplyROT13 = (CefMenuCommand)26509;
private const CefMenuCommand MenuOpenDevTools = (CefMenuCommand)26599; private const CefMenuCommand MenuOpenDevTools = (CefMenuCommand)26599;
protected ContextInfo.LinkInfo LastLink { get; private set; } protected ContextInfo.ContextData Context { get; private set; }
protected ContextInfo.ChirpInfo LastChirp { get; private set; }
private readonly AnalyticsFile.IProvider analytics; private readonly AnalyticsFile.IProvider analytics;
@@ -38,37 +40,27 @@ namespace TweetDuck.Core.Handling{
this.analytics = analytics; this.analytics = analytics;
} }
private void ResetContextInfo(){
LastLink = default(ContextInfo.LinkInfo);
LastChirp = default(ContextInfo.ChirpInfo);
TweetDeckBridge.ContextInfo.Reset();
}
public virtual void OnBeforeContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model){ public virtual void OnBeforeContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model){
if (!TwitterUtils.IsTweetDeckWebsite(frame) || browser.IsLoading){ if (!TwitterUtils.IsTweetDeckWebsite(frame) || browser.IsLoading){
ResetContextInfo(); Context = TweetDeckBridge.ContextInfo.Reset();
} }
else{ else{
LastLink = TweetDeckBridge.ContextInfo.Link; Context = TweetDeckBridge.ContextInfo.Create(parameters);
LastChirp = TweetDeckBridge.ContextInfo.Chirp;
} }
if (parameters.TypeFlags.HasFlag(ContextMenuType.Selection) && !parameters.TypeFlags.HasFlag(ContextMenuType.Editable)){ if (parameters.TypeFlags.HasFlag(ContextMenuType.Selection) && !parameters.TypeFlags.HasFlag(ContextMenuType.Editable)){
model.AddItem(MenuSearchInBrowser, "Search in browser"); model.AddItem(MenuSearchInBrowser, "Search in browser");
model.AddSeparator(); model.AddSeparator();
model.AddItem(MenuReadApplyROT13, "Apply ROT13"); model.AddItem(MenuReadApplyROT13, "Apply ROT13");
model.AddSeparator(); model.AddSeparator();
} }
bool hasTweetImage = LastLink.IsImage;
bool hasTweetVideo = LastLink.IsVideo;
string TextOpen(string name) => "Open "+name+" in browser"; string TextOpen(string name) => "Open "+name+" in browser";
string TextCopy(string name) => "Copy "+name+" address"; string TextCopy(string name) => "Copy "+name+" address";
string TextSave(string name) => "Save "+name+" as..."; string TextSave(string name) => "Save "+name+" as...";
if (parameters.TypeFlags.HasFlag(ContextMenuType.Link) && !parameters.UnfilteredLinkUrl.EndsWith("tweetdeck.twitter.com/#", StringComparison.Ordinal) && !hasTweetImage && !hasTweetVideo){ if (Context.Types.HasFlag(ContextInfo.ContextType.Link) && !Context.UnsafeLinkUrl.EndsWith("tweetdeck.twitter.com/#", StringComparison.Ordinal)){
if (TwitterUtils.RegexAccount.IsMatch(parameters.UnfilteredLinkUrl)){ if (TwitterUtils.RegexAccount.IsMatch(Context.UnsafeLinkUrl)){
model.AddItem(MenuOpenLinkUrl, TextOpen("account")); model.AddItem(MenuOpenLinkUrl, TextOpen("account"));
model.AddItem(MenuCopyLinkUrl, TextCopy("account")); model.AddItem(MenuCopyLinkUrl, TextCopy("account"));
model.AddItem(MenuCopyUsername, "Copy account username"); model.AddItem(MenuCopyUsername, "Copy account username");
@@ -81,19 +73,19 @@ namespace TweetDuck.Core.Handling{
model.AddSeparator(); model.AddSeparator();
} }
if (hasTweetVideo){ if (Context.Types.HasFlag(ContextInfo.ContextType.Video)){
model.AddItem(MenuOpenMediaUrl, TextOpen("video")); model.AddItem(MenuOpenMediaUrl, TextOpen("video"));
model.AddItem(MenuCopyMediaUrl, TextCopy("video")); model.AddItem(MenuCopyMediaUrl, TextCopy("video"));
model.AddItem(MenuSaveMedia, TextSave("video")); model.AddItem(MenuSaveMedia, TextSave("video"));
model.AddSeparator(); model.AddSeparator();
} }
else if (((parameters.TypeFlags.HasFlag(ContextMenuType.Media) && parameters.HasImageContents) || hasTweetImage) && parameters.SourceUrl != TweetNotification.AppLogo.Url){ else if (Context.Types.HasFlag(ContextInfo.ContextType.Image) && Context.MediaUrl != TweetNotification.AppLogo.Url){
model.AddItem(MenuViewImage, "View image in photo viewer"); model.AddItem(MenuViewImage, "View image in photo viewer");
model.AddItem(MenuOpenMediaUrl, TextOpen("image")); model.AddItem(MenuOpenMediaUrl, TextOpen("image"));
model.AddItem(MenuCopyMediaUrl, TextCopy("image")); model.AddItem(MenuCopyMediaUrl, TextCopy("image"));
model.AddItem(MenuSaveMedia, TextSave("image")); model.AddItem(MenuSaveMedia, TextSave("image"));
if (LastChirp.Images.Length > 1){ if (Context.Chirp.Images.Length > 1){
model.AddItem(MenuSaveTweetImages, TextSave("all images")); model.AddItem(MenuSaveTweetImages, TextSave("all images"));
} }
@@ -106,25 +98,28 @@ namespace TweetDuck.Core.Handling{
switch(commandId){ switch(commandId){
case MenuOpenLinkUrl: case MenuOpenLinkUrl:
OpenBrowser(control, LastLink.GetUrl(parameters, true)); OpenBrowser(control, Context.LinkUrl);
break; break;
case MenuCopyLinkUrl: case MenuCopyLinkUrl:
SetClipboardText(control, LastLink.GetUrl(parameters, false)); SetClipboardText(control, Context.UnsafeLinkUrl);
break; break;
case MenuCopyUsername: case MenuCopyUsername: {
Match match = TwitterUtils.RegexAccount.Match(parameters.UnfilteredLinkUrl); string url = Context.UnsafeLinkUrl;
SetClipboardText(control, match.Success ? match.Groups[1].Value : parameters.UnfilteredLinkUrl); Match match = TwitterUtils.RegexAccount.Match(url);
SetClipboardText(control, match.Success ? match.Groups[1].Value : url);
control.InvokeAsyncSafe(analytics.AnalyticsFile.CopiedUsernames.Trigger); control.InvokeAsyncSafe(analytics.AnalyticsFile.CopiedUsernames.Trigger);
break; break;
}
case MenuOpenMediaUrl: case MenuOpenMediaUrl:
OpenBrowser(control, TwitterUtils.GetMediaLink(LastLink.GetMediaSource(parameters), ImageQuality)); OpenBrowser(control, TwitterUtils.GetMediaLink(Context.MediaUrl, ImageQuality));
break; break;
case MenuCopyMediaUrl: case MenuCopyMediaUrl:
SetClipboardText(control, TwitterUtils.GetMediaLink(LastLink.GetMediaSource(parameters), ImageQuality)); SetClipboardText(control, TwitterUtils.GetMediaLink(Context.MediaUrl, ImageQuality));
break; break;
case MenuViewImage: { case MenuViewImage: {
@@ -139,7 +134,7 @@ namespace TweetDuck.Core.Handling{
} }
} }
string url = LastLink.GetMediaSource(parameters); string url = Context.MediaUrl;
string file = Path.Combine(BrowserCache.CacheFolder, TwitterUtils.GetImageFileName(url) ?? Path.GetRandomFileName()); string file = Path.Combine(BrowserCache.CacheFolder, TwitterUtils.GetImageFileName(url) ?? Path.GetRandomFileName());
control.InvokeAsyncSafe(() => { control.InvokeAsyncSafe(() => {
@@ -161,9 +156,9 @@ namespace TweetDuck.Core.Handling{
} }
case MenuSaveMedia: { case MenuSaveMedia: {
bool isVideo = LastLink.IsVideo; bool isVideo = Context.Types.HasFlag(ContextInfo.ContextType.Video);
string url = LastLink.GetMediaSource(parameters); string url = Context.MediaUrl;
string username = LastChirp.Authors.LastOrDefault(); string username = Context.Chirp.Authors.LastOrDefault();
control.InvokeAsyncSafe(() => { control.InvokeAsyncSafe(() => {
if (isVideo){ if (isVideo){
@@ -180,8 +175,8 @@ namespace TweetDuck.Core.Handling{
} }
case MenuSaveTweetImages: { case MenuSaveTweetImages: {
string[] urls = LastChirp.Images; string[] urls = Context.Chirp.Images;
string username = LastChirp.Authors.LastOrDefault(); string username = Context.Chirp.Authors.LastOrDefault();
control.InvokeAsyncSafe(() => { control.InvokeAsyncSafe(() => {
TwitterUtils.DownloadImages(urls, username, ImageQuality); TwitterUtils.DownloadImages(urls, username, ImageQuality);
@@ -212,7 +207,7 @@ namespace TweetDuck.Core.Handling{
} }
public virtual void OnContextMenuDismissed(IWebBrowser browserControl, IBrowser browser, IFrame frame){ public virtual void OnContextMenuDismissed(IWebBrowser browserControl, IBrowser browser, IFrame frame){
ResetContextInfo(); Context = TweetDeckBridge.ContextInfo.Reset();
} }
public virtual bool RunContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model, IRunContextMenuCallback callback){ public virtual bool RunContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model, IRunContextMenuCallback callback){

View File

@@ -1,6 +1,7 @@
using CefSharp; using CefSharp;
using System.Windows.Forms; using System.Windows.Forms;
using TweetDuck.Core.Controls; using TweetDuck.Core.Controls;
using TweetDuck.Core.Management;
using TweetDuck.Core.Utils; using TweetDuck.Core.Utils;
namespace TweetDuck.Core.Handling{ namespace TweetDuck.Core.Handling{
@@ -56,12 +57,12 @@ namespace TweetDuck.Core.Handling{
InsertSelectionSearchItem(model, MenuSearchInColumn, "Search in a column"); InsertSelectionSearchItem(model, MenuSearchInColumn, "Search in a column");
} }
if (!string.IsNullOrEmpty(LastChirp.TweetUrl) && !isSelecting && !isEditing){ if (Context.Types.HasFlag(ContextInfo.ContextType.Chirp) && !isSelecting && !isEditing){
model.AddItem(MenuOpenTweetUrl, "Open tweet in browser"); model.AddItem(MenuOpenTweetUrl, "Open tweet in browser");
model.AddItem(MenuCopyTweetUrl, "Copy tweet address"); model.AddItem(MenuCopyTweetUrl, "Copy tweet address");
model.AddItem(MenuScreenshotTweet, "Screenshot tweet to clipboard"); model.AddItem(MenuScreenshotTweet, "Screenshot tweet to clipboard");
if (!string.IsNullOrEmpty(LastChirp.QuoteUrl)){ if (!string.IsNullOrEmpty(Context.Chirp.QuoteUrl)){
model.AddSeparator(); model.AddSeparator();
model.AddItem(MenuOpenQuotedTweetUrl, "Open quoted tweet in browser"); model.AddItem(MenuOpenQuotedTweetUrl, "Open quoted tweet in browser");
model.AddItem(MenuCopyQuotedTweetUrl, "Copy quoted tweet address"); model.AddItem(MenuCopyQuotedTweetUrl, "Copy quoted tweet address");
@@ -77,7 +78,7 @@ namespace TweetDuck.Core.Handling{
globalMenu.AddItem(CefMenuCommand.Reload, TitleReloadBrowser); globalMenu.AddItem(CefMenuCommand.Reload, TitleReloadBrowser);
globalMenu.AddCheckItem(MenuMute, TitleMuteNotifications); globalMenu.AddCheckItem(MenuMute, TitleMuteNotifications);
globalMenu.SetChecked(MenuMute, Program.UserConfig.MuteNotifications); globalMenu.SetChecked(MenuMute, Config.MuteNotifications);
globalMenu.AddSeparator(); globalMenu.AddSeparator();
globalMenu.AddItem(MenuSettings, TitleSettings); globalMenu.AddItem(MenuSettings, TitleSettings);
@@ -119,11 +120,11 @@ namespace TweetDuck.Core.Handling{
return true; return true;
case MenuOpenTweetUrl: case MenuOpenTweetUrl:
OpenBrowser(form, LastChirp.TweetUrl); OpenBrowser(form, Context.Chirp.TweetUrl);
return true; return true;
case MenuCopyTweetUrl: case MenuCopyTweetUrl:
SetClipboardText(form, LastChirp.TweetUrl); SetClipboardText(form, Context.Chirp.TweetUrl);
return true; return true;
case MenuScreenshotTweet: case MenuScreenshotTweet:
@@ -131,11 +132,11 @@ namespace TweetDuck.Core.Handling{
return true; return true;
case MenuOpenQuotedTweetUrl: case MenuOpenQuotedTweetUrl:
OpenBrowser(form, LastChirp.QuoteUrl); OpenBrowser(form, Context.Chirp.QuoteUrl);
return true; return true;
case MenuCopyQuotedTweetUrl: case MenuCopyQuotedTweetUrl:
SetClipboardText(form, LastChirp.QuoteUrl); SetClipboardText(form, Context.Chirp.QuoteUrl);
return true; return true;
case MenuWriteApplyROT13: case MenuWriteApplyROT13:
@@ -163,7 +164,7 @@ namespace TweetDuck.Core.Handling{
menu.MenuItems.Add(TitleAboutProgram, (sender, args) => form.OpenAbout()); menu.MenuItems.Add(TitleAboutProgram, (sender, args) => form.OpenAbout());
menu.Popup += (sender, args) => { menu.Popup += (sender, args) => {
menu.MenuItems[1].Checked = Program.UserConfig.MuteNotifications; menu.MenuItems[1].Checked = Config.MuteNotifications;
form.AnalyticsFile.BrowserContextMenus.Trigger(); form.AnalyticsFile.BrowserContextMenus.Trigger();
}; };
@@ -171,8 +172,8 @@ namespace TweetDuck.Core.Handling{
} }
private static void ToggleMuteNotifications(){ private static void ToggleMuteNotifications(){
Program.UserConfig.MuteNotifications = !Program.UserConfig.MuteNotifications; Config.MuteNotifications = !Config.MuteNotifications;
Program.UserConfig.Save(); Config.Save();
} }
} }
} }

View File

@@ -1,6 +1,7 @@
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
using CefSharp; using CefSharp;
using TweetDuck.Configuration;
namespace TweetDuck.Core.Handling.General{ namespace TweetDuck.Core.Handling.General{
sealed class BrowserProcessHandler : IBrowserProcessHandler{ sealed class BrowserProcessHandler : IBrowserProcessHandler{
@@ -9,10 +10,12 @@ namespace TweetDuck.Core.Handling.General{
} }
private static void UpdatePrefsInternal(){ private static void UpdatePrefsInternal(){
UserConfig config = Program.Config.User;
using(IRequestContext ctx = Cef.GetGlobalRequestContext()){ using(IRequestContext ctx = Cef.GetGlobalRequestContext()){
ctx.SetPreference("browser.enable_spellchecking", Program.UserConfig.EnableSpellCheck, out string _); ctx.SetPreference("browser.enable_spellchecking", config.EnableSpellCheck, out string _);
ctx.SetPreference("spellcheck.dictionary", Program.UserConfig.SpellCheckLanguage, out string _); ctx.SetPreference("spellcheck.dictionary", config.SpellCheckLanguage, out string _);
ctx.SetPreference("settings.a11y.animation_policy", Program.UserConfig.EnableAnimatedImages ? "allowed" : "none", out string _); ctx.SetPreference("settings.a11y.animation_policy", config.EnableAnimatedImages ? "allowed" : "none", out string _);
} }
} }

View File

@@ -28,7 +28,7 @@ namespace TweetDuck.Core.Management{
} }
public static void RefreshTimer(){ public static void RefreshTimer(){
bool shouldRun = Program.SystemConfig.ClearCacheAutomatically && !ClearOnExit; bool shouldRun = Program.Config.System.ClearCacheAutomatically && !ClearOnExit;
if (!shouldRun && AutoClearTimer != null){ if (!shouldRun && AutoClearTimer != null){
AutoClearTimer.Dispose(); AutoClearTimer.Dispose();
@@ -38,7 +38,7 @@ namespace TweetDuck.Core.Management{
AutoClearTimer = new Timer(state => { AutoClearTimer = new Timer(state => {
if (AutoClearTimer != null){ if (AutoClearTimer != null){
try{ try{
if (CalculateCacheSize() >= Program.SystemConfig.ClearCacheThreshold*1024L*1024L){ if (CalculateCacheSize() >= Program.Config.System.ClearCacheThreshold*1024L*1024L){
SetClearOnExit(); SetClearOnExit();
} }
}catch(Exception){ }catch(Exception){

View File

@@ -1,49 +1,54 @@
using CefSharp; using System;
using CefSharp;
using TweetDuck.Core.Utils; using TweetDuck.Core.Utils;
namespace TweetDuck.Core.Management{ namespace TweetDuck.Core.Management{
sealed class ContextInfo{ sealed class ContextInfo{
public LinkInfo Link { get; private set; } private LinkInfo link;
public ChirpInfo Chirp { get; private set; } private ChirpInfo? chirp;
public ContextInfo(){ public ContextInfo(){
Reset(); Reset();
} }
public void SetLink(string type, string url){ public void SetLink(string type, string url){
Link = string.IsNullOrEmpty(url) ? new LinkInfo() : new LinkInfo(type, url); link = string.IsNullOrEmpty(url) ? null : new LinkInfo(type, url);
} }
public void SetChirp(string tweetUrl, string quoteUrl, string chirpAuthors, string chirpImages){ public void SetChirp(string tweetUrl, string quoteUrl, string chirpAuthors, string chirpImages){
Chirp = new ChirpInfo(tweetUrl, quoteUrl, chirpAuthors, chirpImages); chirp = string.IsNullOrEmpty(tweetUrl) ? (ChirpInfo?)null : new ChirpInfo(tweetUrl, quoteUrl, chirpAuthors, chirpImages);
} }
public void Reset(){ public ContextData Reset(){
Link = new LinkInfo(); link = null;
Chirp = new ChirpInfo(); chirp = null;
return ContextData.Empty;
}
public ContextData Create(IContextMenuParams parameters){
ContextData.Builder builder = new ContextData.Builder();
builder.AddContext(parameters);
if (link != null){
builder.AddOverride(link.Type, link.Url);
}
if (chirp.HasValue){
builder.AddChirp(chirp.Value);
}
return builder.Build();
} }
// Data structures // Data structures
public struct LinkInfo{ private sealed class LinkInfo{
public bool IsLink => type == "link"; public string Type { get; }
public bool IsImage => type == "image"; public string Url { get; }
public bool IsVideo => type == "video";
public string GetUrl(IContextMenuParams parameters, bool safe){
return IsLink ? url : (safe ? parameters.LinkUrl : parameters.UnfilteredLinkUrl);
}
public string GetMediaSource(IContextMenuParams parameters){
return IsImage || IsVideo ? url : parameters.SourceUrl;
}
private readonly string type;
private readonly string url;
public LinkInfo(string type, string url){ public LinkInfo(string type, string url){
this.type = type; this.Type = type;
this.url = url; this.Url = url;
} }
} }
@@ -64,5 +69,93 @@ namespace TweetDuck.Core.Management{
this.chirpImages = chirpImages; this.chirpImages = chirpImages;
} }
} }
// Constructed context
[Flags]
public enum ContextType{
Unknown = 0,
Link = 0b0001,
Image = 0b0010,
Video = 0b0100,
Chirp = 0b1000
}
public sealed class ContextData{
public static readonly ContextData Empty = new Builder().Build();
public ContextType Types { get; }
public string LinkUrl { get; }
public string UnsafeLinkUrl { get; }
public string MediaUrl { get; }
public ChirpInfo Chirp { get; }
public ContextData(ContextType types, string linkUrl, string unsafeLinkUrl, string mediaUrl, ChirpInfo chirp){
Types = types;
LinkUrl = linkUrl;
UnsafeLinkUrl = unsafeLinkUrl;
MediaUrl = mediaUrl;
Chirp = chirp;
}
public sealed class Builder{
private ContextType types = ContextType.Unknown;
private string linkUrl = string.Empty;
private string unsafeLinkUrl = string.Empty;
private string mediaUrl = string.Empty;
private ChirpInfo chirp = default(ChirpInfo);
public void AddContext(IContextMenuParams parameters){
ContextMenuType flags = parameters.TypeFlags;
if (flags.HasFlag(ContextMenuType.Media) && parameters.HasImageContents){
types |= ContextType.Image;
types &= ~ContextType.Video;
mediaUrl = parameters.SourceUrl;
}
if (flags.HasFlag(ContextMenuType.Link)){
types |= ContextType.Link;
linkUrl = parameters.LinkUrl;
unsafeLinkUrl = parameters.UnfilteredLinkUrl;
}
}
public void AddOverride(string type, string url){
switch(type){
case "link":
types |= ContextType.Link;
linkUrl = url;
unsafeLinkUrl = url;
break;
case "image":
types |= ContextType.Image;
types &= ~(ContextType.Video | ContextType.Link);
mediaUrl = url;
break;
case "video":
types |= ContextType.Video;
types &= ~(ContextType.Image | ContextType.Link);
mediaUrl = url;
break;
}
}
public void AddChirp(ChirpInfo chirp){
this.types |= ContextType.Chirp;
this.chirp = chirp;
}
public ContextData Build(){
return new ContextData(types, linkUrl, unsafeLinkUrl, mediaUrl, chirp);
}
}
}
} }
} }

View File

@@ -2,6 +2,7 @@
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
using System.Windows.Forms; using System.Windows.Forms;
using TweetDuck.Configuration;
using TweetDuck.Core.Controls; using TweetDuck.Core.Controls;
using TweetDuck.Core.Other; using TweetDuck.Core.Other;
using TweetDuck.Core.Utils; using TweetDuck.Core.Utils;
@@ -9,6 +10,8 @@ using TweetLib.Communication;
namespace TweetDuck.Core.Management{ namespace TweetDuck.Core.Management{
sealed class VideoPlayer : IDisposable{ sealed class VideoPlayer : IDisposable{
private static UserConfig Config => Program.Config.User;
public bool Running => currentInstance != null && currentInstance.Running; public bool Running => currentInstance != null && currentInstance.Running;
public event EventHandler ProcessExited; public event EventHandler ProcessExited;
@@ -37,7 +40,7 @@ namespace TweetDuck.Core.Management{
if ((process = Process.Start(new ProcessStartInfo{ if ((process = Process.Start(new ProcessStartInfo{
FileName = Path.Combine(Program.ProgramPath, "TweetDuck.Video.exe"), FileName = Path.Combine(Program.ProgramPath, "TweetDuck.Video.exe"),
Arguments = $"{owner.Handle} {Program.UserConfig.VideoPlayerVolume} \"{url}\" \"{pipe.GenerateToken()}\"", Arguments = $"{owner.Handle} {Config.VideoPlayerVolume} \"{url}\" \"{pipe.GenerateToken()}\"",
UseShellExecute = false, UseShellExecute = false,
RedirectStandardOutput = true RedirectStandardOutput = true
})) != null){ })) != null){
@@ -68,9 +71,9 @@ namespace TweetDuck.Core.Management{
owner.InvokeSafe(() => { owner.InvokeSafe(() => {
switch(e.Key){ switch(e.Key){
case "vol": case "vol":
if (int.TryParse(e.Data, out int volume) && volume != Program.UserConfig.VideoPlayerVolume){ if (int.TryParse(e.Data, out int volume) && volume != Config.VideoPlayerVolume){
Program.UserConfig.VideoPlayerVolume = volume; Config.VideoPlayerVolume = volume;
Program.UserConfig.Save(); Config.Save();
} }
break; break;

View File

@@ -8,11 +8,11 @@ using TweetDuck.Resources;
namespace TweetDuck.Core.Notification.Example{ namespace TweetDuck.Core.Notification.Example{
sealed class FormNotificationExample : FormNotificationMain{ sealed class FormNotificationExample : FormNotificationMain{
public override bool RequiresResize => true; public override bool RequiresResize => true;
protected override bool CanDragWindow => Program.UserConfig.NotificationPosition == TweetNotification.Position.Custom; protected override bool CanDragWindow => Config.NotificationPosition == TweetNotification.Position.Custom;
protected override FormBorderStyle NotificationBorderStyle{ protected override FormBorderStyle NotificationBorderStyle{
get{ get{
if (Program.UserConfig.NotificationSize == TweetNotification.Size.Custom){ if (Config.NotificationSize == TweetNotification.Size.Custom){
switch(base.NotificationBorderStyle){ switch(base.NotificationBorderStyle){
case FormBorderStyle.FixedSingle: return FormBorderStyle.Sizable; case FormBorderStyle.FixedSingle: return FormBorderStyle.Sizable;
case FormBorderStyle.FixedToolWindow: return FormBorderStyle.SizableToolWindow; case FormBorderStyle.FixedToolWindow: return FormBorderStyle.SizableToolWindow;
@@ -23,6 +23,8 @@ namespace TweetDuck.Core.Notification.Example{
} }
} }
protected override string BodyClasses => base.BodyClasses+" td-example";
public event EventHandler Ready; public event EventHandler Ready;
private readonly TweetNotification exampleNotification; private readonly TweetNotification exampleNotification;
@@ -36,7 +38,7 @@ namespace TweetDuck.Core.Notification.Example{
exampleTweetHTML = exampleTweetHTML.Replace("</p>", @"</p><div style='margin-top:256px'>Scrollbar test padding...</div>"); exampleTweetHTML = exampleTweetHTML.Replace("</p>", @"</p><div style='margin-top:256px'>Scrollbar test padding...</div>");
#endif #endif
exampleNotification = TweetNotification.Example(exampleTweetHTML, 176); exampleNotification = new TweetNotification(string.Empty, string.Empty, "Home", exampleTweetHTML, 176, string.Empty, string.Empty);
} }
private void browser_LoadingStateChanged(object sender, LoadingStateChangedEventArgs e){ private void browser_LoadingStateChanged(object sender, LoadingStateChangedEventArgs e){

View File

@@ -10,7 +10,9 @@ using TweetDuck.Core.Other.Analytics;
using TweetDuck.Core.Utils; using TweetDuck.Core.Utils;
namespace TweetDuck.Core.Notification{ namespace TweetDuck.Core.Notification{
partial class FormNotificationBase : Form, AnalyticsFile.IProvider{ abstract partial class FormNotificationBase : Form, AnalyticsFile.IProvider{
protected static UserConfig Config => Program.Config.User;
protected static int FontSizeLevel{ protected static int FontSizeLevel{
get{ get{
switch(TweetDeckBridge.FontSize){ switch(TweetDeckBridge.FontSize){
@@ -25,19 +27,18 @@ namespace TweetDuck.Core.Notification{
protected virtual Point PrimaryLocation{ protected virtual Point PrimaryLocation{
get{ get{
UserConfig config = Program.UserConfig;
Screen screen; Screen screen;
if (config.NotificationDisplay > 0 && config.NotificationDisplay <= Screen.AllScreens.Length){ if (Config.NotificationDisplay > 0 && Config.NotificationDisplay <= Screen.AllScreens.Length){
screen = Screen.AllScreens[config.NotificationDisplay-1]; screen = Screen.AllScreens[Config.NotificationDisplay-1];
} }
else{ else{
screen = Screen.FromControl(owner); screen = Screen.FromControl(owner);
} }
int edgeDist = config.NotificationEdgeDistance; int edgeDist = Config.NotificationEdgeDistance;
switch(config.NotificationPosition){ switch(Config.NotificationPosition){
case TweetNotification.Position.TopLeft: case TweetNotification.Position.TopLeft:
return new Point(screen.WorkingArea.X+edgeDist, screen.WorkingArea.Y+edgeDist); return new Point(screen.WorkingArea.X+edgeDist, screen.WorkingArea.Y+edgeDist);
@@ -51,12 +52,12 @@ namespace TweetDuck.Core.Notification{
return new Point(screen.WorkingArea.X+screen.WorkingArea.Width-edgeDist-Width, screen.WorkingArea.Y+screen.WorkingArea.Height-edgeDist-Height); return new Point(screen.WorkingArea.X+screen.WorkingArea.Width-edgeDist-Width, screen.WorkingArea.Y+screen.WorkingArea.Height-edgeDist-Height);
case TweetNotification.Position.Custom: case TweetNotification.Position.Custom:
if (!config.IsCustomNotificationPositionSet){ if (!Config.IsCustomNotificationPositionSet){
config.CustomNotificationPosition = new Point(screen.WorkingArea.X+screen.WorkingArea.Width-edgeDist-Width, screen.WorkingArea.Y+edgeDist); Config.CustomNotificationPosition = new Point(screen.WorkingArea.X+screen.WorkingArea.Width-edgeDist-Width, screen.WorkingArea.Y+edgeDist);
config.Save(); Config.Save();
} }
return config.CustomNotificationPosition; return Config.CustomNotificationPosition;
} }
return Location; return Location;
@@ -93,7 +94,7 @@ namespace TweetDuck.Core.Notification{
protected override bool ShowWithoutActivation => true; protected override bool ShowWithoutActivation => true;
protected float DpiScale { get; } protected float DpiScale { get; }
protected double SizeScale => DpiScale*Program.UserConfig.ZoomLevel/100.0; protected double SizeScale => DpiScale*Config.ZoomLevel/100.0;
protected readonly FormBrowser owner; protected readonly FormBrowser owner;
protected readonly ChromiumWebBrowser browser; protected readonly ChromiumWebBrowser browser;
@@ -130,8 +131,9 @@ namespace TweetDuck.Core.Notification{
this.browser.Dock = DockStyle.None; this.browser.Dock = DockStyle.None;
this.browser.ClientSize = ClientSize; this.browser.ClientSize = ClientSize;
browser.SetupResourceHandler(TwitterUtils.TweetDeckURL, this.resourceHandler); this.browser.SetupResourceHandler(TwitterUtils.TweetDeckURL, this.resourceHandler);
browser.SetupResourceHandler(TweetNotification.AppLogo); this.browser.SetupResourceHandler(TweetNotification.AppLogo);
this.browser.SetupZoomEvents();
Controls.Add(browser); Controls.Add(browser);
@@ -184,9 +186,7 @@ namespace TweetDuck.Core.Notification{
} }
} }
protected virtual string GetTweetHTML(TweetNotification tweet){ protected abstract string GetTweetHTML(TweetNotification tweet);
return tweet.GenerateHtml(IsCursorOverBrowser ? "td-notification td-hover" : "td-notification", this);
}
protected virtual void LoadTweet(TweetNotification tweet){ protected virtual void LoadTweet(TweetNotification tweet){
currentNotification = tweet; currentNotification = tweet;
@@ -202,7 +202,7 @@ namespace TweetDuck.Core.Notification{
protected virtual void UpdateTitle(){ protected virtual void UpdateTitle(){
string title = currentNotification?.ColumnTitle; string title = currentNotification?.ColumnTitle;
Text = string.IsNullOrEmpty(title) || !Program.UserConfig.DisplayNotificationColumn ? Program.BrandName : Program.BrandName+" - "+title; Text = string.IsNullOrEmpty(title) || !Config.DisplayNotificationColumn ? Program.BrandName : $"{Program.BrandName} - {title}";
} }
public void ShowTweetDetail(){ public void ShowTweetDetail(){

View File

@@ -5,7 +5,6 @@ using System.Windows.Forms;
using TweetDuck.Core.Bridge; using TweetDuck.Core.Bridge;
using TweetDuck.Core.Controls; using TweetDuck.Core.Controls;
using TweetDuck.Core.Handling; using TweetDuck.Core.Handling;
using TweetDuck.Core.Other.Interfaces;
using TweetDuck.Core.Utils; using TweetDuck.Core.Utils;
using TweetDuck.Data; using TweetDuck.Data;
using TweetDuck.Plugins; using TweetDuck.Plugins;
@@ -13,7 +12,7 @@ using TweetDuck.Plugins.Enums;
using TweetDuck.Resources; using TweetDuck.Resources;
namespace TweetDuck.Core.Notification{ namespace TweetDuck.Core.Notification{
abstract partial class FormNotificationMain : FormNotificationBase, ITweetDeckBrowser{ abstract partial class FormNotificationMain : FormNotificationBase{
private readonly PluginManager plugins; private readonly PluginManager plugins;
private readonly int timerBarHeight; private readonly int timerBarHeight;
@@ -29,7 +28,7 @@ namespace TweetDuck.Core.Notification{
public virtual bool RequiresResize{ public virtual bool RequiresResize{
get{ get{
return !prevDisplayTimer.HasValue || !prevFontSize.HasValue || prevDisplayTimer != Program.UserConfig.DisplayNotificationTimer || prevFontSize != FontSizeLevel; return !prevDisplayTimer.HasValue || !prevFontSize.HasValue || prevDisplayTimer != Config.DisplayNotificationTimer || prevFontSize != FontSizeLevel;
} }
set{ set{
@@ -38,7 +37,7 @@ namespace TweetDuck.Core.Notification{
prevFontSize = null; prevFontSize = null;
} }
else{ else{
prevDisplayTimer = Program.UserConfig.DisplayNotificationTimer; prevDisplayTimer = Config.DisplayNotificationTimer;
prevFontSize = FontSizeLevel; prevFontSize = FontSizeLevel;
} }
} }
@@ -46,29 +45,31 @@ namespace TweetDuck.Core.Notification{
private int BaseClientWidth{ private int BaseClientWidth{
get{ get{
switch(Program.UserConfig.NotificationSize){ switch(Config.NotificationSize){
default: default:
return BrowserUtils.Scale(284, SizeScale*(1.0+0.05*FontSizeLevel)); return BrowserUtils.Scale(284, SizeScale*(1.0+0.05*FontSizeLevel));
case TweetNotification.Size.Custom: case TweetNotification.Size.Custom:
return Program.UserConfig.CustomNotificationSize.Width; return Config.CustomNotificationSize.Width;
} }
} }
} }
private int BaseClientHeight{ private int BaseClientHeight{
get{ get{
switch(Program.UserConfig.NotificationSize){ switch(Config.NotificationSize){
default: default:
return BrowserUtils.Scale(122, SizeScale*(1.0+0.08*FontSizeLevel)); return BrowserUtils.Scale(122, SizeScale*(1.0+0.08*FontSizeLevel));
case TweetNotification.Size.Custom: case TweetNotification.Size.Custom:
return Program.UserConfig.CustomNotificationSize.Height; return Config.CustomNotificationSize.Height;
} }
} }
} }
protected virtual string BodyClasses => IsCursorOverBrowser ? "td-notification td-hover" : "td-notification";
public Size BrowserSize => Program.UserConfig.DisplayNotificationTimer ? new Size(ClientSize.Width, ClientSize.Height-timerBarHeight) : ClientSize; public Size BrowserSize => Config.DisplayNotificationTimer ? new Size(ClientSize.Width, ClientSize.Height-timerBarHeight) : ClientSize;
protected FormNotificationMain(FormBrowser owner, PluginManager pluginManager, bool enableContextMenu) : base(owner, enableContextMenu){ protected FormNotificationMain(FormBrowser owner, PluginManager pluginManager, bool enableContextMenu) : base(owner, enableContextMenu){
InitializeComponent(); InitializeComponent();
@@ -82,34 +83,12 @@ namespace TweetDuck.Core.Notification{
browser.LoadingStateChanged += Browser_LoadingStateChanged; browser.LoadingStateChanged += Browser_LoadingStateChanged;
browser.FrameLoadEnd += Browser_FrameLoadEnd; browser.FrameLoadEnd += Browser_FrameLoadEnd;
plugins.Register(this, PluginEnvironment.Notification, this); plugins.Register(browser, PluginEnvironment.Notification, this);
mouseHookDelegate = MouseHookProc; mouseHookDelegate = MouseHookProc;
Disposed += (sender, args) => StopMouseHook(true); Disposed += (sender, args) => StopMouseHook(true);
} }
// implementation of ITweetDeckBrowser
bool ITweetDeckBrowser.IsTweetDeckWebsite => IsNotificationVisible;
void ITweetDeckBrowser.RegisterBridge(string name, object obj){
browser.RegisterAsyncJsObject(name, obj);
}
void ITweetDeckBrowser.OnFrameLoaded(Action<IFrame> callback){
browser.FrameLoadEnd += (sender, args) => {
IFrame frame = args.Frame;
if (frame.IsMain && browser.Address != "about:blank"){
callback(frame);
}
};
}
void ITweetDeckBrowser.ExecuteFunction(string name, params object[] args){
browser.ExecuteScriptAsync(name, args);
}
// mouse wheel hook // mouse wheel hook
private void StartMouseHook(){ private void StartMouseHook(){
@@ -131,7 +110,7 @@ namespace TweetDuck.Core.Notification{
int eventType = wParam.ToInt32(); int eventType = wParam.ToInt32();
if (eventType == NativeMethods.WM_MOUSEWHEEL && IsCursorOverBrowser){ if (eventType == NativeMethods.WM_MOUSEWHEEL && IsCursorOverBrowser){
browser.SendMouseWheelEvent(0, 0, 0, BrowserUtils.Scale(NativeMethods.GetMouseHookData(lParam), Program.UserConfig.NotificationScrollSpeed*0.01), CefEventFlags.None); browser.SendMouseWheelEvent(0, 0, 0, BrowserUtils.Scale(NativeMethods.GetMouseHookData(lParam), Config.NotificationScrollSpeed*0.01), CefEventFlags.None);
return NativeMethods.HOOK_HANDLED; return NativeMethods.HOOK_HANDLED;
} }
else if (eventType == NativeMethods.WM_XBUTTONDOWN && DesktopBounds.Contains(Cursor.Position)){ else if (eventType == NativeMethods.WM_XBUTTONDOWN && DesktopBounds.Contains(Cursor.Position)){
@@ -181,9 +160,11 @@ namespace TweetDuck.Core.Notification{
} }
private void Browser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e){ private void Browser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e){
if (e.Frame.IsMain && browser.Address != "about:blank"){ IFrame frame = e.Frame;
e.Frame.ExecuteJavaScriptAsync(PropertyBridge.GenerateScript(PropertyBridge.Environment.Notification));
ScriptLoader.ExecuteScript(e.Frame, ScriptLoader.LoadResource("notification.js", this), "root:notification"); if (frame.IsMain && browser.Address != "about:blank"){
frame.ExecuteJavaScriptAsync(PropertyBridge.GenerateScript(PropertyBridge.Environment.Notification));
ScriptLoader.ExecuteFile(frame, "notification.js", this);
} }
} }
@@ -200,7 +181,7 @@ namespace TweetDuck.Core.Notification{
timeLeft -= timerProgress.Interval; timeLeft -= timerProgress.Interval;
int value = BrowserUtils.Scale(progressBarTimer.Maximum+25, (totalTime-timeLeft)/(double)totalTime); int value = BrowserUtils.Scale(progressBarTimer.Maximum+25, (totalTime-timeLeft)/(double)totalTime);
progressBarTimer.SetValueInstant(Program.UserConfig.NotificationTimerCountDown ? progressBarTimer.Maximum-value : value); progressBarTimer.SetValueInstant(Config.NotificationTimerCountDown ? progressBarTimer.Maximum-value : value);
if (timeLeft <= 0){ if (timeLeft <= 0){
FinishCurrentNotification(); FinishCurrentNotification();
@@ -216,7 +197,7 @@ namespace TweetDuck.Core.Notification{
public override void HideNotification(){ public override void HideNotification(){
base.HideNotification(); base.HideNotification();
progressBarTimer.Value = Program.UserConfig.NotificationTimerCountDown ? progressBarTimer.Maximum : progressBarTimer.Minimum; progressBarTimer.Value = Config.NotificationTimerCountDown ? progressBarTimer.Maximum : progressBarTimer.Minimum;
timerProgress.Stop(); timerProgress.Stop();
totalTime = 0; totalTime = 0;
@@ -247,7 +228,7 @@ namespace TweetDuck.Core.Notification{
} }
protected override string GetTweetHTML(TweetNotification tweet){ protected override string GetTweetHTML(TweetNotification tweet){
string html = base.GetTweetHTML(tweet); string html = tweet.GenerateHtml(BodyClasses, this);
foreach(InjectedHTML injection in plugins.NotificationInjections){ foreach(InjectedHTML injection in plugins.NotificationInjections){
html = injection.InjectInto(html); html = injection.InjectInto(html);
@@ -258,14 +239,14 @@ namespace TweetDuck.Core.Notification{
protected override void LoadTweet(TweetNotification tweet){ protected override void LoadTweet(TweetNotification tweet){
timerProgress.Stop(); timerProgress.Stop();
totalTime = timeLeft = tweet.GetDisplayDuration(Program.UserConfig.NotificationDurationValue); totalTime = timeLeft = tweet.GetDisplayDuration(Config.NotificationDurationValue);
progressBarTimer.Value = Program.UserConfig.NotificationTimerCountDown ? progressBarTimer.Maximum : progressBarTimer.Minimum; progressBarTimer.Value = Config.NotificationTimerCountDown ? progressBarTimer.Maximum : progressBarTimer.Minimum;
base.LoadTweet(tweet); base.LoadTweet(tweet);
} }
protected override void SetNotificationSize(int width, int height){ protected override void SetNotificationSize(int width, int height){
if (Program.UserConfig.DisplayNotificationTimer){ if (Config.DisplayNotificationTimer){
ClientSize = new Size(width, height+timerBarHeight); ClientSize = new Size(width, height+timerBarHeight);
progressBarTimer.Visible = true; progressBarTimer.Visible = true;
} }

View File

@@ -32,10 +32,10 @@ namespace TweetDuck.Core.Notification{
public FormNotificationTweet(FormBrowser owner, PluginManager pluginManager) : base(owner, pluginManager, true){ public FormNotificationTweet(FormBrowser owner, PluginManager pluginManager) : base(owner, pluginManager, true){
InitializeComponent(); InitializeComponent();
Program.UserConfig.MuteToggled += Config_MuteToggled; Config.MuteToggled += Config_MuteToggled;
Disposed += (sender, args) => Program.UserConfig.MuteToggled -= Config_MuteToggled; Disposed += (sender, args) => Config.MuteToggled -= Config_MuteToggled;
if (Program.UserConfig.MuteNotifications){ if (Config.MuteNotifications){
PauseNotification(); PauseNotification();
} }
} }
@@ -57,7 +57,7 @@ namespace TweetDuck.Core.Notification{
// event handlers // event handlers
private void Config_MuteToggled(object sender, EventArgs e){ private void Config_MuteToggled(object sender, EventArgs e){
if (Program.UserConfig.MuteNotifications){ if (Config.MuteNotifications){
PauseNotification(); PauseNotification();
} }
else{ else{
@@ -73,7 +73,7 @@ namespace TweetDuck.Core.Notification{
} }
private void timerIdlePauseCheck_Tick(object sender, EventArgs e){ private void timerIdlePauseCheck_Tick(object sender, EventArgs e){
if (NativeMethods.GetIdleSeconds() < Program.UserConfig.NotificationIdlePauseSeconds){ if (NativeMethods.GetIdleSeconds() < Config.NotificationIdlePauseSeconds){
ResumeNotification(); ResumeNotification();
timerIdlePauseCheck.Stop(); timerIdlePauseCheck.Stop();
} }
@@ -128,7 +128,7 @@ namespace TweetDuck.Core.Notification{
private void LoadNextNotification(){ private void LoadNextNotification(){
if (!IsNotificationVisible){ if (!IsNotificationVisible){
if (Program.UserConfig.NotificationNonIntrusiveMode && IsCursorOverNotificationArea && NativeMethods.GetIdleSeconds() < NonIntrusiveIdleLimit){ if (Config.NotificationNonIntrusiveMode && IsCursorOverNotificationArea && NativeMethods.GetIdleSeconds() < NonIntrusiveIdleLimit){
if (!timerCursorCheck.Enabled){ if (!timerCursorCheck.Enabled){
PauseNotification(); PauseNotification();
timerCursorCheck.Start(); timerCursorCheck.Start();
@@ -136,7 +136,7 @@ namespace TweetDuck.Core.Notification{
return; return;
} }
else if (Program.UserConfig.NotificationIdlePauseSeconds > 0 && NativeMethods.GetIdleSeconds() >= Program.UserConfig.NotificationIdlePauseSeconds){ else if (Config.NotificationIdlePauseSeconds > 0 && NativeMethods.GetIdleSeconds() >= Config.NotificationIdlePauseSeconds){
if (!timerIdlePauseCheck.Enabled){ if (!timerIdlePauseCheck.Enabled){
PauseNotification(); PauseNotification();
timerIdlePauseCheck.Start(); timerIdlePauseCheck.Start();

View File

@@ -10,11 +10,7 @@ namespace TweetDuck.Core.Notification{
sealed class TweetNotification{ sealed class TweetNotification{
private const string DefaultHeadLayout = @"<html class=""scroll-v os-windows dark txt-size--14"" lang=""en-US"" id=""tduck"" data-td-font=""medium"" data-td-theme=""dark""><head><meta charset=""utf-8""><link href=""https://ton.twimg.com/tweetdeck-web/web/dist/bundle.4b1f87e09d.css"" rel=""stylesheet""><style type='text/css'>body { background: rgb(34, 36, 38) !important }</style>"; private const string DefaultHeadLayout = @"<html class=""scroll-v os-windows dark txt-size--14"" lang=""en-US"" id=""tduck"" data-td-font=""medium"" data-td-theme=""dark""><head><meta charset=""utf-8""><link href=""https://ton.twimg.com/tweetdeck-web/web/dist/bundle.4b1f87e09d.css"" rel=""stylesheet""><style type='text/css'>body { background: rgb(34, 36, 38) !important }</style>";
public static readonly ResourceLink AppLogo = new ResourceLink("https://ton.twimg.com/tduck/avatar", ResourceHandler.FromByteArray(Properties.Resources.avatar, "image/png")); public static readonly ResourceLink AppLogo = new ResourceLink("https://ton.twimg.com/tduck/avatar", ResourceHandler.FromByteArray(Properties.Resources.avatar, "image/png"));
public static TweetNotification Example(string html, int characters){
return new TweetNotification(string.Empty, string.Empty, "Home", html, characters, string.Empty, string.Empty, true);
}
public enum Position{ public enum Position{
TopLeft, TopRight, BottomLeft, BottomRight, Custom TopLeft, TopRight, BottomLeft, BottomRight, Custom
} }
@@ -32,11 +28,8 @@ namespace TweetDuck.Core.Notification{
private readonly string html; private readonly string html;
private readonly int characters; private readonly int characters;
private readonly bool isExample;
public TweetNotification(string columnId, string chirpId, string title, string html, int characters, string tweetUrl, string quoteUrl){
public TweetNotification(string columnId, string chirpId, string title, string html, int characters, string tweetUrl, string quoteUrl) : this(columnId, chirpId, title, html, characters, tweetUrl, quoteUrl, false){}
private TweetNotification(string columnId, string chirpId, string title, string html, int characters, string tweetUrl, string quoteUrl, bool isExample){
this.ColumnId = columnId; this.ColumnId = columnId;
this.ChirpId = chirpId; this.ChirpId = chirpId;
@@ -46,7 +39,6 @@ namespace TweetDuck.Core.Notification{
this.html = html; this.html = html;
this.characters = characters; this.characters = characters;
this.isExample = isExample;
} }
public int GetDisplayDuration(int value){ public int GetDisplayDuration(int value){
@@ -54,26 +46,28 @@ namespace TweetDuck.Core.Notification{
} }
public string GenerateHtml(string bodyClasses, Control sync){ public string GenerateHtml(string bodyClasses, Control sync){
StringBuilder build = new StringBuilder(); string headLayout = TweetDeckBridge.NotificationHeadLayout ?? DefaultHeadLayout;
string mainCSS = ScriptLoader.LoadResource("styles/notification.css", sync) ?? string.Empty;
string customCSS = Program.Config.User.CustomNotificationCSS ?? string.Empty;
StringBuilder build = new StringBuilder(320 + headLayout.Length + mainCSS.Length + customCSS.Length + html.Length);
build.Append("<!DOCTYPE html>"); build.Append("<!DOCTYPE html>");
build.Append(TweetDeckBridge.NotificationHeadLayout ?? DefaultHeadLayout); build.Append(headLayout);
build.Append("<style type='text/css'>").Append(ScriptLoader.LoadResource("styles/notification.css", sync) ?? string.Empty).Append("</style>"); build.Append("<style type='text/css'>").Append(mainCSS).Append("</style>");
if (!string.IsNullOrEmpty(Program.UserConfig.CustomNotificationCSS)){ if (!string.IsNullOrWhiteSpace(customCSS)){
build.Append("<style type='text/css'>").Append(Program.UserConfig.CustomNotificationCSS).Append("</style>"); build.Append("<style type='text/css'>").Append(customCSS).Append("</style>");
} }
build.Append("</head>"); build.Append("</head><body class='scroll-styled-v");
build.Append("<body class='scroll-styled-v");
if (!string.IsNullOrEmpty(bodyClasses)){ if (!string.IsNullOrEmpty(bodyClasses)){
build.Append(' ').Append(bodyClasses); build.Append(' ').Append(bodyClasses);
} }
build.Append('\'').Append(isExample ? " td-example-notification" : "").Append("><div class='column' style='width:100%!important;min-height:100vh!important;height:auto!important;overflow:initial!important;'>"); build.Append("'><div class='column' style='width:100%!important;min-height:100vh!important;height:auto!important;overflow:initial!important;'>");
build.Append(html); build.Append(html);
build.Append("</div></body>"); build.Append("</div></body></html>");
build.Append("</html>");
return build.ToString(); return build.ToString();
} }
} }

View File

@@ -40,7 +40,7 @@ namespace TweetDuck.Core.Other.Analytics{
} }
public override string ToString(){ public override string ToString(){
StringBuilder build = new StringBuilder(); StringBuilder build = new StringBuilder(625);
foreach(DictionaryEntry entry in data){ foreach(DictionaryEntry entry in data){
if (entry.Value == null){ if (entry.Value == null){

View File

@@ -119,8 +119,8 @@ namespace TweetDuck.Core.Other.Analytics{
}.FinalizeReport(); }.FinalizeReport();
} }
private static UserConfig UserConfig => Program.UserConfig; private static UserConfig UserConfig => Program.Config.User;
private static SystemConfig SysConfig => Program.SystemConfig; private static SystemConfig SysConfig => Program.Config.System;
private static string Bool(bool value) => value ? "on" : "off"; private static string Bool(bool value) => value ? "on" : "off";
private static string Exact(int value) => value.ToString(); private static string Exact(int value) => value.ToString();

View File

@@ -1,5 +1,4 @@
using System; using System.Drawing;
using System.Drawing;
using System.Windows.Forms; using System.Windows.Forms;
using CefSharp; using CefSharp;
using CefSharp.WinForms; using CefSharp.WinForms;
@@ -15,7 +14,7 @@ namespace TweetDuck.Core.Other{
sealed partial class FormGuide : Form, FormManager.IAppDialog{ sealed partial class FormGuide : Form, FormManager.IAppDialog{
private const string GuideUrl = "https://tweetduck.chylex.com/guide/v2/"; private const string GuideUrl = "https://tweetduck.chylex.com/guide/v2/";
private const string GuidePathRegex = @"^guide(?:/v\d+)?(?:/(#.*))?"; private const string GuidePathRegex = @"^guide(?:/v\d+)?(?:/(#.*))?";
private static readonly ResourceLink DummyPage = new ResourceLink("http://td/dummy", ResourceHandler.FromString("")); private static readonly ResourceLink DummyPage = new ResourceLink("http://td/dummy", ResourceHandler.FromString(""));
public static bool CheckGuideUrl(string url, out string hash){ public static bool CheckGuideUrl(string url, out string hash){
@@ -73,7 +72,6 @@ namespace TweetDuck.Core.Other{
}; };
browser.LoadingStateChanged += browser_LoadingStateChanged; browser.LoadingStateChanged += browser_LoadingStateChanged;
browser.FrameLoadStart += browser_FrameLoadStart;
browser.FrameLoadEnd += browser_FrameLoadEnd; browser.FrameLoadEnd += browser_FrameLoadEnd;
browser.BrowserSettings.BackgroundColor = (uint)BackColor.ToArgb(); browser.BrowserSettings.BackgroundColor = (uint)BackColor.ToArgb();
@@ -81,15 +79,13 @@ namespace TweetDuck.Core.Other{
browser.Location = ControlExtensions.InvisibleLocation; browser.Location = ControlExtensions.InvisibleLocation;
browser.SetupResourceHandler(DummyPage); browser.SetupResourceHandler(DummyPage);
browser.SetupZoomEvents();
Controls.Add(browser); Controls.Add(browser);
Disposed += (sender, args) => { Disposed += (sender, args) => {
Program.UserConfig.ZoomLevelChanged -= Config_ZoomLevelChanged;
browser.Dispose(); browser.Dispose();
}; };
Program.UserConfig.ZoomLevelChanged += Config_ZoomLevelChanged;
} }
private void Reload(string url){ private void Reload(string url){
@@ -116,16 +112,8 @@ namespace TweetDuck.Core.Other{
} }
} }
private void browser_FrameLoadStart(object sender, FrameLoadStartEventArgs e){
BrowserUtils.SetZoomLevel(browser.GetBrowser(), Program.UserConfig.ZoomLevel);
}
private void browser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e){ private void browser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e){
ScriptLoader.ExecuteScript(e.Frame, "Array.prototype.forEach.call(document.getElementsByTagName('A'), ele => ele.addEventListener('click', e => { e.preventDefault(); window.open(ele.getAttribute('href')); }))", "gen:links"); ScriptLoader.ExecuteScript(e.Frame, "Array.prototype.forEach.call(document.getElementsByTagName('A'), ele => ele.addEventListener('click', e => { e.preventDefault(); window.open(ele.getAttribute('href')); }))", "gen:links");
} }
private void Config_ZoomLevelChanged(object sender, EventArgs e){
BrowserUtils.SetZoomLevel(browser.GetBrowser(), Program.UserConfig.ZoomLevel);
}
} }
} }

View File

@@ -3,11 +3,14 @@ using System.Diagnostics;
using System.Drawing; using System.Drawing;
using System.Linq; using System.Linq;
using System.Windows.Forms; using System.Windows.Forms;
using TweetDuck.Configuration;
using TweetDuck.Plugins; using TweetDuck.Plugins;
using TweetDuck.Plugins.Controls; using TweetDuck.Plugins.Controls;
namespace TweetDuck.Core.Other{ namespace TweetDuck.Core.Other{
sealed partial class FormPlugins : Form, FormManager.IAppDialog{ sealed partial class FormPlugins : Form, FormManager.IAppDialog{
private static UserConfig Config => Program.Config.User;
private readonly PluginManager pluginManager; private readonly PluginManager pluginManager;
public FormPlugins(){ public FormPlugins(){
@@ -19,8 +22,8 @@ namespace TweetDuck.Core.Other{
public FormPlugins(PluginManager pluginManager) : this(){ public FormPlugins(PluginManager pluginManager) : this(){
this.pluginManager = pluginManager; this.pluginManager = pluginManager;
if (!Program.UserConfig.PluginsWindowSize.IsEmpty){ if (!Config.PluginsWindowSize.IsEmpty){
Size targetSize = Program.UserConfig.PluginsWindowSize; Size targetSize = Config.PluginsWindowSize;
Size = new Size(Math.Max(MinimumSize.Width, targetSize.Width), Math.Max(MinimumSize.Height, targetSize.Height)); Size = new Size(Math.Max(MinimumSize.Width, targetSize.Width), Math.Max(MinimumSize.Height, targetSize.Height));
} }
@@ -29,8 +32,8 @@ namespace TweetDuck.Core.Other{
}; };
FormClosed += (sender, args) => { FormClosed += (sender, args) => {
Program.UserConfig.PluginsWindowSize = Size; Config.PluginsWindowSize = Size;
Program.UserConfig.Save(); Config.Save();
}; };
ResizeEnd += (sender, args) => { ResizeEnd += (sender, args) => {

View File

@@ -1,12 +0,0 @@
using System;
using CefSharp;
namespace TweetDuck.Core.Other.Interfaces{
interface ITweetDeckBrowser{
bool IsTweetDeckWebsite { get; }
void RegisterBridge(string name, object obj);
void OnFrameLoaded(Action<IFrame> callback);
void ExecuteFunction(string name, params object[] args);
}
}

View File

@@ -4,8 +4,8 @@ using TweetDuck.Configuration;
namespace TweetDuck.Core.Other.Settings{ namespace TweetDuck.Core.Other.Settings{
class BaseTabSettings : UserControl{ class BaseTabSettings : UserControl{
protected static UserConfig Config => Program.UserConfig; protected static UserConfig Config => Program.Config.User;
protected static SystemConfig SysConfig => Program.SystemConfig; protected static SystemConfig SysConfig => Program.Config.System;
public IEnumerable<Control> InteractiveControls{ public IEnumerable<Control> InteractiveControls{
get{ get{

View File

@@ -13,7 +13,7 @@ namespace TweetDuck.Core.Other.Settings.Dialogs{
private readonly Action<string> reinjectBrowserCSS; private readonly Action<string> reinjectBrowserCSS;
private readonly Action openDevTools; private readonly Action openDevTools;
public DialogSettingsCSS(Action<string> reinjectBrowserCSS, Action openDevTools){ public DialogSettingsCSS(string browserCSS, string notificationCSS, Action<string> reinjectBrowserCSS, Action openDevTools){
InitializeComponent(); InitializeComponent();
Text = Program.BrandName+" Options - CSS"; Text = Program.BrandName+" Options - CSS";
@@ -22,10 +22,10 @@ namespace TweetDuck.Core.Other.Settings.Dialogs{
this.openDevTools = openDevTools; this.openDevTools = openDevTools;
textBoxBrowserCSS.EnableMultilineShortcuts(); textBoxBrowserCSS.EnableMultilineShortcuts();
textBoxBrowserCSS.Text = Program.UserConfig.CustomBrowserCSS ?? ""; textBoxBrowserCSS.Text = browserCSS ?? "";
textBoxNotificationCSS.EnableMultilineShortcuts(); textBoxNotificationCSS.EnableMultilineShortcuts();
textBoxNotificationCSS.Text = Program.UserConfig.CustomNotificationCSS ?? ""; textBoxNotificationCSS.Text = notificationCSS ?? "";
if (!BrowserUtils.HasDevTools){ if (!BrowserUtils.HasDevTools){
btnOpenDevTools.Enabled = false; btnOpenDevTools.Enabled = false;

View File

@@ -8,13 +8,15 @@ namespace TweetDuck.Core.Other.Settings.Dialogs{
sealed partial class DialogSettingsCefArgs : Form{ sealed partial class DialogSettingsCefArgs : Form{
public string CefArgs => textBoxArgs.Text; public string CefArgs => textBoxArgs.Text;
public DialogSettingsCefArgs(){ private readonly string initialArgs;
public DialogSettingsCefArgs(string args){
InitializeComponent(); InitializeComponent();
Text = Program.BrandName+" Options - CEF Arguments"; Text = Program.BrandName+" Options - CEF Arguments";
textBoxArgs.EnableMultilineShortcuts(); textBoxArgs.EnableMultilineShortcuts();
textBoxArgs.Text = Program.UserConfig.CustomCefArgs ?? ""; textBoxArgs.Text = initialArgs = args ?? "";
textBoxArgs.Select(textBoxArgs.Text.Length, 0); textBoxArgs.Select(textBoxArgs.Text.Length, 0);
} }
@@ -23,16 +25,14 @@ namespace TweetDuck.Core.Other.Settings.Dialogs{
} }
private void btnApply_Click(object sender, EventArgs e){ private void btnApply_Click(object sender, EventArgs e){
string prevArgs = Program.UserConfig.CustomCefArgs; if (CefArgs == initialArgs){
if (CefArgs == prevArgs){
DialogResult = DialogResult.Cancel; DialogResult = DialogResult.Cancel;
Close(); Close();
return; return;
} }
int count = CommandLineArgs.ReadCefArguments(CefArgs).Count; int count = CommandLineArgs.ReadCefArguments(CefArgs).Count;
string prompt = count == 0 && !string.IsNullOrWhiteSpace(prevArgs) ? "All current arguments will be removed. Continue?" : count+(count == 1 ? " argument was" : " arguments were")+" detected. Continue?"; string prompt = count == 0 && !string.IsNullOrWhiteSpace(initialArgs) ? "All current arguments will be removed. Continue?" : count+(count == 1 ? " argument was" : " arguments were")+" detected. Continue?";
if (FormMessage.Question("Confirm CEF Arguments", prompt, FormMessage.OK, FormMessage.Cancel)){ if (FormMessage.Question("Confirm CEF Arguments", prompt, FormMessage.OK, FormMessage.Cancel)){
DialogResult = DialogResult.OK; DialogResult = DialogResult.OK;

View File

@@ -125,18 +125,19 @@ namespace TweetDuck.Core.Other.Settings.Dialogs{
Program.Config.ProgramRestartRequested += Config_ProgramRestartRequested; Program.Config.ProgramRestartRequested += Config_ProgramRestartRequested;
if (SelectedItems.HasFlag(ProfileManager.Items.UserConfig)){ if (SelectedItems.HasFlag(ProfileManager.Items.UserConfig)){
Program.UserConfig.Reset(); Program.Config.User.Reset();
} }
if (SelectedItems.HasFlag(ProfileManager.Items.SystemConfig)){ if (SelectedItems.HasFlag(ProfileManager.Items.SystemConfig)){
Program.SystemConfig.Reset(); Program.Config.System.Reset();
} }
Program.Config.ProgramRestartRequested -= Config_ProgramRestartRequested; Program.Config.ProgramRestartRequested -= Config_ProgramRestartRequested;
if (SelectedItems.HasFlag(ProfileManager.Items.PluginData)){ if (SelectedItems.HasFlag(ProfileManager.Items.PluginData)){
Program.Config.Plugins.Reset();
try{ try{
File.Delete(Program.PluginConfigFilePath);
Directory.Delete(Program.PluginDataPath, true); Directory.Delete(Program.PluginDataPath, true);
}catch(Exception ex){ }catch(Exception ex){
Program.Reporter.HandleException("Profile Reset", "Could not delete plugin data.", true, ex); Program.Reporter.HandleException("Profile Reset", "Could not delete plugin data.", true, ex);

View File

@@ -10,7 +10,7 @@ namespace TweetDuck.Core.Other.Settings.Dialogs{
Text = Program.BrandName+" Options - Custom Search Engine"; Text = Program.BrandName+" Options - Custom Search Engine";
textBoxUrl.Text = Program.UserConfig.SearchEngineUrl ?? ""; textBoxUrl.Text = Program.Config.User.SearchEngineUrl ?? "";
textBoxUrl.Select(textBoxUrl.Text.Length, 0); textBoxUrl.Select(textBoxUrl.Text.Length, 0);
} }

View File

@@ -103,7 +103,7 @@ namespace TweetDuck.Core.Other.Settings{
#region Configuration #region Configuration
private void btnEditCefArgs_Click(object sender, EventArgs e){ private void btnEditCefArgs_Click(object sender, EventArgs e){
DialogSettingsCefArgs form = new DialogSettingsCefArgs(); DialogSettingsCefArgs form = new DialogSettingsCefArgs(Config.CustomCefArgs);
form.VisibleChanged += (sender2, args2) => { form.VisibleChanged += (sender2, args2) => {
form.MoveToCenter(ParentForm); form.MoveToCenter(ParentForm);
@@ -124,7 +124,7 @@ namespace TweetDuck.Core.Other.Settings{
} }
private void btnEditCSS_Click(object sender, EventArgs e){ private void btnEditCSS_Click(object sender, EventArgs e){
DialogSettingsCSS form = new DialogSettingsCSS(reinjectBrowserCSS, openDevTools); DialogSettingsCSS form = new DialogSettingsCSS(Config.CustomBrowserCSS, Config.CustomNotificationCSS, reinjectBrowserCSS, openDevTools);
form.VisibleChanged += (sender2, args2) => { form.VisibleChanged += (sender2, args2) => {
form.MoveToCenter(ParentForm); form.MoveToCenter(ParentForm);

View File

@@ -10,7 +10,7 @@ namespace TweetDuck.Core.Other{
Disabled, DisplayOnly, MinimizeToTray, CloseToTray, Combined Disabled, DisplayOnly, MinimizeToTray, CloseToTray, Combined
} }
private static UserConfig Config => Program.UserConfig; private static UserConfig Config => Program.Config.User;
public event EventHandler ClickRestore; public event EventHandler ClickRestore;
public event EventHandler ClickClose; public event EventHandler ClickClose;
@@ -56,6 +56,7 @@ namespace TweetDuck.Core.Other{
this.notifyIcon.Text = Program.BrandName; this.notifyIcon.Text = Program.BrandName;
Config.MuteToggled += Config_MuteToggled; Config.MuteToggled += Config_MuteToggled;
Disposed += (sender, args) => Config.MuteToggled -= Config_MuteToggled;
} }
public TrayIcon(IContainer container) : this(){ public TrayIcon(IContainer container) : this(){

View File

@@ -10,12 +10,15 @@ using TweetDuck.Core.Controls;
using TweetDuck.Core.Handling; using TweetDuck.Core.Handling;
using TweetDuck.Core.Handling.General; using TweetDuck.Core.Handling.General;
using TweetDuck.Core.Notification; using TweetDuck.Core.Notification;
using TweetDuck.Core.Other.Interfaces;
using TweetDuck.Core.Utils; using TweetDuck.Core.Utils;
using TweetDuck.Plugins;
using TweetDuck.Plugins.Enums;
using TweetDuck.Resources; using TweetDuck.Resources;
namespace TweetDuck.Core{ namespace TweetDuck.Core{
sealed class TweetDeckBrowser : ITweetDeckBrowser, IDisposable{ sealed class TweetDeckBrowser : IDisposable{
private static UserConfig Config => Program.Config.User;
public bool Ready { get; private set; } public bool Ready { get; private set; }
public bool Enabled{ public bool Enabled{
@@ -39,7 +42,7 @@ namespace TweetDuck.Core{
private string prevSoundNotificationPath = null; private string prevSoundNotificationPath = null;
public TweetDeckBrowser(FormBrowser owner, TweetDeckBridge tdBridge, UpdateBridge updateBridge){ public TweetDeckBrowser(FormBrowser owner, PluginManager plugins, TweetDeckBridge tdBridge, UpdateBridge updateBridge){
RequestHandlerBrowser requestHandler = new RequestHandlerBrowser(); RequestHandlerBrowser requestHandler = new RequestHandlerBrowser();
this.browser = new ChromiumWebBrowser(TwitterUtils.TweetDeckURL){ this.browser = new ChromiumWebBrowser(TwitterUtils.TweetDeckURL){
@@ -66,12 +69,13 @@ namespace TweetDuck.Core{
this.browser.SetupResourceHandler(TweetNotification.AppLogo); this.browser.SetupResourceHandler(TweetNotification.AppLogo);
this.browser.SetupResourceHandler(TwitterUtils.LoadingSpinner); this.browser.SetupResourceHandler(TwitterUtils.LoadingSpinner);
this.browser.SetupZoomEvents();
owner.Controls.Add(browser); owner.Controls.Add(browser);
plugins.Register(browser, PluginEnvironment.Browser, owner, true);
Program.UserConfig.MuteToggled += UserConfig_MuteToggled; Config.MuteToggled += Config_MuteToggled;
Program.UserConfig.ZoomLevelChanged += UserConfig_ZoomLevelChanged; Config.SoundNotificationChanged += Config_SoundNotificationInfoChanged;
Program.UserConfig.SoundNotificationChanged += UserConfig_SoundNotificationInfoChanged;
} }
// setup and management // setup and management
@@ -89,30 +93,11 @@ namespace TweetDuck.Core{
} }
public void Dispose(){ public void Dispose(){
Program.UserConfig.MuteToggled -= UserConfig_MuteToggled; Config.MuteToggled -= Config_MuteToggled;
Program.UserConfig.ZoomLevelChanged -= UserConfig_ZoomLevelChanged; Config.SoundNotificationChanged -= Config_SoundNotificationInfoChanged;
Program.UserConfig.SoundNotificationChanged -= UserConfig_SoundNotificationInfoChanged;
browser.Dispose(); browser.Dispose();
} }
void ITweetDeckBrowser.RegisterBridge(string name, object obj){
browser.RegisterAsyncJsObject(name, obj);
}
void ITweetDeckBrowser.OnFrameLoaded(Action<IFrame> callback){
browser.FrameLoadEnd += (sender, args) => {
IFrame frame = args.Frame;
if (frame.IsMain && TwitterUtils.IsTweetDeckWebsite(frame)){
callback(frame);
}
};
}
void ITweetDeckBrowser.ExecuteFunction(string name, params object[] args){
browser.ExecuteScriptAsync(name, args);
}
// event handlers // event handlers
@@ -131,10 +116,6 @@ namespace TweetDuck.Core{
IFrame frame = e.Frame; IFrame frame = e.Frame;
if (frame.IsMain){ if (frame.IsMain){
if (Program.UserConfig.ZoomLevel != 100){
BrowserUtils.SetZoomLevel(browser.GetBrowser(), Program.UserConfig.ZoomLevel);
}
if (TwitterUtils.IsTwitterWebsite(frame)){ if (TwitterUtils.IsTwitterWebsite(frame)){
ScriptLoader.ExecuteFile(frame, "twitter.js", browser); ScriptLoader.ExecuteFile(frame, "twitter.js", browser);
} }
@@ -149,12 +130,11 @@ namespace TweetDuck.Core{
if (frame.IsMain){ if (frame.IsMain){
if (TwitterUtils.IsTweetDeckWebsite(frame)){ if (TwitterUtils.IsTweetDeckWebsite(frame)){
UpdateProperties(); UpdateProperties();
TweetDeckBridge.RestoreSessionData(frame);
ScriptLoader.ExecuteFile(frame, "code.js", browser); ScriptLoader.ExecuteFile(frame, "code.js", browser);
InjectBrowserCSS(); InjectBrowserCSS();
ReinjectCustomCSS(Program.UserConfig.CustomBrowserCSS); ReinjectCustomCSS(Config.CustomBrowserCSS);
UserConfig_SoundNotificationInfoChanged(null, EventArgs.Empty); Config_SoundNotificationInfoChanged(null, EventArgs.Empty);
TweetDeckBridge.ResetStaticProperties(); TweetDeckBridge.ResetStaticProperties();
@@ -162,7 +142,7 @@ namespace TweetDuck.Core{
ScriptLoader.ExecuteScript(frame, "TD.storage.Account.prototype.requiresConsent = function(){ return false; }", "gen:gdpr"); ScriptLoader.ExecuteScript(frame, "TD.storage.Account.prototype.requiresConsent = function(){ return false; }", "gen:gdpr");
} }
if (Program.UserConfig.FirstRun){ if (Config.FirstRun){
ScriptLoader.ExecuteFile(frame, "introduction.js", browser); ScriptLoader.ExecuteFile(frame, "introduction.js", browser);
} }
} }
@@ -185,24 +165,22 @@ namespace TweetDuck.Core{
} }
} }
private void UserConfig_MuteToggled(object sender, EventArgs e){ private void Config_MuteToggled(object sender, EventArgs e){
UpdateProperties(); UpdateProperties();
} }
private void UserConfig_ZoomLevelChanged(object sender, EventArgs e){ private void Config_SoundNotificationInfoChanged(object sender, EventArgs e){
BrowserUtils.SetZoomLevel(browser.GetBrowser(), Program.UserConfig.ZoomLevel);
}
private void UserConfig_SoundNotificationInfoChanged(object sender, EventArgs e){
const string soundUrl = "https://ton.twimg.com/tduck/updatesnd"; const string soundUrl = "https://ton.twimg.com/tduck/updatesnd";
bool hasCustomSound = Program.UserConfig.IsCustomSoundNotificationSet;
if (prevSoundNotificationPath != Program.UserConfig.NotificationSoundPath){ bool hasCustomSound = Config.IsCustomSoundNotificationSet;
browser.SetupResourceHandler(soundUrl, hasCustomSound ? SoundNotification.CreateFileHandler(Program.UserConfig.NotificationSoundPath) : null); string newNotificationPath = Config.NotificationSoundPath;
prevSoundNotificationPath = Program.UserConfig.NotificationSoundPath;
if (prevSoundNotificationPath != newNotificationPath){
browser.SetupResourceHandler(soundUrl, hasCustomSound ? SoundNotification.CreateFileHandler(newNotificationPath) : null);
prevSoundNotificationPath = newNotificationPath;
} }
browser.ExecuteScriptAsync("TDGF_setSoundNotificationData", hasCustomSound, Program.UserConfig.NotificationSoundVolume); browser.ExecuteScriptAsync("TDGF_setSoundNotificationData", hasCustomSound, Config.NotificationSoundVolume);
} }
// external handling // external handling

View File

@@ -6,6 +6,7 @@ using System.IO;
using System.Net; using System.Net;
using System.Windows.Forms; using System.Windows.Forms;
using CefSharp.WinForms; using CefSharp.WinForms;
using TweetDuck.Configuration;
using TweetDuck.Core.Other; using TweetDuck.Core.Other;
using TweetDuck.Data; using TweetDuck.Data;
@@ -15,14 +16,17 @@ namespace TweetDuck.Core.Utils{
public static string UserAgentChrome => "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/"+Cef.ChromiumVersion+" Safari/537.36"; public static string UserAgentChrome => "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/"+Cef.ChromiumVersion+" Safari/537.36";
public static readonly bool HasDevTools = File.Exists(Path.Combine(Program.ProgramPath, "devtools_resources.pak")); public static readonly bool HasDevTools = File.Exists(Path.Combine(Program.ProgramPath, "devtools_resources.pak"));
private static UserConfig Config => Program.Config.User;
private static SystemConfig SysConfig => Program.Config.System;
public static void SetupCefArgs(IDictionary<string, string> args){ public static void SetupCefArgs(IDictionary<string, string> args){
if (!Program.SystemConfig.HardwareAcceleration){ if (!SysConfig.HardwareAcceleration){
args["disable-gpu"] = "1"; args["disable-gpu"] = "1";
args["disable-gpu-vsync"] = "1"; args["disable-gpu-vsync"] = "1";
} }
if (Program.UserConfig.EnableSmoothScrolling){ if (Config.EnableSmoothScrolling){
args["disable-threaded-scrolling"] = "1"; args["disable-threaded-scrolling"] = "1";
if (args.TryGetValue("disable-features", out string disabledFeatures)){ if (args.TryGetValue("disable-features", out string disabledFeatures)){
@@ -36,7 +40,7 @@ namespace TweetDuck.Core.Utils{
args["disable-smooth-scrolling"] = "1"; args["disable-smooth-scrolling"] = "1";
} }
if (!Program.UserConfig.EnableTouchAdjustment){ if (!Config.EnableTouchAdjustment){
args["disable-touch-adjustment"] = "1"; args["disable-touch-adjustment"] = "1";
} }
@@ -71,6 +75,21 @@ namespace TweetDuck.Core.Utils{
browser.SetupResourceHandler(resource.Url, resource.Handler); browser.SetupResourceHandler(resource.Url, resource.Handler);
} }
public static void SetupZoomEvents(this ChromiumWebBrowser browser){
void UpdateZoomLevel(object sender, EventArgs args){
SetZoomLevel(browser.GetBrowser(), Config.ZoomLevel);
}
Config.ZoomLevelChanged += UpdateZoomLevel;
browser.Disposed += (sender, args) => Config.ZoomLevelChanged -= UpdateZoomLevel;
browser.FrameLoadStart += (sender, args) => {
if (args.Frame.IsMain && Config.ZoomLevel != 100){
SetZoomLevel(args.Browser, Config.ZoomLevel);
}
};
}
private const string TwitterTrackingUrl = "t.co"; private const string TwitterTrackingUrl = "t.co";
public enum UrlCheckResult{ public enum UrlCheckResult{
@@ -98,7 +117,7 @@ namespace TweetDuck.Core.Utils{
FormGuide.Show(hash); FormGuide.Show(hash);
} }
else{ else{
string browserPath = Program.UserConfig.BrowserPath; string browserPath = Config.BrowserPath;
if (browserPath == null || !File.Exists(browserPath)){ if (browserPath == null || !File.Exists(browserPath)){
WindowsUtils.OpenAssociatedProgram(url); WindowsUtils.OpenAssociatedProgram(url);
@@ -115,7 +134,7 @@ namespace TweetDuck.Core.Utils{
break; break;
case UrlCheckResult.Tracking: case UrlCheckResult.Tracking:
if (Program.UserConfig.IgnoreTrackingUrlWarning){ if (Config.IgnoreTrackingUrlWarning){
goto case UrlCheckResult.Fine; goto case UrlCheckResult.Fine;
} }
@@ -127,8 +146,8 @@ namespace TweetDuck.Core.Utils{
DialogResult result = form.ShowDialog(); DialogResult result = form.ShowDialog();
if (result == DialogResult.Ignore){ if (result == DialogResult.Ignore){
Program.UserConfig.IgnoreTrackingUrlWarning = true; Config.IgnoreTrackingUrlWarning = true;
Program.UserConfig.Save(); Config.Save();
} }
if (result == DialogResult.Ignore || result == DialogResult.Yes){ if (result == DialogResult.Ignore || result == DialogResult.Yes){
@@ -147,7 +166,7 @@ namespace TweetDuck.Core.Utils{
public static void OpenExternalSearch(string query){ public static void OpenExternalSearch(string query){
if (string.IsNullOrWhiteSpace(query))return; if (string.IsNullOrWhiteSpace(query))return;
string searchUrl = Program.UserConfig.SearchEngineUrl; string searchUrl = Config.SearchEngineUrl;
if (string.IsNullOrEmpty(searchUrl)){ if (string.IsNullOrEmpty(searchUrl)){
if (FormMessage.Question("Search Options", "You have not configured a default search engine yet, would you like to do it now?", FormMessage.Yes, FormMessage.No)){ if (FormMessage.Question("Search Options", "You have not configured a default search engine yet, would you like to do it now?", FormMessage.Yes, FormMessage.No)){
@@ -160,7 +179,7 @@ namespace TweetDuck.Core.Utils{
if (settings == null)return; if (settings == null)return;
settings.FormClosed += (sender, args) => { settings.FormClosed += (sender, args) => {
if (args.CloseReason == CloseReason.UserClosing && Program.UserConfig.SearchEngineUrl != searchUrl){ if (args.CloseReason == CloseReason.UserClosing && Config.SearchEngineUrl != searchUrl){
OpenExternalSearch(query); OpenExternalSearch(query);
} }
}; };

View File

@@ -2,7 +2,6 @@
using CefSharp; using CefSharp;
using System.Drawing; using System.Drawing;
using System.IO; using System.IO;
using System.Linq;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Windows.Forms; using System.Windows.Forms;
using TweetDuck.Core.Other; using TweetDuck.Core.Other;

View File

@@ -89,7 +89,7 @@ namespace TweetDuck.Plugins.Controls{
} }
private void btnToggleState_Click(object sender, EventArgs e){ private void btnToggleState_Click(object sender, EventArgs e){
pluginManager.Config.ToggleEnabled(plugin); pluginManager.Config.SetEnabled(plugin, !pluginManager.Config.IsEnabled(plugin));
UpdatePluginState(); UpdatePluginState();
} }

14
Plugins/IPluginConfig.cs Normal file
View File

@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using TweetDuck.Plugins.Events;
namespace TweetDuck.Plugins{
interface IPluginConfig{
IEnumerable<string> DisabledPlugins { get; }
event EventHandler<PluginChangedStateEventArgs> PluginChangedState;
void SetEnabled(Plugin plugin, bool enabled);
bool IsEnabled(Plugin plugin);
}
}

View File

@@ -1,72 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using TweetDuck.Plugins.Events;
namespace TweetDuck.Plugins{
sealed class PluginConfig{
public event EventHandler<PluginChangedStateEventArgs> PluginChangedState;
public IEnumerable<string> DisabledPlugins => disabled;
public bool AnyDisabled => disabled.Count > 0;
private static readonly string[] DefaultDisabled = {
"official/clear-columns",
"official/reply-account"
};
private readonly HashSet<string> disabled = new HashSet<string>();
public void SetEnabled(Plugin plugin, bool enabled){
if ((enabled && disabled.Remove(plugin.Identifier)) || (!enabled && disabled.Add(plugin.Identifier))){
PluginChangedState?.Invoke(this, new PluginChangedStateEventArgs(plugin, enabled));
}
}
public void ToggleEnabled(Plugin plugin){
SetEnabled(plugin, !IsEnabled(plugin));
}
public bool IsEnabled(Plugin plugin){
return !disabled.Contains(plugin.Identifier);
}
public void Save(string file){
try{
using(StreamWriter writer = new StreamWriter(new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None), Encoding.UTF8)){
writer.WriteLine("#Disabled");
foreach(string identifier in disabled){
writer.WriteLine(identifier);
}
}
}catch(Exception e){
Program.Reporter.HandleException("Plugin Configuration Error", "Could not save the plugin configuration file.", true, e);
}
}
public void Load(string file){
try{
using(StreamReader reader = new StreamReader(new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read), Encoding.UTF8)){
string line = reader.ReadLine();
if (line == "#Disabled"){
disabled.Clear();
while((line = reader.ReadLine()) != null){
disabled.Add(line);
}
}
}
}catch(FileNotFoundException){
disabled.Clear();
disabled.UnionWith(DefaultDisabled);
Save(file);
}catch(DirectoryNotFoundException){
}catch(Exception e){
Program.Reporter.HandleException("Plugin Configuration Error", "Could not read the plugin configuration file. If you continue, the list of disabled plugins will be reset to default.", true, e);
}
}
}
}

View File

@@ -5,7 +5,7 @@ using System.Diagnostics;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Windows.Forms; using System.Windows.Forms;
using TweetDuck.Core.Other.Interfaces; using TweetDuck.Core.Utils;
using TweetDuck.Data; using TweetDuck.Data;
using TweetDuck.Plugins.Enums; using TweetDuck.Plugins.Enums;
using TweetDuck.Plugins.Events; using TweetDuck.Plugins.Events;
@@ -21,35 +21,38 @@ namespace TweetDuck.Plugins{
public IEnumerable<Plugin> Plugins => plugins; public IEnumerable<Plugin> Plugins => plugins;
public IEnumerable<InjectedHTML> NotificationInjections => bridge.NotificationInjections; public IEnumerable<InjectedHTML> NotificationInjections => bridge.NotificationInjections;
public PluginConfig Config { get; } public IPluginConfig Config { get; }
public event EventHandler<PluginErrorEventArgs> Reloaded; public event EventHandler<PluginErrorEventArgs> Reloaded;
public event EventHandler<PluginErrorEventArgs> Executed; public event EventHandler<PluginErrorEventArgs> Executed;
private readonly string rootPath; private readonly string rootPath;
private readonly string configPath;
private readonly PluginBridge bridge; private readonly PluginBridge bridge;
private readonly HashSet<Plugin> plugins = new HashSet<Plugin>(); private readonly HashSet<Plugin> plugins = new HashSet<Plugin>();
private readonly Dictionary<int, Plugin> tokens = new Dictionary<int, Plugin>(); private readonly Dictionary<int, Plugin> tokens = new Dictionary<int, Plugin>();
private readonly Random rand = new Random(); private readonly Random rand = new Random();
private ITweetDeckBrowser mainBrowser; private IWebBrowser mainBrowser;
public PluginManager(IPluginConfig config, string rootPath){
this.Config = config;
this.Config.PluginChangedState += Config_PluginChangedState;
public PluginManager(string rootPath, string configPath){
this.rootPath = rootPath; this.rootPath = rootPath;
this.configPath = configPath;
this.Config = new PluginConfig();
this.bridge = new PluginBridge(this); this.bridge = new PluginBridge(this);
Config.Load(configPath);
Config.PluginChangedState += Config_PluginChangedState;
} }
public void Register(ITweetDeckBrowser browser, PluginEnvironment environment, Control sync, bool asMainBrowser = false){ public void Register(IWebBrowser browser, PluginEnvironment environment, Control sync, bool asMainBrowser = false){
browser.OnFrameLoaded(frame => ExecutePlugins(frame, environment, sync)); browser.FrameLoadEnd += (sender, args) => {
browser.RegisterBridge("$TDP", bridge); IFrame frame = args.Frame;
if (frame.IsMain && TwitterUtils.IsTweetDeckWebsite(frame)){
ExecutePlugins(frame, environment, sync);
}
};
browser.RegisterAsyncJsObject("$TDP", bridge);
if (asMainBrowser){ if (asMainBrowser){
mainBrowser = browser; mainBrowser = browser;
@@ -57,8 +60,7 @@ namespace TweetDuck.Plugins{
} }
private void Config_PluginChangedState(object sender, PluginChangedStateEventArgs e){ private void Config_PluginChangedState(object sender, PluginChangedStateEventArgs e){
mainBrowser?.ExecuteFunction("TDPF_setPluginState", e.Plugin, e.IsEnabled); mainBrowser?.ExecuteScriptAsync("TDPF_setPluginState", e.Plugin, e.IsEnabled);
Config.Save(configPath);
} }
public bool IsPluginInstalled(string identifier){ public bool IsPluginInstalled(string identifier){
@@ -75,7 +77,7 @@ namespace TweetDuck.Plugins{
public void ConfigurePlugin(Plugin plugin){ public void ConfigurePlugin(Plugin plugin){
if (bridge.WithConfigureFunction.Contains(plugin)){ if (bridge.WithConfigureFunction.Contains(plugin)){
mainBrowser?.ExecuteFunction("TDPF_configurePlugin", plugin); mainBrowser?.ExecuteScriptAsync("TDPF_configurePlugin", plugin);
} }
else if (plugin.HasConfig){ else if (plugin.HasConfig){
if (File.Exists(plugin.ConfigPath)){ if (File.Exists(plugin.ConfigPath)){
@@ -113,8 +115,6 @@ namespace TweetDuck.Plugins{
} }
public void Reload(){ public void Reload(){
Config.Load(configPath);
plugins.Clear(); plugins.Clear();
tokens.Clear(); tokens.Clear();

View File

@@ -1,9 +1,10 @@
using TweetDuck.Plugins.Enums; using System.Linq;
using TweetDuck.Plugins.Enums;
namespace TweetDuck.Plugins{ namespace TweetDuck.Plugins{
static class PluginScriptGenerator{ static class PluginScriptGenerator{
public static string GenerateConfig(PluginConfig config){ public static string GenerateConfig(IPluginConfig config){
return config.AnyDisabled ? "window.TD_PLUGINS.disabled = [\""+string.Join("\",\"", config.DisabledPlugins)+"\"];" : string.Empty; return "window.TD_PLUGINS.disabled = ["+string.Join(",", config.DisabledPlugins.Select(id => $"\"{id}\""))+"]";
} }
public static string GeneratePlugin(string pluginIdentifier, string pluginContents, int pluginToken, PluginEnvironment environment){ public static string GeneratePlugin(string pluginIdentifier, string pluginContents, int pluginToken, PluginEnvironment environment){

View File

@@ -1,4 +1,5 @@
using CefSharp; using CefSharp;
using CefSharp.WinForms;
using System; using System;
using System.Diagnostics; using System.Diagnostics;
using System.Globalization; using System.Globalization;
@@ -19,7 +20,7 @@ namespace TweetDuck{
public const string BrandName = "TweetDuck"; public const string BrandName = "TweetDuck";
public const string Website = "https://tweetduck.chylex.com"; public const string Website = "https://tweetduck.chylex.com";
public const string VersionTag = "1.15.1"; public const string VersionTag = "1.16";
public static readonly string ProgramPath = AppDomain.CurrentDomain.BaseDirectory; public static readonly string ProgramPath = AppDomain.CurrentDomain.BaseDirectory;
public static readonly bool IsPortable = File.Exists(Path.Combine(ProgramPath, "makeportable")); public static readonly bool IsPortable = File.Exists(Path.Combine(ProgramPath, "makeportable"));
@@ -49,11 +50,7 @@ namespace TweetDuck{
public static CultureInfo Culture { get; } public static CultureInfo Culture { get; }
public static Reporter Reporter { get; } public static Reporter Reporter { get; }
public static ConfigManager Config { get; } public static ConfigManager Config { get; }
// TODO
public static UserConfig UserConfig => Config.User;
public static SystemConfig SystemConfig => Config.System;
static Program(){ static Program(){
Culture = CultureInfo.CurrentCulture; Culture = CultureInfo.CurrentCulture;
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
@@ -147,7 +144,7 @@ namespace TweetDuck{
#endif #endif
}; };
CommandLineArgs.ReadCefArguments(UserConfig.CustomCefArgs).ToDictionary(settings.CefCommandLineArgs); CommandLineArgs.ReadCefArguments(Config.User.CustomCefArgs).ToDictionary(settings.CefCommandLineArgs);
BrowserUtils.SetupCefArgs(settings.CefCommandLineArgs); BrowserUtils.SetupCefArgs(settings.CefCommandLineArgs);
Cef.Initialize(settings, false, new BrowserProcessHandler()); Cef.Initialize(settings, false, new BrowserProcessHandler());

View File

@@ -15,7 +15,7 @@ The program was built using Visual Studio 2017. Before opening the solution, ple
After opening the solution, right-click the solution and select **Restore NuGet Packages**, or manually run this command in the **Package Manager Console**: After opening the solution, right-click the solution and select **Restore NuGet Packages**, or manually run this command in the **Package Manager Console**:
``` ```
PM> Install-Package CefSharp.WinForms -Version 67.0.0-CI2662 -Source https://www.myget.org/F/cefsharp/api/v3/index.json PM> Install-Package CefSharp.WinForms -Version 67.0.0-pre01
``` ```
Note that some pre-release builds of CefSharp are not available on NuGet. To correctly restore packages in that case, open **Package Manager Settings**, and add `https://www.myget.org/F/cefsharp/api/v3/index.json` to the list of package sources. Note that some pre-release builds of CefSharp are not available on NuGet. To correctly restore packages in that case, open **Package Manager Settings**, and add `https://www.myget.org/F/cefsharp/api/v3/index.json` to the list of package sources.
@@ -24,7 +24,7 @@ Note that some pre-release builds of CefSharp are not available on NuGet. To cor
The `Debug` configuration uses a separate data folder by default (`%LOCALAPPDATA%\TweetDuckDebug`) to avoid affecting an existing installation of TweetDuck. You can modify this by opening **TweetDuck Properties** in Visual Studio, clicking the **Debug** tab, and changing the **Command line arguments** field. The `Debug` configuration uses a separate data folder by default (`%LOCALAPPDATA%\TweetDuckDebug`) to avoid affecting an existing installation of TweetDuck. You can modify this by opening **TweetDuck Properties** in Visual Studio, clicking the **Debug** tab, and changing the **Command line arguments** field.
While debugging, opening the main menu and clicking **Reload browser** automatically rebuilds all resources in the `Resources/Scripts` and `Resources/Plugins` folders. This allows editing HTML/CSS/JS files and applying the changes without restarting the program, but it will cause a short delay between browser reloads. While debugging, opening the main menu and clicking **Reload browser** automatically rebuilds all resources in `Resources/Scripts` and `Resources/Plugins`. This allows editing HTML/CSS/JS files without restarting the program, but it will cause a short delay between browser reloads. An F# compiler must be present when building the project to enable this feature: `C:\Program Files (x86)\Microsoft SDKs\F#\10.1\Framework\v4.0\fsc.exe`
### Release ### Release
@@ -32,7 +32,7 @@ Open **Batch Build**, tick all `Release` configurations with `x86` platform, and
After the build succeeds, the `bin/x86/Release` folder will contain files intended for distribution (no debug symbols or other unnecessary files). You may package these files yourself, or see the [Installers](#installers) section for automated installer generation. After the build succeeds, the `bin/x86/Release` folder will contain files intended for distribution (no debug symbols or other unnecessary files). You may package these files yourself, or see the [Installers](#installers) section for automated installer generation.
The `Release` configuration omits debug symbols and other unnecessary files. You can modify this behavior by opening `TweetDuck.csproj`, and editing the `<Target Name="AfterBuild" Condition="$(ConfigurationName) == Release">` section. The `Release` configuration omits debug symbols and other unnecessary files, and it will automatically generate the [update installer](#installers) if the environment is setup correctly. You can modify this behavior by opening `TweetDuck.csproj`, and editing the `<Target Name="AfterBuild" Condition="$(ConfigurationName) == Release">` section.
If you decide to publicly release a custom version, please make it clear that it is not an official release of TweetDuck. There are many references to the official website and this repository, especially in the update system, so search for `chylex.com` and `github.com` in all files and replace them appropriately. If you decide to publicly release a custom version, please make it clear that it is not an official release of TweetDuck. There are many references to the official website and this repository, especially in the update system, so search for `chylex.com` and `github.com` in all files and replace them appropriately.
@@ -40,7 +40,7 @@ If you decide to publicly release a custom version, please make it clear that it
#### Error: The command (...) exited with code 1 #### Error: The command (...) exited with code 1
- This indicates a failed post-build event, open the **Output** tab for logs - This indicates a failed post-build event, open the **Output** tab for logs
- Determine if there was an IO error from the `rmdir` commands, or whether the error was in the **PostBuild.ps1** script (`Encountered an error while running PostBuild.ps1 on line <xyz>`) - Determine if there was an IO error from the `rmdir` commands, the custom MSBuild targets near the end of the [.csproj file](https://github.com/chylex/TweetDuck/blob/master/TweetDuck.csproj), or in the **PostBuild.fsx** script (`Encountered an error while running PostBuild`)
- Some files are checked for invalid characters: - Some files are checked for invalid characters:
- `Resources/Plugins/emoji-keyboard/emoji-ordering.txt` line endings must be LF (line feed); any CR (carriage return) in the file will cause a failed build, and you will need to ensure correct line endings in your text editor - `Resources/Plugins/emoji-keyboard/emoji-ordering.txt` line endings must be LF (line feed); any CR (carriage return) in the file will cause a failed build, and you will need to ensure correct line endings in your text editor
@@ -55,22 +55,24 @@ TweetDuck uses **Inno Setup** for installers and updates. First, download and in
Next, add the Inno Setup installation folder (usually `C:\Program Files (x86)\Inno Setup 5`) into your **PATH** environment variable. You may need to restart File Explorer for the change to take place. Next, add the Inno Setup installation folder (usually `C:\Program Files (x86)\Inno Setup 5`) into your **PATH** environment variable. You may need to restart File Explorer for the change to take place.
Now you can generate installers after a build by running `bld/RUN BUILD.bat`. Note that this will only package the files, you still need to run the [release build](#release) in Visual Studio! Now you can generate installers by running `bld/GEN INSTALLERS.bat`. Note that this will only package the files, you still need to run the [release build](#release) in Visual Studio!
After the window closes, three installers will be generated inside the `bld/Output` folder: After the window closes, three installers will be generated inside the `bld/Output` folder:
* **TweetDuck.exe** * **TweetDuck.exe**
* This is the main installer that creates entries in the Start Menu & Programs and Features, and an optional desktop icon * This is the main installer that creates entries in the Start Menu & Programs and Features, and an optional desktop icon
* **TweetDuck.Update.exe** * **TweetDuck.Update.exe**
* This is a lightweight update installer that only contains the most important files that usually change across releases * This is a lightweight update installer that only contains the most important files that usually change across releases
* It will automatically download and apply the full installer if the user's current version of CEF does not match (the download link is in `gen_upd.iss` and points to this repository by default) * It will automatically download and apply the full installer if the user's current version of CEF does not match
* **TweetDuck.Portable.exe** * **TweetDuck.Portable.exe**
* This is a portable installer that does not need administrator privileges * This is a portable installer that does not need administrator privileges
* It automatically creates a `makeportable` file in the program folder, which forces TweetDuck to run in portable mode * It automatically creates a `makeportable` file in the program folder, which forces TweetDuck to run in portable mode
The installers are built for GitHub Releases, where the main and portable installers can download and install Visual C++ if it's missing, and the update installer will download and apply the full installer when needed. If you plan to distribute your own installers via GitHub, you can change the variables in the installer files (`.iss`) and in the update system to point to your repository, and use the power of the existing update system.
#### Notes #### Notes
> When opening **Batch Build**, you will also see `x64` and `AnyCPU` configurations. These are visible due to what I consider a Visual Studio bug, and will not work without significant changes to the project. Manually running the `Resources/PostCefUpdate.ps1` PowerShell script modifies the downloaded CefSharp packages, and removes the invalid configurations. > When opening **Batch Build**, you will also see `x64` and `AnyCPU` configurations. These are visible due to what I consider a Visual Studio bug, and will not work without significant changes to the project. Manually running the `Resources/PostCefUpdate.ps1` PowerShell script modifies the downloaded CefSharp packages, and removes the invalid configurations.
> There is a small chance running `RUN BUILD.bat` immediately shows a resource error. If that happens, close the console window (which terminates all Inno Setup processes and leaves corrupted installers in the output folder), and run it again. > There is a small chance running `GEN INSTALLERS.bat` immediately shows a resource error. If that happens, close the console window (which terminates all Inno Setup processes and leaves corrupted installers in the output folder), and run it again.
> Running `RUN BUILD.bat` uses about 400 MB of RAM due to high compression. You can lower this to about 140 MB by opening `gen_full.iss` and `gen_port.iss`, and changing `LZMADictionarySize=15360` to `LZMADictionarySize=4096`. > Running `GEN INSTALLERS.bat` uses about 400 MB of RAM due to high compression. You can lower this to about 140 MB by opening `gen_full.iss` and `gen_port.iss`, and changing `LZMADictionarySize=15360` to `LZMADictionarySize=4096`.

View File

@@ -0,0 +1,3 @@
run(){
console.info("executed debug plugin in notification");
}

View File

@@ -2,7 +2,6 @@ enabled(){
// elements & data // elements & data
this.css = null; this.css = null;
this.icons = null; this.icons = null;
this.htmlModal = null;
this.config = null; this.config = null;
this.defaultConfig = { this.defaultConfig = {
@@ -41,13 +40,6 @@ enabled(){
const me = this; const me = this;
// modal dialog loading
$TDP.readFileRoot(this.$token, "modal.html").then(contents => {
this.htmlModal = contents;
}).catch(err => {
$TD.alert("error", "Problem loading data for the design edit plugin: "+err.message);
});
// configuration // configuration
const configFile = "config.json"; const configFile = "config.json";
@@ -112,7 +104,7 @@ enabled(){
// settings click event // settings click event
this.onSettingsMenuClickedEvent = () => { this.onSettingsMenuClickedEvent = () => {
return if this.htmlModal === null || this.config === null; return if this.config === null;
setTimeout(() => { setTimeout(() => {
let menu = $(".js-dropdown-content").children("ul").first(); let menu = $(".js-dropdown-content").children("ul").first();
@@ -181,20 +173,26 @@ enabled(){
// SELECTS // SELECTS
else if (tag === "SELECT"){ else if (tag === "SELECT"){
let optionCustom = item.find("option[value^='custom']"); let optionCustom = item.find("option[value^='custom']");
let optionCustomNew = item.find("option[value^='change-custom']");
let resetMyValue = () => { let resetMyValue = () => {
if (!item.val(me.config[key]).val() && optionCustom.length === 1){ if (!item.val(me.config[key]).val() && optionCustom.length === 1){
item.val(optionCustom.attr("value")); item.val(optionCustom.attr("value"));
optionCustom.text(getTextForCustom(key)); optionCustom.text(getTextForCustom(key));
optionCustomNew.show();
}
else{
optionCustom.text("Custom");
optionCustomNew.hide();
} }
}; };
resetMyValue(); resetMyValue();
item.change(function(){ // TODO change doesn't fire when Custom is already selected item.change(function(){
let val = item.val(); let val = item.val();
if (val === "custom-px"){ if (val.endsWith("custom-px")){
val = (prompt("Enter custom value (px):") || "").trim(); val = (prompt("Enter custom value (px):") || "").trim();
if (val){ if (val){
@@ -204,21 +202,17 @@ enabled(){
if (/^[0-9]+$/.test(val)){ if (/^[0-9]+$/.test(val)){
updateKey(key, val+"px"); updateKey(key, val+"px");
optionCustom.text(getTextForCustom(key));
} }
else{ else{
alert("Invalid value, only px values are supported."); alert("Invalid value, only px values are supported.");
resetMyValue();
} }
} }
else{
resetMyValue();
}
} }
else{ else{
updateKey(key, item.val()); updateKey(key, item.val());
optionCustom.text("Custom");
} }
resetMyValue();
}); });
} }
// CUSTOM ELEMENTS // CUSTOM ELEMENTS
@@ -268,13 +262,17 @@ enabled(){
}, 1); }, 1);
}); });
}).methods({ }).methods({
_render: () => $(this.htmlModal), _render: function(){
return $(me.htmlModal);
},
destroy: function(){ destroy: function(){
if (this.reloadPage){ if (this.reloadPage){
window.TDPF_requestReload(); window.TDPF_requestReload();
return; return;
} }
delete me.htmlModal;
$("#td-design-plugin-modal").hide(); $("#td-design-plugin-modal").hide();
this.supr(); this.supr();
} }
@@ -670,7 +668,12 @@ ready(){
} }
configure(){ configure(){
new this.customDesignModal(); $TDP.readFileRoot(this.$token, "modal.html").then(contents => {
this.htmlModal = contents;
new this.customDesignModal();
}).catch(err => {
$TD.alert("error", "Error loading the configuration dialog: "+err.message);
});
} }
disabled(){ disabled(){

View File

@@ -41,6 +41,7 @@
<option value="350px">Wide (350px)</option> <option value="350px">Wide (350px)</option>
<option value="400px">Extreme (400px)</option> <option value="400px">Extreme (400px)</option>
<option value="custom-px">Custom</option> <option value="custom-px">Custom</option>
<option value="change-custom-px">Change custom value...</option>
</optgroup> </optgroup>
<option disabled></option> <option disabled></option>
<optgroup label="Dynamic width"> <optgroup label="Dynamic width">
@@ -66,6 +67,7 @@
<option value="15px">Large (15px)</option> <option value="15px">Large (15px)</option>
<option value="16px">Largest (16px)</option> <option value="16px">Largest (16px)</option>
<option value="custom-px">Custom</option> <option value="custom-px">Custom</option>
<option value="change-custom-px">Change custom value...</option>
</select> </select>
<label class="checkbox"> <label class="checkbox">
<input data-td-key="increaseQuoteTextSize" class="js-theme-checkbox touch-larger-label" type="checkbox"> <input data-td-key="increaseQuoteTextSize" class="js-theme-checkbox touch-larger-label" type="checkbox">

249
Resources/PostBuild.fsx Normal file
View File

@@ -0,0 +1,249 @@
open System
open System.Collections.Generic
open System.Diagnostics
open System.IO
open System.Text.RegularExpressions
open System.Threading.Tasks
// "$(DevEnvDir)CommonExtensions\Microsoft\FSharp\fsi.exe" "$(ProjectDir)Resources\PostBuild.fsx" --exec --nologo -- "$(TargetDir)\" "$(ProjectDir)\" "$(ConfigurationName)"
// "$(ProjectDir)bld\post_build.exe" "$(TargetDir)\" "$(ProjectDir)\" "$(ConfigurationName)"
exception ArgumentUsage of string
#if !INTERACTIVE
[<EntryPoint>]
#endif
let main (argv: string[]) =
try
if argv.Length < 2 then
#if INTERACTIVE
raise (ArgumentUsage "fsi.exe PostBuild.fsx --exec --nologo -- <TargetDir> <ProjectDir> [ConfigurationName] [VersionTag]")
#else
raise (ArgumentUsage "PostBuild.exe <TargetDir> <ProjectDir> [ConfigurationName] [VersionTag]")
#endif
let _time name func =
let sw = Stopwatch.StartNew()
func()
sw.Stop()
printfn "[%s took %i ms]" name (int (Math.Round(sw.Elapsed.TotalMilliseconds)))
let (+/) path1 path2 =
Path.Combine(path1, path2)
let sw = Stopwatch.StartNew()
// Setup
let targetDir = argv.[0]
let projectDir = argv.[1]
let configuration = if argv.Length >= 3 then argv.[2]
else "Release"
let version = if argv.Length >= 4 then argv.[3]
else ((targetDir +/ "TweetDuck.exe") |> FileVersionInfo.GetVersionInfo).FileVersion
printfn "--------------------------"
printfn "TweetDuck version %s" version
printfn "--------------------------"
let localesDir = targetDir +/ "locales"
let scriptsDir = targetDir +/ "scripts"
let pluginsDir = targetDir +/ "plugins"
let importsDir = scriptsDir +/ "imports"
// Functions (Strings)
let filterNotEmpty =
Seq.filter (not << String.IsNullOrEmpty)
let replaceRegex (pattern: string) (replacement: string) input =
Regex.Replace(input, pattern, replacement)
let collapseLines separator (sequence: string seq) =
String.Join(separator, sequence)
let trimStart (line: string) =
line.TrimStart()
// Functions (File Management)
let copyFile source target =
File.Copy(source, target, true)
let createDirectory path =
Directory.CreateDirectory(path) |> ignore
let rec copyDirectoryContentsFiltered source target (filter: string -> bool) =
if not (Directory.Exists(target)) then
Directory.CreateDirectory(target) |> ignore
let src = DirectoryInfo(source)
for file in src.EnumerateFiles() do
if filter file.Name then
file.CopyTo(target +/ file.Name) |> ignore
for dir in src.EnumerateDirectories() do
if filter dir.Name then
copyDirectoryContentsFiltered dir.FullName (target +/ dir.Name) filter
let copyDirectoryContents source target =
copyDirectoryContentsFiltered source target (fun _ -> true)
// Functions (File Processing)
let byPattern path pattern =
Directory.EnumerateFiles(path, pattern, SearchOption.AllDirectories)
let exceptEndingWith name =
Seq.filter (fun (file: string) -> not (file.EndsWith(name)))
let iterateFiles (files: string seq) (func: string -> unit) =
Parallel.ForEach(files, func) |> ignore
let readFile file = seq {
use stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 0x1000, FileOptions.SequentialScan)
use reader = new StreamReader(stream)
let mutable cont = true
while cont do
let line = reader.ReadLine()
if line = null then
cont <- false
else
yield line
}
let writeFile (fullPath: string) (lines: string seq) =
let relativePath = fullPath.[(targetDir.Length)..]
let includeVersion = relativePath.StartsWith(@"scripts\") && not (relativePath.StartsWith(@"scripts\imports\"))
let finalLines = if includeVersion then seq { yield "#" + version; yield! lines } else lines
File.WriteAllLines(fullPath, finalLines |> filterNotEmpty |> Seq.toArray)
printfn "Processed %s" relativePath
let processFiles (files: string seq) (extProcessors: IDictionary<string, (string seq -> string seq)>) =
let rec processFileContents file =
readFile file
|> extProcessors.[Path.GetExtension(file)]
|> Seq.map (fun line ->
Regex.Replace(line, @"#import ""(.*?)""", (fun matchInfo ->
processFileContents(importsDir +/ matchInfo.Groups.[1].Value.Trim())
|> collapseLines (Environment.NewLine)
|> (fun contents -> contents.TrimEnd())
))
)
iterateFiles files (fun file ->
processFileContents file
|> (writeFile file)
)
// Build
copyFile (projectDir +/ "bld/Resources/LICENSES.txt") (targetDir +/ "LICENSES.txt")
copyDirectoryContents (projectDir +/ "Resources/Scripts") scriptsDir
createDirectory (pluginsDir +/ "official")
createDirectory (pluginsDir +/ "user")
copyDirectoryContentsFiltered
(projectDir +/ "Resources/Plugins")
(pluginsDir +/ "official")
(fun name -> name <> ".debug" && name <> "emoji-instructions.txt")
if configuration = "Debug" then
copyDirectoryContents
(projectDir +/ "Resources/Plugins/.debug")
(pluginsDir +/ "user/.debug")
if Directory.Exists(localesDir) || configuration = "Release" then
Directory.EnumerateFiles(localesDir, "*.pak")
|> exceptEndingWith @"\en-US.pak"
|> Seq.iter (File.Delete)
// Validation
if File.ReadAllText(pluginsDir +/ "official/emoji-keyboard/emoji-ordering.txt").IndexOf('\r') <> -1 then
raise (FormatException("emoji-ordering.txt must not have any carriage return characters"))
else
printfn "Verified emoji-ordering.txt"
// Processing
let fileProcessors =
dict [
".js", (fun (lines: string seq) ->
lines
|> Seq.map (fun line ->
line
|> trimStart
|> replaceRegex @"^(.*?)((?<=^|[;{}()])\s?//(?:\s.*|$))?$" "$1"
|> replaceRegex @"(?<!\w)(return|throw)(\s.*?)? if (.*?);" "if ($3)$1$2;"
)
);
".css", (fun (lines: string seq) ->
lines
|> Seq.map (fun line ->
line
|> replaceRegex @"\s*/\*.*?\*/" ""
|> replaceRegex @"^(\S.*) {$" "$1{"
|> replaceRegex @"^\s+(.+?):\s*(.+?)(?:\s*(!important))?;$" "$1:$2$3;"
)
|> filterNotEmpty
|> collapseLines " "
|> replaceRegex @"([{};])\s" "$1"
|> replaceRegex @";}" "}"
|> Seq.singleton
);
".html", (fun (lines: string seq) ->
lines
|> Seq.map trimStart
);
".meta", (fun (lines: string seq) ->
lines
|> Seq.map (fun line -> line.Replace("{version}", version))
);
]
processFiles ((byPattern targetDir "*.js") |> exceptEndingWith @"\configuration.default.js") fileProcessors
processFiles (byPattern targetDir "*.css") fileProcessors
processFiles (byPattern targetDir "*.html") fileProcessors
processFiles (byPattern pluginsDir "*.meta") fileProcessors
// Cleanup
Directory.Delete(importsDir, true)
// Finished
sw.Stop()
printfn "------------------"
printfn "Finished in %i ms" (int (Math.Round(sw.Elapsed.TotalMilliseconds)))
printfn "------------------"
0
with
| ArgumentUsage message ->
printfn ""
printfn "Build script usage:"
printfn "%s" message
printfn ""
1
| ex ->
printfn ""
printfn "Encountered an error while running PostBuild:"
printfn "%A" ex
printfn ""
1
#if INTERACTIVE
printfn "Running PostBuild in interpreter..."
main (fsi.CommandLineArgs |> Array.skip (1 + (fsi.CommandLineArgs |> Array.findIndex (fun arg -> arg = "--"))))
#endif

View File

@@ -1,166 +0,0 @@
Param(
[Parameter(Mandatory = $True, Position = 1)][string] $targetDir,
[Parameter(Mandatory = $True, Position = 2)][string] $projectDir,
[Parameter(Position = 3)][string] $configuration = "Release",
[Parameter(Position = 4)][string] $version = ""
)
$ErrorActionPreference = "Stop"
try{
$sw = [Diagnostics.Stopwatch]::StartNew()
if ($version.Equals("")){
$version = (Get-Item (Join-Path $targetDir "TweetDuck.exe")).VersionInfo.FileVersion
}
Write-Host "--------------------------"
Write-Host "TweetDuck version" $version
Write-Host "--------------------------"
# Cleanup
if (Test-Path (Join-Path $targetDir "locales")){
Remove-Item -Path (Join-Path $targetDir "locales\*.pak") -Exclude "en-US.pak"
}
# Copy resources
Copy-Item (Join-Path $projectDir "bld\Resources\LICENSES.txt") -Destination $targetDir -Force
New-Item -ItemType directory -Path $targetDir -Name "scripts" | Out-Null
New-Item -ItemType directory -Path $targetDir -Name "plugins" | Out-Null
New-Item -ItemType directory -Path $targetDir -Name "plugins\official" | Out-Null
New-Item -ItemType directory -Path $targetDir -Name "plugins\user" | Out-Null
Copy-Item (Join-Path $projectDir "Resources\Scripts\*") -Recurse -Destination (Join-Path $targetDir "scripts")
Copy-Item (Join-Path $projectDir "Resources\Plugins\*") -Recurse -Destination (Join-Path $targetDir "plugins\official") -Exclude ".debug", "emoji-instructions.txt"
if ($configuration -eq "Debug"){
New-Item -ItemType directory -Path $targetDir -Name "plugins\user\.debug" | Out-Null
Copy-Item (Join-Path $projectDir "Resources\Plugins\.debug\*") -Recurse -Destination (Join-Path $targetDir "plugins\user\.debug")
}
# Helper functions
function Remove-Empty-Lines{
Param([Parameter(Mandatory = $True, Position = 1)] $lines)
foreach($line in $lines){
if ($line -ne ''){
$line
}
}
}
function Check-Carriage-Return{
Param([Parameter(Mandatory = $True, Position = 1)] $file)
if (!(Test-Path $file)){
Throw "$file does not exist"
}
if ((Get-Content -Path $file -Raw).Contains("`r")){
Throw "$file must not have any carriage return characters"
}
Write-Host "Verified" $file.Substring($targetDir.Length)
}
function Rewrite-File{
Param([Parameter(Mandatory = $True, Position = 1)] $file,
[Parameter(Mandatory = $True, Position = 2)] $lines,
[Parameter(Mandatory = $True, Position = 3)] $imports)
$lines = Remove-Empty-Lines($lines)
$relativePath = $file.FullName.Substring($targetDir.Length)
foreach($line in $lines){
if ($line.Contains('#import ')){
$imports.Add($file.FullName)
break
}
}
if ($relativePath.StartsWith("scripts\")){
$lines = (,("#" + $version) + $lines)
}
[IO.File]::WriteAllLines($file.FullName, $lines)
Write-Host "Processed" $relativePath
}
# Validation
Check-Carriage-Return(Join-Path $targetDir "plugins\official\emoji-keyboard\emoji-ordering.txt")
# Processing
$imports = New-Object "System.Collections.Generic.List[string]"
foreach($file in Get-ChildItem -Path $targetDir -Filter "*.js" -Exclude "configuration.default.js" -Recurse){
$lines = [IO.File]::ReadLines($file.FullName)
$lines = $lines | ForEach-Object { $_.TrimStart() }
$lines = $lines -Replace '^(.*?)((?<=^|[;{}()])\s?//(?:\s.*|$))?$', '$1'
$lines = $lines -Replace '(?<!\w)(return|throw)(\s.*?)? if (.*?);', 'if ($3)$1$2;'
Rewrite-File $file $lines $imports
}
foreach($file in Get-ChildItem -Path $targetDir -Filter "*.css" -Recurse){
$lines = [IO.File]::ReadLines($file.FullName)
$lines = $lines -Replace '\s*/\*.*?\*/', ''
$lines = $lines -Replace '^(\S.*) {$', '$1{'
$lines = $lines -Replace '^\s+(.+?):\s*(.+?)(?:\s*(!important))?;$', '$1:$2$3;'
$lines = @((Remove-Empty-Lines($lines)) -Join ' ')
$lines = $lines -Replace '([{};])\s', '$1'
$lines = $lines -Replace ';}', '}'
Rewrite-File $file $lines $imports
}
foreach($file in Get-ChildItem -Path $targetDir -Filter "*.html" -Recurse){
$lines = [IO.File]::ReadLines($file.FullName)
$lines = $lines | ForEach-Object { $_.TrimStart() }
Rewrite-File $file $lines $imports
}
foreach($file in Get-ChildItem -Path (Join-Path $targetDir "plugins") -Filter "*.meta" -Recurse){
$lines = [IO.File]::ReadLines($file.FullName)
$lines = $lines -Replace '\{version\}', $version
Rewrite-File $file $lines $imports
}
# Imports
$importFolder = Join-Path $targetDir "scripts\imports"
foreach($path in $imports){
$text = [IO.File]::ReadAllText($path)
$text = [Regex]::Replace($text, '#import "(.*?)"', {
$importPath = Join-Path $importFolder ($args[0].Groups[1].Value.Trim())
$importStr = [IO.File]::ReadAllText($importPath).TrimEnd()
if ($importStr[0] -eq '#'){
$importStr = $importStr.Substring($importStr.IndexOf("`n") + 1)
}
return $importStr
}, [System.Text.RegularExpressions.RegexOptions]::MultiLine)
[IO.File]::WriteAllText($path, $text)
Write-Host "Resolved" $path.Substring($targetDir.Length)
}
[IO.Directory]::Delete($importFolder, $True)
# Finished
$sw.Stop()
Write-Host "------------------"
Write-Host "Finished in" $([math]::Round($sw.Elapsed.TotalMilliseconds)) "ms"
Write-Host "------------------"
}catch{
Write-Host "Encountered an error while running PostBuild.ps1 on line" $_.InvocationInfo.ScriptLineNumber
Write-Host $_
Exit 1
}

View File

@@ -10,10 +10,11 @@ try{
$sharpMatch = Select-String -Path $mainProj '<Import Project="packages\\CefSharp\.Common\.(.*?)\\' $sharpMatch = Select-String -Path $mainProj '<Import Project="packages\\CefSharp\.Common\.(.*?)\\'
$sharpVersion = $sharpMatch.Matches[0].Groups[1].Value $sharpVersion = $sharpMatch.Matches[0].Groups[1].Value
$propsFiles = "..\packages\CefSharp.Common.${sharpVersion}\build\CefSharp.Common.props", $replaceWhenTag = "..\packages\CefSharp.Common.${sharpVersion}\build\CefSharp.Common.props",
"..\packages\CefSharp.WinForms.${sharpVersion}\build\CefSharp.WinForms.props" "..\packages\CefSharp.WinForms.${sharpVersion}\build\CefSharp.WinForms.props",
"..\packages\CefSharp.WinForms.${sharpVersion}\build\CefSharp.WinForms.targets"
$targetFiles = "..\packages\CefSharp.Common.${sharpVersion}\build\CefSharp.Common.targets" $replaceItemGroupTag = "..\packages\CefSharp.Common.${sharpVersion}\build\CefSharp.Common.targets"
# Greetings # Greetings
@@ -39,14 +40,14 @@ try{
Write-Host "Removing x64 and AnyCPU from package files..." Write-Host "Removing x64 and AnyCPU from package files..."
foreach($file in $propsFiles){ foreach($file in $replaceWhenTag){
$contents = [IO.File]::ReadAllText($file) $contents = [IO.File]::ReadAllText($file)
$contents = $contents -Replace '(?<=<When Condition=")(''\$\(Platform\)'' == ''(AnyCPU|x64)'')(?=">)', 'false' $contents = $contents -Replace '(?<=<When Condition=")(''\$\(Platform\)'' == ''(AnyCPU|x64)'')(?=">)', 'false'
[IO.File]::WriteAllText($file, $contents) [IO.File]::WriteAllText($file, $contents)
} }
foreach($file in $targetFiles){ foreach($file in $replaceItemGroupTag){
$contents = [IO.File]::ReadAllText($file) $contents = [IO.File]::ReadAllText($file)
$contents = $contents -Replace '(?<=<ItemGroup Condition=")(''\$\(Platform\)'' == ''(AnyCPU|x64)'')(?=">)', 'false' $contents = $contents -Replace '(?<=<ItemGroup Condition=")(''\$\(Platform\)'' == ''(AnyCPU|x64)'')(?=">)', 'false'

View File

@@ -87,7 +87,7 @@ namespace TweetDuck.Resources{
#if DEBUG #if DEBUG
private static readonly string HotSwapProjectRoot = FixPathSlash(Path.GetFullPath(Path.Combine(Program.ProgramPath, "../../../"))); private static readonly string HotSwapProjectRoot = FixPathSlash(Path.GetFullPath(Path.Combine(Program.ProgramPath, "../../../")));
private static readonly string HotSwapTargetDir = FixPathSlash(Path.Combine(HotSwapProjectRoot, "bin", "tmp")); private static readonly string HotSwapTargetDir = FixPathSlash(Path.Combine(HotSwapProjectRoot, "bin", "tmp"));
private static readonly string HotSwapRebuildScript = Path.Combine(HotSwapProjectRoot, "Resources", "PostBuild.ps1"); private static readonly string HotSwapRebuildScript = Path.Combine(HotSwapProjectRoot, "bld", "post_build.exe");
static ScriptLoader(){ static ScriptLoader(){
if (File.Exists(HotSwapRebuildScript)){ if (File.Exists(HotSwapRebuildScript)){
@@ -110,8 +110,8 @@ namespace TweetDuck.Resources{
Stopwatch sw = Stopwatch.StartNew(); Stopwatch sw = Stopwatch.StartNew();
using(Process process = Process.Start(new ProcessStartInfo{ using(Process process = Process.Start(new ProcessStartInfo{
FileName = "powershell", FileName = HotSwapRebuildScript,
Arguments = $"-ExecutionPolicy Unrestricted -File \"{HotSwapRebuildScript}\" \"{HotSwapTargetDir}\\\" \"{HotSwapProjectRoot}\\\" \"Debug\" \"{Program.VersionTag}\"", Arguments = $"\"{HotSwapTargetDir}\\\" \"{HotSwapProjectRoot}\\\" \"Debug\" \"{Program.VersionTag}\"",
WindowStyle = ProcessWindowStyle.Hidden WindowStyle = ProcessWindowStyle.Hidden
})){ })){
// ReSharper disable once PossibleNullReferenceException // ReSharper disable once PossibleNullReferenceException

View File

@@ -1,14 +1,4 @@
(function($TD, $TDX, $, TD){ (function($TD, $TDX, $, TD){
//
// Variable: Current highlighted column jQuery & data objects.
//
let highlightedColumnEle, highlightedColumnObj;
//
// Variable: Currently highlighted tweet jQuery & data objects.
//
let highlightedTweetEle, highlightedTweetObj;
// //
// Variable: Array of functions called after the website app is loaded. // Variable: Array of functions called after the website app is loaded.
// //
@@ -111,6 +101,53 @@
} }
}; };
//
// Function: Returns an object containing data about the column below the cursor.
//
const getHoveredColumn = function(){
let hovered = document.querySelectorAll(":hover");
for(let index = hovered.length-1; index >= 0; index--){
let ele = hovered[index];
if (ele.tagName === "SECTION" && ele.classList.contains("js-column")){
let obj = TD.controller.columnManager.get(ele.getAttribute("data-column"));
if (obj){
return { ele, obj };
}
}
}
return null;
};
//
// Function: Returns an object containing data about the tweet below the cursor.
//
const getHoveredTweet = function(){
let hovered = document.querySelectorAll(":hover");
for(let index = hovered.length-1; index >= 0; index--){
let ele = hovered[index];
if (ele.tagName === "ARTICLE" && ele.classList.contains("js-stream-item") && ele.hasAttribute("data-account-key")){
let column = getHoveredColumn();
if (column){
let wrap = column.obj.findChirp(ele.getAttribute("data-key"));
let obj = column.obj.findChirp(ele.getAttribute("data-tweet-id")) || wrap;
if (obj){
return { ele, obj, wrap, column };
}
}
}
}
return null;
};
// //
// Function: Retrieves a property of an element with a specified class. // Function: Retrieves a property of an element with a specified class.
// //
@@ -280,6 +317,7 @@
html.children().first().addClass("td-notification-padded"); html.children().first().addClass("td-notification-padded");
} }
else if (type.includes("list_member")){ else if (type.includes("list_member")){
html.children().first().addClass("td-notification-padded td-notification-padded-alt");
html.find(".activity-header").css("margin-top", "2px"); html.find(".activity-header").css("margin-top", "2px");
html.find(".avatar").first().css("margin-bottom", "0"); html.find(".avatar").first().css("margin-bottom", "0");
} }
@@ -625,8 +663,11 @@
$(document.body).delegate("a", "contextmenu", function(){ $(document.body).delegate("a", "contextmenu", function(){
let me = $(this)[0]; let me = $(this)[0];
if (me.classList.contains("js-media-image-link") && highlightedTweetObj){ if (me.classList.contains("js-media-image-link")){
let tweet = highlightedTweetObj.hasMedia() ? highlightedTweetObj : highlightedTweetObj.quotedTweet; let hovered = getHoveredTweet();
return if !hovered;
let tweet = hovered.obj.hasMedia() ? hovered.obj : hovered.obj.quotedTweet;
let media = tweet.getMedia().find(media => media.mediaId === me.getAttribute("data-media-entity-id")); let media = tweet.getMedia().find(media => media.mediaId === me.getAttribute("data-media-entity-id"));
if ((media.isVideo && media.service === "twitter") || media.isAnimatedGif){ if ((media.isVideo && media.service === "twitter") || media.isAnimatedGif){
@@ -639,7 +680,7 @@
else if (me.classList.contains("js-gif-play")){ else if (me.classList.contains("js-gif-play")){
$TD.setRightClickedLink("video", $(this).closest(".js-media-gif-container").find("video").attr("src")); $TD.setRightClickedLink("video", $(this).closest(".js-media-gif-container").find("video").attr("src"));
} }
else{ else if (me.hasAttribute("data-full-url")){
$TD.setRightClickedLink("link", me.getAttribute("data-full-url")); $TD.setRightClickedLink("link", me.getAttribute("data-full-url"));
} }
}); });
@@ -677,65 +718,37 @@
}; };
// //
// Block: Update highlighted column and tweet for context menu and other functionality. // Block: Add tweet-related options to the context menu.
// //
execSafe(function setupHighlightedColumn(){ execSafe(function setupTweetContextMenu(){
throw 1 if !ensurePropertyExists(TD, "controller", "columnManager", "get"); throw 1 if !ensurePropertyExists(TD, "controller", "columnManager", "get");
throw 2 if !ensurePropertyExists(TD, "services", "ChirpBase", "TWEET"); throw 2 if !ensurePropertyExists(TD, "services", "ChirpBase", "TWEET");
throw 3 if !ensurePropertyExists(TD, "services", "TwitterActionFollow");
const updateHighlightedColumn = function(ele){
highlightedColumnEle = ele;
highlightedColumnObj = ele ? TD.controller.columnManager.get(ele.attr("data-column")) : null;
return !!highlightedColumnObj;
};
const updateHighlightedTweet = function(ele, obj){
highlightedTweetEle = ele;
highlightedTweetObj = obj;
};
const processMedia = function(chirp){ const processMedia = function(chirp){
return chirp.getMedia().filter(item => !item.isAnimatedGif).map(item => item.entity.media_url_https+":small").join(";"); return chirp.getMedia().filter(item => !item.isAnimatedGif).map(item => item.entity.media_url_https+":small").join(";");
}; };
app.delegate("section.js-column", { app.delegate("section.js-column", {
mouseenter: function(){
if (!highlightedColumnObj){
updateHighlightedColumn($(this));
}
},
mouseleave: function(){
updateHighlightedColumn(null);
},
contextmenu: function(){ contextmenu: function(){
let tweet = highlightedTweetObj; let hovered = getHoveredTweet();
return if !hovered;
if (tweet && tweet.chirpType === TD.services.ChirpBase.TWEET){ let tweet = hovered.obj;
let quote = tweet.quotedTweet;
if (tweet.chirpType === TD.services.ChirpBase.TWEET){
let tweetUrl = tweet.getChirpURL(); let tweetUrl = tweet.getChirpURL();
let quoteUrl = tweet.quotedTweet ? tweet.quotedTweet.getChirpURL() : ""; let quoteUrl = quote && quote.getChirpURL();
let chirpAuthors = tweet.quotedTweet ? [ tweet.getMainUser().screenName, tweet.quotedTweet.getMainUser().screenName ].join(";") : tweet.getMainUser().screenName;
let chirpImages = tweet.hasImage() ? processMedia(tweet) : tweet.quotedTweet && tweet.quotedTweet.hasImage() ? processMedia(tweet.quotedTweet) : ""; let chirpAuthors = quote ? [ tweet.getMainUser().screenName, quote.getMainUser().screenName ].join(";") : tweet.getMainUser().screenName;
let chirpImages = tweet.hasImage() ? processMedia(tweet) : quote && quote.hasImage() ? processMedia(quote) : "";
$TD.setRightClickedChirp(tweetUrl || "", quoteUrl || "", chirpAuthors, chirpImages); $TD.setRightClickedChirp(tweetUrl || "", quoteUrl || "", chirpAuthors, chirpImages);
} }
} else if (tweet instanceof TD.services.TwitterActionFollow){
}); $TD.setRightClickedLink("link", tweet.following.getProfileURL());
}
app.delegate("article.js-stream-item", {
mouseenter: function(){
let me = $(this);
return if !me[0].hasAttribute("data-account-key") || (!highlightedColumnObj && !updateHighlightedColumn(me.closest("section.js-column")));
let tweet = highlightedColumnObj.findChirp(me.attr("data-tweet-id")) || highlightedColumnObj.findChirp(me.attr("data-key"));
return if !tweet;
updateHighlightedTweet(me, tweet);
},
mouseleave: function(){
updateHighlightedTweet(null, null);
} }
}); });
}); });
@@ -745,20 +758,20 @@
// //
execSafe(function setupTweetScreenshot(){ execSafe(function setupTweetScreenshot(){
window.TDGF_triggerScreenshot = function(){ window.TDGF_triggerScreenshot = function(){
return if !highlightedTweetObj || !highlightedColumnObj; let hovered = getHoveredTweet();
return if !hovered;
let chirp = highlightedColumnObj.findChirp(highlightedTweetEle.attr("data-key")) || highlightedTweetObj; let columnWidth = $(hovered.column.ele).width();
let tweet = hovered.wrap || hovered.obj;
let columnWidth = highlightedColumnEle.width(); let html = $(tweet.render({
let html = $(chirp.render({
withFooter: false, withFooter: false,
withTweetActions: false, withTweetActions: false,
isInConvo: false, isInConvo: false,
isFavorite: false, isFavorite: false,
isRetweeted: false, // keeps retweet mark above tweet isRetweeted: false, // keeps retweet mark above tweet
isPossiblySensitive: false, isPossiblySensitive: false,
mediaPreviewSize: highlightedColumnObj.getMediaPreviewSize() mediaPreviewSize: hovered.column.obj.getMediaPreviewSize()
})); }));
html.find("footer").last().remove(); // apparently withTweetActions breaks for certain tweets, nice html.find("footer").last().remove(); // apparently withTweetActions breaks for certain tweets, nice
@@ -786,12 +799,12 @@
let gif = html.find(".js-media-gif-container"); let gif = html.find(".js-media-gif-container");
if (gif.length){ if (gif.length){
gif.css("background-image", 'url("'+chirp.getMedia()[0].small()+'")'); gif.css("background-image", 'url("'+tweet.getMedia()[0].small()+'")');
} }
let type = chirp.getChirpType(); let type = tweet.getChirpType();
if ((type.startsWith("favorite") || type.startsWith("retweet")) && chirp.isAboutYou()){ if ((type.startsWith("favorite") || type.startsWith("retweet")) && tweet.isAboutYou()){
html.addClass("td-notification-padded"); html.addClass("td-notification-padded");
} }
@@ -860,10 +873,11 @@
}; };
const tryCloseHighlightedColumn = function(){ const tryCloseHighlightedColumn = function(){
if (highlightedColumnEle){ let column = getHoveredColumn();
let column = highlightedColumnEle.closest(".js-column"); return false if !column;
return (column.is(".is-shifted-2") && tryClickSelector(".js-tweet-social-proof-back", column)) || (column.is(".is-shifted-1") && tryClickSelector(".js-column-back", column));
} let ele = $(column.ele);
return ((ele.is(".is-shifted-2") && tryClickSelector(".js-tweet-social-proof-back", ele)) || (ele.is(".is-shifted-1") && tryClickSelector(".js-column-back", ele)));
}; };
window.TDGF_onMouseClickExtra = function(button){ window.TDGF_onMouseClickExtra = function(button){
@@ -879,8 +893,10 @@
$(".is-shifted-1 .js-column-back").click(); $(".is-shifted-1 .js-column-back").click();
} }
else if (button === 2){ // forward button else if (button === 2){ // forward button
if (highlightedTweetEle){ let hovered = getHoveredTweet();
highlightedTweetEle.children().first().click();
if (hovered){
$(hovered.ele).children().first().click();
} }
} }
}; };
@@ -1182,7 +1198,8 @@
let src = !e.ctrlKey && getGifLink($(this).closest(".js-media-gif-container").find("video")); let src = !e.ctrlKey && getGifLink($(this).closest(".js-media-gif-container").find("video"));
if (src){ if (src){
window.TDGF_playVideo(src, getUsername(highlightedTweetObj)); let hovered = getHoveredTweet();
window.TDGF_playVideo(src, getUsername(hovered && hovered.obj));
} }
else{ else{
$TD.openBrowser(getVideoTweetLink($(this))); $TD.openBrowser(getVideoTweetLink($(this)));
@@ -1469,16 +1486,53 @@
// //
// Block: Fix DM notifications not showing if the conversation is open. // Block: Fix DM notifications not showing if the conversation is open.
// //
if (ensurePropertyExists(TD, "services", "TwitterConversation", "prototype", "getUnreadChirps")){ if (ensurePropertyExists(TD, "vo", "Column", "prototype", "mergeMissingChirps")){
const prevFunc = TD.services.TwitterConversation.prototype.getUnreadChirps; TD.vo.Column.prototype.mergeMissingChirps = prependToFunction(TD.vo.Column.prototype.mergeMissingChirps, function(e){
let model = this.model;
TD.services.TwitterConversation.prototype.getUnreadChirps = function(e){
return (e && e.sortIndex && !e.id && !this.notificationsDisabled) if (model && model.state && model.state.type === "privateMe" && !this.notificationsDisabled && e.poller.feed.managed){
? this.messages.filter(t => t.chirpType === TD.services.ChirpBase.MESSAGE && !t.isOwnChirp() && !t.read && !t.belongsBelow(e)) // changed from belongsAbove let unread = [];
: prevFunc.apply(this, arguments);
}; for(let chirp of e.chirps){
if (Array.isArray(chirp.messages)){
Array.prototype.push.apply(unread, chirp.messages.filter(message => message.read === false));
}
}
if (unread.length > 0){
if (ensurePropertyExists(TD, "util", "chirpReverseColumnSort")){
unread.sort(TD.util.chirpReverseColumnSort);
}
for(let message of unread){
onNewTweet(this, message);
}
// TODO sound notifications are borked as well
// TODO figure out what to do with missed notifications at startup
}
}
});
} }
//
// Block: Fix DMs not being marked as read when replying to them.
//
execSafe(function markRepliedDMsAsRead(){
throw 1 if !ensurePropertyExists(TD, "controller", "clients", "getClient");
throw 2 if !ensurePropertyExists(TD, "services", "Conversations", "prototype", "getConversation");
$(document).on("dataDmSent", function(e, data){
let client = TD.controller.clients.getClient(data.request.accountKey);
return if !client;
let conversation = client.conversations.getConversation(data.request.conversationId);
return if !conversation;
conversation.markAsRead();
});
});
// //
// Block: Limit amount of loaded DMs to avoid massive lag from re-opening them several times. // Block: Limit amount of loaded DMs to avoid massive lag from re-opening them several times.
// //
@@ -1555,79 +1609,12 @@
// Block: Custom reload function with memory cleanup. // Block: Custom reload function with memory cleanup.
// //
window.TDGF_reload = function(){ window.TDGF_reload = function(){
try{ window.gc && window.gc();
let session = TD.storage.feedController.getAll() window.location.reload();
.filter(feed => !!feed.getTopSortIndex())
.reduce((obj, feed) => (obj[feed.privateState.key] = feed.getTopSortIndex(), obj), {});
$TD.setSessionData("gc", JSON.stringify(session)).then(() => {
window.gc && window.gc();
window.location.reload();
});
}catch(err){
$TD.crashDebug("Error saving session during a reload");
window.location.reload();
}
window.TDGF_reload = function(){}; // redefine to prevent reloading multiple times window.TDGF_reload = function(){}; // redefine to prevent reloading multiple times
}; };
if (window.TD_SESSION && window.TD_SESSION.gc){
let state;
try{
state = JSON.parse(window.TD_SESSION.gc);
}catch(err){
$TD.crashDebug("Invalid session gc data: "+window.TD_SESSION.gc);
state = {};
}
const showMissedNotifications = function(){
let tweets = [];
let columns = {};
let tmp = new TD.services.ChirpBase;
for(let column of Object.values(TD.controller.columnManager.getAll())){
for(let feed of column.getFeeds()){
if (feed.privateState.key in state){
tmp.sortIndex = state[feed.privateState.key];
for(let tweet of [].concat.apply([], column.updateArray.map(function(chirp){
return chirp.getUnreadChirps(tmp);
}))){
tweets.push(tweet);
columns[tweet.id] = column;
}
}
}
}
tweets.sort(TD.util.chirpReverseColumnSort);
for(let tweet of tweets){
onNewTweet(columns[tweet.id], tweet);
}
};
execSafe(function showMissedNotifications(){
throw 1 if !ensurePropertyExists(TD, "controller", "columnManager", "getAll");
$(document).one("dataColumnsLoaded", function(){
let columns = Object.values(TD.controller.columnManager.getAll());
let remaining = columns.length;
for(let column of columns){
column.ui.getChirpContainer().one("dataColumnFeedUpdated", () => {
if (--remaining === 0){
setTimeout(showMissedNotifications, 1);
}
});
}
});
});
}
// //
// Block: Disable default TweetDeck update notification. // Block: Disable default TweetDeck update notification.
// //
@@ -1662,8 +1649,6 @@
onAppReady.forEach(func => execSafe(func)); onAppReady.forEach(func => execSafe(func));
onAppReady = null; onAppReady = null;
delete window.TD_SESSION;
if (window.TD_PLUGINS){ if (window.TD_PLUGINS){
window.TD_PLUGINS.onReady(); window.TD_PLUGINS.onReady();
} }

View File

@@ -121,16 +121,14 @@
// //
// Block: Setup a skip button. // Block: Setup a skip button.
// //
if (!document.body.hasAttribute("td-example-notification")){ document.body.children[0].insertAdjacentHTML("beforeend", `
document.body.children[0].insertAdjacentHTML("beforeend", `
<svg id="td-skip" width="10" height="17" viewBox="0 0 350 600"> <svg id="td-skip" width="10" height="17" viewBox="0 0 350 600">
<path fill="#888" d="M0,151.656l102.208-102.22l247.777,247.775L102.208,544.986L0,442.758l145.546-145.547"> <path fill="#888" d="M0,151.656l102.208-102.22l247.777,247.775L102.208,544.986L0,442.758l145.546-145.547">
</svg>`); </svg>`);
document.getElementById("td-skip").addEventListener("click", function(){ document.getElementById("td-skip").addEventListener("click", function(){
$TD.loadNextNotification(); $TD.loadNextNotification();
}); });
}
// //
// Block: Setup a hover class on body. // Block: Setup a hover class on body.

View File

@@ -174,23 +174,46 @@ html[data-td-theme='dark'] .stream-item:not(:hover) .js-user-actions-menu {
opacity: 0.25; opacity: 0.25;
} }
.stream-item[data-key^="favorite"] .has-source-avatar .item-img, .stream-item[data-key^="retweet"] .has-source-avatar .item-img { .stream-item[data-key^="favorite"] .has-source-avatar .item-img,
.stream-item[data-key^="retweet"] .has-source-avatar .item-img {
position: absolute; position: absolute;
left: 21px; left: 21px;
top: 48px; top: 48px;
width: 0 !important; width: 0 !important;
} }
.stream-item[data-key^="favorite"] .has-source-avatar > .nbfc, .stream-item[data-key^="retweet"] .has-source-avatar > .nbfc { .stream-item[data-key^="favorite"] .has-source-avatar > .nbfc,
.stream-item[data-key^="retweet"] .has-source-avatar > .nbfc {
margin-left: 46px; margin-left: 46px;
line-height: unset !important; line-height: unset !important;
} }
.stream-item[data-key^="favorite"] .has-source-avatar > .nbfc > .avatar, .stream-item[data-key^="retweet"] .has-source-avatar > .nbfc > .avatar { .stream-item[data-key^="favorite"] .has-source-avatar > .nbfc > .avatar,
.stream-item[data-key^="retweet"] .has-source-avatar > .nbfc > .avatar {
position: absolute; position: absolute;
margin-left: -34px; margin-left: -34px;
} }
.stream-item[data-key^="list_"] .activity-header .item-img {
position: relative;
left: 10px;
top: 2px;
width: 0 !important;
}
.stream-item[data-key^="list_"] .activity-header > .nbfc {
margin-left: 46px;
padding-bottom: 0 !important;
min-height: 30px !important;
line-height: unset !important;
}
.stream-item[data-key^="list_"] .activity-header > .nbfc > .avatar {
position: absolute;
margin-left: -34px;
padding-top: 1px;
}
/***********************/ /***********************/
/* Tweaks for features */ /* Tweaks for features */
/***********************/ /***********************/
@@ -361,7 +384,7 @@ a:not(.tweet-detail-action) .reply-triangle {
display: none !important; display: none !important;
} }
.column-message.is-actionable span:hover > .icon-small-valigned { .column-message.is-actionable > span:hover .icon {
/* add a visual response when hovering individual filter icons; black theme uses a value of 20 */ /* add a visual response when hovering individual filter icons; black theme uses a value of 20 */
filter: saturate(10); filter: saturate(10);
} }
@@ -386,6 +409,11 @@ a:not(.tweet-detail-action) .reply-triangle {
border-width: 0 !important; border-width: 0 !important;
} }
#actions-modal .mdl {
/* fix action dialog (RT, Add to List/Collection) width with small window size */
max-width: 100%;
}
/***************************************************************/ /***************************************************************/
/* Fix glaring visual issues that twitter hasn't fixed yet smh */ /* Fix glaring visual issues that twitter hasn't fixed yet smh */
/***************************************************************/ /***************************************************************/

View File

@@ -104,7 +104,7 @@ html[data-td-font='smallest'] .fullname-badged:before, html[data-td-font='small'
vertical-align: sub !important; vertical-align: sub !important;
margin-right: 4px !important; margin-right: 4px !important;
} }
.td-notification-padded .item-img { .td-notification-padded .item-img {
position: absolute; position: absolute;
left: 21px; left: 21px;
@@ -122,6 +122,18 @@ html[data-td-font='smallest'] .fullname-badged:before, html[data-td-font='small'
margin-left: -34px; margin-left: -34px;
} }
.td-notification-padded-alt .item-img {
/* td-notification-padded-alt is used alongside td-notification-padded to save space in the file */
position: relative;
left: 10px;
top: 2px;
width: 0 !important;
}
.td-notification-padded-alt .activity-header > .nbfc > .avatar {
padding-top: 1px;
}
/*********/ /*********/
/* Media */ /* Media */
/*********/ /*********/
@@ -159,6 +171,10 @@ html[data-td-font='smallest'] .fullname-badged:before, html[data-td-font='small'
transition: opacity 0.15s ease; transition: opacity 0.15s ease;
} }
.td-example #td-skip {
display: none;
}
.td-hover #td-skip { .td-hover #td-skip {
opacity: 0.75; opacity: 0.75;
} }

View File

@@ -1,9 +1,9 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="packages\CefSharp.WinForms.67.0.0-CI2662\build\CefSharp.WinForms.props" Condition="Exists('packages\CefSharp.WinForms.67.0.0-CI2662\build\CefSharp.WinForms.props')" /> <Import Project="packages\CefSharp.WinForms.67.0.0-pre01\build\CefSharp.WinForms.props" Condition="Exists('packages\CefSharp.WinForms.67.0.0-pre01\build\CefSharp.WinForms.props')" />
<Import Project="packages\CefSharp.Common.67.0.0-CI2662\build\CefSharp.Common.props" Condition="Exists('packages\CefSharp.Common.67.0.0-CI2662\build\CefSharp.Common.props')" /> <Import Project="packages\CefSharp.Common.67.0.0-pre01\build\CefSharp.Common.props" Condition="Exists('packages\CefSharp.Common.67.0.0-pre01\build\CefSharp.Common.props')" />
<Import Project="packages\cef.redist.x86.3.3396.1777\build\cef.redist.x86.props" Condition="Exists('packages\cef.redist.x86.3.3396.1777\build\cef.redist.x86.props')" /> <Import Project="packages\cef.redist.x86.3.3396.1786\build\cef.redist.x86.props" Condition="Exists('packages\cef.redist.x86.3.3396.1786\build\cef.redist.x86.props')" />
<Import Project="packages\cef.redist.x64.3.3396.1777\build\cef.redist.x64.props" Condition="Exists('packages\cef.redist.x64.3.3396.1777\build\cef.redist.x64.props')" /> <Import Project="packages\cef.redist.x64.3.3396.1786\build\cef.redist.x64.props" Condition="Exists('packages\cef.redist.x64.3.3396.1786\build\cef.redist.x64.props')" />
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup> <PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@@ -57,6 +57,7 @@
<Compile Include="Configuration\Instance\FileConfigInstance.cs" /> <Compile Include="Configuration\Instance\FileConfigInstance.cs" />
<Compile Include="Configuration\ConfigManager.cs" /> <Compile Include="Configuration\ConfigManager.cs" />
<Compile Include="Configuration\Instance\IConfigInstance.cs" /> <Compile Include="Configuration\Instance\IConfigInstance.cs" />
<Compile Include="Configuration\Instance\PluginConfigInstance.cs" />
<Compile Include="Configuration\LockManager.cs" /> <Compile Include="Configuration\LockManager.cs" />
<Compile Include="Configuration\SystemConfig.cs" /> <Compile Include="Configuration\SystemConfig.cs" />
<Compile Include="Configuration\UserConfig.cs" /> <Compile Include="Configuration\UserConfig.cs" />
@@ -95,7 +96,6 @@
<Compile Include="Core\Handling\RequestHandlerBase.cs" /> <Compile Include="Core\Handling\RequestHandlerBase.cs" />
<Compile Include="Core\Handling\RequestHandlerBrowser.cs" /> <Compile Include="Core\Handling\RequestHandlerBrowser.cs" />
<Compile Include="Core\Handling\ResourceHandlerNotification.cs" /> <Compile Include="Core\Handling\ResourceHandlerNotification.cs" />
<Compile Include="Core\Other\Interfaces\ITweetDeckBrowser.cs" />
<Compile Include="Core\Management\ContextInfo.cs" /> <Compile Include="Core\Management\ContextInfo.cs" />
<Compile Include="Core\Notification\Example\FormNotificationExample.cs"> <Compile Include="Core\Notification\Example\FormNotificationExample.cs">
<SubType>Form</SubType> <SubType>Form</SubType>
@@ -260,10 +260,11 @@
<SubType>Component</SubType> <SubType>Component</SubType>
</Compile> </Compile>
<Compile Include="Plugins\Enums\PluginFolder.cs" /> <Compile Include="Plugins\Enums\PluginFolder.cs" />
<Compile Include="Plugins\IPluginConfig.cs" />
<Compile Include="Plugins\Plugin.cs" /> <Compile Include="Plugins\Plugin.cs" />
<Compile Include="Plugins\Events\PluginChangedStateEventArgs.cs" /> <Compile Include="Plugins\Events\PluginChangedStateEventArgs.cs" />
<Compile Include="Plugins\PluginBridge.cs" /> <Compile Include="Plugins\PluginBridge.cs" />
<Compile Include="Plugins\PluginConfig.cs" /> <Compile Include="Configuration\PluginConfig.cs" />
<Compile Include="Plugins\Enums\PluginEnvironment.cs" /> <Compile Include="Plugins\Enums\PluginEnvironment.cs" />
<Compile Include="Plugins\Enums\PluginGroup.cs" /> <Compile Include="Plugins\Enums\PluginGroup.cs" />
<Compile Include="Plugins\Events\PluginErrorEventArgs.cs" /> <Compile Include="Plugins\Events\PluginErrorEventArgs.cs" />
@@ -333,9 +334,9 @@
<None Include="Resources\Images\icon-tray-new.ico" /> <None Include="Resources\Images\icon-tray-new.ico" />
<None Include="Resources\Images\icon-tray.ico" /> <None Include="Resources\Images\icon-tray.ico" />
<None Include="Resources\Images\spinner.apng" /> <None Include="Resources\Images\spinner.apng" />
<None Include="Resources\PostBuild.ps1" />
<None Include="Resources\Plugins\.debug\.meta" /> <None Include="Resources\Plugins\.debug\.meta" />
<None Include="Resources\Plugins\.debug\browser.js" /> <None Include="Resources\Plugins\.debug\browser.js" />
<None Include="Resources\Plugins\.debug\notification.js" />
<None Include="Resources\Plugins\clear-columns\.meta" /> <None Include="Resources\Plugins\clear-columns\.meta" />
<None Include="Resources\Plugins\clear-columns\browser.js" /> <None Include="Resources\Plugins\clear-columns\browser.js" />
<None Include="Resources\Plugins\edit-design\.meta" /> <None Include="Resources\Plugins\edit-design\.meta" />
@@ -354,7 +355,10 @@
<None Include="Resources\Plugins\templates\modal.html" /> <None Include="Resources\Plugins\templates\modal.html" />
<None Include="Resources\Plugins\timeline-polls\.meta" /> <None Include="Resources\Plugins\timeline-polls\.meta" />
<None Include="Resources\Plugins\timeline-polls\browser.js" /> <None Include="Resources\Plugins\timeline-polls\browser.js" />
<None Include="Resources\PostBuild.fsx" />
<None Include="Resources\PostCefUpdate.ps1" />
<None Include="Resources\Scripts\code.js" /> <None Include="Resources\Scripts\code.js" />
<None Include="Resources\Scripts\imports\markup\introduction.html" />
<None Include="Resources\Scripts\imports\scripts\plugins.base.js" /> <None Include="Resources\Scripts\imports\scripts\plugins.base.js" />
<None Include="Resources\Scripts\imports\styles\introduction.css" /> <None Include="Resources\Scripts\imports\styles\introduction.css" />
<None Include="Resources\Scripts\imports\styles\twitter.base.css" /> <None Include="Resources\Scripts\imports\styles\twitter.base.css" />
@@ -394,15 +398,22 @@ rmdir "$(ProjectDir)bin\Release"
rmdir "$(TargetDir)scripts" /S /Q rmdir "$(TargetDir)scripts" /S /Q
rmdir "$(TargetDir)plugins" /S /Q rmdir "$(TargetDir)plugins" /S /Q
powershell -ExecutionPolicy Unrestricted -File "$(ProjectDir)Resources\PostBuild.ps1" "$(TargetDir)\" "$(ProjectDir)\" "$(ConfigurationName)" IF EXIST "$(ProjectDir)bld\post_build.exe" (
"$(ProjectDir)bld\post_build.exe" "$(TargetDir)\" "$(ProjectDir)\" "$(ConfigurationName)"
) ELSE (
"$(DevEnvDir)CommonExtensions\Microsoft\FSharp\fsi.exe" "$(ProjectDir)Resources\PostBuild.fsx" --exec --nologo -- "$(TargetDir)\" "$(ProjectDir)\" "$(ConfigurationName)"
)
</PostBuildEvent> </PostBuildEvent>
</PropertyGroup> </PropertyGroup>
<Target Name="BeforeBuild" Condition="(!$([System.IO.File]::Exists(&quot;$(ProjectDir)\bld\post_build.exe&quot;)) OR ($([System.IO.File]::GetLastWriteTime(&quot;$(ProjectDir)\Resources\PostBuild.fsx&quot;).Ticks) &gt; $([System.IO.File]::GetLastWriteTime(&quot;$(ProjectDir)\bld\post_build.exe&quot;).Ticks)))">
<Exec Command="&quot;$(ProjectDir)bld\POST BUILD.bat&quot;" WorkingDirectory="$(ProjectDir)bld\" IgnoreExitCode="true" />
</Target>
<Target Name="AfterBuild" Condition="$(ConfigurationName) == Release"> <Target Name="AfterBuild" Condition="$(ConfigurationName) == Release">
<Exec Command="del &quot;$(TargetDir)*.pdb&quot;" /> <Exec Command="del &quot;$(TargetDir)*.pdb&quot;" />
<Exec Command="del &quot;$(TargetDir)*.xml&quot;" /> <Exec Command="del &quot;$(TargetDir)*.xml&quot;" />
<Delete Files="$(TargetDir)CefSharp.BrowserSubprocess.exe" /> <Delete Files="$(TargetDir)CefSharp.BrowserSubprocess.exe" />
<Delete Files="$(TargetDir)widevinecdmadapter.dll" /> <Delete Files="$(TargetDir)widevinecdmadapter.dll" />
<Exec Command="&quot;$(ProjectDir)bld\UPDATE ONLY.bat&quot;" WorkingDirectory="$(ProjectDir)bld\" IgnoreExitCode="true" /> <Exec Command="start &quot;&quot; /B &quot;ISCC.exe&quot; /Q &quot;$(ProjectDir)bld\gen_upd.iss&quot;" WorkingDirectory="$(ProjectDir)bld\" IgnoreExitCode="true" />
</Target> </Target>
<PropertyGroup> <PropertyGroup>
<PreBuildEvent>powershell Get-Process TweetDuck.Browser -ErrorAction SilentlyContinue ^| Where-Object {$_.Path -eq '$(TargetDir)TweetDuck.Browser.exe'} ^| Stop-Process; Exit 0</PreBuildEvent> <PreBuildEvent>powershell Get-Process TweetDuck.Browser -ErrorAction SilentlyContinue ^| Where-Object {$_.Path -eq '$(TargetDir)TweetDuck.Browser.exe'} ^| Stop-Process; Exit 0</PreBuildEvent>
@@ -411,11 +422,13 @@ powershell -ExecutionPolicy Unrestricted -File "$(ProjectDir)Resources\PostBuild
<PropertyGroup> <PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText> <ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup> </PropertyGroup>
<Error Condition="!Exists('packages\cef.redist.x64.3.3396.1777\build\cef.redist.x64.props')" Text="$([System.String]::Format('$(ErrorText)', 'packages\cef.redist.x64.3.3396.1777\build\cef.redist.x64.props'))" /> <Error Condition="!Exists('packages\cef.redist.x64.3.3396.1786\build\cef.redist.x64.props')" Text="$([System.String]::Format('$(ErrorText)', 'packages\cef.redist.x64.3.3396.1786\build\cef.redist.x64.props'))" />
<Error Condition="!Exists('packages\cef.redist.x86.3.3396.1777\build\cef.redist.x86.props')" Text="$([System.String]::Format('$(ErrorText)', 'packages\cef.redist.x86.3.3396.1777\build\cef.redist.x86.props'))" /> <Error Condition="!Exists('packages\cef.redist.x86.3.3396.1786\build\cef.redist.x86.props')" Text="$([System.String]::Format('$(ErrorText)', 'packages\cef.redist.x86.3.3396.1786\build\cef.redist.x86.props'))" />
<Error Condition="!Exists('packages\CefSharp.Common.67.0.0-CI2662\build\CefSharp.Common.props')" Text="$([System.String]::Format('$(ErrorText)', 'packages\CefSharp.Common.67.0.0-CI2662\build\CefSharp.Common.props'))" /> <Error Condition="!Exists('packages\CefSharp.Common.67.0.0-pre01\build\CefSharp.Common.props')" Text="$([System.String]::Format('$(ErrorText)', 'packages\CefSharp.Common.67.0.0-pre01\build\CefSharp.Common.props'))" />
<Error Condition="!Exists('packages\CefSharp.Common.67.0.0-CI2662\build\CefSharp.Common.targets')" Text="$([System.String]::Format('$(ErrorText)', 'packages\CefSharp.Common.67.0.0-CI2662\build\CefSharp.Common.targets'))" /> <Error Condition="!Exists('packages\CefSharp.Common.67.0.0-pre01\build\CefSharp.Common.targets')" Text="$([System.String]::Format('$(ErrorText)', 'packages\CefSharp.Common.67.0.0-pre01\build\CefSharp.Common.targets'))" />
<Error Condition="!Exists('packages\CefSharp.WinForms.67.0.0-CI2662\build\CefSharp.WinForms.props')" Text="$([System.String]::Format('$(ErrorText)', 'packages\CefSharp.WinForms.67.0.0-CI2662\build\CefSharp.WinForms.props'))" /> <Error Condition="!Exists('packages\CefSharp.WinForms.67.0.0-pre01\build\CefSharp.WinForms.props')" Text="$([System.String]::Format('$(ErrorText)', 'packages\CefSharp.WinForms.67.0.0-pre01\build\CefSharp.WinForms.props'))" />
<Error Condition="!Exists('packages\CefSharp.WinForms.67.0.0-pre01\build\CefSharp.WinForms.targets')" Text="$([System.String]::Format('$(ErrorText)', 'packages\CefSharp.WinForms.67.0.0-pre01\build\CefSharp.WinForms.targets'))" />
</Target> </Target>
<Import Project="packages\CefSharp.Common.67.0.0-CI2662\build\CefSharp.Common.targets" Condition="Exists('packages\CefSharp.Common.67.0.0-CI2662\build\CefSharp.Common.targets')" /> <Import Project="packages\CefSharp.Common.67.0.0-pre01\build\CefSharp.Common.targets" Condition="Exists('packages\CefSharp.Common.67.0.0-pre01\build\CefSharp.Common.targets')" />
<Import Project="packages\CefSharp.WinForms.67.0.0-pre01\build\CefSharp.WinForms.targets" Condition="Exists('packages\CefSharp.WinForms.67.0.0-pre01\build\CefSharp.WinForms.targets')" />
</Project> </Project>

View File

@@ -39,7 +39,7 @@ namespace TweetDuck.Updates{
timer.Stop(); timer.Stop();
if (Program.UserConfig.EnableUpdateCheck){ if (Program.Config.User.EnableUpdateCheck){
DateTime now = DateTime.Now; DateTime now = DateTime.Now;
TimeSpan nextHour = now.AddSeconds(60*(60-now.Minute)-now.Second)-now; TimeSpan nextHour = now.AddSeconds(60*(60-now.Minute)-now.Second)-now;
@@ -53,7 +53,7 @@ namespace TweetDuck.Updates{
} }
public int Check(bool force){ public int Check(bool force){
if (Program.UserConfig.EnableUpdateCheck || force){ if (Program.Config.User.EnableUpdateCheck || force){
int nextEventId = unchecked(++lastEventId); int nextEventId = unchecked(++lastEventId);
Task<UpdateInfo> checkTask = client.Check(); Task<UpdateInfo> checkTask = client.Check();

16
bld/POST BUILD.bat Normal file
View File

@@ -0,0 +1,16 @@
@ECHO OFF
DEL "post_build.exe"
SET fsc="%PROGRAMFILES(x86)%\Microsoft SDKs\F#\10.1\Framework\v4.0\fsc.exe"
IF NOT EXIST %fsc% (
SET fsc="%PROGRAMFILES%\Microsoft SDKs\F#\10.1\Framework\v4.0\fsc.exe"
)
IF NOT EXIST %fsc% (
ECHO fsc.exe not found
EXIT 1
)
%fsc% --standalone --deterministic --preferreduilang:en-US --platform:x86 --target:exe --out:post_build.exe "%~dp0..\Resources\PostBuild.fsx"

View File

@@ -1 +0,0 @@
start "" /B "ISCC.exe" /Q "gen_upd.iss"

View File

@@ -220,10 +220,19 @@ begin
end; end;
{ Return whether the version of the installed libcef.dll library matches internal one. } { Return whether the version of the installed libcef.dll library matches internal one. }
{ TODO: Remove workaround that forces full installation for 1.15 and older eventually. }
function TDIsMatchingCEFVersion: Boolean; function TDIsMatchingCEFVersion: Boolean;
var CEFVersion: String; var CEFVersion: String;
var TDVersionMS: Cardinal;
var TDVersionLS: Cardinal;
begin begin
if (GetVersionNumbers(UpdatePath+'TweetDuck.exe', TDVersionMS, TDVersionLS)) and ((TDVersionMS and $FFFF) < 16) then
begin
Result := False
Exit
end;
Result := (GetVersionNumbersString(UpdatePath+'libcef.dll', CEFVersion) and (CompareStr(CEFVersion, '{#CefVersion}') = 0)) Result := (GetVersionNumbersString(UpdatePath+'libcef.dll', CEFVersion) and (CompareStr(CEFVersion, '{#CefVersion}') = 0))
end; end;

View File

@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<packages> <packages>
<package id="cef.redist.x64" version="3.3396.1777" targetFramework="net452" /> <package id="cef.redist.x64" version="3.3396.1786" targetFramework="net452" />
<package id="cef.redist.x86" version="3.3396.1777" targetFramework="net452" /> <package id="cef.redist.x86" version="3.3396.1786" targetFramework="net452" />
<package id="CefSharp.Common" version="67.0.0-CI2662" targetFramework="net452" /> <package id="CefSharp.Common" version="67.0.0-pre01" targetFramework="net452" />
<package id="CefSharp.WinForms" version="67.0.0-CI2662" targetFramework="net452" /> <package id="CefSharp.WinForms" version="67.0.0-pre01" targetFramework="net452" />
</packages> </packages>

View File

@@ -28,7 +28,7 @@
<ItemGroup> <ItemGroup>
<Reference Include="CefSharp.BrowserSubprocess.Core, Version=67.0.0.0, Culture=neutral, PublicKeyToken=40c4b6fc221f4138, processorArchitecture=x86"> <Reference Include="CefSharp.BrowserSubprocess.Core, Version=67.0.0.0, Culture=neutral, PublicKeyToken=40c4b6fc221f4138, processorArchitecture=x86">
<SpecificVersion>False</SpecificVersion> <SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\CefSharp.Common.67.0.0-CI2662\CefSharp\x86\CefSharp.BrowserSubprocess.Core.dll</HintPath> <HintPath>..\packages\CefSharp.Common.67.0.0-pre01\CefSharp\x86\CefSharp.BrowserSubprocess.Core.dll</HintPath>
</Reference> </Reference>
<Reference Include="System" /> <Reference Include="System" />
</ItemGroup> </ItemGroup>