Skip to content

Commit

Permalink
reworked a bunch of stuff, especially the weird way setting were handled
Browse files Browse the repository at this point in the history
  • Loading branch information
lukasaldersley committed Dec 25, 2021
1 parent 48b77e9 commit 1780fde
Show file tree
Hide file tree
Showing 10 changed files with 174 additions and 103 deletions.
9 changes: 8 additions & 1 deletion CodeStats/CodeStats.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,9 @@
<PropertyGroup>
<ApplicationManifest>app.manifest</ApplicationManifest>
</PropertyGroup>
<PropertyGroup>
<RunPostBuildEvent>OnOutputUpdated</RunPostBuildEvent>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Drawing" />
Expand All @@ -72,7 +75,7 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="CodeStatsSettings.cs" />
<Compile Include="CodeStatsSettingsProvider.cs" />
<Compile Include="Constants.cs" />
<Compile Include="Pulse.cs" />
<Compile Include="Logger.cs" />
Expand Down Expand Up @@ -139,6 +142,10 @@
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<Import Project="$(MSBuildProjectDirectory)\PluginInfrastructure\DllExport\NppPlugin.DllExport.targets" />
<PropertyGroup>
<PostBuildEvent>
</PostBuildEvent>
</PropertyGroup>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
Expand Down
44 changes: 22 additions & 22 deletions CodeStats/CodeStatsPackage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,19 +29,19 @@ class CodeStatsPackage
static int idMyDlg = -1;
static Bitmap tbBmp = Properties.Resources.CodeStats;

static CodeStatsSettings codeStatsSettings;
public static CodeStatsSettingsProvider codeStatsSettings;
public static CodeStats.Forms.SettingsForm _settingsForm;
public static CodeStats.Forms.ApiKeyForm _apikeyForm; // should be null if not needed
static string _lastStatusBarDocTypeText;
static DateTime _lastPulse = DateTime.Now;
static DateTime _lastActivity = DateTime.Now;
static int pulseFrequency = 10000; // ms

public static bool Debug;
public static bool TrackPlaintext;
public static string ApiKey;
public static string ApiUrl;
public static string Proxy;
//public static bool Debug;
//public static bool TrackPlaintext;
//public static string ApiKey;
//public static string ApiUrl;
//public static string Proxy;
public static bool proxyChangePending = false;
public static List<Constants.DetectionType> DetectionOrder;

Expand Down Expand Up @@ -110,15 +110,15 @@ private static void InitializeAsync()
Logger.Info("Initialized settings form"); // it takes 5 seconds to get here from Initializing Code::Stats message...

// Load config file
codeStatsSettings = new CodeStatsSettings();
codeStatsSettings = CodeStatsSettingsProvider.GetSingleton();
GetSettings(true);

Logger.Debug("Loaded config");

LoadExtensionMapping();


if (String.IsNullOrEmpty(ApiKey))
if (String.IsNullOrEmpty(codeStatsSettings.ApiKey))
{
PromptApiKey(); // Prompt for API token if not already set
}
Expand Down Expand Up @@ -284,7 +284,7 @@ public static void OnNotification(ScNotification notification)
{
Logger.Debug("[notification] SCN_CHARADDED");
HandleActicity();
if (Debug)
if (codeStatsSettings.EnableDebugLogging)
{
Logger.Debug("SCN_CHARADDED - File: " + GetCurrentFile() + ", char: " + (char)notification.character + " (" + notification.character + "), lang: " + GetCurrentLanguage());
}
Expand All @@ -299,15 +299,15 @@ public static void OnNotification(ScNotification notification)
// It will skip Ctrl+V if it wasn't pasted on some existing text, but never mind, it is still counting the most we want
// And we would not like it to count random file opens or other actions in
HandleActicity();
if (Debug)
if (codeStatsSettings.EnableDebugLogging)
{
Logger.Debug("SC_PERFORMED_USER & SC_MOD_DELETETEXT - File: " + GetCurrentFile() + ", char: " + notification.character + ", flags: " + notification.ModificationType.ToString("X"));
}
}

