Exemplo n.º 1
0
        public static async Task <String> TryGetHighlightedCodeAsync([NotNull] String code, [NotNull] String path,
                                                                     SyntaxHighlightStyle style, bool lineNumbers, CancellationToken token)
        {
            // Check if the code is possibly invalid
            const int threshold = 50, length = 1000;

            if (code.Substring(0, length > code.Length ? code.Length : length).Count(
                    c => char.IsControl(c) && c != '\n' && c != '\r' && c != '\t') > threshold)
            {
                return(null);
            }

            // Try to extract the code language
            Match match = Regex.Match(path, @".*([.]\w+)");

            if (!match.Success || match.Groups.Count != 2)
            {
                return(null);
            }
            String
                extension = match.Groups[1].Value.ToLowerInvariant(),
                lexer     = UncommonExtensions.ContainsKey(extension)
                    ? UncommonExtensions[extension]
                    : extension.Substring(1); // Remove the leading '.'

            // Prepare the POST request content
            Dictionary <String, String> values = new Dictionary <String, String>
            {
                { "code", code },                                                                         // The code to highlight
                { "lexer", lexer },                                                                       // The code language
                { "style", style.ToString().ToLowerInvariant() },                                         // The requested syntax highlight style
                { "divstyles", "border:solid gray;border-width:.0em .0em .0em .0em;padding:.2em .6em;" }, // Default CSS properties
                { "linenos", lineNumbers ? "pls" : String.Empty } // Includes the line numbers if not empty
            };

            // Make the POST
            WrappedHTTPWebResult <String> result = await HTTPHelper.POSTWithCacheSupportAsync(APIUrl, values, token);

            // Check if the lexer is unsupported
            if (result.StatusCode == HttpStatusCode.InternalServerError)
            {
#if DEBUG
                //For debugging, inform if an unsupported extesion is found
                System.Diagnostics.Debug.WriteLine($"Possible unsupported extension: {extension} > {lexer}");
#endif
                // Retry with the fallback lexer
                values["lexer"] = FallbackLexer;
                return((await HTTPHelper.POSTWithCacheSupportAsync(APIUrl, values, token)).Result);
            }

            // Return the result
            return(result.Result);
        }
