Skip to content

Commit

Permalink
Settings: Start porting settings usage
Browse files Browse the repository at this point in the history
About 1/4th done.
Also correct some usages & properties.
Fixes madskristensen#480, madskristensen#387
  • Loading branch information
SLaks committed Jan 13, 2014
1 parent b089f3e commit 314da37
Show file tree
Hide file tree
Showing 20 changed files with 87 additions and 90 deletions.
10 changes: 5 additions & 5 deletions EditorExtensions/BrowserLink/Menu/MenuBrowserLink.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@ public class MenuBrowserLinkFactory : IBrowserLinkExtensionFactory
{
public BrowserLinkExtension CreateExtensionInstance(BrowserLinkConnection connection)
{
if (!WESettings.GetBoolean(WESettings.Keys.EnableBrowserLinkMenu))
if (!WESettings.Instance.BrowserLink.EnableMenu)
return null;

return new MenuBrowserLink();
}

public string GetScript()
{
if (!WESettings.GetBoolean(WESettings.Keys.EnableBrowserLinkMenu))
if (!WESettings.Instance.BrowserLink.EnableMenu)
return null;

using (Stream stream = GetType().Assembly.GetManifestResourceStream("MadsKristensen.EditorExtensions.BrowserLink.Menu.MenuBrowserLink.js"))
Expand All @@ -33,15 +33,15 @@ public class MenuBrowserLink : BrowserLinkExtension
{
public override void OnConnected(BrowserLinkConnection connection)
{
Browsers.Client(connection).Invoke("setVisibility", WESettings.GetBoolean(WESettings.Keys.BrowserLink_ShowMenu));
Browsers.Client(connection).Invoke("setVisibility", WESettings.Instance.BrowserLink.ShowMenu);
}

[SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
[BrowserLinkCallback] // This method can be called from JavaScript
public void ToggleVisibility(bool visible)
{
Settings.SetValue(WESettings.Keys.BrowserLink_ShowMenu, visible);
Settings.Save();
WESettings.Instance.BrowserLink.ShowMenu = visible;
SettingsStore.Save();
}
}
}
5 changes: 3 additions & 2 deletions EditorExtensions/BrowserLink/PixelPushing/PixelPushingMode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,10 @@ public static IEnumerable<Regex> IgnoreList
{
get
{
var ignorePatterns = WESettings.GetString(WESettings.Keys.UnusedCss_IgnorePatterns) ?? "";
var ignorePatterns = WESettings.Instance.BrowserLink.CssIgnorePatterns ?? "";

return _ignoreList ?? (_ignoreList = ignorePatterns.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => new Regex(UnusedCssExtension.FilePatternToRegex(x.Trim()))).ToList());
return _ignoreList ?? (_ignoreList = ignorePatterns.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => new Regex(UnusedCssExtension.FilePatternToRegex(x.Trim()))).ToList());
}
}

