Ejemplo n.º 1
0
        private static string ExportJson(IEnumerable <SpriteFragment> fragments, string imageFile)
        {
            var map = new
            {
                images = fragments.Select(fragment =>
                {
                    var item = new
                    {
                        Name    = Path.GetFileName(fragment.FileName),
                        Width   = fragment.Width,
                        Height  = fragment.Height,
                        OffsetX = fragment.X,
                        OffsetY = fragment.Y,
                    };

                    return(item);
                })
            };

            string outputFile = GetFileName(imageFile, ExportFormat.Json);

            ProjectHelpers.CheckOutFileFromSourceControl(outputFile);

            using (StreamWriter sw = new StreamWriter(outputFile))
                using (JsonWriter jw = new JsonTextWriter(sw))
                {
                    jw.Formatting = Formatting.Indented;

                    var serializer = new JsonSerializer();
                    serializer.ContractResolver = new CamelCasePropertyNamesContractResolver();
                    serializer.Serialize(jw, map);
                }

            return(outputFile);
        }
Ejemplo n.º 2
0
        private async static Task <bool> MinifyFile(string file, string minFile, CodeSettings settings)
        {
            Minifier minifier = new Minifier();

            // If the source file is not itself mapped, add the filename for mapping
            // TODO: Make sure this works for compiled output too. (check for .map?)
            if (!((await FileHelpers.ReadAllLinesRetry(file))
                  .SkipWhile(string.IsNullOrWhiteSpace)
                  .FirstOrDefault() ?? "")
                .Trim()
                .StartsWith("///#source", StringComparison.CurrentCulture))
            {
                minifier.FileName = file;
            }

            string content = minifier.MinifyJavaScript(await FileHelpers.ReadAllTextRetry(file), settings);

            if (File.Exists(minFile) && content == await FileHelpers.ReadAllTextRetry(minFile))
            {
                return(false);
            }

            ProjectHelpers.CheckOutFileFromSourceControl(minFile);
            await FileHelpers.WriteAllTextRetry(minFile, content);

            ProjectHelpers.AddFileToProject(file, minFile);

            return(true);
        }
Ejemplo n.º 3
0
        public async static Task <IEnumerable <SpriteFragment> > MakeImage(SpriteDocument document, string imageFile, Func <string, bool, Task> updateSprite)
        {
            ProjectHelpers.CheckOutFileFromSourceControl(imageFile);

            Dictionary <string, Image> images = await WatchFiles(document, updateSprite);

            int width  = document.IsVertical ? images.Values.Max(i => i.Width) + (document.Margin * 2) : images.Values.Sum(i => i.Width) + (document.Margin * images.Count) + document.Margin;
            int height = document.IsVertical ? images.Values.Sum(img => img.Height) + (document.Margin * images.Count) + document.Margin : images.Values.Max(img => img.Height) + (document.Margin * 2);

            List <SpriteFragment> fragments = new List <SpriteFragment>();

            using (var bitmap = new Bitmap(width, height))
            {
                using (Graphics canvas = Graphics.FromImage(bitmap))
                {
                    if (document.IsVertical)
                    {
                        Vertical(images, fragments, canvas, document.Margin);
                    }
                    else
                    {
                        Horizontal(images, fragments, canvas, document.Margin);
                    }
                }

                bitmap.Save(imageFile, PasteImage.GetImageFormat("." + document.FileExtension));
            }

            return(fragments);
        }
Ejemplo n.º 4
0
        private static bool MinifyFile(string file, string minFile, CodeSettings settings)
        {
            Minifier minifier = new Minifier();

            // If the source file is not itself mapped, add the filename for mapping
            // TODO: Make sure this works for compiled output too. (check for .map?)
            if (!(File.ReadLines(file)
                  .SkipWhile(string.IsNullOrWhiteSpace)
                  .FirstOrDefault() ?? "")
                .Trim()
                .StartsWith("///#source", StringComparison.CurrentCulture))
            {
                minifier.FileName = Path.GetFileName(file);
            }

            string content = minifier.MinifyJavaScript(File.ReadAllText(file), settings);

            content += "\r\n/*\r\n//# sourceMappingURL=" + Path.GetFileName(minFile) + ".map\r\n*/";

            if (File.Exists(minFile) && content == File.ReadAllText(minFile))
            {
                return(false);
            }

            ProjectHelpers.CheckOutFileFromSourceControl(minFile);
            File.WriteAllText(minFile, content, Encoding.UTF8);
            ProjectHelpers.AddFileToProject(file, minFile);

            return(true);
        }