Exemplo n.º 2
0
        public async Task Load(Tuple <Repository, string, string> repoPath)  //This page recieves RepositoryId and name of the file
        {
            IsSupportedFile = true;
            Repository      = repoPath.Item1;
            Path            = repoPath.Item2;

            if (!GlobalHelper.IsInternet())
            {
                //Sending NoInternet message to all viewModels
                Messenger.Default.Send(new GlobalHelper.LocalNotificationMessageType {
                    Message = "No Internet", Glyph = "\uE704"
                });
            }
            else
            {
                isLoading = true;

                if (string.IsNullOrWhiteSpace(repoPath.Item3))
                {
                    SelectedBranch = await RepositoryUtility.GetDefaultBranch(Repository.Id);
                }
                else
                {
                    SelectedBranch = repoPath.Item3;
                }

                IsImage = false;

                if ((Path.ToLower().EndsWith(".exe")) ||
                    (Path.ToLower().EndsWith(".pdf")) ||
                    (Path.ToLower().EndsWith(".ttf")) ||
                    (Path.ToLower().EndsWith(".suo")) ||
                    (Path.ToLower().EndsWith(".mp3")) ||
                    (Path.ToLower().EndsWith(".mp4")) ||
                    (Path.ToLower().EndsWith(".avi")))
                {
                    /*
                     * Unsupported file types
                     */
                    IsSupportedFile = false;
                    isLoading       = false;
                    return;
                }
                if ((Path.ToLower()).EndsWith(".png") ||
                    (Path.ToLower()).EndsWith(".jpg") ||
                    (Path.ToLower()).EndsWith(".jpeg") ||
                    (Path.ToLower().EndsWith(".gif")))
                {
                    /*
                     * Image file types
                     */

                    IsImage = true;

                    Uri uri = (await RepositoryUtility.GetRepositoryContentByPath(Repository, Path, SelectedBranch))[0].Content.DownloadUrl;
                    ImageFile = new BitmapImage(uri);
                    isLoading = false;
                    return;
                }
                if ((Path.ToLower()).EndsWith(".md"))
                {
                    /*
                     *  Files with .md extension
                     */

                    TextContent = (await RepositoryUtility.GetRepositoryContentByPath(Repository, Path, SelectedBranch))[0].Content.Content;
                    isLoading   = false;
                    return;
                }

                /*
                 *  Code files
                 */

                String content = (await RepositoryUtility.GetRepositoryContentByPath(Repository, Path, SelectedBranch))?[0].Content.Content;
                if (content == null)
                {
                    IsSupportedFile = false;
                    isLoading       = false;
                    return;
                }
                SyntaxHighlightStyle style = (SyntaxHighlightStyle)SettingsService.Get <int>(SettingsKeys.HighlightStyleIndex);
                bool lineNumbers           = SettingsService.Get <bool>(SettingsKeys.ShowLineNumbers);
                HTMLContent = await HiliteAPI.TryGetHighlightedCodeAsync(content, Path, style, lineNumbers, CancellationToken.None);

                if (HTMLContent == null)
                {
                    /*
                     *  Plain text files (Getting HTML for syntax highlighting failed)
                     */

                    RepositoryContent result = await RepositoryUtility.GetRepositoryContentTextByPath(Repository, Path, SelectedBranch);

                    TextContent = result.Content;
                }

                if (HTMLContent == null && TextContent == null)
                {
                    IsSupportedFile = false;
                }

                isLoading = false;
            }
        }
        private static async void OnHighlightStylePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            // Unpack the parameters and lock the UI
            Hilite_meHighlightStylePreviewControl @this = d.To <Hilite_meHighlightStylePreviewControl>();
            await @this.AnimationSemaphore.WaitAsync();

            SyntaxHighlightStyle style = e.NewValue.To <SyntaxHighlightStyle>();

            // Check if there's a background transition
            HighlightTransitionType transition = HighlightTransitionType.None;

            if (e.OldValue != DependencyProperty.UnsetValue && e.OldValue != null)
            {
                SyntaxHighlightStyle old = e.OldValue.To <SyntaxHighlightStyle>();
                if (LightStyles.Contains(style) && !LightStyles.Contains(old))
                {
                    // Dark to light transition needed
                    transition = HighlightTransitionType.DarkToLight;
                }
                else if (!LightStyles.Contains(style) && LightStyles.Contains(old))
                {
                    // Light to dark transition
                    transition = HighlightTransitionType.LightToDark;
                }
            }
            else
            {
                bool light = LightStyles.Contains(style);
                @this.FadeCanvas.Background             = new SolidColorBrush(light ? Colors.White : Colors.Black);
                @this.WebControl.DefaultBackgroundColor = light ? Colors.White : Colors.Black;
            }

            // Function to load the sample HTML
            Task <String> htmlTask = @this.LoadHTMLPreviewAsync();

            // Await the out animations and the HTML loading
            List <Task> outTasks = new List <Task>
            {
                @this.BlurAsync(20, TimeSpan.FromMilliseconds(AnimationDuration)),
                htmlTask
            };

            if (transition != HighlightTransitionType.None)
            {
                @this.FadeCanvas.Background = new SolidColorBrush(transition == HighlightTransitionType.LightToDark ? Colors.Black : Colors.White);
                outTasks.Add(
                    @this.WebControl.StartCompositionFadeScaleAnimationAsync(1, 0.4f, 1, 1.05f, AnimationDuration, null, null, EasingFunctionNames.Linear));
            }
            else
            {
                outTasks.Add(
                    @this.WebControl.StartCompositionScaleAnimationAsync(1, 1.05f, AnimationDuration, null, EasingFunctionNames.Linear));
            }
            await Task.WhenAll(outTasks);

            // Show the HTML, animate back in and then release the semaphore
            @this.WebControl.SetVisualOpacity(1);
            @this.WebControl.NavigateToString(htmlTask.Result);
            await Task.WhenAll(
                @this.WebControl.StartCompositionScaleAnimationAsync(1.05f, 1, AnimationDuration, null, EasingFunctionNames.Linear),
                @this.BlurAsync(0, TimeSpan.FromMilliseconds(AnimationDuration)));

            if (@this.LoadingRing.Visibility == Visibility.Visible)
            {
                @this.LoadingRing.Visibility = Visibility.Collapsed;
            }
            @this.AnimationSemaphore.Release();
        }