if (notification.Header.Code == (uint)SciMsg.SCEN_CHANGE) // Does not seem to be ever triggered (ah, right, GTK+ only it seems?)
{
if (Debug)
if (codeStatsSettings.EnableDebugLogging)
{
Logger.Debug("SCEN_CHANGE - File: " + GetCurrentFile() + ", char: " + notification.character + ", lang: " + GetCurrentLanguage());
}
Expand Down Expand Up @@ -403,7 +403,7 @@ private static Task ProcessPulses(CancellationTokenSource tokenSource)
currentCount = 0;
}
if (String.IsNullOrWhiteSpace(ApiKey))
if (String.IsNullOrWhiteSpace(codeStatsSettings.ApiKey))
{
Logger.Debug("No API token - cannot pulse!");
return;
Expand All @@ -423,13 +423,13 @@ private static Task ProcessPulses(CancellationTokenSource tokenSource)
string URL;
bool usesCustomEndpoint = false;
if (String.IsNullOrWhiteSpace(ApiUrl))
if (String.IsNullOrWhiteSpace(codeStatsSettings.PulseEndpoint))
{
URL = Constants.DefaultPulseURL;
}
else
{
URL = ApiUrl;
URL = codeStatsSettings.PulseEndpoint;
usesCustomEndpoint = true;
}
/*client.Headers["User-Agent"] = Constants.PluginUserAgent;
Expand All @@ -454,7 +454,7 @@ private static Task ProcessPulses(CancellationTokenSource tokenSource)
Headers = {
{ "User-Agent", Constants.PluginUserAgent },
{ "Accept", "*/*" },
{ "X-API-Token", ApiKey }
{ "X-API-Token", codeStatsSettings.ApiKey }
},
Content = new StringContent(json = jsonSerializer.Serialize(result), Encoding.UTF8, "application/json")
};
Expand Down Expand Up @@ -704,11 +704,11 @@ public static void GetSettings(bool skipRead = false)
codeStatsSettings.ReadConfigFile();
}

ApiKey = codeStatsSettings.ApiKey;
ApiUrl = codeStatsSettings.ApiUrl;
Debug = codeStatsSettings.EnableDebugLogging;
TrackPlaintext = codeStatsSettings.TrackPlainText;
Proxy = codeStatsSettings.Proxy;
//ApiKey = codeStatsSettings.ApiKey;
//ApiUrl = codeStatsSettings.PulseEndpoint;
//Debug = codeStatsSettings.EnableDebugLogging;
//TrackPlaintext = codeStatsSettings.TrackPlainText;
//Proxy = codeStatsSettings.Proxy;
DetectionOrder = codeStatsSettings.DetectionOrder;