Ejemplo n.º 5
0
        public static IEnumerable <SpriteFragment> CreateImage(SpriteDocument sprite, out string imageFile)
        {
            imageFile = Path.ChangeExtension(sprite.FileName, sprite.FileExtension);
            ProjectHelpers.CheckOutFileFromSourceControl(imageFile);

            Dictionary <string, Image> images = GetImages(sprite);

            int width  = sprite.IsVertical ? images.Values.Max(i => i.Width) : images.Values.Sum(i => i.Width);
            int height = sprite.IsVertical ? images.Values.Sum(img => img.Height) : images.Values.Max(img => img.Height);

            List <SpriteFragment> fragments = new List <SpriteFragment>();

            using (var bitmap = new Bitmap(width, height))
            {
                using (Graphics canvas = Graphics.FromImage(bitmap))
                {
                    if (sprite.IsVertical)
                    {
                        Vertical(images, fragments, canvas);
                    }
                    else
                    {
                        Horizontal(images, fragments, canvas);
                    }
                }

                bitmap.Save(imageFile, PasteImage.GetImageFormat("." + sprite.FileExtension));
            }

            return(fragments);
        }
Ejemplo n.º 6
0
        private async static Task <bool> MinifyFileWithSourceMap(string file, string minFile)
        {
            bool         result;
            string       mapPath = minFile + ".map";
            StringWriter writer  = new StringWriter();

            ProjectHelpers.CheckOutFileFromSourceControl(mapPath);

            using (V3SourceMap sourceMap = new V3SourceMap(writer))
            {
                var settings = CreateSettings();

                settings.SymbolsMap = sourceMap;
                sourceMap.StartPackage(minFile, mapPath);

                // This fails when debugger is attached. Bug raised with Ron Logan
                result = await MinifyFile(file, minFile, settings);
            }

            await FileHelpers.WriteAllTextRetry(mapPath, writer.ToString(), false);

            ProjectHelpers.AddFileToProject(minFile, mapPath);

            return(result);
        }
Ejemplo n.º 7
0
        private async static Task <string> ExportStylesheet(IEnumerable <SpriteFragment> fragments, SpriteDocument sprite, string imageFile, ExportFormat format)
        {
            string        outputFile      = GetFileName(imageFile, sprite, format);
            var           outputDirectory = Path.GetDirectoryName(outputFile);
            StringBuilder sb   = new StringBuilder().AppendLine(GetDescription(format));
            string        root = ProjectHelpers.GetRootFolder();

            foreach (SpriteFragment fragment in fragments)
            {
                var rootAbsoluteUrl = FileHelpers.RelativePath(root, fragment.FileName);

                var bgUrl = sprite.UseAbsoluteUrl ? "/" + FileHelpers.RelativePath(root, imageFile) : FileHelpers.RelativePath(outputFile, imageFile);

                sb.AppendLine(GetSelector(rootAbsoluteUrl, sprite, format) + " {");
                sb.AppendLine("/* You may have to set 'display: block' */");
                sb.AppendLine("\twidth: " + fragment.Width + "px;");
                sb.AppendLine("\theight: " + fragment.Height + "px;");
                sb.AppendLine("\tbackground: url('" + bgUrl + "') -" + fragment.X + "px -" + fragment.Y + "px;");
                sb.AppendLine("}");
            }

            bool IsExists = System.IO.Directory.Exists(outputDirectory);

            if (!IsExists)
            {
                System.IO.Directory.CreateDirectory(outputDirectory);
            }

            ProjectHelpers.CheckOutFileFromSourceControl(outputFile);
            await FileHelpers.WriteAllTextRetry(outputFile, sb.ToString().Replace("-0px", "0"));

            return(outputFile);
        }