Exemplo n.º 4
0
        public async Task Load(Tuple <Repository, string, string> repoPath)  //This page recieves RepositoryId and name of the file
        {
            IsSupportedFile = true;
            Repository      = repoPath.Item1;
            Path            = repoPath.Item2;

            if (string.IsNullOrWhiteSpace(repoPath.Item3))
            {
                SelectedBranch = await RepositoryUtility.GetDefaultBranch(Repository.Id);
            }
            else
            {
                SelectedBranch = repoPath.Item3;
            }


            MarkdownOptions options = new MarkdownOptions
            {
                AsteriskIntraWordEmphasis = true,
                AutoNewlines     = true,
                StrictBoldItalic = true,
                AutoHyperlink    = false,
                LinkEmails       = true
            };
            Markdown markDown = new Markdown(options);

            if (!GlobalHelper.IsInternet())
            {
                Messenger.Default.Send(new GlobalHelper.NoInternetMessageType()); //Sending NoInternet message to all viewModels
            }
            else
            {
                Messenger.Default.Send(new GlobalHelper.HasInternetMessageType()); //Sending Internet available message to all viewModels
                isLoading = true;
                IsImage   = false;

                if ((Path.ToLower().EndsWith(".exe")) ||
                    (Path.ToLower().EndsWith(".pdf")) ||
                    (Path.ToLower().EndsWith(".ttf")) ||
                    (Path.ToLower().EndsWith(".suo")) ||
                    (Path.ToLower().EndsWith(".mp3")) ||
                    (Path.ToLower().EndsWith(".mp4")) ||
                    (Path.ToLower().EndsWith(".avi")))
                {
                    /*
                     * Unsupported file types
                     */
                    IsSupportedFile = false;
                    isLoading       = false;
                    return;
                }
                if ((Path.ToLower()).EndsWith(".png") ||
                    (Path.ToLower()).EndsWith(".jpg") ||
                    (Path.ToLower()).EndsWith(".jpeg") ||
                    (Path.ToLower().EndsWith(".gif")))
                {
                    /*
                     * Image file types
                     */

                    IsImage = true;
                    // TODO: loading the WHOLE files list is really necessary here?
                    var uri = (await RepositoryUtility.GetRepositoryContentByPath(Repository, Path, SelectedBranch))[0].Content.DownloadUrl;
                    ImageFile = new BitmapImage(uri);
                    isLoading = false;
                    return;
                }
                if ((Path.ToLower()).EndsWith(".md"))
                {
                    /*
                     *  Files with .md extension will be shown with full markdown
                     */
                    HTMLBackgroundColor = Colors.White;
                    var str = (await RepositoryUtility.GetRepositoryContentByPath(Repository, Path, SelectedBranch))[0].Content.Content;
                    HTMLContent = "<html><head><meta charset = \"utf-8\" /></head><body style=\"font-family: sans-serif\">" + markDown.Transform(str) + "</body></html>";
                    isLoading   = false;
                    return;
                }

                String content = (await RepositoryUtility.GetRepositoryContentByPath(Repository, Path, SelectedBranch))?[0].Content.Content;
                if (content == null)
                {
                    IsSupportedFile = false;
                    isLoading       = false;
                    return;
                }
                SyntaxHighlightStyle style = (SyntaxHighlightStyle)SettingsService.Get <int>(SettingsKeys.HighlightStyleIndex);
                bool lineNumbers           = SettingsService.Get <bool>(SettingsKeys.ShowLineNumbers);
                HTMLContent = await HiliteAPI.TryGetHighlightedCodeAsync(content, Path, style, lineNumbers, CancellationToken.None);

                IsSupportedFile = HTMLContent != null;
                isLoading       = false;
            }
        }