1
0
mirror of https://github.com/chylex/TweetDuck.git synced 2025-04-24 06:15:48 +02:00

Reformat (missing space after comma), minor code tweaks

This commit is contained in:
chylex 2016-09-02 13:34:41 +02:00
parent 45bdd95dc8
commit 31a475861b
46 changed files with 287 additions and 287 deletions

View File

@ -4,7 +4,7 @@
using System.Threading;
namespace TweetDck.Configuration{
class LockManager{
sealed class LockManager{
public Process LockingProcess { get; private set; }
private readonly string file;
@ -20,10 +20,10 @@ private bool CreateLockFile(){
}
try{
lockStream = new FileStream(file,FileMode.Create,FileAccess.Write,FileShare.Read);
lockStream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.Read);
byte[] id = BitConverter.GetBytes(Process.GetCurrentProcess().Id);
lockStream.Write(id,0,id.Length);
lockStream.Write(id, 0, id.Length);
lockStream.Flush();
if (LockingProcess != null){
@ -48,11 +48,11 @@ public bool Lock(){
try{
byte[] bytes = new byte[4];
using(FileStream fileStream = new FileStream(file,FileMode.Open,FileAccess.Read,FileShare.ReadWrite)){
fileStream.Read(bytes,0,4);
using(FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)){
fileStream.Read(bytes, 0, 4);
}
int pid = BitConverter.ToInt32(bytes,0);
int pid = BitConverter.ToInt32(bytes, 0);
try{
Process foundProcess = Process.GetProcessById(pid);

View File

@ -65,7 +65,7 @@ public bool MuteNotifications{
muteNotifications = value;
if (MuteToggled != null){
MuteToggled(this,new EventArgs());
MuteToggled(this, new EventArgs());
}
}
}
@ -81,7 +81,7 @@ public TrayIcon.Behavior TrayBehavior{
trayBehavior = value;
if (TrayBehaviorChanged != null){
TrayBehaviorChanged(this,new EventArgs());
TrayBehaviorChanged(this, new EventArgs());
}
}
}
@ -108,7 +108,7 @@ private UserConfig(string file){
DisplayNotificationTimer = true;
NotificationDuration = TweetNotification.Duration.Medium;
NotificationPosition = TweetNotification.Position.TopRight;
CustomNotificationPosition = new Point(-32000,-32000);
CustomNotificationPosition = new Point(-32000, -32000);
NotificationEdgeDistance = 8;
NotificationDurationValue = 25;
EnableUpdateCheck = true;
@ -170,16 +170,16 @@ public bool Save(){
if (File.Exists(file)){
string backupFile = GetBackupFile(file);
File.Delete(backupFile);
File.Move(file,backupFile);
File.Move(file, backupFile);
}
using(Stream stream = new FileStream(file,FileMode.Create,FileAccess.Write,FileShare.None)){
Formatter.Serialize(stream,this);
using(Stream stream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None)){
Formatter.Serialize(stream, this);
}
return true;
}catch(Exception e){
Program.HandleException("Could not save the configuration file.",e);
Program.HandleException("Could not save the configuration file.", e);
return false;
}
}
@ -189,7 +189,7 @@ public static UserConfig Load(string file){
for(int attempt = 0; attempt < 2; attempt++){
try{
using(Stream stream = new FileStream(attempt == 0 ? file : GetBackupFile(file),FileMode.Open,FileAccess.Read,FileShare.Read)){
using(Stream stream = new FileStream(attempt == 0 ? file : GetBackupFile(file), FileMode.Open, FileAccess.Read, FileShare.Read)){
if ((config = Formatter.Deserialize(stream) as UserConfig) != null){
config.file = file;
}
@ -202,7 +202,7 @@ public static UserConfig Load(string file){
break;
}catch(FileNotFoundException){
}catch(Exception e){
Program.HandleException("Could not open the configuration file.",e);
Program.HandleException("Could not open the configuration file.", e);
}
}
@ -216,13 +216,13 @@ public static string GetBackupFile(string file){
private class SerializationCompatibilityHandler : SerializationBinder{
public override Type BindToType(string assemblyName, string typeName){
#if DUCK
assemblyName = assemblyName.Replace("TweetDick","TweetDuck");
assemblyName = assemblyName.Replace("TweetDick", "TweetDuck");
#else
assemblyName = assemblyName.Replace("TweetDuck","TweetDick");
assemblyName = assemblyName.Replace("TweetDuck", "TweetDick");
#endif
typeName = typeName.Replace("TweetDick","TweetDck");
return Type.GetType(string.Format(CultureInfo.CurrentCulture,"{0}, {1}",typeName,assemblyName));
typeName = typeName.Replace("TweetDick", "TweetDck");
return Type.GetType(string.Format(CultureInfo.CurrentCulture, "{0}, {1}", typeName, assemblyName));
}
}
}

View File

@ -14,7 +14,7 @@ public static void InvokeSafe(this Control control, Action func){
}
public static void MoveToCenter(this Form targetForm, Form parentForm){
targetForm.Location = new Point(parentForm.Location.X+parentForm.Width/2-targetForm.Width/2,parentForm.Location.Y+parentForm.Height/2-targetForm.Height/2);
targetForm.Location = new Point(parentForm.Location.X+parentForm.Width/2-targetForm.Width/2, parentForm.Location.Y+parentForm.Height/2-targetForm.Height/2);
}
public static void SetValueInstant(this ProgressBar bar, int value){

View File

@ -2,18 +2,18 @@
using System.Windows.Forms;
namespace TweetDck.Core.Controls{
public partial class FlatProgressBar : ProgressBar{
sealed partial class FlatProgressBar : ProgressBar{
private readonly SolidBrush brush;
public FlatProgressBar(){
brush = new SolidBrush(Color.White);
SetStyle(ControlStyles.UserPaint,true);
SetStyle(ControlStyles.OptimizedDoubleBuffer,true);
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
}
public void SetValueInstant(int value){
ControlExtensions.SetValueInstant(this,value);
ControlExtensions.SetValueInstant(this, value);
}
protected override void OnPaint(PaintEventArgs e){

View File

@ -14,9 +14,9 @@ public void SetupButton(int locationX, int sizeWidth, string title, Action callb
FlatAppearance.MouseDownBackColor = Color.White;
FlatAppearance.MouseOverBackColor = Color.White;
FlatStyle = FlatStyle.Flat;
Location = new Point(locationX,0);
Location = new Point(locationX, 0);
Margin = new Padding(0);
Size = new Size(sizeWidth,30);
Size = new Size(sizeWidth, 30);
Text = title;
UseVisualStyleBackColor = true;
ResumeLayout(true);

View File

@ -33,7 +33,7 @@ public void SetupTabPanel(int buttonWidth){
public TabButton AddButton(string title, Action callback){
TabButton button = new TabButton();
button.SetupButton((btnWidth-1)*panelButtons.Controls.Count,btnWidth,title,callback);
button.SetupButton((btnWidth-1)*panelButtons.Controls.Count, btnWidth, title, callback);
button.Click += (sender, args) => SelectTab((TabButton)sender);
panelButtons.Controls.Add(button);

View File

@ -54,8 +54,8 @@ public FormBrowser(PluginManager pluginManager){
this.browser.LoadingStateChanged += Browser_LoadingStateChanged;
this.browser.FrameLoadEnd += Browser_FrameLoadEnd;
this.browser.RegisterJsObject("$TD",new TweetDeckBridge(this,notification));
this.browser.RegisterAsyncJsObject("$TDP",plugins.Bridge);
this.browser.RegisterJsObject("$TD", new TweetDeckBridge(this, notification));
this.browser.RegisterAsyncJsObject("$TDP", plugins.Bridge);
Controls.Add(browser);
@ -67,7 +67,7 @@ public FormBrowser(PluginManager pluginManager){
UpdateTrayIcon();
this.updates = new UpdateHandler(browser,this);
this.updates = new UpdateHandler(browser, this);
this.updates.UpdateAccepted += updates_UpdateAccepted;
}
@ -82,13 +82,13 @@ private void ForceClose(){
}
public FormNotification CreateNotificationForm(bool autoHide){
return new FormNotification(this,plugins,autoHide);
return new FormNotification(this, plugins, autoHide);
}
// window setup
private void SetupWindow(){
Config.BrowserWindow.Restore(this,true);
Config.BrowserWindow.Restore(this, true);
prevState = WindowState;
isLoaded = true;
}
@ -108,11 +108,11 @@ private void Browser_LoadingStateChanged(object sender, LoadingStateChangedEvent
private void Browser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e){
if (e.Frame.IsMain){
ScriptLoader.ExecuteFile(e.Frame,"code.js");
ScriptLoader.ExecuteFile(e.Frame, "code.js");
if (plugins.HasAnyPlugin(PluginEnvironment.Browser)){
ScriptLoader.ExecuteFile(e.Frame,PluginManager.PluginBrowserScriptFile);
plugins.ExecutePlugins(e.Frame,PluginEnvironment.Browser,true);
ScriptLoader.ExecuteFile(e.Frame, PluginManager.PluginBrowserScriptFile);
plugins.ExecutePlugins(e.Frame, PluginEnvironment.Browser, true);
}
}
}
@ -135,7 +135,7 @@ private void FormBrowser_Resize(object sender, EventArgs e){
}
}
else{
FormBrowser_ResizeEnd(sender,e);
FormBrowser_ResizeEnd(sender, e);
}
}
}
@ -185,7 +185,7 @@ private void plugins_Reloaded(object sender, PluginLoadEventArgs e){
}
private void plugins_PluginChangedState(object sender, PluginChangedStateEventArgs e){
browser.ExecuteScriptAsync("window.TDPF_setPluginState",e.Plugin,e.IsEnabled ? 1 : 0); // ExecuteScriptAsync cannot handle boolean values as of yet
browser.ExecuteScriptAsync("window.TDPF_setPluginState", e.Plugin, e.IsEnabled ? 1 : 0); // ExecuteScriptAsync cannot handle boolean values as of yet
}
private void updates_UpdateAccepted(object sender, UpdateAcceptedEventArgs e){
@ -209,12 +209,12 @@ private void updates_UpdateAccepted(object sender, UpdateAcceptedEventArgs e){
protected override void WndProc(ref Message m){
if (isLoaded && m.Msg == Program.WindowRestoreMessage){
trayIcon_ClickRestore(trayIcon,new EventArgs());
trayIcon_ClickRestore(trayIcon, new EventArgs());
return;
}
if (isLoaded && m.Msg == 0x210 && (m.WParam.ToInt32() & 0xFFFF) == 0x020B){ // WM_PARENTNOTIFY, WM_XBUTTONDOWN
browser.ExecuteScriptAsync("TDGF_onMouseClickExtra",(m.WParam.ToInt32() >> 16) & 0xFFFF);
browser.ExecuteScriptAsync("TDGF_onMouseClickExtra", (m.WParam.ToInt32() >> 16) & 0xFFFF);
return;
}
@ -230,7 +230,7 @@ public void OpenSettings(){
else{
bool prevEnableUpdateCheck = Config.EnableUpdateCheck;
currentFormSettings = new FormSettings(this,updates);
currentFormSettings = new FormSettings(this, updates);
currentFormSettings.FormClosed += (sender, args) => {
currentFormSettings = null;
@ -284,17 +284,17 @@ public void DisplayTooltip(string text){
}
else{
Point position = PointToClient(Cursor.Position);
position.Offset(20,10);
toolTip.Show(text,this,position);
position.Offset(20, 10);
toolTip.Show(text, this, position);
}
}
public void OnImagePasted(){
browser.ExecuteScriptAsync("TDGF_tryPasteImage",new object[0]);
browser.ExecuteScriptAsync("TDGF_tryPasteImage", new object[0]);
}
public void OnImagePastedFinish(){
browser.ExecuteScriptAsync("TDGF_tryPasteImageFinish",new object[0]);
browser.ExecuteScriptAsync("TDGF_tryPasteImageFinish", new object[0]);
}
public void ReloadBrowser(){

View File

@ -95,14 +95,14 @@ public FormNotification(FormBrowser owner, PluginManager pluginManager, bool aut
pluginJS = ScriptLoader.LoadResource(PluginManager.PluginNotificationScriptFile);
browser = new ChromiumWebBrowser("about:blank"){
MenuHandler = new ContextMenuNotification(this,autoHide),
MenuHandler = new ContextMenuNotification(this, autoHide),
LifeSpanHandler = new LifeSpanHandler()
};
browser.IsBrowserInitializedChanged += Browser_IsBrowserInitializedChanged;
browser.FrameLoadEnd += Browser_FrameLoadEnd;
browser.RegisterJsObject("$TD",new TweetDeckBridge(owner,this));
browser.RegisterAsyncJsObject("$TDP",plugins.Bridge);
browser.RegisterJsObject("$TD", new TweetDeckBridge(owner, this));
browser.RegisterAsyncJsObject("$TDP", plugins.Bridge);
panelBrowser.Controls.Add(browser);
@ -112,7 +112,7 @@ public FormNotification(FormBrowser owner, PluginManager pluginManager, bool aut
}
mouseHookDelegate = MouseHookProc;
mouseHook = NativeMethods.SetWindowsHookEx(NativeMethods.WH_MOUSE_LL,mouseHookDelegate,IntPtr.Zero,0);
mouseHook = NativeMethods.SetWindowsHookEx(NativeMethods.WH_MOUSE_LL, mouseHookDelegate, IntPtr.Zero, 0);
Disposed += FormNotification_Disposed;
}
@ -129,12 +129,12 @@ private IntPtr MouseHookProc(int nCode, IntPtr wParam, IntPtr lParam){
if (!ContainsFocus && wParam.ToInt32() == NativeMethods.WH_MOUSEWHEEL && browser.Bounds.Contains(PointToClient(Cursor.Position))){
// fuck it, Activate() doesn't work with this
Point prevPos = Cursor.Position;
Cursor.Position = PointToScreen(new Point(-1,-1));
Cursor.Position = PointToScreen(new Point(-1, -1));
NativeMethods.SimulateMouseClick(NativeMethods.MouseButton.Left);
Cursor.Position = prevPos;
}
return NativeMethods.CallNextHookEx(mouseHook,nCode,wParam,lParam);
return NativeMethods.CallNextHookEx(mouseHook, nCode, wParam, lParam);
}
// event handlers
@ -145,7 +145,7 @@ private void timerHideProgress_Tick(object sender, EventArgs e){
timeLeft -= timerProgress.Interval;
int value = (int)Math.Round(1025.0*(totalTime-timeLeft)/totalTime);
progressBarTimer.SetValueInstant(Math.Min(1000,Math.Max(0,Program.UserConfig.NotificationTimerCountDown ? 1000-value : value)));
progressBarTimer.SetValueInstant(Math.Min(1000, Math.Max(0, Program.UserConfig.NotificationTimerCountDown ? 1000-value : value)));
if (timeLeft <= 0){
FinishCurrentTweet();
@ -163,7 +163,7 @@ private void Config_MuteToggled(object sender, EventArgs e){
private void Browser_IsBrowserInitializedChanged(object sender, IsBrowserInitializedChangedEventArgs e){
if (e.IsBrowserInitialized && Initialized != null){
Initialized(this,new EventArgs());
Initialized(this, new EventArgs());
}
}
@ -174,15 +174,15 @@ private void Browser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e){
isInitialized = true;
if (Initialized != null){
Initialized(this,new EventArgs());
Initialized(this, new EventArgs());
}
}
else if (notificationJS != null && browser.Address != "about:blank"){
ScriptLoader.ExecuteScript(e.Frame,notificationJS,NotificationScriptIdentifier);
ScriptLoader.ExecuteScript(e.Frame, notificationJS, NotificationScriptIdentifier);
if (plugins.HasAnyPlugin(PluginEnvironment.Notification)){
ScriptLoader.ExecuteScript(e.Frame,pluginJS,PluginScriptIdentifier);
plugins.ExecutePlugins(e.Frame,PluginEnvironment.Notification,false);
ScriptLoader.ExecuteScript(e.Frame, pluginJS, PluginScriptIdentifier);
plugins.ExecutePlugins(e.Frame, PluginEnvironment.Notification, false);
}
}
}
@ -231,10 +231,10 @@ public void ShowNotificationForSettings(bool reset){
public void HideNotification(bool loadBlank){
if (loadBlank || Program.UserConfig.NotificationLegacyLoad){
browser.LoadHtml("","about:blank");
browser.LoadHtml("", "about:blank");
}
Location = new Point(-32000,-32000);
Location = new Point(-32000, -32000);
progressBarTimer.Value = Program.UserConfig.NotificationTimerCountDown ? 1000 : 0;
timerProgress.Stop();
}
@ -268,7 +268,7 @@ private void LoadTweet(TweetNotification tweet){
totalTime = timeLeft = tweet.GetDisplayDuration(Program.UserConfig.NotificationDurationValue);
progressBarTimer.Value = Program.UserConfig.NotificationTimerCountDown ? 1000 : 0;
browser.LoadHtml(tweet.GenerateHtml(),"http://tweetdeck.twitter.com/?"+DateTime.Now.Ticks);
browser.LoadHtml(tweet.GenerateHtml(), "http://tweetdeck.twitter.com/?"+DateTime.Now.Ticks);
if (Program.UserConfig.NotificationLegacyLoad){
OnNotificationReady();
@ -282,11 +282,11 @@ private void MoveToVisibleLocation(){
RequiresResize = false;
if (config.DisplayNotificationTimer){
ClientSize = new Size(BaseClientWidth,BaseClientHeight+4);
ClientSize = new Size(BaseClientWidth, BaseClientHeight+4);
progressBarTimer.Visible = true;
}
else{
ClientSize = new Size(BaseClientWidth,BaseClientHeight);
ClientSize = new Size(BaseClientWidth, BaseClientHeight);
progressBarTimer.Visible = false;
}
@ -304,24 +304,24 @@ private void MoveToVisibleLocation(){
switch(config.NotificationPosition){
case TweetNotification.Position.TopLeft:
Location = new Point(screen.WorkingArea.X+edgeDist,screen.WorkingArea.Y+edgeDist);
Location = new Point(screen.WorkingArea.X+edgeDist, screen.WorkingArea.Y+edgeDist);
break;
case TweetNotification.Position.TopRight:
Location = new Point(screen.WorkingArea.X+screen.WorkingArea.Width-edgeDist-Width,screen.WorkingArea.Y+edgeDist);
Location = new Point(screen.WorkingArea.X+screen.WorkingArea.Width-edgeDist-Width, screen.WorkingArea.Y+edgeDist);
break;
case TweetNotification.Position.BottomLeft:
Location = new Point(screen.WorkingArea.X+edgeDist,screen.WorkingArea.Y+screen.WorkingArea.Height-edgeDist-Height);
Location = new Point(screen.WorkingArea.X+edgeDist, screen.WorkingArea.Y+screen.WorkingArea.Height-edgeDist-Height);
break;
case TweetNotification.Position.BottomRight:
Location = new Point(screen.WorkingArea.X+screen.WorkingArea.Width-edgeDist-Width,screen.WorkingArea.Y+screen.WorkingArea.Height-edgeDist-Height);
Location = new Point(screen.WorkingArea.X+screen.WorkingArea.Width-edgeDist-Width, screen.WorkingArea.Y+screen.WorkingArea.Height-edgeDist-Height);
break;
case TweetNotification.Position.Custom:
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();
}
@ -330,7 +330,7 @@ private void MoveToVisibleLocation(){
}
if (needsReactivating){
NativeMethods.SetFormPos(this,NativeMethods.HWND_TOPMOST,NativeMethods.SWP_NOACTIVATE);
NativeMethods.SetFormPos(this, NativeMethods.HWND_TOPMOST, NativeMethods.SWP_NOACTIVATE);
}
}
@ -344,8 +344,8 @@ public void DisplayTooltip(string text){
}
else{
Point position = PointToClient(Cursor.Position);
position.Offset(20,5);
toolTip.Show(text,this,position);
position.Offset(20, 5);
toolTip.Show(text, this, position);
}
}
}

View File

@ -13,16 +13,16 @@ abstract class ContextMenuBase : IContextMenuHandler{
private const int MenuCopyImageUrl = 26504;
public virtual void OnBeforeContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model){
if (parameters.TypeFlags.HasFlag(ContextMenuType.Link) && !parameters.UnfilteredLinkUrl.EndsWith("tweetdeck.twitter.com/#",StringComparison.Ordinal)){
model.AddItem((CefMenuCommand)MenuOpenUrlInBrowser,"Open in browser");
model.AddItem((CefMenuCommand)MenuCopyUrl,"Copy link address");
if (parameters.TypeFlags.HasFlag(ContextMenuType.Link) && !parameters.UnfilteredLinkUrl.EndsWith("tweetdeck.twitter.com/#", StringComparison.Ordinal)){
model.AddItem((CefMenuCommand)MenuOpenUrlInBrowser, "Open in browser");
model.AddItem((CefMenuCommand)MenuCopyUrl, "Copy link address");
model.AddSeparator();
}
if (parameters.TypeFlags.HasFlag(ContextMenuType.Media) && parameters.HasImageContents){
model.AddItem((CefMenuCommand)MenuOpenImageInBrowser,"Open image in browser");
model.AddItem((CefMenuCommand)MenuSaveImage,"Save image as...");
model.AddItem((CefMenuCommand)MenuCopyImageUrl,"Copy image URL");
model.AddItem((CefMenuCommand)MenuOpenImageInBrowser, "Open image in browser");
model.AddItem((CefMenuCommand)MenuSaveImage, "Save image as...");
model.AddItem((CefMenuCommand)MenuCopyImageUrl, "Copy image URL");
model.AddSeparator();
}
}
@ -34,7 +34,7 @@ public virtual bool OnContextMenuCommand(IWebBrowser browserControl, IBrowser br
break;
case MenuCopyUrl:
Clipboard.SetText(string.IsNullOrEmpty(TweetDeckBridge.LastRightClickedLink) ? parameters.UnfilteredLinkUrl : TweetDeckBridge.LastRightClickedLink,TextDataFormat.UnicodeText);
Clipboard.SetText(string.IsNullOrEmpty(TweetDeckBridge.LastRightClickedLink) ? parameters.UnfilteredLinkUrl : TweetDeckBridge.LastRightClickedLink, TextDataFormat.UnicodeText);
break;
case MenuOpenImageInBrowser:
@ -57,15 +57,15 @@ public virtual bool OnContextMenuCommand(IWebBrowser browserControl, IBrowser br
}
if (saveTarget != null){
BrowserUtils.DownloadFileAsync(parameters.SourceUrl,saveTarget,ex => {
MessageBox.Show("An error occurred while downloading the image: "+ex.Message,Program.BrandName+" Has Failed :(",MessageBoxButtons.OK,MessageBoxIcon.Error);
BrowserUtils.DownloadFileAsync(parameters.SourceUrl, saveTarget, ex => {
MessageBox.Show("An error occurred while downloading the image: "+ex.Message, Program.BrandName+" Has Failed :(", MessageBoxButtons.OK, MessageBoxIcon.Error);
});
}
break;
case MenuCopyImageUrl:
Clipboard.SetText(parameters.SourceUrl,TextDataFormat.UnicodeText);
Clipboard.SetText(parameters.SourceUrl, TextDataFormat.UnicodeText);
break;
}
@ -89,10 +89,10 @@ private static string GetImageFileName(string url){
int dot = url.LastIndexOf('.');
if (dot != -1){
int colon = url.IndexOf(':',dot);
int colon = url.IndexOf(':', dot);
if (colon != -1){
url = url.Substring(0,colon);
url = url.Substring(0, colon);
}
}

View File

@ -25,34 +25,34 @@ public override void OnBeforeContextMenu(IWebBrowser browserControl, IBrowser br
RemoveSeparatorIfLast(model);
if (!string.IsNullOrEmpty(TweetDeckBridge.LastHighlightedTweet)){
model.AddItem((CefMenuCommand)MenuCopyTweetUrl,"Copy tweet address");
model.AddItem((CefMenuCommand)MenuCopyTweetUrl, "Copy tweet address");
if (!string.IsNullOrEmpty(TweetDeckBridge.LastHighlightedTweetEmbedded)){
model.AddItem((CefMenuCommand)MenuCopyTweetEmbeddedUrl,"Copy quoted tweet address");
model.AddItem((CefMenuCommand)MenuCopyTweetEmbeddedUrl, "Copy quoted tweet address");
}
model.AddSeparator();
}
base.OnBeforeContextMenu(browserControl,browser,frame,parameters,model);
base.OnBeforeContextMenu(browserControl, browser, frame, parameters, model);
if (model.Count > 0){
RemoveSeparatorIfLast(model);
model.AddSeparator();
}
model.AddItem(CefMenuCommand.Reload,"Reload");
model.AddCheckItem((CefMenuCommand)MenuMute,"Mute notifications");
model.SetChecked((CefMenuCommand)MenuMute,Program.UserConfig.MuteNotifications);
model.AddItem(CefMenuCommand.Reload, "Reload");
model.AddCheckItem((CefMenuCommand)MenuMute, "Mute notifications");
model.SetChecked((CefMenuCommand)MenuMute, Program.UserConfig.MuteNotifications);
model.AddSeparator();
model.AddItem((CefMenuCommand)MenuSettings,"Settings");
model.AddItem((CefMenuCommand)MenuPlugins,"Plugins");
model.AddItem((CefMenuCommand)MenuAbout,"About "+Program.BrandName);
model.AddItem((CefMenuCommand)MenuSettings, "Settings");
model.AddItem((CefMenuCommand)MenuPlugins, "Plugins");
model.AddItem((CefMenuCommand)MenuAbout, "About "+Program.BrandName);
}
public override bool OnContextMenuCommand(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, CefMenuCommand commandId, CefEventFlags eventFlags){
if (base.OnContextMenuCommand(browserControl,browser,frame,parameters,commandId,eventFlags)){
if (base.OnContextMenuCommand(browserControl, browser, frame, parameters, commandId, eventFlags)){
return true;
}
@ -82,11 +82,11 @@ public override bool OnContextMenuCommand(IWebBrowser browserControl, IBrowser b
return true;
case MenuCopyTweetUrl:
Clipboard.SetText(TweetDeckBridge.LastHighlightedTweet,TextDataFormat.UnicodeText);
Clipboard.SetText(TweetDeckBridge.LastHighlightedTweet, TextDataFormat.UnicodeText);
return true;
case MenuCopyTweetEmbeddedUrl:
Clipboard.SetText(TweetDeckBridge.LastHighlightedTweetEmbedded,TextDataFormat.UnicodeText);
Clipboard.SetText(TweetDeckBridge.LastHighlightedTweetEmbedded, TextDataFormat.UnicodeText);
return true;
}

View File

@ -21,30 +21,30 @@ public override void OnBeforeContextMenu(IWebBrowser browserControl, IBrowser br
model.Clear();
if (enableCustomMenu){
model.AddItem((CefMenuCommand)MenuSkipTweet,"Skip tweet");
model.AddCheckItem((CefMenuCommand)MenuFreeze,"Freeze");
model.SetChecked((CefMenuCommand)MenuFreeze,form.FreezeTimer);
model.AddItem((CefMenuCommand)MenuSkipTweet, "Skip tweet");
model.AddCheckItem((CefMenuCommand)MenuFreeze, "Freeze");
model.SetChecked((CefMenuCommand)MenuFreeze, form.FreezeTimer);
model.AddSeparator();
if (!string.IsNullOrEmpty(form.CurrentUrl)){
model.AddItem((CefMenuCommand)MenuCopyTweetUrl,"Copy tweet address");
model.AddItem((CefMenuCommand)MenuCopyTweetUrl, "Copy tweet address");
if (!string.IsNullOrEmpty(TweetDeckBridge.NotificationTweetEmbedded)){
model.AddItem((CefMenuCommand)MenuCopyTweetEmbeddedUrl,"Copy quoted tweet address");
model.AddItem((CefMenuCommand)MenuCopyTweetEmbeddedUrl, "Copy quoted tweet address");
}
model.AddSeparator();
}
}
base.OnBeforeContextMenu(browserControl,browser,frame,parameters,model);
base.OnBeforeContextMenu(browserControl, browser, frame, parameters, model);
RemoveSeparatorIfLast(model);
form.InvokeSafe(() => form.ContextMenuOpen = true);
}
public override bool OnContextMenuCommand(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, CefMenuCommand commandId, CefEventFlags eventFlags){
if (base.OnContextMenuCommand(browserControl,browser,frame,parameters,commandId,eventFlags)){
if (base.OnContextMenuCommand(browserControl, browser, frame, parameters, commandId, eventFlags)){
return true;
}
@ -58,11 +58,11 @@ public override bool OnContextMenuCommand(IWebBrowser browserControl, IBrowser b
return true;
case MenuCopyTweetUrl:
Clipboard.SetText(form.CurrentUrl,TextDataFormat.UnicodeText);
Clipboard.SetText(form.CurrentUrl, TextDataFormat.UnicodeText);
return true;
case MenuCopyTweetEmbeddedUrl:
Clipboard.SetText(TweetDeckBridge.NotificationTweetEmbedded,TextDataFormat.UnicodeText);
Clipboard.SetText(TweetDeckBridge.NotificationTweetEmbedded, TextDataFormat.UnicodeText);
return true;
}
@ -70,7 +70,7 @@ public override bool OnContextMenuCommand(IWebBrowser browserControl, IBrowser b
}
public override void OnContextMenuDismissed(IWebBrowser browserControl, IBrowser browser, IFrame frame){
base.OnContextMenuDismissed(browserControl,browser,frame);
base.OnContextMenuDismissed(browserControl, browser, frame);
form.InvokeSafe(() => form.ContextMenuOpen = false);
}
}

View File

@ -12,7 +12,7 @@ public DialogHandlerBrowser(FormBrowser form){
public bool OnFileDialog(IWebBrowser browserControl, IBrowser browser, CefFileDialogMode mode, string title, string defaultFilePath, List<string> acceptFilters, int selectedAcceptFilter, IFileDialogCallback callback){
if (!string.IsNullOrEmpty(TweetDeckBridge.ClipboardImagePath)){
callback.Continue(selectedAcceptFilter,new List<string>{ TweetDeckBridge.ClipboardImagePath });
callback.Continue(selectedAcceptFilter, new List<string>{ TweetDeckBridge.ClipboardImagePath });
form.InvokeSafe(() => {
TweetDeckBridge.ClipboardImagePath = string.Empty;

View File

@ -96,7 +96,7 @@ public void OpenPluginsMenu(){
public void OnTweetPopup(string tweetHtml, string tweetUrl, int tweetCharacters){
notification.InvokeSafe(() => {
form.OnTweetNotification();
notification.ShowNotification(new TweetNotification(tweetHtml,tweetUrl,tweetCharacters));
notification.ShowNotification(new TweetNotification(tweetHtml, tweetUrl, tweetCharacters));
});
}
@ -128,12 +128,12 @@ public void TryPasteImage(){
try{
Directory.CreateDirectory(Program.TemporaryPath);
ClipboardImagePath = Path.Combine(Program.TemporaryPath,"TD-Img-"+DateTime.Now.Ticks+".png");
img.Save(ClipboardImagePath,ImageFormat.Png);
ClipboardImagePath = Path.Combine(Program.TemporaryPath, "TD-Img-"+DateTime.Now.Ticks+".png");
img.Save(ClipboardImagePath, ImageFormat.Png);
form.OnImagePasted();
}catch(Exception e){
Program.HandleException("Could not paste image from clipboard.",e);
Program.HandleException("Could not paste image from clipboard.", e);
}
}
});
@ -143,7 +143,7 @@ public void ClickUploadImage(int offsetX, int offsetY){
form.InvokeSafe(() => {
Point prevPos = Cursor.Position;
Cursor.Position = form.PointToScreen(new Point(offsetX,offsetY));
Cursor.Position = form.PointToScreen(new Point(offsetX, offsetY));
NativeMethods.SimulateMouseClick(NativeMethods.MouseButton.Left);
Cursor.Position = prevPos;

View File

@ -50,7 +50,7 @@ public static TweetNotification ExampleTweet{
build.Append(@"<div class='tweet-body'><p class='js-tweet-text tweet-text with-linebreaks'>This is an example tweet, which lets you test the location and duration of popup notifications.</p></div>");
build.Append(@"</div></div></article>");
return new TweetNotification(build.ToString(),"",95);
return new TweetNotification(build.ToString(), "", 95);
}
}
@ -87,7 +87,7 @@ public TweetNotification(string html, string url, int characters){
}
public int GetDisplayDuration(int value){
return 2000+Math.Max(1000,value*characters);
return 2000+Math.Max(1000, value*characters);
}
public string GenerateHtml(){

View File

@ -13,9 +13,9 @@ public FormAbout(){
labelDescription.Text = Program.BrandName+" was created by chylex as a replacement to the discontinued official TweetDeck client for Windows.\n\nThe program is available for free under the open source MIT license.";
labelWebsite.Links.Add(new LinkLabel.Link(0,labelWebsite.Text.Length,Program.Website));
labelSourceCode.Links.Add(new LinkLabel.Link(0,labelSourceCode.Text.Length,GitHubLink));
labelIssues.Links.Add(new LinkLabel.Link(0,labelIssues.Text.Length,IssuesLink));
labelWebsite.Links.Add(new LinkLabel.Link(0, labelWebsite.Text.Length, Program.Website));
labelSourceCode.Links.Add(new LinkLabel.Link(0, labelSourceCode.Text.Length, GitHubLink));
labelIssues.Links.Add(new LinkLabel.Link(0, labelIssues.Text.Length, IssuesLink));
}
private void OnLinkClicked(object sender, LinkLabelLinkClickedEventArgs e){

View File

@ -28,14 +28,14 @@ public FormPlugins(PluginManager pluginManager) : this(){
this.tabPanelPlugins.SetupTabPanel(90);
this.tabPanelPlugins.ReplaceContent(flowLayoutPlugins);
this.tabBtnOfficial = tabPanelPlugins.AddButton("",() => SelectGroup(PluginGroup.Official));
this.tabBtnCustom = tabPanelPlugins.AddButton("",() => SelectGroup(PluginGroup.Custom));
this.tabBtnOfficial = tabPanelPlugins.AddButton("", () => SelectGroup(PluginGroup.Official));
this.tabBtnCustom = tabPanelPlugins.AddButton("", () => SelectGroup(PluginGroup.Custom));
this.tabPanelPlugins.SelectTab(tabBtnOfficial);
this.pluginManager_Reloaded(pluginManager,null);
this.pluginManager_Reloaded(pluginManager, null);
Shown += (sender, args) => {
Program.UserConfig.PluginsWindow.Restore(this,false);
Program.UserConfig.PluginsWindow.Restore(this, false);
};
FormClosed += (sender, args) => {
@ -59,10 +59,10 @@ public void ReloadPluginTab(){
flowLayoutPlugins.Controls.Clear();
foreach(Plugin plugin in pluginManager.GetPluginsByGroup(selectedGroup.Value)){
flowLayoutPlugins.Controls.Add(new PluginControl(pluginManager,plugin));
flowLayoutPlugins.Controls.Add(new PluginControl(pluginManager, plugin));
}
flowLayoutPlugins_Resize(flowLayoutPlugins,new EventArgs());
flowLayoutPlugins_Resize(flowLayoutPlugins, new EventArgs());
flowLayoutPlugins.ResumeLayout(true);
}
@ -80,7 +80,7 @@ private void flowLayoutPlugins_Resize(object sender, EventArgs e){
}
private void btnOpenFolder_Click(object sender, EventArgs e){
using(Process.Start("explorer.exe","\""+pluginManager.PathCustomPlugins+"\"")){}
using(Process.Start("explorer.exe", "\""+pluginManager.PathCustomPlugins+"\"")){}
}
private void btnReload_Click(object sender, EventArgs e){

View File

@ -8,7 +8,7 @@
namespace TweetDck.Core.Other{
sealed partial class FormSettings : Form{
private readonly Dictionary<Type,BaseTabSettings> tabs = new Dictionary<Type,BaseTabSettings>(4);
private readonly Dictionary<Type, BaseTabSettings> tabs = new Dictionary<Type, BaseTabSettings>(4);
public FormSettings(FormBrowser browserForm, UpdateHandler updates){
InitializeComponent();
@ -16,10 +16,10 @@ public FormSettings(FormBrowser browserForm, UpdateHandler updates){
Text = Program.BrandName+" Settings";
this.tabPanel.SetupTabPanel(100);
this.tabPanel.AddButton("General",SelectTab<TabSettingsGeneral>);
this.tabPanel.AddButton("Notifications",() => SelectTab(() => new TabSettingsNotifications(browserForm.CreateNotificationForm(false))));
this.tabPanel.AddButton("Updates",() => SelectTab(() => new TabSettingsUpdates(updates)));
this.tabPanel.AddButton("Advanced",() => SelectTab(() => new TabSettingsAdvanced(browserForm.ReloadBrowser)));
this.tabPanel.AddButton("General", SelectTab<TabSettingsGeneral>);
this.tabPanel.AddButton("Notifications", () => SelectTab(() => new TabSettingsNotifications(browserForm.CreateNotificationForm(false))));
this.tabPanel.AddButton("Updates", () => SelectTab(() => new TabSettingsUpdates(updates)));
this.tabPanel.AddButton("Advanced", () => SelectTab(() => new TabSettingsAdvanced(browserForm.ReloadBrowser)));
this.tabPanel.SelectTab(tabPanel.Buttons.First());
}
@ -30,7 +30,7 @@ public FormSettings(FormBrowser browserForm, UpdateHandler updates){
private void SelectTab<T>(Func<T> constructor) where T : BaseTabSettings{
BaseTabSettings control;
if (tabs.TryGetValue(typeof(T),out control)){
if (tabs.TryGetValue(typeof(T), out control)){
tabPanel.ReplaceContent(control);
}
else{

View File

@ -12,7 +12,7 @@ protected static UserConfig Config{
public bool Ready { get; set; }
public BaseTabSettings(){
Padding = new Padding(6,6,6,6);
Padding = new Padding(6);
}
}
}

View File

@ -17,7 +17,7 @@ public DialogSettingsCefArgs(){
Text = Program.BrandName+" Settings - CEF Arguments";
textBoxArgs.Text = Program.UserConfig.CustomCefArgs ?? "";
textBoxArgs.Select(textBoxArgs.Text.Length,0);
textBoxArgs.Select(textBoxArgs.Text.Length, 0);
}
private void btnHelp_Click(object sender, EventArgs e){
@ -33,10 +33,10 @@ private void btnApply_Click(object sender, EventArgs e){
return;
}
int count = CommandLineArgsParser.AddToDictionary(CefArgs,new Dictionary<string,string>());
int count = CommandLineArgsParser.AddToDictionary(CefArgs, new Dictionary<string, string>());
string prompt = count == 0 && !string.IsNullOrWhiteSpace(prevArgs) ? "All arguments will be removed from the settings. Continue?" : count+(count == 1 ? " argument" : " arguments")+" will be added to the settings. Continue?";
if (MessageBox.Show(prompt,"Confirm CEF Arguments",MessageBoxButtons.OKCancel,MessageBoxIcon.Question,MessageBoxDefaultButton.Button2) == DialogResult.OK){
if (MessageBox.Show(prompt, "Confirm CEF Arguments", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK){
DialogResult = DialogResult.OK;
Close();
}

View File

@ -13,14 +13,14 @@ public CombinedFileStream(Stream stream){
public void WriteFile(string identifier, string path){
byte[] contents;
using(FileStream fileStream = new FileStream(path,FileMode.Open,FileAccess.Read,FileShare.ReadWrite)){
using(FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)){
int index = 0;
int left = (int)fileStream.Length;
contents = new byte[left];
while(left > 0){
int read = fileStream.Read(contents,index,left);
int read = fileStream.Read(contents, index, left);
index += read;
left -= read;
}
@ -30,9 +30,9 @@ public void WriteFile(string identifier, string path){
byte[] contentsLength = BitConverter.GetBytes(contents.Length);
stream.WriteByte((byte)name.Length);
stream.Write(name,0,name.Length);
stream.Write(contentsLength,0,4);
stream.Write(contents,0,contents.Length);
stream.Write(name, 0, name.Length);
stream.Write(contentsLength, 0, 4);
stream.Write(contents, 0, contents.Length);
}
public Entry ReadFile(){
@ -43,15 +43,15 @@ public Entry ReadFile(){
}
byte[] name = new byte[nameLength];
stream.Read(name,0,nameLength);
stream.Read(name, 0, nameLength);
byte[] contentLength = new byte[4];
stream.Read(contentLength,0,4);
stream.Read(contentLength, 0, 4);
byte[] contents = new byte[BitConverter.ToInt32(contentLength,0)];
stream.Read(contents,0,contents.Length);
byte[] contents = new byte[BitConverter.ToInt32(contentLength, 0)];
stream.Read(contents, 0, contents.Length);
return new Entry(Encoding.UTF8.GetString(name),contents);
return new Entry(Encoding.UTF8.GetString(name), contents);
}
public void Flush(){
@ -73,7 +73,7 @@ public Entry(string identifier, byte[] contents){
}
public void WriteToFile(string path){
File.WriteAllBytes(path,contents);
File.WriteAllBytes(path, contents);
}
}
}

View File

@ -5,8 +5,8 @@
namespace TweetDck.Core.Other.Settings.Export{
sealed class ExportManager{
public static readonly string CookiesPath = Path.Combine(Program.StoragePath,"Cookies");
public static readonly string TempCookiesPath = Path.Combine(Program.StoragePath,"CookiesTmp");
public static readonly string CookiesPath = Path.Combine(Program.StoragePath, "Cookies");
public static readonly string TempCookiesPath = Path.Combine(Program.StoragePath, "CookiesTmp");
public Exception LastException { get; private set; }
@ -18,11 +18,11 @@ public ExportManager(string file){
public bool Export(bool includeSession){
try{
using(CombinedFileStream stream = new CombinedFileStream(new FileStream(file,FileMode.Create,FileAccess.Write,FileShare.None))){
stream.WriteFile("config",Program.ConfigFilePath);
using(CombinedFileStream stream = new CombinedFileStream(new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None))){
stream.WriteFile("config", Program.ConfigFilePath);
if (includeSession){
stream.WriteFile("cookies",CookiesPath);
stream.WriteFile("cookies", CookiesPath);
}
stream.Flush();
@ -37,7 +37,7 @@ public bool Export(bool includeSession){
public bool Import(){
try{
using(CombinedFileStream stream = new CombinedFileStream(new FileStream(file,FileMode.Open,FileAccess.Read,FileShare.None))){
using(CombinedFileStream stream = new CombinedFileStream(new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.None))){
CombinedFileStream.Entry entry;
while((entry = stream.ReadFile()) != null){
@ -48,11 +48,11 @@ public bool Import(){
break;
case "cookies":
if (MessageBox.Show("Do you want to import the login session? This will restart "+Program.BrandName+".","Importing "+Program.BrandName+" Settings",MessageBoxButtons.YesNo,MessageBoxIcon.Question,MessageBoxDefaultButton.Button2) == DialogResult.Yes){
entry.WriteToFile(Path.Combine(Program.StoragePath,TempCookiesPath));
if (MessageBox.Show("Do you want to import the login session? This will restart "+Program.BrandName+".", "Importing "+Program.BrandName+" Settings", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes){
entry.WriteToFile(Path.Combine(Program.StoragePath, TempCookiesPath));
// okay to and restart, 'cookies' is always the last entry
Process.Start(Application.ExecutablePath,"-restart -importcookies");
Process.Start(Application.ExecutablePath, "-restart -importcookies");
Application.Exit();
}

View File

@ -33,7 +33,7 @@ private void btnClearCache_Click(object sender, EventArgs e){
btnClearCache.Enabled = false;
BrowserCache.SetClearOnExit();
MessageBox.Show("Cache will be automatically cleared when "+Program.BrandName+" exits.","Clear Cache",MessageBoxButtons.OK,MessageBoxIcon.Information);
MessageBox.Show("Cache will be automatically cleared when "+Program.BrandName+" exits.", "Clear Cache", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void checkHardwareAcceleration_CheckedChanged(object sender, EventArgs e){
@ -46,7 +46,7 @@ private void checkHardwareAcceleration_CheckedChanged(object sender, EventArgs e
succeeded = HardwareAcceleration.Enable();
}
else{
MessageBox.Show("Cannot enable hardware acceleration, the libraries libEGL.dll and libGLESv2.dll could not be restored.",Program.BrandName+" Settings",MessageBoxButtons.OK,MessageBoxIcon.Error);
MessageBox.Show("Cannot enable hardware acceleration, the libraries libEGL.dll and libGLESv2.dll could not be restored.", Program.BrandName+" Settings", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else{
@ -81,14 +81,14 @@ private void btnEditCSS_Click(object sender, EventArgs e){
Config.CustomBrowserCSS = form.BrowserCSS;
Config.CustomNotificationCSS = form.NotificationCSS;
if (hasChangedBrowser && MessageBox.Show("The browser CSS has changed, do you want to reload it?","Browser CSS Changed",MessageBoxButtons.YesNo,MessageBoxIcon.Question,MessageBoxDefaultButton.Button2) == DialogResult.Yes){
if (hasChangedBrowser && MessageBox.Show("The browser CSS has changed, do you want to reload it?", "Browser CSS Changed", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes){
browserReloadAction();
}
}
}
private void btnExport_Click(object sender, EventArgs e){
DialogResult resultSaveCredentials = MessageBox.Show("Do you want to include your login session? This will not save your password into the file, but it will allow anyone with the file to login into TweetDeck as you.","Export "+Program.BrandName+" Settings",MessageBoxButtons.YesNoCancel,MessageBoxIcon.Question,MessageBoxDefaultButton.Button3);
DialogResult resultSaveCredentials = MessageBox.Show("Do you want to include your login session? This will not save your password into the file, but it will allow anyone with the file to login into TweetDeck as you.", "Export "+Program.BrandName+" Settings", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button3);
if (resultSaveCredentials == DialogResult.Cancel)return;
bool saveCredentials = resultSaveCredentials == DialogResult.Yes;
@ -112,7 +112,7 @@ private void btnExport_Click(object sender, EventArgs e){
ExportManager manager = new ExportManager(file);
if (!manager.Export(saveCredentials)){
Program.HandleException("An exception happened while exporting "+Program.BrandName+" settings.",manager.LastException);
Program.HandleException("An exception happened while exporting "+Program.BrandName+" settings.", manager.LastException);
}
}
}
@ -136,21 +136,21 @@ private void btnImport_Click(object sender, EventArgs e){
((FormSettings)ParentForm).ReloadUI();
}
else{
Program.HandleException("An exception happened while importing "+Program.BrandName+" settings.",manager.LastException);
Program.HandleException("An exception happened while importing "+Program.BrandName+" settings.", manager.LastException);
}
}
}
private void btnReset_Click(object sender, EventArgs e){
if (MessageBox.Show("This will reset all of your settings, including disabled plugins. Do you want to proceed?","Reset "+Program.BrandName+" Settings",MessageBoxButtons.YesNo,MessageBoxIcon.Warning,MessageBoxDefaultButton.Button2) == DialogResult.Yes){
if (MessageBox.Show("This will reset all of your settings, including disabled plugins. Do you want to proceed?", "Reset "+Program.BrandName+" Settings", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.Yes){
Program.ResetConfig();
((FormSettings)ParentForm).ReloadUI();
}
}
private static void PromptRestart(){
if (MessageBox.Show("The application must restart for the setting to take place. Do you want to restart now?",Program.BrandName+" Settings",MessageBoxButtons.YesNo,MessageBoxIcon.Information) == DialogResult.Yes){
Process.Start(Application.ExecutablePath,"-restart");
if (MessageBox.Show("The application must restart for the setting to take place. Do you want to restart now?", Program.BrandName+" Settings", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes){
Process.Start(Application.ExecutablePath, "-restart");
Application.Exit();
}
}

View File

@ -10,7 +10,7 @@ public TabSettingsGeneral(){
comboBoxTrayType.Items.Add("Minimize to Tray");
comboBoxTrayType.Items.Add("Close to Tray");
comboBoxTrayType.Items.Add("Combined");
comboBoxTrayType.SelectedIndex = Math.Min(Math.Max((int)Config.TrayBehavior,0),comboBoxTrayType.Items.Count-1);
comboBoxTrayType.SelectedIndex = Math.Min(Math.Max((int)Config.TrayBehavior, 0), comboBoxTrayType.Items.Count-1);
checkExpandLinks.Checked = Program.UserConfig.ExpandLinksOnHover;
checkTrayHighlight.Checked = Program.UserConfig.EnableTrayHighlight;

View File

@ -43,7 +43,7 @@ public TabSettingsNotifications(FormNotification notification){
comboBoxDisplay.Items.Add(screen.DeviceName+" ("+screen.Bounds.Width+"x"+screen.Bounds.Height+")");
}
comboBoxDisplay.SelectedIndex = Math.Min(comboBoxDisplay.Items.Count-1,Config.NotificationDisplay);
comboBoxDisplay.SelectedIndex = Math.Min(comboBoxDisplay.Items.Count-1, Config.NotificationDisplay);
checkNotificationTimer.Checked = Config.DisplayNotificationTimer;
checkTimerCountDown.Enabled = checkNotificationTimer.Checked;

View File

@ -40,7 +40,7 @@ private void updates_CheckFinished(object sender, UpdateCheckEventArgs e){
btnCheckUpdates.Enabled = true;
if (!e.UpdateAvailable){
MessageBox.Show("Your version of "+Program.BrandName+" is up to date.","No Updates Available",MessageBoxButtons.OK,MessageBoxIcon.Information);
MessageBox.Show("Your version of "+Program.BrandName+" is up to date.", "No Updates Available", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}

View File

@ -45,7 +45,7 @@ public TrayIcon(){
private void trayIcon_MouseClick(object sender, MouseEventArgs e){
if (e.Button == MouseButtons.Left){
restoreToolStripMenuItem_Click(sender,e);
restoreToolStripMenuItem_Click(sender, e);
}
}
@ -60,7 +60,7 @@ private void contextMenuTray_Opened(object sender, EventArgs e){
private void restoreToolStripMenuItem_Click(object sender, EventArgs e){
if (ClickRestore != null){
ClickRestore(this,e);
ClickRestore(this, e);
}
}
@ -71,7 +71,7 @@ private void muteNotificationsToolStripMenuItem_CheckedChanged(object sender, Ev
private void closeToolStripMenuItem_Click(object sender, EventArgs e){
if (ClickClose != null){
ClickClose(this,e);
ClickClose(this, e);
}
}
}

View File

@ -8,13 +8,13 @@ namespace TweetDck.Core.Utils{
static class BrowserCache{
private static bool ClearOnExit { get; set; }
private static readonly string IndexFile = Path.Combine(Program.StoragePath,"index");
private static readonly string IndexFile = Path.Combine(Program.StoragePath, "index");
private static IEnumerable<string> CacheFiles{
get{
return Directory.EnumerateFiles(Program.StoragePath).Where(path => {
string file = Path.GetFileName(path);
return file != null && (file.StartsWith("data_",StringComparison.Ordinal) || file.StartsWith("f_",StringComparison.Ordinal));
return file != null && (file.StartsWith("data_", StringComparison.Ordinal) || file.StartsWith("f_", StringComparison.Ordinal));
}).Concat(new[]{ IndexFile });
}
}
@ -30,7 +30,7 @@ public static void CalculateCacheSize(Action<long> callbackBytes){
}).Sum();
});
task.ContinueWith(originalTask => callbackBytes(originalTask.Exception == null ? originalTask.Result : -1L),TaskContinuationOptions.ExecuteSynchronously);
task.ContinueWith(originalTask => callbackBytes(originalTask.Exception == null ? originalTask.Result : -1L), TaskContinuationOptions.ExecuteSynchronously);
task.Start();
}

View File

@ -45,7 +45,7 @@ public static void DownloadFileAsync(string url, string target, Action<Exception
}
};
client.DownloadFileAsync(new Uri(url),target);
client.DownloadFileAsync(new Uri(url), target);
}
}
}

View File

@ -7,11 +7,11 @@ static class CommandLineArgsParser{
private static Regex SplitRegex{
get{
return splitRegex ?? (splitRegex = new Regex(@"([^=\s]+(?:=(?:""[^""]*?""|[^ ]*))?)",RegexOptions.Compiled));
return splitRegex ?? (splitRegex = new Regex(@"([^=\s]+(?:=(?:""[^""]*?""|[^ ]*))?)", RegexOptions.Compiled));
}
}
public static int AddToDictionary(string args, IDictionary<string,string> dictionary){
public static int AddToDictionary(string args, IDictionary<string, string> dictionary){
if (string.IsNullOrWhiteSpace(args)){
return 0;
}
@ -29,7 +29,7 @@ public static int AddToDictionary(string args, IDictionary<string,string> dictio
value = "1";
}
else{
key = matchValue.Substring(0,indexEquals).TrimStart('-');
key = matchValue.Substring(0, indexEquals).TrimStart('-');
value = matchValue.Substring(indexEquals+1).Trim('"');
}

View File

@ -3,8 +3,8 @@
namespace TweetDck.Core.Utils{
static class HardwareAcceleration{
private static readonly string LibEGL = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"libEGL.dll");
private static readonly string LibGLES = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"libGLESv2.dll");
private static readonly string LibEGL = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "libEGL.dll");
private static readonly string LibGLES = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "libGLESv2.dll");
private static readonly string DisabledLibEGL = LibEGL+".bak";
private static readonly string DisabledLibGLES = LibGLES+".bak";
@ -25,8 +25,8 @@ public static bool Enable(){
if (IsEnabled)return false;
try{
File.Move(DisabledLibEGL,LibEGL);
File.Move(DisabledLibGLES,LibGLES);
File.Move(DisabledLibEGL, LibEGL);
File.Move(DisabledLibGLES, LibGLES);
return true;
}catch{
return false;
@ -49,8 +49,8 @@ public static bool Disable(){
}
try{
File.Move(LibEGL,DisabledLibEGL);
File.Move(LibGLES,DisabledLibGLES);
File.Move(LibEGL, DisabledLibEGL);
File.Move(LibGLES, DisabledLibGLES);
return true;
}catch{
return false;

View File

@ -54,7 +54,7 @@ public enum MouseButton{
public static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, IntPtr wParam, IntPtr lParam);
public static void SetFormPos(Form form, int hWndOrder, uint flags){
SetWindowPos(form.Handle.ToInt32(),hWndOrder,form.Left,form.Top,form.Width,form.Height,flags);
SetWindowPos(form.Handle.ToInt32(), hWndOrder, form.Left, form.Top, form.Width, form.Height, flags);
}
public static void SimulateMouseClick(MouseButton button){
@ -74,8 +74,8 @@ public static void SimulateMouseClick(MouseButton button){
default: return;
}
mouse_event(flagHold,Cursor.Position.X,Cursor.Position.Y,0,0);
mouse_event(flagRelease,Cursor.Position.X,Cursor.Position.Y,0,0);
mouse_event(flagHold, Cursor.Position.X, Cursor.Position.Y, 0, 0);
mouse_event(flagRelease, Cursor.Position.X, Cursor.Position.Y, 0, 0);
}
}
}

View File

@ -13,7 +13,7 @@ public FormMigrationQuestion(){
}
protected override void OnPaint(PaintEventArgs e){
e.Graphics.DrawIcon(SystemIcons.Question,10,10);
e.Graphics.DrawIcon(SystemIcons.Question, 10, 10);
base.OnPaint(e);
}

View File

@ -26,7 +26,7 @@ public void SetComment(string newComment){
public void SetPath(string newPath){
if (obj == null)return;
obj.Path = newPath;
obj.SetIconLocation(newPath,0);
obj.SetIconLocation(newPath, 0);
}
public void SetWorkingDirectory(string newWorkingDirectory){

View File

@ -5,12 +5,12 @@
namespace TweetDck.Migration.Helpers{
static class ProgramRegistrySearch{
public static string FindByDisplayName(string displayName){
Predicate<RegistryKey> predicate = key => displayName.Equals(key.GetValue("DisplayName") as string,StringComparison.OrdinalIgnoreCase);
Predicate<RegistryKey> predicate = key => displayName.Equals(key.GetValue("DisplayName") as string, StringComparison.OrdinalIgnoreCase);
string guid;
return FindMatchingSubKey(Registry.LocalMachine,@"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall",predicate,out guid) ||
FindMatchingSubKey(Registry.LocalMachine,@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",predicate,out guid) ||
FindMatchingSubKey(Registry.CurrentUser,@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",predicate,out guid)
return FindMatchingSubKey(Registry.LocalMachine, @"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall", predicate, out guid) ||
FindMatchingSubKey(Registry.LocalMachine, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", predicate, out guid) ||
FindMatchingSubKey(Registry.CurrentUser, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", predicate, out guid)
? guid : null;
}
@ -18,10 +18,10 @@ private static bool FindMatchingSubKey(RegistryKey keyHandle, string path, Predi
string outputId = null;
try{
RegistryKey parentKey = keyHandle.OpenSubKey(path,false);
RegistryKey parentKey = keyHandle.OpenSubKey(path, false);
if (parentKey == null)throw new InvalidOperationException();
foreach(RegistryKey subKey in parentKey.GetSubKeyNames().Select(subName => parentKey.OpenSubKey(subName,false)).Where(subKey => subKey != null)){
foreach(RegistryKey subKey in parentKey.GetSubKeyNames().Select(subName => parentKey.OpenSubKey(subName, false)).Where(subKey => subKey != null)){
if (predicate(subKey)){
outputId = subKey.Name.Substring(subKey.Name.LastIndexOf('\\')+1);
subKey.Close();

View File

@ -12,8 +12,8 @@
namespace TweetDck.Migration{
static class MigrationManager{
private static readonly string TweetDeckPathParent = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),"twitter");
private static readonly string TweetDeckPath = Path.Combine(TweetDeckPathParent,"TweetDeck");
private static readonly string TweetDeckPathParent = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "twitter");
private static readonly string TweetDeckPath = Path.Combine(TweetDeckPathParent, "TweetDeck");
public static void Run(){
if (!Program.UserConfig.IgnoreMigration && Directory.Exists(TweetDeckPath)){
@ -29,11 +29,11 @@ public static void Run(){
FormBackgroundWork formWait = new FormBackgroundWork();
formWait.ShowWorkDialog(() => {
if (!BeginMigration(decision,ex => formWait.Invoke(new Action(() => {
if (!BeginMigration(decision, ex => formWait.Invoke(new Action(() => {
formWait.Close();
if (ex != null){
Program.HandleException("An unexpected exception has occurred during the migration process.",ex);
Program.HandleException("An unexpected exception has occurred during the migration process.", ex);
return;
}
@ -55,8 +55,8 @@ public static void Run(){
else if (!Program.UserConfig.IgnoreUninstallCheck){
string guid = ProgramRegistrySearch.FindByDisplayName("TweetDeck");
if (guid != null && MessageBox.Show("TweetDeck is still installed on your computer, do you want to uninstall it?","Uninstall TweetDeck",MessageBoxButtons.YesNo,MessageBoxIcon.Question,MessageBoxDefaultButton.Button2) == DialogResult.Yes){
RunUninstaller(guid,0);
if (guid != null && MessageBox.Show("TweetDeck is still installed on your computer, do you want to uninstall it?", "Uninstall TweetDeck", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes){
RunUninstaller(guid, 0);
CleanupTweetDeck();
}
@ -72,8 +72,8 @@ private static bool BeginMigration(MigrationDecision decision, Action<Exception>
Task task = new Task(() => {
Directory.CreateDirectory(Program.StoragePath);
Directory.CreateDirectory(Path.Combine(Program.StoragePath,"localStorage"));
Directory.CreateDirectory(Path.Combine(Program.StoragePath,"Local Storage"));
Directory.CreateDirectory(Path.Combine(Program.StoragePath, "localStorage"));
Directory.CreateDirectory(Path.Combine(Program.StoragePath, "Local Storage"));
CopyFile("Cookies");
CopyFile("Cookies-journal");
@ -105,7 +105,7 @@ private static bool BeginMigration(MigrationDecision decision, Action<Exception>
// delete folders
for(int wait = 0; wait < 50; wait++){
try{
Directory.Delete(TweetDeckPath,true);
Directory.Delete(TweetDeckPath, true);
break;
}catch(Exception){
// browser subprocess not ended yet, wait
@ -114,7 +114,7 @@ private static bool BeginMigration(MigrationDecision decision, Action<Exception>
}
try{
Directory.Delete(TweetDeckPathParent,false);
Directory.Delete(TweetDeckPathParent, false);
}catch(IOException){
// most likely not empty, ignore
}
@ -125,7 +125,7 @@ private static bool BeginMigration(MigrationDecision decision, Action<Exception>
foreach(string location in GetLnkDirectories()){
if (string.IsNullOrEmpty(location))continue;
string linkFile = Path.Combine(location,"TweetDeck.lnk");
string linkFile = Path.Combine(location, "TweetDeck.lnk");
if (File.Exists(linkFile)){
LnkEditor lnk = new LnkEditor(linkFile);
@ -134,11 +134,11 @@ private static bool BeginMigration(MigrationDecision decision, Action<Exception>
lnk.SetComment(Program.BrandName+" client for Windows");
lnk.Save();
string renamed = Path.Combine(location,Program.BrandName+".lnk");
string renamed = Path.Combine(location, Program.BrandName+".lnk");
try{
if (!File.Exists(renamed)){
File.Move(linkFile,renamed);
File.Move(linkFile, renamed);
}
else{
File.Delete(linkFile);
@ -149,13 +149,13 @@ private static bool BeginMigration(MigrationDecision decision, Action<Exception>
}
}
NativeMethods.SHChangeNotify(0x8000000,0x1000,IntPtr.Zero,IntPtr.Zero); // refreshes desktop
NativeMethods.SHChangeNotify(0x8000000, 0x1000, IntPtr.Zero, IntPtr.Zero); // refreshes desktop
// uninstall in the background
string guid = ProgramRegistrySearch.FindByDisplayName("TweetDeck");
if (guid != null){
RunUninstaller(guid,5000);
RunUninstaller(guid, 5000);
}
// registry cleanup
@ -165,7 +165,7 @@ private static bool BeginMigration(MigrationDecision decision, Action<Exception>
}
});
task.ContinueWith(originalTask => onFinished(originalTask.Exception),TaskContinuationOptions.ExecuteSynchronously);
task.ContinueWith(originalTask => onFinished(originalTask.Exception), TaskContinuationOptions.ExecuteSynchronously);
task.Start();
return true;
@ -173,7 +173,7 @@ private static bool BeginMigration(MigrationDecision decision, Action<Exception>
private static void CopyFile(string relativePath){
try{
File.Copy(Path.Combine(TweetDeckPath,relativePath),Path.Combine(Program.StoragePath,relativePath),true);
File.Copy(Path.Combine(TweetDeckPath, relativePath), Path.Combine(Program.StoragePath, relativePath), true);
}catch(FileNotFoundException){
}catch(DirectoryNotFoundException){
}
@ -186,7 +186,7 @@ private static IEnumerable<string> GetLnkDirectories(){
}
private static void RunUninstaller(string guid, int timeout){
Process uninstaller = Process.Start("msiexec.exe","/x "+guid+" /quiet /qn");
Process uninstaller = Process.Start("msiexec.exe", "/x "+guid+" /quiet /qn");
if (uninstaller != null){
if (timeout > 0){
@ -199,7 +199,7 @@ private static void RunUninstaller(string guid, int timeout){
private static void CleanupTweetDeck(){
try{
Registry.CurrentUser.DeleteSubKeyTree(@"Software\Twitter\TweetDeck",true);
Registry.CurrentUser.DeleteSubKeyTree(@"Software\Twitter\TweetDeck", true);
Registry.CurrentUser.DeleteSubKey(@"Software\Twitter"); // only if empty
}catch(Exception){
// not found or too bad

View File

@ -31,7 +31,7 @@ public PluginControl(PluginManager pluginManager, Plugin plugin) : this(){
labelDescription.Visible = false;
}
panelDescription_Resize(panelDescription,new EventArgs());
panelDescription_Resize(panelDescription, new EventArgs());
}
private void panelDescription_Resize(object sender, EventArgs e){
@ -39,8 +39,8 @@ private void panelDescription_Resize(object sender, EventArgs e){
Height = MinimumSize.Height;
}
else{
labelDescription.MaximumSize = new Size(panelDescription.Width-SystemInformation.VerticalScrollBarWidth,0);
Height = Math.Min(MinimumSize.Height+9+labelDescription.Height,MaximumSize.Height);
labelDescription.MaximumSize = new Size(panelDescription.Width-SystemInformation.VerticalScrollBarWidth, 0);
Height = Math.Min(MinimumSize.Height+9+labelDescription.Height, MaximumSize.Height);
}
}
@ -52,7 +52,7 @@ private void labelWebsite_Click(object sender, EventArgs e){
private void btnToggleState_Click(object sender, EventArgs e){
bool newState = !pluginManager.Config.IsEnabled(plugin);
pluginManager.Config.SetEnabled(plugin,newState);
pluginManager.Config.SetEnabled(plugin, newState);
btnToggleState.Text = newState ? "Disable" : "Enable";
}

View File

@ -4,7 +4,7 @@
namespace TweetDck.Plugins.Controls{
sealed partial class PluginListFlowLayout : FlowLayoutPanel{
protected override void WndProc(ref Message m){
NativeMethods.ShowScrollBar(Handle,NativeMethods.SB_HORZ,false); // basically fuck the horizontal scrollbar very much
NativeMethods.ShowScrollBar(Handle, NativeMethods.SB_HORZ, false); // basically fuck the horizontal scrollbar very much
base.WndProc(ref m);
}
}

View File

@ -30,7 +30,7 @@ public string FolderPath{
private readonly string path;
private readonly string identifier;
private readonly Dictionary<string,string> metadata = new Dictionary<string,string>(4){
private readonly Dictionary<string, string> metadata = new Dictionary<string, string>(4){
{ "NAME", "" },
{ "DESCRIPTION", "" },
{ "AUTHOR", "(anonymous)" },
@ -51,7 +51,7 @@ private Plugin(string path, PluginGroup group){
public string GetScriptPath(PluginEnvironment environment){
if (Environments.HasFlag(environment)){
string file = environment.GetScriptFile();
return file != null ? Path.Combine(path,file) : string.Empty;
return file != null ? Path.Combine(path, file) : string.Empty;
}
else{
return string.Empty;
@ -72,13 +72,13 @@ public override bool Equals(object obj){
}
public static Plugin CreateFromFolder(string path, PluginGroup group, out string error){
Plugin plugin = new Plugin(path,group);
Plugin plugin = new Plugin(path, group);
if (!LoadMetadata(path,plugin,out error)){
if (!LoadMetadata(path, plugin, out error)){
return null;
}
if (!LoadEnvironments(path,plugin,out error)){
if (!LoadEnvironments(path, plugin, out error)){
return null;
}
@ -87,8 +87,8 @@ public static Plugin CreateFromFolder(string path, PluginGroup group, out string
}
private static bool LoadEnvironments(string path, Plugin plugin, out string error){
foreach(string file in Directory.EnumerateFiles(path,"*.js",SearchOption.TopDirectoryOnly).Select(Path.GetFileName)){
PluginEnvironment environment = PluginEnvironmentExtensions.Values.FirstOrDefault(env => file.Equals(env.GetScriptFile(),StringComparison.Ordinal));
foreach(string file in Directory.EnumerateFiles(path, "*.js", SearchOption.TopDirectoryOnly).Select(Path.GetFileName)){
PluginEnvironment environment = PluginEnvironmentExtensions.Values.FirstOrDefault(env => file.Equals(env.GetScriptFile(), StringComparison.Ordinal));
if (environment != PluginEnvironment.None){
plugin.Environments |= environment;
@ -111,14 +111,14 @@ private static bool LoadEnvironments(string path, Plugin plugin, out string erro
private static readonly string[] endTag = { "[END]" };
private static bool LoadMetadata(string path, Plugin plugin, out string error){
string metaFile = Path.Combine(path,".meta");
string metaFile = Path.Combine(path, ".meta");
if (!File.Exists(metaFile)){
error = "Missing .meta file.";
return false;
}
string[] lines = File.ReadAllLines(metaFile,Encoding.UTF8);
string[] lines = File.ReadAllLines(metaFile, Encoding.UTF8);
string currentTag = null, currentContents = "";
foreach(string line in lines.Concat(endTag).Select(line => line.TrimEnd()).Where(line => line.Length > 0)){
@ -127,7 +127,7 @@ private static bool LoadMetadata(string path, Plugin plugin, out string error){
plugin.metadata[currentTag] = currentContents;
}
currentTag = line.Substring(1,line.Length-2).ToUpperInvariant();
currentTag = line.Substring(1, line.Length-2).ToUpperInvariant();
currentContents = "";
if (line.Equals(endTag[0])){
@ -155,7 +155,7 @@ private static bool LoadMetadata(string path, Plugin plugin, out string error){
Version ver;
if (plugin.RequiredVersion.Length == 0 || !(plugin.RequiredVersion.Equals("*") || System.Version.TryParse(plugin.RequiredVersion,out ver))){
if (plugin.RequiredVersion.Length == 0 || !(plugin.RequiredVersion.Equals("*") || System.Version.TryParse(plugin.RequiredVersion, out ver))){
error = "Plugin contains invalid version: "+plugin.RequiredVersion;
return false;
}
@ -165,7 +165,7 @@ private static bool LoadMetadata(string path, Plugin plugin, out string error){
}
private static bool CheckRequiredVersion(string requires){
return requires.Equals("*",StringComparison.Ordinal) || Program.Version >= new Version(requires);
return requires.Equals("*", StringComparison.Ordinal) || Program.Version >= new Version(requires);
}
}
}

View File

@ -7,7 +7,7 @@
namespace TweetDck.Plugins{
class PluginBridge{
private readonly PluginManager manager;
private readonly Dictionary<string,string> fileCache = new Dictionary<string,string>(2);
private readonly Dictionary<string, string> fileCache = new Dictionary<string, string>(2);
public PluginBridge(PluginManager manager){
this.manager = manager;
@ -25,7 +25,7 @@ private string GetFullPathIfSafe(int token, string path){
return string.Empty;
}
string fullPath = Path.Combine(plugin.FolderPath,path);
string fullPath = Path.Combine(plugin.FolderPath, path);
try{
string folderPathName = new DirectoryInfo(plugin.FolderPath).FullName;
@ -47,7 +47,7 @@ private string GetFullPathIfSafe(int token, string path){
}
public void WriteFile(int token, string path, string contents){
string fullPath = GetFullPathIfSafe(token,path);
string fullPath = GetFullPathIfSafe(token, path);
if (fullPath == string.Empty){
throw new Exception("File path has to be relative to the plugin folder.");
@ -56,12 +56,12 @@ public void WriteFile(int token, string path, string contents){
// ReSharper disable once AssignNullToNotNullAttribute
Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
File.WriteAllText(fullPath,contents,Encoding.UTF8);
File.WriteAllText(fullPath, contents, Encoding.UTF8);
fileCache[fullPath] = contents;
}
public string ReadFile(int token, string path, bool cache){
string fullPath = GetFullPathIfSafe(token,path);
string fullPath = GetFullPathIfSafe(token, path);
if (fullPath == string.Empty){
throw new Exception("File path has to be relative to the plugin folder.");
@ -69,15 +69,15 @@ public string ReadFile(int token, string path, bool cache){
string cachedContents;
if (cache && fileCache.TryGetValue(fullPath,out cachedContents)){
if (cache && fileCache.TryGetValue(fullPath, out cachedContents)){
return cachedContents;
}
return fileCache[fullPath] = File.ReadAllText(fullPath,Encoding.UTF8);
return fileCache[fullPath] = File.ReadAllText(fullPath, Encoding.UTF8);
}
public void DeleteFile(int token, string path){
string fullPath = GetFullPathIfSafe(token,path);
string fullPath = GetFullPathIfSafe(token, path);
if (fullPath == string.Empty){
throw new Exception("File path has to be relative to the plugin folder.");

View File

@ -25,7 +25,7 @@ public bool AnyDisabled{
public void SetEnabled(Plugin plugin, bool enabled){
if ((enabled && Disabled.Remove(plugin.Identifier)) || (!enabled && Disabled.Add(plugin.Identifier))){
if (PluginChangedState != null){
PluginChangedState(this,new PluginChangedStateEventArgs(plugin,enabled));
PluginChangedState(this, new PluginChangedStateEventArgs(plugin, enabled));
}
}
}

View File

@ -11,8 +11,8 @@ class PluginManager{
public const string PluginBrowserScriptFile = "plugins.browser.js";
public const string PluginNotificationScriptFile = "plugins.notification.js";
public string PathOfficialPlugins { get { return Path.Combine(rootPath,"official"); } }
public string PathCustomPlugins { get { return Path.Combine(rootPath,"user"); } }
public string PathOfficialPlugins { get { return Path.Combine(rootPath, "official"); } }
public string PathCustomPlugins { get { return Path.Combine(rootPath, "user"); } }
public IEnumerable<Plugin> Plugins { get { return plugins; } }
public PluginConfig Config { get; private set; }
@ -22,7 +22,7 @@ class PluginManager{
private readonly string rootPath;
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 List<string> loadErrors;
@ -47,7 +47,7 @@ public bool HasAnyPlugin(PluginEnvironment environment){
public Plugin GetPluginFromToken(int token){
Plugin plugin;
return tokens.TryGetValue(token,out plugin) ? plugin : null;
return tokens.TryGetValue(token, out plugin) ? plugin : null;
}
public void Reload(){
@ -57,22 +57,22 @@ public void Reload(){
loadErrors = new List<string>(2);
foreach(Plugin plugin in LoadPluginsFrom(PathOfficialPlugins,PluginGroup.Official)){
foreach(Plugin plugin in LoadPluginsFrom(PathOfficialPlugins, PluginGroup.Official)){
plugins.Add(plugin);
}
foreach(Plugin plugin in LoadPluginsFrom(PathCustomPlugins,PluginGroup.Custom)){
foreach(Plugin plugin in LoadPluginsFrom(PathCustomPlugins, PluginGroup.Custom)){
plugins.Add(plugin);
}
if (Reloaded != null && (loadErrors.Count > 0 || !prevPlugins.SetEquals(plugins))){
Reloaded(this,new PluginLoadEventArgs(loadErrors));
Reloaded(this, new PluginLoadEventArgs(loadErrors));
}
}
public void ExecutePlugins(IFrame frame, PluginEnvironment environment, bool includeDisabled){
if (includeDisabled){
ScriptLoader.ExecuteScript(frame,PluginScriptGenerator.GenerateConfig(Config),"gen:pluginconfig");
ScriptLoader.ExecuteScript(frame, PluginScriptGenerator.GenerateConfig(Config), "gen:pluginconfig");
}
foreach(Plugin plugin in Plugins){
@ -98,14 +98,14 @@ public void ExecutePlugins(IFrame frame, PluginEnvironment environment, bool inc
tokens[token] = plugin;
}
ScriptLoader.ExecuteScript(frame,PluginScriptGenerator.GeneratePlugin(plugin.Identifier,script,token,environment),"plugin:"+plugin);
ScriptLoader.ExecuteScript(frame, PluginScriptGenerator.GeneratePlugin(plugin.Identifier, script, token, environment), "plugin:"+plugin);
}
}
private IEnumerable<Plugin> LoadPluginsFrom(string path, PluginGroup group){
foreach(string fullDir in Directory.EnumerateDirectories(path,"*",SearchOption.TopDirectoryOnly)){
foreach(string fullDir in Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly)){
string error;
Plugin plugin = Plugin.CreateFromFolder(fullDir,group,out error);
Plugin plugin = Plugin.CreateFromFolder(fullDir, group, out error);
if (plugin == null){
loadErrors.Add(group.GetIdentifierPrefix()+Path.GetFileName(fullDir)+": "+error);

View File

@ -3,7 +3,7 @@
namespace TweetDck.Plugins{
static class PluginScriptGenerator{
public static string GenerateConfig(PluginConfig config){
return config.AnyDisabled ? "window.TD_PLUGINS.disabled = [\""+string.Join("\",\"",config.DisabledPlugins)+"\"];" : string.Empty;
return config.AnyDisabled ? "window.TD_PLUGINS.disabled = [\""+string.Join("\",\"", config.DisabledPlugins)+"\"];" : string.Empty;
}
public static string GeneratePlugin(string pluginIdentifier, string pluginContents, int pluginToken, PluginEnvironment environment){

View File

@ -33,21 +33,21 @@ static class Program{
public static readonly Version Version = new Version(VersionTag);
public static readonly string StoragePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),BrandName);
public static readonly string PluginPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"plugins");
public static readonly string TemporaryPath = Path.Combine(Path.GetTempPath(),BrandName);
public static readonly string ConfigFilePath = Path.Combine(StoragePath,"TD_UserConfig.cfg");
public static readonly string StoragePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), BrandName);
public static readonly string PluginPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "plugins");
public static readonly string TemporaryPath = Path.Combine(Path.GetTempPath(), BrandName);
public static readonly string ConfigFilePath = Path.Combine(StoragePath, "TD_UserConfig.cfg");
public static uint WindowRestoreMessage;
private static readonly LockManager LockManager = new LockManager(Path.Combine(StoragePath,".lock"));
private static readonly LockManager LockManager = new LockManager(Path.Combine(StoragePath, ".lock"));
private static bool HasCleanedUp;
public static UserConfig UserConfig { get; private set; }
public static string LogFile{
get{
return Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"td-log.txt");
return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "td-log.txt");
}
}
@ -66,7 +66,7 @@ private static void Main(){
break;
}
else if (attempt == 20){
MessageBox.Show(BrandName+" is taking too long to close, please wait and then start the application again manually.",BrandName+" Cannot Restart",MessageBoxButtons.OK,MessageBoxIcon.Error);
MessageBox.Show(BrandName+" is taking too long to close, please wait and then start the application again manually.", BrandName+" Cannot Restart", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
else{
@ -77,12 +77,12 @@ private static void Main(){
else{
if (!LockManager.Lock()){
if (LockManager.LockingProcess.MainWindowHandle == IntPtr.Zero && LockManager.LockingProcess.Responding){ // restore if the original process is in tray
NativeMethods.SendMessage(NativeMethods.HWND_BROADCAST,WindowRestoreMessage,0,IntPtr.Zero);
NativeMethods.SendMessage(NativeMethods.HWND_BROADCAST, WindowRestoreMessage, 0, IntPtr.Zero);
return;
}
else if (MessageBox.Show("Another instance of "+BrandName+" is already running.\r\nDo you want to close it?",BrandName+" is Already Running",MessageBoxButtons.YesNo,MessageBoxIcon.Error,MessageBoxDefaultButton.Button2) == DialogResult.Yes){
else if (MessageBox.Show("Another instance of "+BrandName+" is already running.\r\nDo you want to close it?", BrandName+" is Already Running", MessageBoxButtons.YesNo, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2) == DialogResult.Yes){
if (!LockManager.CloseLockingProcess(10000)){
MessageBox.Show("Could not close the other process.",BrandName+" Has Failed :(",MessageBoxButtons.OK,MessageBoxIcon.Error);
MessageBox.Show("Could not close the other process.", BrandName+" Has Failed :(", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
@ -98,9 +98,9 @@ private static void Main(){
File.Delete(ExportManager.CookiesPath);
}
File.Move(ExportManager.TempCookiesPath,ExportManager.CookiesPath);
File.Move(ExportManager.TempCookiesPath, ExportManager.CookiesPath);
}catch(Exception e){
HandleException("Could not import the cookie file to restore login session.",e);
HandleException("Could not import the cookie file to restore login session.", e);
}
}
@ -111,7 +111,7 @@ private static void Main(){
Cef.OnContextInitialized = () => {
using(IRequestContext ctx = Cef.GetGlobalRequestContext()){
string err;
ctx.SetPreference("browser.enable_spellchecking",false,out err);
ctx.SetPreference("browser.enable_spellchecking", false, out err);
}
};
@ -126,7 +126,7 @@ private static void Main(){
#endif
};
CommandLineArgsParser.AddToDictionary(UserConfig.CustomCefArgs,settings.CefCommandLineArgs);
CommandLineArgsParser.AddToDictionary(UserConfig.CustomCefArgs, settings.CefCommandLineArgs);
Cef.Initialize(settings);
@ -134,13 +134,13 @@ private static void Main(){
Exception ex = args.ExceptionObject as Exception;
if (ex != null){
HandleException("An unhandled exception has occurred.",ex);
HandleException("An unhandled exception has occurred.", ex);
}
};
Application.ApplicationExit += (sender, args) => ExitCleanup();
PluginManager plugins = new PluginManager(PluginPath,UserConfig.Plugins);
PluginManager plugins = new PluginManager(PluginPath, UserConfig.Plugins);
plugins.Reloaded += plugins_Reloaded;
plugins.Config.PluginChangedState += (sender, args) => UserConfig.Save();
plugins.Reload();
@ -151,21 +151,21 @@ private static void Main(){
if (mainForm.UpdateInstallerPath != null){
ExitCleanup();
Process.Start(mainForm.UpdateInstallerPath,"/SP- /SILENT /NOICONS /CLOSEAPPLICATIONS");
Process.Start(mainForm.UpdateInstallerPath, "/SP- /SILENT /NOICONS /CLOSEAPPLICATIONS");
Application.Exit();
}
}
private static void plugins_Reloaded(object sender, PluginLoadEventArgs e){
if (!e.Success){
MessageBox.Show("The following plugins will not be available until the issues are resolved:\n"+string.Join("\n",e.Errors),"Error Loading Plugins",MessageBoxButtons.OK,MessageBoxIcon.Warning);
MessageBox.Show("The following plugins will not be available until the issues are resolved:\n"+string.Join("\n", e.Errors), "Error Loading Plugins", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
public static void HandleException(string message, Exception e){
Log(e.ToString());
if (MessageBox.Show(message+"\r\nDo you want to open the log file to report the issue?",BrandName+" Has Failed :(",MessageBoxButtons.YesNo,MessageBoxIcon.Error,MessageBoxDefaultButton.Button2) == DialogResult.Yes){
if (MessageBox.Show(message+"\r\nDo you want to open the log file to report the issue?", BrandName+" Has Failed :(", MessageBoxButtons.YesNo, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2) == DialogResult.Yes){
Process.Start(LogFile);
}
}
@ -181,7 +181,7 @@ public static void Log(string data){
build.Append(data).Append("\r\n\r\n");
try{
File.AppendAllText(LogFile,build.ToString(),Encoding.UTF8);
File.AppendAllText(LogFile, build.ToString(), Encoding.UTF8);
}catch{
// oops
}
@ -196,7 +196,7 @@ public static void ResetConfig(){
File.Delete(ConfigFilePath);
File.Delete(UserConfig.GetBackupFile(ConfigFilePath));
}catch(Exception e){
HandleException("Could not delete configuration files to reset the settings.",e);
HandleException("Could not delete configuration files to reset the settings.", e);
return;
}
@ -209,7 +209,7 @@ private static void ExitCleanup(){
UserConfig.Save();
try{
Directory.Delete(TemporaryPath,true);
Directory.Delete(TemporaryPath, true);
}catch(DirectoryNotFoundException){
}catch(Exception e){
// welp, too bad

View File

@ -11,33 +11,33 @@ static class ScriptLoader{
public static string LoadResource(string name){
try{
return File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,name),Encoding.UTF8);
return File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, name), Encoding.UTF8);
}catch(Exception ex){
MessageBox.Show("Unfortunately, "+Program.BrandName+" could not load the "+name+" file. The program will continue running with limited functionality.\r\n\r\n"+ex.Message,Program.BrandName+" Has Failed :(",MessageBoxButtons.OK,MessageBoxIcon.Error);
MessageBox.Show("Unfortunately, "+Program.BrandName+" could not load the "+name+" file. The program will continue running with limited functionality.\r\n\r\n"+ex.Message, Program.BrandName+" Has Failed :(", MessageBoxButtons.OK, MessageBoxIcon.Error);
return null;
}
}
public static void ExecuteFile(ChromiumWebBrowser browser, string file){
ExecuteScript(browser,LoadResource(file),GetRootIdentifier(file));
ExecuteScript(browser, LoadResource(file), GetRootIdentifier(file));
}
public static void ExecuteFile(IFrame frame, string file){
ExecuteScript(frame,LoadResource(file),GetRootIdentifier(file));
ExecuteScript(frame, LoadResource(file), GetRootIdentifier(file));
}
public static void ExecuteScript(ChromiumWebBrowser browser, string script, string identifier){
if (script == null)return;
using(IFrame frame = browser.GetMainFrame()){
frame.ExecuteJavaScriptAsync(script,UrlPrefix+identifier,1);
frame.ExecuteJavaScriptAsync(script, UrlPrefix+identifier, 1);
}
}
public static void ExecuteScript(IFrame frame, string script, string identifier){
if (script == null)return;
frame.ExecuteJavaScriptAsync(script,UrlPrefix+identifier,1);
frame.ExecuteJavaScriptAsync(script, UrlPrefix+identifier, 1);
}
public static string GetRootIdentifier(string file){

View File

@ -13,7 +13,7 @@ sealed partial class FormUpdateDownload : Form{
public string InstallerPath{
get{
return Path.Combine(Path.GetTempPath(),updateInfo.FileName);
return Path.Combine(Path.GetTempPath(), updateInfo.FileName);
}
}
@ -45,7 +45,7 @@ public FormUpdateDownload(UpdateInfo info){
}
private void FormUpdateDownload_Shown(object sender, EventArgs e){
webClient.DownloadFileAsync(new Uri(updateInfo.DownloadUrl),InstallerPath);
webClient.DownloadFileAsync(new Uri(updateInfo.DownloadUrl), InstallerPath);
}
private void btnCancel_Click(object sender, EventArgs e){
@ -69,7 +69,7 @@ private void webClient_DownloadProgressChanged(object sender, DownloadProgressCh
progressDownload.SetValueInstant(1000);
}
labelStatus.Text = (e.BytesReceived/BytesToMB).ToString("0.0",CultureInfo.CurrentCulture)+" MB";
labelStatus.Text = (e.BytesReceived/BytesToMB).ToString("0.0", CultureInfo.CurrentCulture)+" MB";
}
else{
if (progressDownload.Style != ProgressBarStyle.Continuous){
@ -77,7 +77,7 @@ private void webClient_DownloadProgressChanged(object sender, DownloadProgressCh
}
progressDownload.SetValueInstant(e.ProgressPercentage*10);
labelStatus.Text = (e.BytesReceived/BytesToMB).ToString("0.0",CultureInfo.CurrentCulture)+" / "+(e.TotalBytesToReceive/BytesToMB).ToString("0.0",CultureInfo.CurrentCulture)+" MB";
labelStatus.Text = (e.BytesReceived/BytesToMB).ToString("0.0", CultureInfo.CurrentCulture)+" / "+(e.TotalBytesToReceive/BytesToMB).ToString("0.0", CultureInfo.CurrentCulture)+" MB";
}
});
}
@ -92,7 +92,7 @@ private void webClient_DownloadFileCompleted(object sender, AsyncCompletedEventA
else if (e.Error != null){
Program.Log(e.Error.ToString());
if (MessageBox.Show("Could not download the update: "+e.Error.Message+"\r\n\r\nDo you want to open the website and try downloading the update manually?","Update Has Failed",MessageBoxButtons.YesNo,MessageBoxIcon.Error,MessageBoxDefaultButton.Button1) == DialogResult.Yes){
if (MessageBox.Show("Could not download the update: "+e.Error.Message+"\r\n\r\nDo you want to open the website and try downloading the update manually?", "Update Has Failed", MessageBoxButtons.YesNo, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1) == DialogResult.Yes){
BrowserUtils.OpenExternalBrowser(Program.Website);
UpdateStatus = Status.Manual;
}

View File

@ -19,29 +19,29 @@ public UpdateHandler(ChromiumWebBrowser browser, FormBrowser form){
this.browser = browser;
this.form = form;
browser.FrameLoadEnd += browser_FrameLoadEnd;
browser.RegisterJsObject("$TDU",new Bridge(this));
browser.RegisterJsObject("$TDU", new Bridge(this));
}
private void browser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e){
if (e.Frame.IsMain){
ScriptLoader.ExecuteFile(e.Frame,"update.js");
ScriptLoader.ExecuteFile(e.Frame, "update.js");
}
}
public int Check(bool force){
browser.ExecuteScriptAsync("TDUF_runUpdateCheck",force,++lastEventId);
browser.ExecuteScriptAsync("TDUF_runUpdateCheck", force, ++lastEventId);
return lastEventId;
}
private void TriggerUpdateAcceptedEvent(UpdateAcceptedEventArgs args){
if (UpdateAccepted != null){
form.InvokeSafe(() => UpdateAccepted(this,args));
form.InvokeSafe(() => UpdateAccepted(this, args));
}
}
private void TriggerCheckFinishedEvent(UpdateCheckEventArgs args){
if (CheckFinished != null){
form.InvokeSafe(() => CheckFinished(this,args));
form.InvokeSafe(() => CheckFinished(this, args));
}
}
@ -77,11 +77,11 @@ public Bridge(UpdateHandler owner){
}
public void OnUpdateCheckFinished(int eventId, bool isUpdateAvailable, string latestVersion){
owner.TriggerCheckFinishedEvent(new UpdateCheckEventArgs(eventId,isUpdateAvailable,latestVersion));
owner.TriggerCheckFinishedEvent(new UpdateCheckEventArgs(eventId, isUpdateAvailable, latestVersion));
}
public void OnUpdateAccepted(string versionTag, string downloadUrl){
owner.TriggerUpdateAcceptedEvent(new UpdateAcceptedEventArgs(new UpdateInfo(versionTag,downloadUrl)));
owner.TriggerUpdateAcceptedEvent(new UpdateAcceptedEventArgs(new UpdateInfo(versionTag, downloadUrl)));
}
public void OnUpdateDismissed(string versionTag){