Ejemplo n.º 8
0
        public async Task <XDocument> WriteSpriteRecipe()
        {
            string            root     = ProjectHelpers.GetRootFolder();
            XmlWriterSettings settings = new XmlWriterSettings()
            {
                Indent = true
            };
            XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";

            if (string.IsNullOrEmpty(root))
            {
                root = ProjectHelpers.GetProjectFolder(FileName);
            }

            ProjectHelpers.CheckOutFileFromSourceControl(FileName);

            using (XmlWriter writer = await Task.Run(() => XmlWriter.Create(FileName, settings)))
            {
                XDocument doc =
                    new XDocument(
                        new XElement("sprite",
                                     new XAttribute(XNamespace.Xmlns + "xsi", xsi),
                                     new XAttribute(xsi + "noNamespaceSchemaLocation", "http://vswebessentials.com/schemas/v1/sprite.xsd"),
                                     new XElement("settings",
                                                  new XComment("Determines if the sprite image should be automatically optimized after creation/update."),
                                                  new XElement("optimize", Optimize.ToString().ToLowerInvariant()),
                                                  new XComment("Determines the orientation of images to form this sprite. The value must be vertical or horizontal."),
                                                  new XElement("orientation", IsVertical ? "vertical" : "horizontal"),
                                                  new XComment("The margin (in pixel) around and between the constituent images."),
                                                  new XElement("margin", Margin),
                                                  new XComment("File extension of sprite image."),
                                                  new XElement("outputType", FileExtension.ToString().ToLowerInvariant()),
                                                  new XComment("Determine whether to generate/re-generate this sprite on building the solution."),
                                                  new XElement("runOnBuild", RunOnBuild.ToString().ToLowerInvariant()),
                                                  new XComment("Use full path to generate unique class or mixin name in CSS, LESS and SASS files. Consider disabling this if you want class names to be filename only."),
                                                  new XElement("fullPathForIdentifierName", UseFullPathForIdentifierName.ToString().ToLowerInvariant()),
                                                  new XComment("Use absolute path in the generated CSS-like files. By default, the URLs are relative to sprite image file (and the location of CSS, LESS and SCSS)."),
                                                  new XElement("useAbsoluteUrl", UseAbsoluteUrl.ToString().ToLowerInvariant()),
                                                  new XComment("Specifies a custom subfolder to save files to. By default, compiled output will be placed in the same folder and nested under the original file."),
                                                  new XElement("outputDirectory", OutputDirectory),
                                                  new XComment("Specifies a custom subfolder to save CSS files to. By default, compiled output will be placed in the same folder and nested under the original file."),
                                                  new XElement("outputDirectoryForCss", CssOutputDirectory),
                                                  new XComment("Specifies a custom subfolder to save LESS files to. By default, compiled output will be placed in the same folder and nested under the original file."),
                                                  new XElement("outputDirectoryForLess", LessOutputDirectory),
                                                  new XComment("Specifies a custom subfolder to save SCSS files to. By default, compiled output will be placed in the same folder and nested under the original file."),
                                                  new XElement("outputDirectoryForScss", ScssOutputDirectory)
                                                  ),
                                     new XComment("The order of the <file> elements determines the order of the images in the sprite."),
                                     new XElement("files", BundleAssets.Select(file => new XElement("file", "/" + FileHelpers.RelativePath(root, file))))
                                     )
                        );

                doc.Save(writer);

                return(doc);
            }
        }
Ejemplo n.º 9
0
        protected async override Task <CompilerResult> RunCompilerAsync(string sourcePath, string targetPath)
        {
            var result = new MarkdownSharp.Markdown(WESettings.Instance.Markdown).Transform(await FileHelpers.ReadAllTextRetry(sourcePath));

            if (!string.IsNullOrEmpty(targetPath))
            {
                ProjectHelpers.CheckOutFileFromSourceControl(targetPath);   // TODO: Only if output changed?
                await FileHelpers.WriteAllTextRetry(targetPath, result);
            }

            var compilerResult = await CompilerResultFactory.GenerateResult(sourcePath, targetPath, true, result, null);

            return(compilerResult);
        }