Expand Down
5 changes: 3 additions & 2 deletions EditorExtensions/Commands/Css/CssSaveListener.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ namespace MadsKristensen.EditorExtensions
[TextViewRole(PredefinedTextViewRoles.Document)]
public class CssSaveListener : IWpfTextViewCreationListener
{
//TODO: Move to common base class
[Import]
public ITextDocumentFactoryService TextDocumentFactoryService { get; set; }

Expand All @@ -30,7 +31,7 @@ public void TextViewCreated(IWpfTextView textView)

void document_FileActionOccurred(object sender, TextDocumentFileActionEventArgs e)
{
if (!WESettings.GetBoolean(WESettings.Keys.EnableCssMinification))
if (!WESettings.Instance.Css.MinifyOnSave)
return;

if (e.FileActionType == FileActionTypes.ContentSavedToDisk && e.FilePath.EndsWith(".css", StringComparison.OrdinalIgnoreCase))
Expand Down Expand Up @@ -62,7 +63,7 @@ public static void Minify(string file, string minFile)
writer.Write(content);
}

if (WESettings.GetBoolean(WESettings.Keys.CssEnableGzipping))
if (WESettings.Instance.Css.GzipMinifiedFiles)
GzipFile(file, minFile, content);
}
catch
Expand Down
2 changes: 1 addition & 1 deletion EditorExtensions/Commands/HTML/EnterFormatCommandTarget.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public EnterFormat(IVsTextView adapter, IWpfTextView textView, IEditorFormatterP

protected override bool Execute(CommandId commandId, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
{
if (_broker.IsCompletionActive(TextView) || !IsValidTextBuffer() || !WESettings.GetBoolean(WESettings.Keys.EnableEnterFormat))
if (_broker.IsCompletionActive(TextView) || !IsValidTextBuffer() || !WESettings.Instance.Html.EnableEnterFormat)
return false;

int position = TextView.Caret.Position.BufferPosition.Position;
Expand Down
2 changes: 1 addition & 1 deletion EditorExtensions/Commands/HTML/HtmlSaveListener.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public void TextViewCreated(IWpfTextView textView)

void document_FileActionOccurred(object sender, TextDocumentFileActionEventArgs e)
{
if (!WESettings.GetBoolean(WESettings.Keys.EnableHtmlMinification))
if (!WESettings.Instance.Html.MinifyOnSave)
return;

if (e.FileActionType == FileActionTypes.ContentSavedToDisk && e.FilePath.EndsWith(".html", StringComparison.OrdinalIgnoreCase))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public CommentCompletionCommandTarget(IVsTextView adapter, IWpfTextView textView

protected override bool Execute(CommandId commandId, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
{
if (!WESettings.GetBoolean(WESettings.Keys.JavaScriptCommentCompletion))
if (!WESettings.Instance.JavaScript.BlockCommentCompletion)
return false;

char typedChar = (char)(ushort)Marshal.GetObjectForNativeVariant(pvaIn);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public CommentIndentationCommandTarget(IVsTextView adapter, IWpfTextView textVie

protected override bool Execute(CommandId commandId, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
{
if (!WESettings.GetBoolean(WESettings.Keys.JavaScriptCommentCompletion) || _broker.IsCompletionActive(TextView))
if (!WESettings.Instance.JavaScript.BlockCommentCompletion || _broker.IsCompletionActive(TextView))
return false;

int position = TextView.Caret.Position.BufferPosition.Position;
Expand Down
21 changes: 11 additions & 10 deletions EditorExtensions/Commands/JavaScript/JsHintRunner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -194,22 +194,23 @@ private ErrorTask CreateTask(CompilerError error)

private static TaskErrorCategory GetOutputLocation()
{
var location = (WESettings.Keys.FullErrorLocation)WESettings.GetInt(WESettings.Keys.JsHintErrorLocation);

if (location == WESettings.Keys.FullErrorLocation.Errors)
return TaskErrorCategory.Error;

if (location == WESettings.Keys.FullErrorLocation.Warnings)
return TaskErrorCategory.Warning;

return TaskErrorCategory.Message;
switch (WESettings.Instance.JavaScript.LintResultLocation)
{
case ErrorLocation.Errors:
return TaskErrorCategory.Error;
case ErrorLocation.Warnings:
return TaskErrorCategory.Warning;
case ErrorLocation.Messages:
default:
return TaskErrorCategory.Message;
}
}

private void task_Navigate(object sender, EventArgs e)
{
Task task = sender as Task;

_provider.Navigate(task, new Guid(EnvDTE.Constants.vsViewKindPrimary));
_provider.Navigate(task, new Guid(Constants.vsViewKindPrimary));

if (task.Column > 0)
{
Expand Down
4 changes: 2 additions & 2 deletions EditorExtensions/Commands/TypeScript/TsLintProjectRunner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,15 @@ public TsLintProjectRunner(ITextDocument document)
_document.FileActionOccurred += DocumentSavedHandler;
_runner = new TsLintRunner(_document.FilePath);

if (WESettings.GetBoolean(WESettings.Keys.EnableTsLint))
if (WESettings.Instance.TypeScript.LintOnSave)
{
Dispatcher.CurrentDispatcher.BeginInvoke(new Action(_runner.RunCompiler), DispatcherPriority.ApplicationIdle, null);
}
}

private void DocumentSavedHandler(object sender, TextDocumentFileActionEventArgs e)
{
if (!WESettings.GetBoolean(WESettings.Keys.EnableTsLint))
if (!WESettings.Instance.TypeScript.LintOnSave)
return;

ITextDocument document = (ITextDocument)sender;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public TypeScriptTypeThroughController(ITextView textView, IList<ITextBuffer> su

protected override bool CanComplete(ITextBuffer textBuffer, int position)
{
bool result = WESettings.GetBoolean(WESettings.Keys.TypeScriptBraceCompletion);
bool result = WESettings.Instance.TypeScript.BraceCompletion;

if (result)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ private void OnPostTypeChar(char typedCharacter)
// current caret position may be beyond projection boundary like when
// typing at the end of onclick="return foo(".

if (WESettings.GetBoolean(WESettings.Keys.TypeScriptBraceCompletion))
if (WESettings.Instance.TypeScript.BraceCompletion)
{
char completionCharacter = GetCompletionCharacter(typedCharacter);
if (completionCharacter != '\0')
Expand Down
11 changes: 5 additions & 6 deletions EditorExtensions/Compilers/CoffeeScript/CoffeeScriptCompiler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,10 @@ protected override string GetArguments(string sourceFileName, string targetFileN
{
var args = new StringBuilder();

if (WESettings.GetBoolean(WESettings.Keys.WrapCoffeeScriptClosure))
if (!WESettings.Instance.CoffeeScript.WrapClosure)
args.Append("--bare ");

if (WESettings.GetBoolean(WESettings.Keys.CoffeeScriptSourceMaps) && !InUnitTests)
if (WESettings.Instance.CoffeeScript.GenerateSourceMaps && !InUnitTests)

This comment has been minimized.

Copy link
@SLaks

SLaks Jan 14, 2014

Author Owner

@am11 Why do we need this in LESS but not SASS?
Can we always use pure relative paths & get rid of this dependency?

This comment has been minimized.

Copy link
@am11

am11 Jan 14, 2014

@SLaks, there is no standard way of CLI arguments so far. Every compiler is using different arguments. While CoffeeScript and SASS are providing one (or two), LESS provides 6 arguments to handle it:

  --source-map[=FILENAME]      # Outputs a v3 sourcemap to the filename (or output filename.map)
  --source-map-rootpath=X         # adds this path onto the sourcemap filename and less file paths
  --source-map-basepath=X       # Sets sourcemap base path, defaults to current working directory.
  --source-map-url=URL             # the complete url and filename put in the less file
  --source-map-less-inline          # puts the less files into the map instead of referencing them
  --source-map-map-inline         # puts the map (and any less files) into the output css file

See this: jashkenas/coffeescript#3296

I opened issue with all of them (except LESS; because they made it easy on them but hard for us to figure out). I guess, libsass guys would make it right before anyone. That is; one argument --map and we won't need any post-processing for URLs.

According to @nschonni (here):

I don't think the Windows style paths are valid whether they are escaped or not. Going by the spec https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#! any paths need to be in URL format

args.Append("--map ");

args.AppendFormat(CultureInfo.CurrentCulture, "--output \"{0}\" --compile \"{1}\"", Path.GetDirectoryName(targetFileName), sourceFileName);
Expand Down Expand Up @@ -65,18 +65,17 @@ private static void ProcessMapFile(string jsFileName)
File.Delete(oldSourceMapFile);
// end-Hack

if (WESettings.GetBoolean(WESettings.Keys.CoffeeScriptSourceMaps))
if (WESettings.Instance.CoffeeScript.GenerateSourceMaps)
{
Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
{
Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() => {
ProjectHelpers.AddFileToProject(jsFileName, sourceMapFile);
}), DispatcherPriority.ApplicationIdle, null);
}
}

private static string UpdateSourceMapUrls(string content, string compiledFileName)
{
if (!WESettings.GetBoolean(WESettings.Keys.LessSourceMaps) || !File.Exists(compiledFileName))
if (!WESettings.Instance.CoffeeScript.GenerateSourceMaps || !File.Exists(compiledFileName))
return content;

string sourceMapFilename = compiledFileName + ".map";
Expand Down
7 changes: 4 additions & 3 deletions EditorExtensions/Compilers/LESS/LessCompiler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ protected override string GetArguments(string sourceFileName, string targetFileN
{
var args = new StringBuilder("--no-color --relative-urls ");

if (WESettings.GetBoolean(WESettings.Keys.LessSourceMaps))
if (WESettings.Instance.Less.GenerateSourceMaps)
{
string baseFolder = null;

This comment has been minimized.

Copy link
@SLaks

SLaks Jan 14, 2014

Author Owner

Sorry; I meant to ask that on this line.

Why do we need to use the project directory?
Can't we simply use the target directory & get normal relative paths?

This comment has been minimized.

Copy link
@am11

am11 Jan 14, 2014

@SLaks, actually this is for the LESS compiler specific argument --source-map-basepath. Other than this, we get undesired results (especially in the case when css and map are generated in a custom directory).

This comment has been minimized.

Copy link
@SLaks

SLaks Jan 14, 2014

Author Owner

I know.
But what happens if we always use the target directory? (Path.GetDirectoryName(targetFileName))

This comment has been minimized.

Copy link
@am11

am11 Jan 14, 2014

Yes! that makes sense. Lately, we are not using absolute URLs at all. Using targetFileName's directory should generate all relative paths:

  • Map to the CSS file
  • Map to all source LESS files
  • CSS to MAP

Should I test it and push the fix or just tell you here?

This comment has been minimized.

Copy link
@am11

am11 Jan 14, 2014

@SLaks, confirmed; We can replace it with this block:

if (WESettings.Instance.Less.GenerateSourceMaps)
{
    args.AppendFormat(CultureInfo.CurrentCulture, "--source-map-basepath=\"{0}\" --source-map=\"{1}.map\" ",
                    Path.GetDirectoryName(targetFileName).Replace("\\", "/"), targetFileName);
}

This comment has been minimized.

Copy link
@am11

am11 Jan 14, 2014

Very nice catch BTW! Thanks 👍

This comment has been minimized.

Copy link
@am11

am11 Jan 14, 2014

@SLaks, Please use this:

if (WESettings.Instance.Less.GenerateSourceMaps)
{
    args.AppendFormat(CultureInfo.CurrentCulture, "--source-map-basepath=\"{0}\" --source-map=\"{1}.map\" ",
                      Path.GetDirectoryName(targetFileName).targetFileName);
}

(without Replace( .. ))

if (!InUnitTests)
Expand All @@ -57,7 +57,8 @@ protected override string PostProcessResult(string resultSource, string sourceFi
var message = "LESS: " + Path.GetFileName(sourceFileName) + " compiled.";

// If the caller wants us to renormalize URLs to a different filename, do so.
if (!string.IsNullOrWhiteSpace(WESettings.GetString(WESettings.Keys.LessCompileToLocation)) && targetFileName != null && resultSource.IndexOf("url(", StringComparison.OrdinalIgnoreCase) > 0)
if (targetFileName != null && Path.GetDirectoryName(targetFileName) != Path.GetDirectoryName(sourceFileName)
&& resultSource.IndexOf("url(", StringComparison.OrdinalIgnoreCase) > 0)
{
try
{
Expand All @@ -80,7 +81,7 @@ protected override string PostProcessResult(string resultSource, string sourceFi

private static string UpdateSourceMapUrls(string content, string compiledFileName)
{
if (!WESettings.GetBoolean(WESettings.Keys.LessSourceMaps) || !File.Exists(compiledFileName))
if (!WESettings.Instance.Less.GenerateSourceMaps || !File.Exists(compiledFileName))
return content;

string sourceMapFilename = compiledFileName + ".map";
Expand Down
4 changes: 2 additions & 2 deletions EditorExtensions/Compilers/SASS/SassCompiler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ protected override string GetArguments(string sourceFileName, string targetFileN
{
var args = new StringBuilder();

if (WESettings.GetBoolean(WESettings.Keys.SassSourceMaps) && !InUnitTests)
if (WESettings.Instance.Sass.GenerateSourceMaps && !InUnitTests)
{
args.Append("--source-map ");
}
Expand Down Expand Up @@ -73,7 +73,7 @@ protected override string PostProcessResult(string resultSource, string sourceFi

private static string UpdateSourceMapUrls(string content, string compiledFileName)
{
if (!WESettings.GetBoolean(WESettings.Keys.SassSourceMaps) || !File.Exists(compiledFileName))
if (WESettings.Instance.Sass.GenerateSourceMaps || !File.Exists(compiledFileName))
return content;

string sourceMapFilename = compiledFileName + ".map";
Expand Down
31 changes: 12 additions & 19 deletions EditorExtensions/EditorExtensionsPackage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -118,36 +118,29 @@ protected override void Initialize()
private async void BuildEvents_OnBuildDone(vsBuildScope Scope, vsBuildAction Action)
{
if (Action != vsBuildAction.vsBuildActionClean)
{
await ThreadingTask.Task.Run(async () => {
if (WESettings.GetBoolean(WESettings.Keys.LessCompileOnBuild))
if (WESettings.Instance.Less.CompileOnBuild)
await BuildMenu.BuildLess();

if (WESettings.GetBoolean(WESettings.Keys.SassCompileOnBuild))
if (WESettings.Instance.Sass.CompileOnBuild)
await BuildMenu.BuildSass();

if (WESettings.GetBoolean(WESettings.Keys.CoffeeScriptCompileOnBuild))
if (WESettings.Instance.CoffeeScript.CompileOnBuild)
await BuildMenu.BuildCoffeeScript();

BuildMenu.UpdateBundleFiles();

if (WESettings.GetBoolean(WESettings.Keys.RunJsHintOnBuild))
{
await Dispatcher.CurrentDispatcher.BeginInvoke(
new Action(() => JsHintProjectRunner.RunOnAllFilesInProject()),
DispatcherPriority.ApplicationIdle, null);
}

if (WESettings.GetBoolean(WESettings.Keys.RunTsLintOnBuild))
{
await Dispatcher.CurrentDispatcher.BeginInvoke(
new Action(() => TsLintProjectRunner.RunOnAllFilesInProject()),
DispatcherPriority.ApplicationIdle, null);
}
});

if (WESettings.Instance.JavaScript.LintOnBuild)
JsHintProjectRunner.RunOnAllFilesInProject();
if (WESettings.Instance.TypeScript.LintOnBuild)
TsLintProjectRunner.RunOnAllFilesInProject();
}
else if (Action == vsBuildAction.vsBuildActionClean)
{
await ThreadingTask.Task.Run(() => JsHintRunner.Reset());
await ThreadingTask.Task.Run(() => TsLintRunner.Reset());
JsHintRunner.Reset();
TsLintRunner.Reset();
}
}

Expand Down
14 changes: 6 additions & 8 deletions EditorExtensions/MenuItems/BundleFiles.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,7 @@ private void document_FileActionOccurred(object sender, TextDocumentFileActionEv
{
string file = e.FilePath.EndsWith(_ext, StringComparison.OrdinalIgnoreCase) ? e.FilePath : null;

System.Threading.Tasks.Task.Run(() =>
{
System.Threading.Tasks.Task.Run(() => {
UpdateBundles(file, true);
});
}
Expand Down Expand Up @@ -321,7 +320,7 @@ private static void WriteBundleFile(string filePath, XmlDocument doc)
//{
// sb.AppendLine("/*#source " + files[file] + " */");
//}
if (extension.Equals(".js", StringComparison.OrdinalIgnoreCase) && WESettings.GetBoolean(WESettings.Keys.GenerateJavaScriptSourceMaps))
if (extension.Equals(".js", StringComparison.OrdinalIgnoreCase) && WESettings.Instance.JavaScript.GenerateSourceMaps)
{
sb.AppendLine("///#source 1 1 " + files[file]);
}
Expand All @@ -336,7 +335,7 @@ private static void WriteBundleFile(string filePath, XmlDocument doc)
// or if does not have URLs, no need to normalize.
if (Path.GetDirectoryName(file) != Path.GetDirectoryName(bundlePath)
&& source.IndexOf("url(", StringComparison.OrdinalIgnoreCase) > 0
&& !WESettings.GetBoolean(WESettings.Keys.CssPreserveRelativePathsOnMinify))
&& WESettings.Instance.Css.AdjustRelativePaths)
source = CssUrlNormalizer.NormalizeUrls(
tree: new CssParser().Parse(source, true),
targetFile: bundlePath,
Expand Down Expand Up @@ -369,15 +368,14 @@ private static void WriteMinFile(string filePath, string bundlePath, string cont
if (!bundleChanged && File.Exists(minPath))
return;

// TODO: Refactor to common class that takes settings interface & minifier
if (extension.Equals(".js", StringComparison.OrdinalIgnoreCase))
{
JavaScriptSaveListener.Minify(bundlePath, minPath, true);
ProjectHelpers.AddFileToProject(filePath, minPath);

if (WESettings.GetBoolean(WESettings.Keys.GenerateJavaScriptSourceMaps))
{
if (WESettings.Instance.JavaScript.GenerateSourceMaps)
ProjectHelpers.AddFileToProject(filePath, minPath + ".map");
}

ProjectHelpers.AddFileToProject(filePath, minPath + ".gzip");
}
Expand All @@ -389,7 +387,7 @@ private static void WriteMinFile(string filePath, string bundlePath, string cont
File.WriteAllText(minPath, minContent, new UTF8Encoding(true));
ProjectHelpers.AddFileToProject(filePath, minPath);

if (WESettings.GetBoolean(WESettings.Keys.CssEnableGzipping))
if (WESettings.Instance.Css.GzipMinifiedFiles)
CssSaveListener.GzipFile(filePath, minPath, minContent);
}
else if (extension.Equals(".html", StringComparison.OrdinalIgnoreCase))
Expand Down
Loading

0 comments on commit 314da37

Please sign in to comment.