proxyChangePending = true;
Expand Down Expand Up @@ -741,15 +741,15 @@ public static WebProxy GetProxy()
{
WebProxy proxy = null;

if (String.IsNullOrWhiteSpace(Proxy))
if (String.IsNullOrWhiteSpace(codeStatsSettings.Proxy))
{
Logger.Debug("No proxy will be used. It's not set.");
return proxy;
}

try
{
string proxyStr = Proxy;
string proxyStr = codeStatsSettings.Proxy;

// Regex that matches proxy address with authentication
Regex regProxyWithAuth = new Regex(@"\s*(https?:\/\/)?([^\s:]+):([^\s:]+)@([^\s:]+):(\d+)\s*");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,19 @@

namespace CodeStats
{
public class CodeStatsSettings
public class CodeStatsSettingsProvider
{
internal string ApiKey { get; set; }
internal string ApiUrl { get; set; }
internal string Proxy { get; set; }
internal bool TrackPlainText { get; set; } = false;
internal bool EnableDebugLogging { get; set; }
public string ApiKey { get { return APIKeyString ?? Constants.DefaultApiKey; } internal set { APIKeyString = String.IsNullOrWhiteSpace(value) ? Constants.DefaultApiKey : value.Trim(); } }
public string PulseEndpoint { get { return PulseEndpointString ?? Constants.DefaultPulseURL; } internal set { PulseEndpointString = String.IsNullOrWhiteSpace(value) ? Constants.DefaultPulseURL : value.Trim(); } }
public string Proxy { get { return ProxyString ?? Constants.DefaultProxy; } internal set { ProxyString = String.IsNullOrWhiteSpace(value) ? Constants.DefaultProxy : value.Trim(); } }
public bool TrackPlainText { get; set; } = false;
public bool EnableDebugLogging { get; set; } = false;

#region BackingVariables
private string PulseEndpointString;
private String APIKeyString;
private string ProxyString;
#endregion

internal bool UseExtensionMapping { get; set; }
internal bool UseLexerLanguage { get; set; }
Expand All @@ -24,16 +30,27 @@ public class CodeStatsSettings

internal List<Constants.DetectionType> DetectionOrder { get; set; }

private readonly string INISectionGeneral = "general";
private readonly string INISettingAPIKey = "api_key";
private readonly string INISettingAPIURL = "api_url";
private readonly string INISettingProxy = "proxy";
private readonly string INISettingDebugging = "debug_logging";
private readonly string INISettingTrackPlain = "track_plaintext";
private const string INISectionGeneral = "general";
private const string INISettingAPIKey = "api_key";
private const string INISettingPulseEndpoint = "pulse_endpoint";
private const string INISettingProxy = "proxy";
private const string INISettingDebugging = "debug_logging";
private const string INISettingTrackPlain = "track_plaintext";

private readonly string _configFilepath;

internal CodeStatsSettings()
private static CodeStatsSettingsProvider cssp = null;

public static CodeStatsSettingsProvider GetSingleton()
{
if (cssp == null)
{
cssp = new CodeStatsSettingsProvider();
}
return cssp;
}

private CodeStatsSettingsProvider()
{
// get path of plugin configuration and initially read the config file
StringBuilder INIPath = new StringBuilder(Win32.MAX_PATH);
Expand All @@ -45,38 +62,38 @@ internal CodeStatsSettings()

internal void ReadConfigFile()
{
StringBuilder ret = new StringBuilder(4096);//the size here is basically arbitrary but 4k shuould be enough for a simple config file
StringBuilder readSettingsFileStringBuilder = new StringBuilder(4096);//the size here is basically arbitrary but 4k shuould be enough for a simple config file

ApiKey = Kernel32NativeMethods.GetPrivateProfileString(INISectionGeneral, INISettingAPIKey, "", ret, ret.Capacity, _configFilepath) > 0
? ret.ToString()
: String.Empty;
ApiKey = Kernel32NativeMethods.GetPrivateProfileString(INISectionGeneral, INISettingAPIKey, Constants.DefaultApiKey, readSettingsFileStringBuilder, readSettingsFileStringBuilder.Capacity, _configFilepath) > 0
? readSettingsFileStringBuilder.ToString()
: Constants.DefaultApiKey;//I think this should be alredy handled by the default value

ApiUrl = Kernel32NativeMethods.GetPrivateProfileString(INISectionGeneral, INISettingAPIURL, "", ret, ret.Capacity, _configFilepath) > 0
? ret.ToString()
: String.Empty;
PulseEndpoint = Kernel32NativeMethods.GetPrivateProfileString(INISectionGeneral, INISettingPulseEndpoint, Constants.DefaultPulseURL, readSettingsFileStringBuilder, readSettingsFileStringBuilder.Capacity, _configFilepath) > 0
? readSettingsFileStringBuilder.ToString()
: Constants.DefaultPulseURL;

Proxy = Kernel32NativeMethods.GetPrivateProfileString(INISectionGeneral, INISettingProxy, "", ret, ret.Capacity, _configFilepath) > 0
? ret.ToString()
: String.Empty;
Proxy = Kernel32NativeMethods.GetPrivateProfileString(INISectionGeneral, INISettingProxy, Constants.DefaultProxy, readSettingsFileStringBuilder, readSettingsFileStringBuilder.Capacity, _configFilepath) > 0
? readSettingsFileStringBuilder.ToString()
: Constants.DefaultProxy;

//if the config was valid, use that, if not default to NOT tracking it.
TrackPlainText = (Kernel32NativeMethods.GetPrivateProfileString(INISectionGeneral, INISettingTrackPlain, "", ret, ret.Capacity, _configFilepath) > 0)
? Boolean.TryParse(ret.ToString(), out bool trackPlain) ? trackPlain : false
TrackPlainText = (Kernel32NativeMethods.GetPrivateProfileString(INISectionGeneral, INISettingTrackPlain, "", readSettingsFileStringBuilder, readSettingsFileStringBuilder.Capacity, _configFilepath) > 0)
? Boolean.TryParse(readSettingsFileStringBuilder.ToString(), out bool trackPlain) ? trackPlain : false
: false;

if (Kernel32NativeMethods.GetPrivateProfileString(INISectionGeneral, INISettingDebugging, "", ret, ret.Capacity, _configFilepath) > 0)
if (Kernel32NativeMethods.GetPrivateProfileString(INISectionGeneral, INISettingDebugging, "", readSettingsFileStringBuilder, readSettingsFileStringBuilder.Capacity, _configFilepath) > 0)
{
#if DEBUG
EnableDebugLogging = true; //if running a debug build (as defined by Visual Studio configuration) Debug Logging is enabled
#else
EnableDebugLogging = Boolean.TryParse(ret.ToString(), out bool debug) ? debug : false; //if the config was valid, use that if not, default to NOT debugging
EnableDebugLogging = Boolean.TryParse(readSettingsFileStringBuilder.ToString(), out bool debug) ? debug : false; //if the config was valid, use that if not, default to NOT debugging
#endif
}

#region detection order settings
if (Kernel32NativeMethods.GetPrivateProfileString("detection_order", "use_extension_mapping", "true", ret, ret.Capacity, _configFilepath) > 0)
if (Kernel32NativeMethods.GetPrivateProfileString("detection_order", "use_extension_mapping", "true", readSettingsFileStringBuilder, readSettingsFileStringBuilder.Capacity, _configFilepath) > 0)
{
if (bool.TryParse(ret.ToString(), out bool extmap))
if (bool.TryParse(readSettingsFileStringBuilder.ToString(), out bool extmap))
{
UseExtensionMapping = extmap;
}
Expand All @@ -86,9 +103,9 @@ internal void ReadConfigFile()
UseExtensionMapping = true;
}

if (Kernel32NativeMethods.GetPrivateProfileString("detection_order", "use_lexer_language", "true", ret, ret.Capacity, _configFilepath) > 0)
if (Kernel32NativeMethods.GetPrivateProfileString("detection_order", "use_lexer_language", "true", readSettingsFileStringBuilder, readSettingsFileStringBuilder.Capacity, _configFilepath) > 0)
{
if (bool.TryParse(ret.ToString(), out bool lexlag))
if (bool.TryParse(readSettingsFileStringBuilder.ToString(), out bool lexlag))
{
UseLexerLanguage = lexlag;
}
Expand All @@ -98,15 +115,15 @@ internal void ReadConfigFile()
UseLexerLanguage = true;
}

DetectionPriority = Kernel32NativeMethods.GetPrivateProfileString("detection_order", "priority", ((int)Constants.DetectionType.EXTENSION_MAPPING).ToString(), ret, ret.Capacity, _configFilepath) > 0
? (Constants.DetectionType)System.Int32.Parse(ret.ToString())
DetectionPriority = Kernel32NativeMethods.GetPrivateProfileString("detection_order", "priority", ((int)Constants.DetectionType.EXTENSION_MAPPING).ToString(), readSettingsFileStringBuilder, readSettingsFileStringBuilder.Capacity, _configFilepath) > 0
? (Constants.DetectionType)System.Int32.Parse(readSettingsFileStringBuilder.ToString())
: Constants.DetectionType.EXTENSION_MAPPING;

RefreshDetectionOrder();

if (Kernel32NativeMethods.GetPrivateProfileString("detection_order", "use_custom_mapping", "false", ret, ret.Capacity, _configFilepath) > 0)
if (Kernel32NativeMethods.GetPrivateProfileString("detection_order", "use_custom_mapping", "false", readSettingsFileStringBuilder, readSettingsFileStringBuilder.Capacity, _configFilepath) > 0)
{
if (bool.TryParse(ret.ToString(), out bool cusmap))
if (bool.TryParse(readSettingsFileStringBuilder.ToString(), out bool cusmap))
{
UseCustomMapping = cusmap;
}
Expand All @@ -120,9 +137,9 @@ internal void ReadConfigFile()

internal void SaveConfigFile()
{
Kernel32NativeMethods.WritePrivateProfileString(INISectionGeneral, INISettingAPIKey, String.IsNullOrWhiteSpace(ApiKey) ? "" : ApiKey.Trim(), _configFilepath);
Kernel32NativeMethods.WritePrivateProfileString(INISectionGeneral, INISettingAPIURL, (String.IsNullOrWhiteSpace(ApiUrl) || ApiUrl == Constants.DefaultPulseURL) ? "" : ApiUrl, _configFilepath);
Kernel32NativeMethods.WritePrivateProfileString(INISectionGeneral, INISettingProxy, Proxy.Trim(), _configFilepath);
Kernel32NativeMethods.WritePrivateProfileString(INISectionGeneral, INISettingAPIKey, ApiKey, _configFilepath);
Kernel32NativeMethods.WritePrivateProfileString(INISectionGeneral, INISettingPulseEndpoint, PulseEndpoint, _configFilepath);
Kernel32NativeMethods.WritePrivateProfileString(INISectionGeneral, INISettingProxy, Proxy, _configFilepath);
Kernel32NativeMethods.WritePrivateProfileString(INISectionGeneral, INISettingTrackPlain, TrackPlainText.ToString().ToLower(), _configFilepath);
Kernel32NativeMethods.WritePrivateProfileString(INISectionGeneral, INISettingDebugging, EnableDebugLogging.ToString().ToLower(), _configFilepath);

Expand Down
11 changes: 6 additions & 5 deletions CodeStats/Constants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,19 @@ internal static class Constants
internal const string PluginName = "Code::Stats";
internal const string PluginNameSafe = "CodeStats";
internal const string PluginKey = "notepadpp-CodeStats";
internal static string PluginVersion = string.Format("{0}.{1}.{2}", CodeStatsPackage.CoreAssembly.Version.Major, CodeStatsPackage.CoreAssembly.Version.Minor, CodeStatsPackage.CoreAssembly.Version.Build);
internal static string PluginUserAgent = string.Format("code-stats-notepadpp/{0}", PluginVersion);
internal static string PluginVersion = $"{CodeStatsPackage.CoreAssembly.Version.Major}.{CodeStatsPackage.CoreAssembly.Version.Minor}.{CodeStatsPackage.CoreAssembly.Version.Build}";
internal static string PluginUserAgent = $"code-stats-notepadpp/{PluginVersion}";
internal const string EditorName = "notepadpp";
internal static string EditorVersion
{
get {
int ver = (int)Win32.SendMessage(PluginBase.nppData._nppHandle, (uint)NppMsg.NPPM_GETNPPVERSION, 0, 0);
return ver.ToString();
return ((int)Win32.SendMessage(PluginBase.nppData._nppHandle, (uint)NppMsg.NPPM_GETNPPVERSION, 0, 0)).ToString();
}
}

internal static string DefaultPulseURL = "https://codestats.net/api/my/pulses";
internal const string DefaultPulseURL = "https://codestats.net/api/my/pulses";
internal const string DefaultApiKey = "";
internal const string DefaultProxy = "";

internal static string OSVersionString = System.Environment.OSVersion.VersionString;
internal static int OSVersionBuild = System.Environment.OSVersion.Version.Build;
Expand Down
7 changes: 3 additions & 4 deletions CodeStats/Forms/ApiKeyForm.cs
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
using System;
using System;
using System.Windows.Forms;

namespace CodeStats.Forms
{
public partial class ApiKeyForm : Form
{
private readonly CodeStatsSettings _CodeStatsConfigFile;
private readonly CodeStatsSettingsProvider _CodeStatsConfigFile;

public ApiKeyForm()
{
InitializeComponent();

_CodeStatsConfigFile = new CodeStatsSettings();
_CodeStatsConfigFile = CodeStatsSettingsProvider.GetSingleton();
}

private void ApiKeyForm_Load(object sender, EventArgs e)
Expand Down Expand Up @@ -44,7 +44,6 @@ private void btnOk_Click(object sender, EventArgs e)
//{
_CodeStatsConfigFile.ApiKey = apiKey;
_CodeStatsConfigFile.SaveConfigFile();
CodeStatsPackage.ApiKey = apiKey;
CodeStatsPackage._hasAlreadyShownInvalidApiTokenMessage = false;
/*}
else // - kept in case we check API tokens in future
Expand Down
Loading

0 comments on commit 1780fde

Please sign in to comment.