Ejemplo n.º 10
0
        public virtual bool MinifyFile(string sourcePath, string targetPath)
        {
            var result = MinifyString(File.ReadAllText(sourcePath));

            if (result != null && (!File.Exists(targetPath) || result != File.ReadAllText(targetPath)))
            {
                ProjectHelpers.CheckOutFileFromSourceControl(targetPath);
                File.WriteAllText(targetPath, result, Encoding.UTF8);
                ProjectHelpers.AddFileToProject(sourcePath, targetPath);

                return(true);
            }

            return(false);
        }
Ejemplo n.º 11
0
        protected override Task <CompilerResult> RunCompilerAsync(string sourcePath, string targetPath)
        {
            var result = new MarkdownSharp.Markdown(WESettings.Instance.Markdown).Transform(File.ReadAllText(sourcePath));

            if (!string.IsNullOrEmpty(targetPath))
            {
                ProjectHelpers.CheckOutFileFromSourceControl(targetPath);   // TODO: Only if output changed?
                File.WriteAllText(targetPath, result, new UTF8Encoding(false));
            }

            return(Task.FromResult(new CompilerResult(sourcePath, targetPath)
            {
                IsSuccess = true, Result = result
            }));
        }
Ejemplo n.º 12
0
        public async virtual Task <bool> MinifyFile(string sourcePath, string targetPath)
        {
            var result = MinifyString(await FileHelpers.ReadAllTextRetry(sourcePath));

            if (result != null && (!File.Exists(targetPath) || result != await FileHelpers.ReadAllTextRetry(targetPath)))
            {
                ProjectHelpers.CheckOutFileFromSourceControl(targetPath);
                await FileHelpers.WriteAllTextRetry(targetPath, result);

                ProjectHelpers.AddFileToProject(sourcePath, targetPath);

                return(true);
            }

            return(false);
        }
Ejemplo n.º 13
0
        private static void HandleResult(string file, CompressionResult result)
        {
            string name = file.Contains(_dataUriPrefix) ? "The dataUri" : Path.GetFileName(file);

            if (result.Saving > 0)
            {
                ProjectHelpers.CheckOutFileFromSourceControl(result.OriginalFileName);
                File.Copy(result.ResultFileName, result.OriginalFileName, true);

                string text = "Compressed " + name + " by " + result.Saving + " bytes / " + result.Percent + "%";
                WebEssentialsPackage.DTE.StatusBar.Text = text;
                Logger.Log(result.ToString());
            }
            else
            {
                WebEssentialsPackage.DTE.StatusBar.Text = name + " is already optimized";
            }
        }
Ejemplo n.º 14
0
        private static bool MinifyFileWithSourceMap(string file, string minFile)
        {
            string mapPath = minFile + ".map";

            ProjectHelpers.CheckOutFileFromSourceControl(mapPath);

            using (TextWriter writer = new StreamWriter(mapPath, false, new UTF8Encoding(false)))
                using (V3SourceMap sourceMap = new V3SourceMap(writer))
                {
                    var settings = CreateSettings();
                    settings.SymbolsMap = sourceMap;
                    sourceMap.StartPackage(Path.GetFileName(minFile), Path.GetFileName(mapPath));

                    // This fails when debugger is attached. Bug raised with Ron Logan
                    bool result = MinifyFile(file, minFile, settings);
                    ProjectHelpers.AddFileToProject(minFile, mapPath);

                    return(result);
                }
        }
Ejemplo n.º 15
0
        protected async override Task <CompilerResult> RunCompilerAsync(string sourcePath, string targetPath)
        {
            var markdown = new MarkdownDeep.Markdown();

            markdown.ExtraMode       = true;
            markdown.SafeMode        = false;
            markdown.FormatCodeBlock = FormatCodePrettyPrint;

            string content = await FileHelpers.ReadAllTextRetry(sourcePath);

            // Issue with MarkdownDeep reported here https://github.com/toptensoftware/markdowndeep/issues/62
            content = content.Replace("```", "~~~");

            // Change the fenced code block language for the markdown.FormatCodeBlock method
            content = Regex.Replace(content, @"(~~~\s?)(?<lang>[^\s]+)", "~~~\r{{${lang}}}");

            // Issue with MarkdownDeep reported here https://github.com/toptensoftware/markdowndeep/issues/63
            foreach (Match match in Regex.Matches(content, "( {0,3}>)+( {0,3})([^\r\n]+)", RegexOptions.Multiline))
            {
                content = content.Replace(match.Value, match.Value + "  ");
            }

            var result = markdown
                         .Transform(content)
                         .Replace("[ ] ", "<input type=\"checkbox\" disabled /> ")
                         .Replace("[x] ", "<input type=\"checkbox\" disabled checked /> ");

            if (!string.IsNullOrEmpty(targetPath) &&
                (!File.Exists(targetPath) || await FileHelpers.ReadAllTextRetry(targetPath) != result))
            {
                ProjectHelpers.CheckOutFileFromSourceControl(targetPath);

                await FileHelpers.WriteAllTextRetry(targetPath, result);
            }

            var compilerResult = await CompilerResultFactory.GenerateResult(sourcePath, targetPath, true, result, null);

            Telemetry.TrackEvent("Compiled markdown");

            return(compilerResult);
        }
Ejemplo n.º 16
0
        protected async override Task <CompilerResult> RunCompilerAsync(string sourcePath, string targetPath)
        {
            var cmSettings = new CommonMark.CommonMarkSettings()
            {
                RenderSoftLineBreaksAsLineBreaks = WESettings.Instance.Markdown.RenderSoftLineBreaksAsLineBreaks,
                TrackSourcePosition = WESettings.Instance.Markdown.TrackSourcePosition
            };
            var result = CommonMark.CommonMarkConverter.Convert(await FileHelpers.ReadAllTextRetry(sourcePath), cmSettings);

            if (!string.IsNullOrEmpty(targetPath) &&
                (!File.Exists(targetPath) || await FileHelpers.ReadAllTextRetry(targetPath) != result))
            {
                ProjectHelpers.CheckOutFileFromSourceControl(targetPath);

                await FileHelpers.WriteAllTextRetry(targetPath, result);
            }

            var compilerResult = await CompilerResultFactory.GenerateResult(sourcePath, targetPath, true, result, null);

            return(compilerResult);
        }
Ejemplo n.º 17
0
        protected async override Task <CompilerResult> RunCompilerAsync(string sourcePath, string targetPath)
        {
            Encoding encoding   = _document == null ? null : _document.Encoding;
            var      sourceText = await FileHelpers.ReadAllTextRetry(sourcePath, encoding);

            var settings = new CommonMark.CommonMarkSettings
            {
                OutputFormat = CommonMark.OutputFormat.Html
            };
            var result = CommonMark.CommonMarkConverter.Convert(sourceText, settings);

            if (!string.IsNullOrEmpty(targetPath) &&
                (!File.Exists(targetPath) || await FileHelpers.ReadAllTextRetry(targetPath, encoding) != result))
            {
                ProjectHelpers.CheckOutFileFromSourceControl(targetPath);

                await FileHelpers.WriteAllTextRetry(targetPath, result);
            }

            var compilerResult = await CompilerResultFactory.GenerateResult(sourcePath, targetPath, true, result, null);

            return(compilerResult);
        }
Ejemplo n.º 18
0
        private static string ExportStylesheet(IEnumerable <SpriteFragment> fragments, string imageFile, ExportFormat format)
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine(GetDescription(format));

            foreach (SpriteFragment fragment in fragments)
            {
                sb.AppendLine(GetSelector(fragment.FileName, format) + " {");
                sb.AppendLine("/* You may have to set 'display: block' */");
                sb.AppendLine("\twidth: " + fragment.Width + "px;");
                sb.AppendLine("\theight: " + fragment.Height + "px;");
                sb.AppendLine("\tbackground: url('" + Path.GetFileName(imageFile) + "') -" + fragment.X + "px -" + fragment.Y + "px;");
                sb.AppendLine("}");
            }

            string outputFile = GetFileName(imageFile, format);

            ProjectHelpers.CheckOutFileFromSourceControl(outputFile);
            File.WriteAllText(outputFile, sb.ToString().Replace("-0px", "0"), Encoding.UTF8);

            return(outputFile);
        }
Ejemplo n.º 19
0
 ///<summary>Saves the current settings to the specified settings file.</summary>
 private static void Save(string filename)
 {
     ProjectHelpers.CheckOutFileFromSourceControl(filename);
     WESettings.Instance.WriteJsonFile(filename);
     UpdateStatusBar("updated");
 }