/// <summary>
        /// Captures an image to file
        /// </summary>
        /// <returns></returns>
        public string CaptureImageToFile()
        {
            var OldState = WindowState.Minimized;

            if (ActiveForm != null)
            {
                OldState = ActiveForm.WindowState;
                ActiveForm.WindowState = WindowState.Minimized;
            }

            object snagIt = SnagItCom;

            try
            {
                ReflectionUtils.SetPropertyCom(snagIt, "Input", CaptureMode);
            }
            catch
            {
                SetError("SnagIt isn't installed - COM Access failed.\r\nPlease install SnagIt from Techsmith Corporation (www.techsmith.com\\snagit).");
                return(null);
            }

            ReflectionUtils.SetPropertyCom(snagIt, "Input", CaptureMode);
            ReflectionUtils.SetPropertyCom(snagIt, "Output", 2);           // file
            ReflectionUtils.SetPropertyCom(snagIt, "EnablePreviewWindow", ShowPreviewWindow);

            ReflectionUtils.SetPropertyExCom(snagIt, "OutputImageFile.Directory", CapturePath);
            ReflectionUtils.SetPropertyExCom(snagIt, "OutputImageFile.Filename", OutputCaptureFile);
            ReflectionUtils.SetPropertyExCom(snagIt, "OutputImageFile.Quality", 86); //86% quality
            int type = (int)OutputFileCaptureFormat;

            ReflectionUtils.SetPropertyExCom(snagIt, "OutputImageFile.FileType", type);
            ReflectionUtils.SetPropertyExCom(snagIt, "OutputImageFile.ColorDepth", ColorDepth);

            ReflectionUtils.SetPropertyCom(snagIt, "IncludeCursor", IncludeCursor);

            if (DelayInSeconds > 0)
            {
                ReflectionUtils.SetPropertyExCom(snagIt, "DelayOptions.EnableDelayedCapture", true);
                ReflectionUtils.SetPropertyExCom(snagIt, "DelayOptions.DelaySeconds", DelayInSeconds);
            }


            if (ActiveForm != null)
            {
                // *** Need to delay a little here so that the form has properly minimized first
                // *** especially under Vista/Win7
                for (int i = 0; i < 20; i++)
                {
                    WindowUtilities.DoEvents();
                    Thread.Sleep(5);
                }
            }

            // Works but doesn't really add anything. Won't work in .NET Core due to dynamic not working with COM
            //((dynamic) snagIt).OnStateChange += new Action<CaptureState>(SnagImg_OnStateChange);

            try
            {
                IsDone = false;
                ReflectionUtils.CallMethodCom(snagIt, "Capture");

                while (!IsDone && !HasError)
                {
                    IsDone = (bool)ReflectionUtils.GetPropertyCom(snagIt, "IsCaptureDone");
                    if (IsDone)
                    {
                        break;
                    }

                    WindowUtilities.DoEvents();
                    Thread.Sleep(5);
                }
            }
            catch (Exception ex)
            {
                ErrorMessage = "An error occurred during the image capture: " + ex.Message;
            }
            // *** No catch let it throw
            finally
            {
                if (IsDone)
                {
                    _outputCaptureFile = ReflectionUtils.GetPropertyCom(snagIt, "LastFileWritten") as string;
                }
                else
                {
                    _outputCaptureFile = null;
                    ErrorMessage       = "Image capture failed.";
                }

                if (ActiveForm != null)
                {
                    // Reactivate Editor
                    ActiveForm.WindowState = OldState;

                    // Make sure it pops on top of SnagIt Editors
                    ActiveForm.Topmost = true;
                    WindowUtilities.DoEvents();
                    Thread.Sleep(5);
                    ActiveForm.Topmost = false;
                }

                Marshal.ReleaseComObject(SnagItCom);
            }


            // If deleting the file we'll fire on a new thread and then delay by
            // a few seconds until Writer has picked up the image.
            if ((DeleteImageFromDisk))
            {
                new Timer(
                    (imgFile) =>
                {
                    var image = imgFile as string;
                    if (image == null)
                    {
                        return;
                    }
                    try
                    {
                        File.Delete(image);
                    }
                    catch {}
                }, _outputCaptureFile, 10000, Timeout.Infinite);
            }

            return(OutputCaptureFile);
        }
        private void DropDownButton_Click(object sender, RoutedEventArgs e)
        {
            StatusBar.ShowStatusProgress("Getting Blog listing information from service...");
            WindowUtilities.DoEvents();

            var context = Resources["BlogsContextMenu"] as ContextMenu;

            context.Items.Clear();

            IEnumerable <UserBlog> blogs = null;

            try
            {
                if (Model.ActiveWeblogInfo.Type == WeblogTypes.Medium)
                {
                    var client = new MediumApiClient(Model.ActiveWeblogInfo);
                    blogs = client.GetBlogs();
                    if (blogs == null)
                    {
                        StatusBar.ShowStatusError("Failed to get blog listing: " + client.ErrorMessage);
                    }
                }
                else if (Model.ActiveWeblogInfo.Type == WeblogTypes.MetaWeblogApi ||
                         Model.ActiveWeblogInfo.Type == WeblogTypes.Wordpress)
                {
                    var client = new MetaWebLogWordpressApiClient(Model.ActiveWeblogInfo);
                    blogs = client.GetBlogs();
                    if (blogs == null)
                    {
                        StatusBar.ShowStatusError("Failed to get blog listing: " + client.ErrorMessage);
                    }
                }
            }
            catch (Exception ex)
            {
                StatusBar.ShowStatusError($"Failed to get blogs: {ex.Message}");
                return;
            }

            StatusBar.ShowStatusSuccess("Blogs retrieved.");

            if (blogs == null)
            {
                return;
            }

            string blogId = Model.ActiveWeblogInfo.BlogId as string;

            if (!string.IsNullOrEmpty(blogId) && !blogs.Any(b => blogId == b.BlogId as string))
            {
                context.Items.Add(new MenuItem {
                    Header = blogId, Tag = blogId
                });
            }

            foreach (var blog in blogs)
            {
                var item = new MenuItem()
                {
                    Header = blog.BlogName,
                    Tag    = blog.BlogId,
                };
                item.Click += (s, ea) =>
                {
                    var mitem = s as MenuItem;
                    if (mitem == null)
                    {
                        return;
                    }

                    Model.ActiveWeblogInfo.BlogId = mitem.Tag as string;
                    context.Items.Clear();
                };
                context.Items.Add(item);
            }
        }
Exemple #3
0
        private async void Button_DownloadPosts_Click(object sender, RoutedEventArgs e)
        {
            WeblogInfo weblogInfo = Model.ActiveWeblogInfo;

            var wrapper = new MetaWeblogWrapper(weblogInfo.ApiUrl,
                                                weblogInfo.Username,
                                                weblogInfo.DecryptPassword(weblogInfo.Password),
                                                +weblogInfo.BlogId);


            Model.Configuration.LastWeblogAccessed = weblogInfo.Name;

            Dispatcher.Invoke(() =>
            {
                Model.PostList = new List <Post>();
                SetStatusIcon(FontAwesomeIcon.Download, Colors.Orange, true);
                ShowStatus("Downloading last " + Model.NumberOfPostsToRetrieve + " posts...");
            });

            WindowUtilities.DoEvents();

            List <Post> posts = null;

            try
            {
                bool result = await Task.Run(() =>
                {
                    posts = wrapper.GetRecentPosts(Model.NumberOfPostsToRetrieve).ToList();
                    return(false);
                });
            }
            catch (XmlRpcException ex)
            {
                string message = ex.Message;
                if (message == "Not Found")
                {
                    message = "Invalid Blog API Url:\r\n" + weblogInfo.ApiUrl;
                }
                MessageBox.Show("Unable to download posts:\r\n" + message, mmApp.ApplicationName,
                                MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unable to download posts:\r\n" + ex.Message, mmApp.ApplicationName,
                                MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }


            for (int i = 0; i < posts.Count; i++)
            {
                var post = posts[i];
                post.mt_excerpt = StringUtils.TextAbstract(post.mt_excerpt, 220);
            }

            WindowUtilities.DoEvents();

            Dispatcher.Invoke(() =>
            {
                ShowStatus(posts.Count + " posts downloaded.", 5000);
                SetStatusIcon();
                Model.PostList = posts;
            });
        }
Exemple #4
0
        private static bool DispatchLivePreviewBitmapMessage(ref System.Windows.Forms.Message m, TaskbarWindow taskbarWindow)
        {
            if (m.Msg == (int)TaskbarNativeMethods.WmDwmSendIconicLivePreviewBitmap)
            {
                // Try to get the width/height
                var width  = (int)(((long)m.LParam) >> 16);
                var height = (int)(((long)m.LParam) & (0xFFFF));

                // Default size for the thumbnail
                var realWindowSize = new Size(200, 200);

                if (taskbarWindow.TabbedThumbnail.WindowHandle != IntPtr.Zero)
                {
                    TabbedThumbnailNativeMethods.GetClientSize(taskbarWindow.TabbedThumbnail.WindowHandle, out realWindowSize);
                }
                else if (taskbarWindow.TabbedThumbnail.WindowsControl != null)
                {
                    realWindowSize = new Size(
                        Convert.ToInt32(taskbarWindow.TabbedThumbnail.WindowsControl.RenderSize.Width),
                        Convert.ToInt32(taskbarWindow.TabbedThumbnail.WindowsControl.RenderSize.Height));
                }

                // If we don't have a valid height/width, use the original window's size
                if (width <= 0)
                {
                    width = realWindowSize.Width;
                }
                if (height <= 0)
                {
                    height = realWindowSize.Height;
                }

                // Fire an event to let the user update their bitmap
                // Raise the event
                taskbarWindow.TabbedThumbnail.OnTabbedThumbnailBitmapRequested();

                // capture the bitmap for the given control
                // If the user has already specified us a bitmap to use, use that.
                var hBitmap = taskbarWindow.TabbedThumbnail.CurrentHBitmap == IntPtr.Zero ? GrabBitmap(taskbarWindow, realWindowSize) : taskbarWindow.TabbedThumbnail.CurrentHBitmap;

                // If we have a valid parent window handle,
                // calculate the offset so we can place the "peek" bitmap
                // correctly on the app window
                if (taskbarWindow.TabbedThumbnail.ParentWindowHandle != IntPtr.Zero && taskbarWindow.TabbedThumbnail.WindowHandle != IntPtr.Zero)
                {
                    var offset = new System.Drawing.Point();

                    // if we don't have a offset specified already by the user...
                    if (!taskbarWindow.TabbedThumbnail.PeekOffset.HasValue)
                    {
                        offset = WindowUtilities.GetParentOffsetOfChild(taskbarWindow.TabbedThumbnail.WindowHandle, taskbarWindow.TabbedThumbnail.ParentWindowHandle);
                    }
                    else
                    {
                        offset = new System.Drawing.Point(Convert.ToInt32(taskbarWindow.TabbedThumbnail.PeekOffset.Value.X),
                                                          Convert.ToInt32(taskbarWindow.TabbedThumbnail.PeekOffset.Value.Y));
                    }

                    // Only set the peek bitmap if it's not null.
                    // If it's null (either we didn't get the bitmap or size was 0),
                    // let DWM handle it
                    if (hBitmap != IntPtr.Zero)
                    {
                        if (offset.X >= 0 && offset.Y >= 0)
                        {
                            TabbedThumbnailNativeMethods.SetPeekBitmap(
                                taskbarWindow.WindowToTellTaskbarAbout,
                                hBitmap, offset,
                                taskbarWindow.TabbedThumbnail.DisplayFrameAroundBitmap);
                        }
                    }

                    // If the bitmap we have is not coming from the user (i.e. we created it here),
                    // then make sure we delete it as we don't need it now.
                    if (taskbarWindow.TabbedThumbnail.CurrentHBitmap == IntPtr.Zero)
                    {
                        ShellNativeMethods.DeleteObject(hBitmap);
                    }

                    return(true);
                }
                // Else, we don't have a valid window handle from the user. This is mostly likely because
                // we have a WPF UIElement control. If that's the case, use a different screen capture method
                // and also couple of ways to try to calculate the control's offset w.r.t it's parent.
                else if (taskbarWindow.TabbedThumbnail.ParentWindowHandle != IntPtr.Zero &&
                         taskbarWindow.TabbedThumbnail.WindowsControl != null)
                {
                    System.Windows.Point offset;

                    if (!taskbarWindow.TabbedThumbnail.PeekOffset.HasValue)
                    {
                        // Calculate the offset for a WPF UIElement control
                        // For hidden controls, we can't seem to perform the transform.
                        var objGeneralTransform = taskbarWindow.TabbedThumbnail.WindowsControl.TransformToVisual(taskbarWindow.TabbedThumbnail.WindowsControlParentWindow);
                        offset = objGeneralTransform.Transform(new System.Windows.Point(0, 0));
                    }
                    else
                    {
                        offset = new System.Windows.Point(taskbarWindow.TabbedThumbnail.PeekOffset.Value.X, taskbarWindow.TabbedThumbnail.PeekOffset.Value.Y);
                    }

                    // Only set the peek bitmap if it's not null.
                    // If it's null (either we didn't get the bitmap or size was 0),
                    // let DWM handle it
                    if (hBitmap != IntPtr.Zero)
                    {
                        if (offset.X >= 0 && offset.Y >= 0)
                        {
                            TabbedThumbnailNativeMethods.SetPeekBitmap(
                                taskbarWindow.WindowToTellTaskbarAbout,
                                hBitmap, new System.Drawing.Point((int)offset.X, (int)offset.Y),
                                taskbarWindow.TabbedThumbnail.DisplayFrameAroundBitmap);
                        }
                        else
                        {
                            TabbedThumbnailNativeMethods.SetPeekBitmap(
                                taskbarWindow.WindowToTellTaskbarAbout,
                                hBitmap,
                                taskbarWindow.TabbedThumbnail.DisplayFrameAroundBitmap);
                        }
                    }

                    // If the bitmap we have is not coming from the user (i.e. we created it here),
                    // then make sure we delete it as we don't need it now.
                    if (taskbarWindow.TabbedThumbnail.CurrentHBitmap == IntPtr.Zero)
                    {
                        ShellNativeMethods.DeleteObject(hBitmap);
                    }

                    return(true);
                }
                else
                {
                    // Else (no parent specified), just set the bitmap. It would take over the entire
                    // application window (would work only if you are a MDI app)

                    // Only set the peek bitmap if it's not null.
                    // If it's null (either we didn't get the bitmap or size was 0),
                    // let DWM handle it
                    if (hBitmap != null)
                    {
                        TabbedThumbnailNativeMethods.SetPeekBitmap(taskbarWindow.WindowToTellTaskbarAbout, hBitmap, taskbarWindow.TabbedThumbnail.DisplayFrameAroundBitmap);
                    }

                    // If the bitmap we have is not coming from the user (i.e. we created it here),
                    // then make sure we delete it as we don't need it now.
                    if (taskbarWindow.TabbedThumbnail.CurrentHBitmap == IntPtr.Zero)
                    {
                        ShellNativeMethods.DeleteObject(hBitmap);
                    }

                    return(true);
                }
            }
            return(false);
        }
Exemple #5
0
 public void Dispose()
 {
     manager_.render_windows -= RenderWindow;
     WindowUtilities.ClearLock(this);
     GC.SuppressFinalize(this);
 }
Exemple #6
0
        /// <summary>
        /// Takes action on the selected string in the editor using
        /// predefined commands.
        /// </summary>
        /// <param name="action"></param>
        /// <param name="input"></param>
        /// <param name="style"></param>
        /// <returns></returns>
        public string MarkupMarkdown(string action, string input, string style = null)
        {
            if (string.IsNullOrEmpty(action))
            {
                return(input);
            }

            action = action.ToLower();

            // check for insert actions that don't require a pre selection
            if (string.IsNullOrEmpty(input) && !StringUtils.Inlist(action, new string[] { "image", "href", "code", "emoji" }))
            {
                return(null);
            }

            string html = input;

            if (action == "bold")
            {
                html = "**" + input + "**";
            }
            else if (action == "italic")
            {
                html = "*" + input + "*";
            }
            else if (action == "small")
            {
                html = "<small>" + input + "</small>";
            }
            else if (action == "underline")
            {
                html = "<u>" + input + "</u>";
            }
            else if (action == "strikethrough")
            {
                html = "~~" + input + "~~";
            }
            else if (action == "inlinecode")
            {
                html = "`" + input + "`";
            }
            else if (action == "h1")
            {
                html = "# " + input;
            }
            else if (action == "h2")
            {
                html = "## " + input;
            }
            else if (action == "h3")
            {
                html = "### " + input;
            }
            else if (action == "h4")
            {
                html = "#### " + input;
            }
            else if (action == "h5")
            {
                html = "##### " + input;
            }

            else if (action == "quote")
            {
                StringBuilder sb    = new StringBuilder();
                var           lines = StringUtils.GetLines(input);
                foreach (var line in lines)
                {
                    sb.AppendLine("> " + line);
                }
                html = sb.ToString();
            }
            else if (action == "list")
            {
                StringBuilder sb    = new StringBuilder();
                var           lines = StringUtils.GetLines(input);
                foreach (var line in lines)
                {
                    sb.AppendLine("* " + line);
                }
                html = sb.ToString();
            }
            else if (action == "numberlist")
            {
                StringBuilder sb    = new StringBuilder();
                var           lines = StringUtils.GetLines(input);
                int           ct    = 0;
                foreach (var line in lines)
                {
                    ct++;
                    sb.AppendLine($"{ct}. " + line);
                }
                html = sb.ToString();
            }
            else if (action == "emoji")
            {
                var form = new EmojiWindow();
                form.Owner = Window;
                form.ShowDialog();

                if (form.Cancelled)
                {
                    return(input);
                }

                html = form.EmojiString;
            }
            else if (action == "href")
            {
                var form = new PasteHref()
                {
                    Owner        = Window,
                    LinkText     = input,
                    MarkdownFile = MarkdownDocument.Filename
                };

                // check for links in input or on clipboard
                string link = input;
                if (string.IsNullOrEmpty(link))
                {
                    link = Clipboard.GetText();
                }

                if (!(input.StartsWith("http:") || input.StartsWith("https:") || input.StartsWith("mailto:") || input.StartsWith("ftp:")))
                {
                    link = string.Empty;
                }
                form.Link = link;

                bool?res = form.ShowDialog();
                if (res != null && res.Value)
                {
                    if (form.IsExternal)
                    {
                        html = $"<a href=\"{form.Link}\" target=\"_blank\">{form.LinkText}</a>";
                    }
                    else
                    {
                        html = $"[{form.LinkText}]({form.Link})";
                    }
                }
            }
            else if (action == "image")
            {
                var form = new PasteImageWindow(Window)
                {
                    ImageText    = input,
                    MarkdownFile = MarkdownDocument.Filename
                };


                // check for links in input or on clipboard
                string link = input;
                if (string.IsNullOrEmpty(link))
                {
                    link = Clipboard.GetText();
                }

                if (!(input.StartsWith("http:") || input.StartsWith("https:") || input.StartsWith("mailto:") || input.StartsWith("ftp:")))
                {
                    link = string.Empty;
                }

                if (input.Contains(".png") || input.Contains(".jpg") || input.Contains(".gif"))
                {
                    link = input;
                }

                form.Image = link;

                bool?res = form.ShowDialog();
                if (res != null && res.Value)
                {
                    var image = form.Image;
                    if (!image.StartsWith("data:image/"))
                    {
                        html = $"![{form.ImageText}]({form.Image})";
                    }
                    else
                    {
                        var id = "image_ref_" + DataUtils.GenerateUniqueId();

                        dynamic pos    = AceEditor.getCursorPosition(false);
                        dynamic scroll = AceEditor.getscrolltop(false);

                        // the ID tag
                        html = $"\r\n\r\n[{id}]: {image}\r\n";

                        // set selction position to bottom of document
                        AceEditor.gotoBottom(false);
                        SetSelection(html);

                        // reset the selection point
                        AceEditor.setcursorposition(pos); //pos.column,pos.row);

                        if (scroll != null)
                        {
                            AceEditor.setscrolltop(scroll);
                        }

                        WindowUtilities.DoEvents();
                        html = $"![{form.ImageText}][{id}]";
                    }
                }
            }
            else if (action == "code")
            {
                var form = new PasteCode();
                form.Owner        = Window;
                form.Code         = input;
                form.CodeLanguage = "csharp";
                bool?res = form.ShowDialog();

                if (res != null && res.Value)
                {
                    html = "```" + form.CodeLanguage + "\r\n" +
                           form.Code.Trim() + "\r\n" +
                           "```\r\n";
                }
            }
            else
            {
                // allow addins to handle custom actions
                string addinAction = AddinManager.Current.RaiseOnEditorCommand(action, input);
                if (!string.IsNullOrEmpty(addinAction))
                {
                    html = addinAction;
                }
            }

            return(html);
        }
        /// <summary>
        /// Captures an image to file
        /// </summary>
        /// <returns></returns>
        public string CaptureImageToFile()
        {
            var OldState = WindowState.Minimized;

            if (ActiveForm != null)
            {
                OldState = ActiveForm.WindowState;
                ActiveForm.WindowState = WindowState.Minimized;
            }

            dynamic snagIt = SnagItCom;

            try
            {
                snagIt.OutputImageFile.Directory = CapturePath;
            }
            catch
            {
                SetError("SnagIt isn't installed - COM Access failed.\r\nPlease install SnagIt from Techsmith Corporation (www.techsmith.com\\snagit).");
                return(null);
            }


            snagIt.Input = CaptureMode;
            snagIt.EnablePreviewWindow = ShowPreviewWindow;

            snagIt.OutputImageFile.Filename   = OutputCaptureFile;
            snagIt.OutputImageFile.Quality    = 86; //86% quality
            snagIt.OutputImageFile.FileType   = (int)OutputFileCaptureFormat;
            snagIt.OutputImageFile.ColorDepth = ColorDepth;

            snagIt.IncludeCursor = IncludeCursor;

            if (DelayInSeconds > 0)
            {
                snagIt.DelayOptions.EnableDelayedCapture = true;
                snagIt.DelayOptions.DelaySeconds         = DelayInSeconds;
            }


            if (ActiveForm != null)
            {
                // *** Need to delay a little here so that the form has properly minimized first
                // *** especially under Vista/Win7
                for (int i = 0; i < 20; i++)
                {
                    WindowUtilities.DoEvents();
                    Thread.Sleep(5);
                }
            }

            snagIt.OnStateChange += new Action <CaptureState>(SnagImg_OnStateChange);

            try
            {
                IsDone = false;
                snagIt.Capture();

                while (!IsDone && !HasError)
                {
                    WindowUtilities.DoEvents();
                    Thread.Sleep(20);
                }
            }
            catch (Exception ex)
            {
                ErrorMessage = "An error occurred during the image capture: " + ex.Message;
            }
            // *** No catch let it throw
            finally
            {
                if (IsDone)
                {
                    _outputCaptureFile = snagIt.LastFileWritten;
                }
                else
                {
                    _outputCaptureFile = null;
                    ErrorMessage       = "Image capture failed.";
                }

                if (ActiveForm != null)
                {
                    // Reactivate Editor
                    ActiveForm.WindowState = OldState;

                    // Make sure it pops on top of SnagIt Editors
                    ActiveForm.Topmost = true;
                    WindowUtilities.DoEvents();
                    Thread.Sleep(5);
                    ActiveForm.Topmost = false;
                }

                Marshal.ReleaseComObject(SnagItCom);
            }


            // If deleting the file we'll fire on a new thread and then delay by
            // a few seconds until Writer has picked up the image.
            if ((DeleteImageFromDisk))
            {
                new Timer(
                    (imgFile) =>
                {
                    var image = imgFile as string;
                    if (image == null)
                    {
                        return;
                    }
                    try
                    {
                        File.Delete(image);
                    }
                    catch {}
                }, _outputCaptureFile, 10000, Timeout.Infinite);
            }

            return(OutputCaptureFile);
        }
        private void SettingsButton_Click(object sender, RoutedEventArgs e)
        {
            WindowUtilities.OpenOrActivateWindow <SettingsWindow>();

            this.Close();
        }
 private void TryFullscreen_Click(object sender, RoutedEventArgs e)
 {
     WindowUtilities.LaunchFullScreenGrab(true);
 }
Exemple #10
0
 private void CancelMenuItem_Click(object sender, RoutedEventArgs e)
 {
     WindowUtilities.CloseAllFullscreenGrabs();
 }
Exemple #11
0
        private async void RegionClickCanvas_MouseUp(object sender, MouseButtonEventArgs e)
        {
            if (isSelecting == false)
            {
                return;
            }

            isSelecting = false;
            CursorClipper.UnClipCursor();
            RegionClickCanvas.ReleaseMouseCapture();
            Matrix m = PresentationSource.FromVisual(this).CompositionTarget.TransformToDevice;

            System.Windows.Point mPt         = GetMousePos();
            System.Windows.Point movingPoint = e.GetPosition(this);
            movingPoint.X *= m.M11;
            movingPoint.Y *= m.M22;

            movingPoint.X = Math.Round(movingPoint.X);
            movingPoint.Y = Math.Round(movingPoint.Y);

            if (mPt == movingPoint)
            {
                Debug.WriteLine("Probably on Screen 1");
            }

            double correctedLeft = Left;
            double correctedTop  = Top;

            if (correctedLeft < 0)
            {
                correctedLeft = 0;
            }

            if (correctedTop < 0)
            {
                correctedTop = 0;
            }

            double xDimScaled = Canvas.GetLeft(selectBorder) * m.M11;
            double yDimScaled = Canvas.GetTop(selectBorder) * m.M22;

            Rectangle regionScaled = new Rectangle(
                (int)xDimScaled,
                (int)yDimScaled,
                (int)(selectBorder.Width * m.M11),
                (int)(selectBorder.Height * m.M22));

            string grabbedText = "";

            try { RegionClickCanvas.Children.Remove(selectBorder); } catch { }

            if (regionScaled.Width < 3 || regionScaled.Height < 3)
            {
                BackgroundBrush.Opacity = 0;
                grabbedText             = await ImageMethods.GetClickedWord(this, new System.Windows.Point(xDimScaled, yDimScaled));
            }
            else
            {
                grabbedText = await ImageMethods.GetRegionsText(this, regionScaled);
            }

            if (Settings.Default.CorrectErrors)
            {
                grabbedText.TryFixEveryWordLetterNumberErrors();
            }

            if (SingleLineMenuItem.IsChecked == true)
            {
                grabbedText = grabbedText.MakeStringSingleLine();
            }

            if (string.IsNullOrWhiteSpace(grabbedText) == false)
            {
                textFromOCR = grabbedText;

                if (Settings.Default.NeverAutoUseClipboard == false &&
                    EditWindow is null)
                {
                    Clipboard.SetText(grabbedText);
                }

                if (Settings.Default.ShowToast &&
                    EditWindow is null)
                {
                    NotificationUtilities.ShowToast(grabbedText);
                }

                if (EditWindow is not null)
                {
                    EditWindow.AddThisText(grabbedText);
                }

                WindowUtilities.CloseAllFullscreenGrabs();
            }
            else
            {
                BackgroundBrush.Opacity = .2;
                clippingGeometry.Rect   = new Rect(
                    new System.Windows.Point(0, 0),
                    new System.Windows.Size(0, 0));
            }
        }
Exemple #12
0
 private void NewEditTextMenuItem_Click(object sender, RoutedEventArgs e)
 {
     WindowUtilities.OpenOrActivateWindow <EditTextWindow>();
     WindowUtilities.CloseAllFullscreenGrabs();
 }
Exemple #13
0
 private void SettingsMenuItem_Click(object sender, RoutedEventArgs e)
 {
     WindowUtilities.OpenOrActivateWindow <SettingsWindow>();
     WindowUtilities.CloseAllFullscreenGrabs();
 }
Exemple #14
0
 protected override Window CreateShell() => WindowUtilities.CreateShell <MainWindow, MainWindowViewModel>(Container);
Exemple #15
0
        void appStartup(object sender, StartupEventArgs e)
        {
            NumberOfRunningInstances = Process.GetProcessesByName("Text-Grab").Length;

            // Register COM server and activator type
            bool handledArgument = false;

            ToastNotificationManagerCompat.OnActivated += toastArgs =>
            {
                string argsInvoked = toastArgs.Argument;
                // Need to dispatch to UI thread if performing UI operations
                Dispatcher.BeginInvoke((Action)(() =>
                {
                    if (String.IsNullOrWhiteSpace(argsInvoked) == false)
                    {
                        EditTextWindow mtw = new EditTextWindow(argsInvoked);
                        mtw.Show();
                        handledArgument = true;
                    }
                }));
            };

            if (Settings.Default.RunInTheBackground == true &&
                NumberOfRunningInstances < 2)
            {
                NotifyIconUtilities.SetupNotifyIcon();
            }

            Current.DispatcherUnhandledException += CurrentDispatcherUnhandledException;

            for (int i = 0; i != e.Args.Length && !handledArgument; ++i)
            {
                Debug.WriteLine($"ARG {i}:{e.Args[i]}");
                if (e.Args[i].Contains("ToastActivated"))
                {
                    Debug.WriteLine("Launched from toast");
                    handledArgument = true;
                }
                else if (e.Args[i] == "Settings")
                {
                    SettingsWindow sw = new SettingsWindow();
                    sw.Show();
                    handledArgument = true;
                }
                else if (e.Args[i] == "GrabFrame")
                {
                    GrabFrame gf = new GrabFrame();
                    gf.Show();
                    handledArgument = true;
                }
                else if (e.Args[i] == "Fullscreen")
                {
                    WindowUtilities.LaunchFullScreenGrab();
                    handledArgument = true;
                }
                else if (e.Args[i] == "EditText")
                {
                    EditTextWindow manipulateTextWindow = new EditTextWindow();
                    manipulateTextWindow.Show();
                    handledArgument = true;
                }
                else if (File.Exists(e.Args[i]))
                {
                    EditTextWindow manipulateTextWindow = new EditTextWindow();
                    manipulateTextWindow.OpenThisPath(e.Args[i]);
                    manipulateTextWindow.Show();
                    handledArgument = true;
                }
            }

            if (!handledArgument)
            {
                if (Settings.Default.FirstRun)
                {
                    FirstRunWindow frw = new FirstRunWindow();
                    frw.Show();

                    Settings.Default.FirstRun = false;
                    Settings.Default.Save();
                }
                else
                {
                    switch (Settings.Default.DefaultLaunch)
                    {
                    case "Fullscreen":
                        WindowUtilities.LaunchFullScreenGrab();
                        break;

                    case "GrabFrame":
                        GrabFrame gf = new GrabFrame();
                        gf.Show();
                        break;

                    case "EditText":
                        EditTextWindow manipulateTextWindow = new EditTextWindow();
                        manipulateTextWindow.Show();
                        break;

                    default:
                        EditTextWindow editTextWindow = new EditTextWindow();
                        editTextWindow.Show();
                        break;
                    }
                }
            }
        }
 private void TryGrabFrame_Click(object sender, RoutedEventArgs e)
 {
     WindowUtilities.OpenOrActivateWindow <GrabFrame>();
 }
Exemple #17
0
        public string EditorSelectionOperation(string action, string text)
        {
            if (action == "image")
            {
                string label = StringUtils.ExtractString(text, "![", "]");
                string link  = StringUtils.ExtractString(text, "](", ")");

                var form = new PasteImageWindow(Window)
                {
                    Image     = link,
                    ImageText = label
                };
                form.SetImagePreview();

                bool?  res  = form.ShowDialog();
                string html = null;

                if (res != null && res.Value)
                {
                    var image = form.Image;
                    if (!image.StartsWith("data:image/"))
                    {
                        html = $"![{form.ImageText}]({form.Image})";
                    }
                    else
                    {
                        var id = "image_ref_" + DataUtils.GenerateUniqueId();

                        dynamic pos    = AceEditor.getCursorPosition(false);
                        dynamic scroll = AceEditor.getscrolltop(false);

                        // the ID tag
                        html = $"\r\n\r\n[{id}]: {image}\r\n";

                        // set selction position to bottom of document
                        AceEditor.gotoBottom(false);
                        SetSelection(html);

                        // reset the selection point
                        AceEditor.setcursorposition(pos); //pos.column,pos.row);

                        if (scroll != null)
                        {
                            AceEditor.setscrolltop(scroll);
                        }

                        WindowUtilities.DoEvents();
                        html = $"![{form.ImageText}][{id}]";
                    }

                    if (!string.IsNullOrEmpty(html))
                    {
                        SetSelection(html);
                        PreviewMarkdownCallback();
                    }
                }
            }
            else if (action == "link")
            {
                MessageBox.Show("Link to Edit", text);
            }
            else if (action == "code")
            {
                MessageBox.Show("Link to Edit", text);
            }
            return(null);
        }
 private void TryEditWindow_Click(object sender, RoutedEventArgs e)
 {
     WindowUtilities.OpenOrActivateWindow <EditTextWindow>();
 }
        /// <summary>
        /// Parses each of the images in the document and posts them to the server.
        /// Updates the HTML with the returned Image Urls
        /// </summary>
        /// <param name="html">HTML that contains images</param>
        /// <param name="basePath">image file name</param>
        /// <param name="wrapper">blog wrapper instance that sends</param>
        /// <param name="metaData">metadata containing post info</param>
        /// <returns>update HTML string for the document with updated images</returns>
        private string SendImages(string html, string basePath,
                                  MetaWeblogWrapper wrapper)
        {
            // base folder name for uploads - just the folder name of the image
            var baseName = Path.GetFileName(basePath);

            baseName = FileUtils.SafeFilename(baseName).Replace(" ", "-");

            var doc = new HtmlDocument();

            doc.LoadHtml(html);
            try
            {
                // send up normalized path images as separate media items
                var images = doc.DocumentNode.SelectNodes("//img");
                if (images != null)
                {
                    foreach (HtmlNode img in images)
                    {
                        string imgFile = img.Attributes["src"]?.Value;
                        imgFile = StringUtils.UrlDecode(imgFile);

                        if (imgFile == null)
                        {
                            continue;
                        }

                        if (!imgFile.StartsWith("http://") && !imgFile.StartsWith("https://"))
                        {
                            if (!imgFile.Contains(":\\"))
                            {
                                imgFile = Path.Combine(basePath, imgFile.Replace("/", "\\"));
                            }

                            if (System.IO.File.Exists(imgFile))
                            {
                                var uploadFilename = Path.GetFileName(imgFile);
                                var media          = new MediaObject()
                                {
                                    Type = ImageUtils.GetImageMediaTypeFromFilename(imgFile),
                                    Bits = System.IO.File.ReadAllBytes(imgFile),
                                    Name = baseName + "/" + uploadFilename
                                };
                                var mediaResult = wrapper.NewMediaObject(media);
                                img.Attributes["src"].Value = mediaResult.URL;

                                // use first image as featured image
                                if (!DontInferFeaturedImage)
                                {
                                    if (string.IsNullOrEmpty(FeaturedImageUrl))
                                    {
                                        FeaturedImageUrl = mediaResult.URL;
                                    }
                                    if (string.IsNullOrEmpty(FeatureImageId))
                                    {
                                        FeatureImageId = mediaResult.Id;
                                    }
                                }
                            }
                        }
                        WindowUtilities.DoEvents();
                    }

                    html = doc.DocumentNode.OuterHtml;
                }
            }
            catch (Exception ex)
            {
                ErrorMessage = "Error posting images to Weblog: " + ex.Message;
                return(null);
            }

            return(html);
        }
 private void Window_Closed(object?sender, EventArgs e)
 {
     WindowUtilities.ShouldShutDown();
 }
 public void UpdateWindowTitle()
 {
     WindowTitle = WindowUtilities.GetActiveWindowTitle();
 }
Exemple #22
0
        /// <summary>
        /// Captures a screenshot of the specified window at the specified
        /// bitmap size. <para/>NOTE: This method will not accurately capture controls
        /// that are hidden or obstructed (partially or completely) by another control (e.g. hidden tabs,
        /// or MDI child windows that are obstructed by other child windows/forms).
        /// </summary>
        /// <param name="windowHandle">The window handle.</param>
        /// <param name="bitmapSize">The requested bitmap size.</param>
        /// <returns>A screen capture of the window.</returns>
        public static Bitmap GrabWindowBitmap(IntPtr windowHandle, System.Drawing.Size bitmapSize)
        {
            if (bitmapSize.Height <= 0 || bitmapSize.Width <= 0)
            {
                return(null);
            }

            IntPtr windowDC = IntPtr.Zero;

            try
            {
                windowDC = TabbedThumbnailNativeMethods.GetWindowDC(windowHandle);

                System.Drawing.Size realWindowSize;
                TabbedThumbnailNativeMethods.GetClientSize(windowHandle, out realWindowSize);

                if (realWindowSize == System.Drawing.Size.Empty)
                {
                    realWindowSize = new System.Drawing.Size(200, 200);
                }

                System.Drawing.Size size = (bitmapSize == System.Drawing.Size.Empty) ?
                                           realWindowSize : bitmapSize;

                Bitmap targetBitmap = null;
                try
                {
                    targetBitmap = new Bitmap(size.Width, size.Height);

                    using (Graphics targetGr = Graphics.FromImage(targetBitmap))
                    {
                        IntPtr targetDC  = targetGr.GetHdc();
                        uint   operation = 0x00CC0020 /*SRCCOPY*/;

                        System.Drawing.Size ncArea = WindowUtilities.GetNonClientArea(windowHandle);

                        bool success = TabbedThumbnailNativeMethods.StretchBlt(
                            targetDC, 0, 0, targetBitmap.Width, targetBitmap.Height,
                            windowDC, ncArea.Width, ncArea.Height, realWindowSize.Width,
                            realWindowSize.Height, operation);

                        targetGr.ReleaseHdc(targetDC);

                        if (!success)
                        {
                            return(null);
                        }

                        return(targetBitmap);
                    }
                }
                catch
                {
                    if (targetBitmap != null)
                    {
                        targetBitmap.Dispose();
                    }
                    throw;
                }
            }
            finally
            {
                if (windowDC != IntPtr.Zero)
                {
                    TabbedThumbnailNativeMethods.ReleaseDC(windowHandle, windowDC);
                }
            }
        }
Exemple #23
0
        private void CreateCommands()
        {
            // SAVE COMMAND
            SaveCommand = new CommandBase((s, e) =>
            {
                var tab = Window.TabControl?.SelectedItem as TabItem;
                if (tab == null)
                {
                    return;
                }
                var doc = tab.Tag as MarkdownDocumentEditor;

                if (doc.MarkdownDocument.Filename == "untitled")
                {
                    SaveAsCommand.Execute(tab);
                }
                else if (!doc.SaveDocument())
                {
                    SaveAsCommand.Execute(tab);
                }

                Window.PreviewMarkdown(doc, keepScrollPosition: true);
            }, (s, e) =>
            {
                if (ActiveDocument == null)
                {
                    return(false);
                }

                return(this.ActiveDocument.IsDirty);
            });

            // SAVEAS COMMAND
            SaveAsCommand = new CommandBase((parameter, e) =>
            {
                bool isEncrypted = parameter != null && parameter.ToString() == "Secure";

                var tab = Window.TabControl?.SelectedItem as TabItem;
                if (tab == null)
                {
                    return;
                }
                var doc = tab.Tag as MarkdownDocumentEditor;
                if (doc == null)
                {
                    return;
                }

                var filename = doc.MarkdownDocument.Filename;
                var folder   = Path.GetDirectoryName(doc.MarkdownDocument.Filename);

                if (filename == "untitled")
                {
                    folder = mmApp.Configuration.LastFolder;

                    var match = Regex.Match(doc.GetMarkdown(), @"^# (\ *)(?<Header>.+)", RegexOptions.Multiline);

                    if (match.Success)
                    {
                        filename = match.Groups["Header"].Value;
                        if (!string.IsNullOrEmpty(filename))
                        {
                            filename = mmFileUtils.SafeFilename(filename);
                        }
                    }
                }

                if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder))
                {
                    folder = mmApp.Configuration.LastFolder;
                    if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder))
                    {
                        folder = KnownFolders.GetPath(KnownFolder.Libraries);
                    }
                }


                SaveFileDialog sd = new SaveFileDialog
                {
                    Filter           = "Markdown files (*.md)|*.md|Markdown files (*.markdown)|*.markdown|All files (*.*)|*.*",
                    FilterIndex      = 1,
                    InitialDirectory = folder,
                    FileName         = filename,
                    CheckFileExists  = false,
                    OverwritePrompt  = false,
                    CheckPathExists  = true,
                    RestoreDirectory = true
                };

                bool?result = null;
                try
                {
                    result = sd.ShowDialog();
                }
                catch (Exception ex)
                {
                    mmApp.Log("Unable to save file: " + doc.MarkdownDocument.Filename, ex);
                    MessageBox.Show(
                        $@"Unable to open file:\r\n\r\n" + ex.Message,
                        "An error occurred trying to open a file",
                        MessageBoxButton.OK,
                        MessageBoxImage.Error);
                }

                if (!isEncrypted)
                {
                    doc.MarkdownDocument.Password = null;
                }
                else
                {
                    var pwdDialog = new FilePasswordDialog(doc.MarkdownDocument, false)
                    {
                        Owner = Window
                    };
                    bool?pwdResult = pwdDialog.ShowDialog();
                }

                if (result != null && result.Value)
                {
                    doc.MarkdownDocument.Filename = sd.FileName;
                    if (!doc.SaveDocument())
                    {
                        MessageBox.Show(Window, $"{sd.FileName}\r\n\r\nThis document can't be saved in this location. The file is either locked or you don't have permissions to save it. Please choose another location to save the file.",
                                        "Unable to save Document", MessageBoxButton.OK, MessageBoxImage.Warning);
                        SaveAsCommand.Execute(tab);
                        return;
                    }
                }

                mmApp.Configuration.LastFolder = folder;

                Window.SetWindowTitle();
                Window.PreviewMarkdown(doc, keepScrollPosition: true);
            }, (s, e) =>
            {
                if (ActiveDocument == null)
                {
                    return(false);
                }

                return(true);
            });

            // SAVEASHTML COMMAND
            SaveAsHtmlCommand = new CommandBase((s, e) =>
            {
                var tab = Window.TabControl?.SelectedItem as TabItem;
                var doc = tab?.Tag as MarkdownDocumentEditor;
                if (doc == null)
                {
                    return;
                }

                var folder = Path.GetDirectoryName(doc.MarkdownDocument.Filename);

                SaveFileDialog sd = new SaveFileDialog
                {
                    Filter           = "Html files (Html only) (*.html)|*.html|Html files (Html and dependencies in a folder)|*.html",
                    FilterIndex      = 1,
                    InitialDirectory = folder,
                    FileName         = Path.ChangeExtension(doc.MarkdownDocument.Filename, "html"),
                    CheckFileExists  = false,
                    OverwritePrompt  = false,
                    CheckPathExists  = true,
                    RestoreDirectory = true
                };

                bool?result = null;
                try
                {
                    result = sd.ShowDialog();
                }catch (Exception ex)
                {
                    mmApp.Log("Unable to save html file: " + doc.MarkdownDocument.Filename, ex);
                    MessageBox.Show(
                        $@"Unable to open file:\r\n\r\n" + ex.Message,
                        "An error occurred trying to open a file",
                        MessageBoxButton.OK,
                        MessageBoxImage.Error);
                }

                if (result != null && result.Value)
                {
                    if (sd.FilterIndex != 2)
                    {
                        var html = doc.RenderMarkdown(doc.GetMarkdown(), mmApp.Configuration.MarkdownOptions.RenderLinksAsExternal);

                        if (!doc.MarkdownDocument.WriteFile(sd.FileName, html))
                        {
                            MessageBox.Show(Window,
                                            $"{sd.FileName}\r\n\r\nThis document can't be saved in this location. The file is either locked or you don't have permissions to save it. Please choose another location to save the file.",
                                            "Unable to save Document", MessageBoxButton.OK, MessageBoxImage.Warning);
                            SaveAsHtmlCommand.Execute(null);
                            return;
                        }
                    }
                    else
                    {
                        string msg   = @"This feature is not available yet.

For now, you can use 'View in Web Browser' to view the document in your favorite Web Browser and use 'Save As...' to save the Html document with all CSS and Image dependencies.

Do you want to View in Browser now?
";
                        var mbResult = MessageBox.Show(msg,
                                                       mmApp.ApplicationName,
                                                       MessageBoxButton.YesNo,
                                                       MessageBoxImage.Asterisk,
                                                       MessageBoxResult.Yes);

                        if (mbResult == MessageBoxResult.Yes)
                        {
                            Window.Model.ViewInExternalBrowserCommand.Execute(null);
                        }
                    }
                }

                Window.PreviewMarkdown(doc, keepScrollPosition: true);
            }, (s, e) =>
            {
                if (ActiveDocument == null || ActiveEditor == null)
                {
                    return(false);
                }
                if (ActiveDocument.Filename == "untitled")
                {
                    return(true);
                }
                if (ActiveEditor.EditorSyntax != "markdown")
                {
                    return(false);
                }

                return(true);
            });

            // NEW DOCUMENT COMMAND (ctrl-n)
            NewDocumentCommand = new CommandBase((s, e) =>
            {
                Window.OpenTab("untitled");
            });

            // OPEN DOCUMENT COMMAND
            OpenDocumentCommand = new CommandBase((s, e) =>
            {
                var fd = new OpenFileDialog
                {
                    DefaultExt = ".md",
                    Filter     = "Markdown files (*.md,*.markdown)|*.md;*.markdown|" +
                                 "Html files (*.htm,*.html)|*.htm;*.html|" +
                                 "Javascript files (*.js)|*.js|" +
                                 "Typescript files (*.ts)|*.ts|" +
                                 "Json files (*.json)|*.json|" +
                                 "Css files (*.css)|*.css|" +
                                 "Xml files (*.xml,*.config)|*.xml;*.config|" +
                                 "C# files (*.cs)|*.cs|" +
                                 "C# Razor files (*.cshtml)|*.cshtml|" +
                                 "Foxpro files (*.prg)|*.prg|" +
                                 "Powershell files (*.ps1)|*.ps1|" +
                                 "Php files (*.php)|*.php|" +
                                 "Python files (*.py)|*.py|" +
                                 "All files (*.*)|*.*",
                    CheckFileExists  = true,
                    RestoreDirectory = true,
                    Multiselect      = true,
                    Title            = "Open Markdown File"
                };

                if (!string.IsNullOrEmpty(mmApp.Configuration.LastFolder))
                {
                    fd.InitialDirectory = mmApp.Configuration.LastFolder;
                }

                bool?res = null;
                try
                {
                    res = fd.ShowDialog();
                }
                catch (Exception ex)
                {
                    mmApp.Log("Unable to open file.", ex);
                    MessageBox.Show(
                        $@"Unable to open file:\r\n\r\n" + ex.Message,
                        "An error occurred trying to open a file",
                        MessageBoxButton.OK,
                        MessageBoxImage.Error);
                    return;
                }
                if (res == null || !res.Value)
                {
                    return;
                }

                foreach (var file in fd.FileNames)
                {
                    // TODO: Check AddRecentFile and make sure Tab Selection works
                    Window.OpenTab(file, rebindTabHeaders: true);
                    //Window.AddRecentFile(file);
                }
            });

            // CLOSE ACTIVE DOCUMENT COMMAND
            CloseActiveDocumentCommand = new CommandBase((s, e) =>
            {
                var tab = Window.TabControl.SelectedItem as TabItem;
                if (tab == null)
                {
                    return;
                }

                if (Window.CloseTab(tab))
                {
                    Window.TabControl.Items.Remove(tab);
                }
            }, null)
            {
                Caption = "_Close Document",
                ToolTip = "Closes the active tab and asks to save the document."
            };


            // COMMIT TO GIT Command
            CommitToGitCommand = new CommandBase(async(s, e) =>
            {
                string file = ActiveDocument?.Filename;
                if (string.IsNullOrEmpty(file))
                {
                    return;
                }

                Window.ShowStatus("Committing and pushing to Git...");
                WindowUtilities.DoEvents();

                string error = null;

                bool pushToGit = mmApp.Configuration.GitCommitBehavior == GitCommitBehaviors.CommitAndPush;
                bool result    = await Task.Run(() => mmFileUtils.CommitFileToGit(file, pushToGit, out error));

                if (result)
                {
                    Window.ShowStatus($"File {Path.GetFileName(file)} committed and pushed.", 6000);
                }
                else
                {
                    Window.ShowStatus(error, 7000);
                    Window.SetStatusIcon(FontAwesomeIcon.Warning, Colors.Red);
                }
            }, (s, e) => IsEditorActive);


            // PREVIEW BUTTON COMMAND
            PreviewBrowserCommand = new CommandBase((s, e) =>
            {
                var tab = Window.TabControl.SelectedItem as TabItem;
                if (tab == null)
                {
                    return;
                }

                var editor = tab.Tag as MarkdownDocumentEditor;

                Configuration.IsPreviewVisible = IsPreviewBrowserVisible;

                if (!IsPreviewBrowserVisible && IsPresentationMode)
                {
                    PresentationModeCommand.Execute(null);
                }


                Window.ShowPreviewBrowser(!IsPreviewBrowserVisible);
                if (IsPreviewBrowserVisible)
                {
                    Window.PreviewMarkdown(editor);
                }
            }, null);

            // SHOW FILE BROWSER COMMAND
            ShowFolderBrowserCommand = new CommandBase((s, e) =>
            {
                mmApp.Configuration.FolderBrowser.Visible = !mmApp.Configuration.FolderBrowser.Visible;

                mmApp.Model.Window.ShowFolderBrowser(!mmApp.Configuration.FolderBrowser.Visible);
            });

            // WORD WRAP COMMAND
            WordWrapCommand = new CommandBase((parameter, command) =>
            {
                //MessageBox.Show("alt-z WPF");
                mmApp.Model.Configuration.EditorWrapText = !mmApp.Model.Configuration.EditorWrapText;
                mmApp.Model.ActiveEditor?.SetWordWrap(mmApp.Model.Configuration.EditorWrapText);
            }, (p, c) => IsEditorActive);

            // MARKDOWN EDIT COMMANDS TOOLBAR COMMAND
            ToolbarInsertMarkdownCommand = new CommandBase((s, e) =>
            {
                string action = s as string;

                var editor = Window.GetActiveMarkdownEditor();
                editor?.ProcessEditorUpdateCommand(action);
            }, null);

            // Settings
            SettingsCommand = new CommandBase((s, e) =>
            {
                var file = Path.Combine(mmApp.Configuration.CommonFolder, "MarkdownMonster.json");

                // save settings first so we're looking at current setting
                Configuration.Write();

                string fileText = File.ReadAllText(file);
                if (!fileText.StartsWith("//"))
                {
                    fileText = "// Reference: http://markdownmonster.west-wind.com/docs/_4nk01yq6q.htm\r\n" +
                               fileText;
                    File.WriteAllText(file, fileText);
                }

                Window.OpenTab(file, syntax: "json");
            }, null);

            // DISTRACTION FREE MODE
            DistractionFreeModeCommand = new CommandBase((s, e) =>
            {
                GridLength glToolbar = new GridLength(0);
                GridLength glMenu    = new GridLength(0);
                GridLength glStatus  = new GridLength(0);

                GridLength glFileBrowser = new GridLength(0);

                if (Window.ToolbarGridRow.Height == glToolbar)
                {
                    Window.SaveSettings();

                    glToolbar = GridLength.Auto;
                    glMenu    = GridLength.Auto;
                    glStatus  = GridLength.Auto;

                    //mmApp.Configuration.WindowPosition.IsTabHeaderPanelVisible = true;
                    Window.TabControl.IsHeaderPanelVisible = true;

                    IsPreviewBrowserVisible = true;
                    Window.PreviewMarkdown();

                    Window.WindowState = mmApp.Configuration.WindowPosition.WindowState;

                    IsFullScreen = false;

                    Window.ShowFolderBrowser(!mmApp.Configuration.FolderBrowser.Visible);
                }
                else
                {
                    var tokens = mmApp.Configuration.DistractionFreeModeHideOptions.ToLower().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                    if (tokens.All(d => d != "menu"))
                    {
                        glMenu = GridLength.Auto;
                    }

                    if (tokens.All(d => d != "toolbar"))
                    {
                        glToolbar = GridLength.Auto;
                    }

                    if (tokens.All(d => d != "statusbar"))
                    {
                        glStatus = GridLength.Auto;
                    }

                    if (tokens.Any(d => d == "tabs"))
                    {
                        Window.TabControl.IsHeaderPanelVisible = false;
                    }

                    if (tokens.Any(d => d == "preview"))
                    {
                        IsPreviewBrowserVisible = false;
                        Window.ShowPreviewBrowser(hide: true);
                    }

                    mmApp.Configuration.WindowPosition.WindowState = Window.WindowState;
                    if (tokens.Any(d => d == "maximized"))
                    {
                        Window.WindowState = WindowState.Maximized;
                    }

                    Window.ShowFolderBrowser(true);

                    IsFullScreen = true;
                }

                // toolbar
                Window.MainMenuGridRow.Height  = glMenu;
                Window.ToolbarGridRow.Height   = glToolbar;
                Window.StatusBarGridRow.Height = glStatus;
            }, null);

            // PRESENTATION MODE
            PresentationModeCommand = new CommandBase((s, e) =>
            {
                if (IsFullScreen)
                {
                    DistractionFreeModeCommand.Execute(null);
                }

                GridLength gl = new GridLength(0);
                if (Window.WindowGrid.RowDefinitions[1].Height == gl)
                {
                    gl = GridLength.Auto; // toolbar height

                    Window.MainWindowEditorColumn.Width    = new GridLength(1, GridUnitType.Star);
                    Window.MainWindowSeparatorColumn.Width = new GridLength(0);
                    Window.MainWindowPreviewColumn.Width   = new GridLength(mmApp.Configuration.WindowPosition.SplitterPosition);

                    Window.PreviewMarkdown();

                    Window.ShowFolderBrowser(!mmApp.Configuration.FolderBrowser.Visible);

                    IsPresentationMode = false;
                }
                else
                {
                    Window.SaveSettings();

                    mmApp.Configuration.WindowPosition.SplitterPosition =
                        Convert.ToInt32(Window.MainWindowPreviewColumn.Width.Value);

                    // don't allow presentation mode for non-Markdown documents
                    var editor = Window.GetActiveMarkdownEditor();
                    if (editor != null)
                    {
                        var file = editor.MarkdownDocument.Filename.ToLower();
                        var ext  = Path.GetExtension(file);
                        if (file != "untitled" && ext != ".md" && ext != ".htm" && ext != ".html")
                        {
                            // don't allow presentation mode for non markdown files
                            IsPresentationMode      = false;
                            IsPreviewBrowserVisible = false;
                            Window.ShowPreviewBrowser(true);
                            return;
                        }
                    }

                    Window.ShowPreviewBrowser();
                    Window.ShowFolderBrowser(true);

                    Window.MainWindowEditorColumn.Width    = gl;
                    Window.MainWindowSeparatorColumn.Width = gl;
                    Window.MainWindowPreviewColumn.Width   = new GridLength(1, GridUnitType.Star);

                    IsPresentationMode      = true;
                    IsPreviewBrowserVisible = true;
                }

                Window.WindowGrid.RowDefinitions[1].Height = gl;
                //Window.WindowGrid.RowDefinitions[3].Height = gl;
            }, null);

            // EXTERNAL BROWSER VIEW
            ViewInExternalBrowserCommand = new CommandBase((p, e) =>
            {
                if (ActiveDocument == null)
                {
                    return;
                }
                mmFileUtils.ShowExternalBrowser(ActiveDocument.HtmlRenderFilename);
            }, (p, e) => IsPreviewBrowserVisible);

            ViewHtmlSourceCommand = new CommandBase((p, e) =>
            {
                if (ActiveDocument == null)
                {
                    return;
                }
                Window.OpenTab(ActiveDocument.HtmlRenderFilename);
            }, (p, e) => IsPreviewBrowserVisible);


            // PRINT PREVIEW
            PrintPreviewCommand = new CommandBase((s, e) =>
            {
                dynamic dom = Window.PreviewBrowser.Document;
                dom.execCommand("print", true, null);
            }, (s, e) => IsPreviewBrowserVisible);

            // PDF GENERATION PREVIEW
            GeneratePdfCommand = new CommandBase((s, e) =>
            {
                var form = new GeneratePdfWindow()
                {
                    Owner = mmApp.Model.Window
                };
                form.Show();
            }, (s, e) => IsPreviewBrowserVisible);

            // F1 Help Command - Pass option CommandParameter="TopicId"
            HelpCommand = new CommandBase((topicId, e) =>
            {
                string url = mmApp.Urls.DocumentationBaseUrl;

                if (topicId != null)
                {
                    url = mmApp.GetDocumentionUrl(topicId as string);
                }

                ShellUtils.GoUrl(url);
            }, (s, e) => IsPreviewBrowserVisible);
        }
Exemple #24
0
        private void ButtonWindowResize_Click(object sender, RoutedEventArgs e)
        {
            var model = Window.Model;

            var size   = ((MenuItem)sender).Header as string;
            var tokens = size.Split('x');

            Window.Width  = double.Parse(tokens[0].Trim());
            Window.Height = double.Parse(tokens[1].Trim());

            if (model.ActiveEditor?.EditorPreviewPane != null)
            {
                var width = model.ActiveEditor.EditorPreviewPane.ActualWidth;

                if (width < 2000 && width > 800)
                {
                    model.ActiveEditor.EditorPreviewPane.EditorWebBrowserEditorColumn.Width = GridLengthHelper.Star;
                    if (model.Configuration.IsPreviewVisible)
                    {
                        model.ActiveEditor.EditorPreviewPane.EditorWebBrowserPreviewColumn.Width =
                            new GridLength(width * 0.45);
                    }
                }
                else if (width > 2000)
                {
                    Window.ShowLeftSidebar();
                    if (model.ActiveEditor.EditorPreviewPane.EditorWebBrowserPreviewColumn.Width.Value < 750 &&
                        model.Configuration.IsPreviewVisible)
                    {
                        model.ActiveEditor.EditorPreviewPane.EditorWebBrowserPreviewColumn.Width = new GridLength(750);
                    }
                }
                else if (width <= 900)
                {
                    Window.ShowLeftSidebar(hide: true);
                    WindowUtilities.DoEvents();

                    width = model.ActiveEditor.EditorPreviewPane.ActualWidth;
                    model.ActiveEditor.EditorPreviewPane.EditorWebBrowserEditorColumn.Width = GridLengthHelper.Star;
                    if (model.Configuration.IsPreviewVisible)
                    {
                        model.ActiveEditor.EditorPreviewPane.EditorWebBrowserPreviewColumn.Width =
                            new GridLength(width * 0.45);
                    }
                }
            }

            var screen       = Screen.FromHandle(Window.Hwnd);
            var ratio        = (double)WindowUtilities.GetDpiRatio(Window.Hwnd);
            var windowWidth  = screen.Bounds.Width * ratio;
            var windowHeight = screen.Bounds.Height * ratio;

            if (windowWidth < Window.Width || windowHeight < Window.Height)
            {
                Window.Top    = screen.Bounds.Y * ratio;
                Window.Left   = screen.Bounds.X * ratio;
                Window.Width  = windowWidth - 20;
                Window.Height = windowHeight - 40;
            }

            if (windowWidth < Window.Width + Window.Left ||
                windowHeight < Window.Height + Window.Top)
            {
                WindowUtilities.CenterWindow(Window);
            }
        }
        void StartCapture()
        {
            Hide();
            ExternalWindow?.Hide();

            StatusImageSize.Text = "";

            // make sure windows actually hides before we wait
            WindowUtilities.DoEvents();

            // Display counter
            if (CaptureDelaySeconds > 0)
            {
                IsPreviewCapturing = true;
                Cancelled          = false;

                var counterForm = new ScreenOverlayCounter();

                try
                {
                    counterForm.Show();
                    counterForm.Topmost = true;
                    counterForm.SetWindowText("1");

                    for (int i = CaptureDelaySeconds; i > 0; i--)
                    {
                        counterForm.SetWindowText(i.ToString());
                        WindowUtilities.DoEvents();

                        for (int j = 0; j < 100; j++)
                        {
                            Thread.Sleep(10);
                            WindowUtilities.DoEvents();
                        }
                        if (Cancelled)
                        {
                            CancelCapture(true);
                            return;
                        }
                    }
                }
                finally
                {
                    counterForm.Close();
                    IsPreviewCapturing = false;
                    Cancelled          = true;
                }
            }

            IsMouseClickCapturing = true;

            Desktop = new ScreenOverlayDesktop(this);
            Desktop.SetDesktop(IncludeCursor);
            Desktop.Show();

            WindowUtilities.DoEvents();

            Overlay = new ScreenClickOverlay(this)
            {
                Width  = 0,
                Height = 0
            };
            Overlay.Show();

            LastWindow   = null;
            CaptureTimer = new Timer(Capture, null, 0, 200);
        }
Exemple #26
0
        /// <summary>
        /// Creates a context menu.
        /// </summary>
        /// <param name="parms"></param>
        /// <param name="model"></param>
        /// <param name="webBrowser"></param>
        public void ShowContextMenu(PositionAndDocumentType parms, AppModel model, WebBrowser webBrowser)
        {
            var      ctm = new ContextMenu();
            MenuItem mi;

            // Image Selected
            if (!string.IsNullOrEmpty(parms.Src))
            {
                mi = new MenuItem()
                {
                    Header = "Copy Image to Clipboard"
                };
                mi.Click += (o, args) =>
                {
                    string image      = null;
                    bool   deleteFile = false;

                    if (parms.Src.StartsWith("https://") || parms.Src.StartsWith("http://"))
                    {
                        image = HttpUtils.DownloadImageToFile(parms.Src);
                        if (string.IsNullOrEmpty(image))
                        {
                            model.Window.ShowStatusError("Unable to copy image from URL to clipboard: " + parms.Src);
                            return;
                        }
                        deleteFile = true;
                    }
                    else
                    {
                        try
                        {
                            image = new Uri(parms.Src).LocalPath;
                        }
                        catch
                        {
                            image = FileUtils.NormalizePath(parms.Src);
                        }

                        image = mmFileUtils.NormalizeFilenameWithBasePath(image,
                                                                          Path.GetDirectoryName(model.ActiveDocument.Filename));
                    }

                    try
                    {
                        BitmapSource bmpSrc;
                        using (var bmp = new Bitmap(image))
                        {
                            bmpSrc = WindowUtilities.BitmapToBitmapSource(bmp);
                            Clipboard.SetImage(bmpSrc);
                        }

                        model.Window.ShowStatusSuccess("Image copied to clipboard.");
                    }
                    catch (Exception ex)
                    {
                        model.Window.ShowStatusError("Couldn't copy image to clipboard: " + ex.Message);
                    }
                    finally
                    {
                        if (deleteFile && File.Exists(image))
                        {
                            File.Delete(image);
                        }
                    }
                };
                ctm.Items.Add(mi);

                mi = new MenuItem()
                {
                    Header = "Edit Image in Image editor"
                };
                mi.Click += (o, args) =>
                {
                    string image = null;
                    if (parms.Src.StartsWith("https://") || parms.Src.StartsWith("http://"))
                    {
                        image = HttpUtils.DownloadImageToFile(parms.Src);
                        if (string.IsNullOrEmpty(image))
                        {
                            model.Window.ShowStatusError("Unable to copy image from URL to clipboard: " + parms.Src);
                            return;
                        }
                    }
                    else
                    {
                        try
                        {
                            image = new Uri(parms.Src).LocalPath;
                        }
                        catch
                        {
                            image = FileUtils.NormalizePath(parms.Src);
                        }
                        image = mmFileUtils.NormalizeFilenameWithBasePath(image, Path.GetDirectoryName(model.ActiveDocument.Filename));
                    }

                    mmFileUtils.OpenImageInImageEditor(image);
                };
                ctm.Items.Add(mi);

                ctm.Items.Add(new Separator());
            }


            // HREF link selected
            if (!string.IsNullOrEmpty(parms.Href))
            {
                // Navigate relative hash links in the document
                if (parms.Href.StartsWith("#") && parms.Href.Length > 1)
                {
                    var docModel = new DocumentOutlineModel();
                    int lineNo   = docModel.FindHeaderHeadline(model.ActiveEditor?.GetMarkdown(), parms.Href?.Substring(1));
                    if (lineNo > -1)
                    {
                        mi = new MenuItem()
                        {
                            Header = "Jump to: " + parms.Href, CommandParameter = parms.Href.Substring(1)
                        };
                        mi.Click += (s, e) =>
                        {
                            var mitem = s as MenuItem;

                            var anchor = mitem.CommandParameter as string;
                            if (string.IsNullOrEmpty(anchor))
                            {
                                return;
                            }

                            docModel = new DocumentOutlineModel();
                            lineNo   = docModel.FindHeaderHeadline(model.ActiveEditor?.GetMarkdown(), anchor);

                            if (lineNo != -1)
                            {
                                model.ActiveEditor.GotoLine(lineNo);
                            }
                        };
                        ctm.Items.Add(mi);

                        ctm.Items.Add(new Separator());
                    }
                }
            }

            // ID to clipboard
            if (!string.IsNullOrEmpty(parms.Id))
            {
                mi = new MenuItem()
                {
                    Header = "Copy Id to Clipboard: #" + parms.Id,
                };
                mi.Click += (s, e) =>
                {
                    ClipboardHelper.SetText("#" + parms.Id);
                    model.Window.ShowStatusSuccess("'#" + parms.Id + "' copied to the clipboard.");
                };
                ctm.Items.Add(mi);

                ctm.Items.Add(new Separator());
            }


            mi = new MenuItem()
            {
                Header           = "View in Web _Browser",
                Command          = model.Commands.ViewInExternalBrowserCommand,
                InputGestureText = model.Commands.ViewInExternalBrowserCommand.KeyboardShortcut
            };
            ctm.Items.Add(mi);

            mi = new MenuItem()
            {
                Header           = "Refresh _Browser",
                Command          = model.Commands.RefreshPreviewCommand,
                InputGestureText = "F5"
            };
            ctm.Items.Add(mi);

            mi = new MenuItem()
            {
                Header  = "View Html _Source",
                Command = model.Commands.ViewHtmlSourceCommand
            };
            ctm.Items.Add(mi);

            ctm.Items.Add(new Separator());


            mi = new MenuItem()
            {
                Header  = "Save As _Html",
                Command = model.Commands.SaveAsHtmlCommand,
            };
            ctm.Items.Add(mi);

            mi = new MenuItem()
            {
                Header  = "Save As _PDF",
                Command = model.Commands.GeneratePdfCommand,
            };
            ctm.Items.Add(mi);

            mi = new MenuItem()
            {
                Header  = "P_rint...",
                Command = model.Commands.PrintPreviewCommand,
            };
            ctm.Items.Add(mi);

            ctm.Items.Add(new Separator());

            mi = new MenuItem()
            {
                Header  = "Edit Preview _Theme",
                Command = model.Commands.EditPreviewThemeCommand,
            };
            ctm.Items.Add(mi);

            mi = new MenuItem()
            {
                Header  = "Configure Preview Syncing",
                Command = model.Commands.PreviewSyncModeCommand,
            };
            ctm.Items.Add(mi);

            ctm.Items.Add(new Separator());


            mi = new MenuItem()
            {
                Header           = "Toggle Preview Window",
                Command          = model.Commands.TogglePreviewBrowserCommand,
                IsCheckable      = true,
                InputGestureText = model.Commands.TogglePreviewBrowserCommand.KeyboardShortcut,
                IsChecked        = model.IsPreviewBrowserVisible
            };
            ctm.Items.Add(mi);

            webBrowser.ContextMenu = ctm;

            ContextMenuOpening?.Invoke(this, ctm);

            ctm.Placement       = System.Windows.Controls.Primitives.PlacementMode.MousePoint;
            ctm.PlacementTarget = webBrowser;
            ctm.IsOpen          = true;
        }
        /// <summary>
        /// Parses each of the images in the document and posts them to the server.
        /// Updates the HTML with the returned Image Urls
        /// </summary>
        /// <param name="html">HTML that contains images</param>
        /// <param name="basePath">image file name</param>
        /// <param name="wrapper">blog wrapper instance that sends</param>
        /// <param name="metaData">metadata containing post info</param>
        /// <param name="imgFileMapping">mapping of filename with hash to NewMediaObject</param>
        /// <returns>update HTML string for the document with updated images</returns>
        private string SendImages(string html, string basePath,
                                  MetaWeblogWrapper wrapper, Dictionary <string, MediaObjectInfo> imgFileMapping)
        {
            // base folder name for uploads - just the folder name of the image
            var baseName = Path.GetFileName(basePath);

            baseName = FileUtils.SafeFilename(baseName).Replace(" ", "-");

            var doc = new HtmlDocument();

            doc.LoadHtml(html);
            try
            {
                // send up normalized path images as separate media items
                var images = doc.DocumentNode.SelectNodes("//img");
                if (images != null)
                {
                    foreach (HtmlNode img in images)
                    {
                        string origImageLink = img.Attributes["src"]?.Value;
                        string imgFile       = StringUtils.UrlDecode(origImageLink);

                        if (imgFile == null)
                        {
                            continue;
                        }

                        if (!imgFile.StartsWith("http://") && !imgFile.StartsWith("https://"))
                        {
                            if (!imgFile.Contains(":\\"))
                            {
                                imgFile = Path.Combine(basePath, imgFile.Replace("/", "\\"));
                            }


                            if (System.IO.File.Exists(imgFile))
                            {
                                var uploadFilename = Path.GetFileName(imgFile);
                                var media          = new MediaObject()
                                {
                                    Type = ImageUtils.GetImageMediaTypeFromFilename(imgFile),
                                    Bits = System.IO.File.ReadAllBytes(imgFile),
                                    Name = baseName + "/" + uploadFilename
                                };

                                //use file name with hash to check if file is already uploaded
                                var             imgFileChk  = origImageLink + "#" + Convert.ToBase64String(MD5.Create().ComputeHash(media.Bits));
                                MediaObjectInfo mediaResult = null;
                                if (imgFileMapping != null && imgFileMapping.ContainsKey(imgFileChk))
                                {
                                    //Image has already uploaded
                                    mediaResult = imgFileMapping[imgFileChk];
                                }
                                else
                                {
                                    mediaResult = wrapper.NewMediaObject(media);
                                    if (imgFileMapping != null)
                                    {
                                        imgFileMapping.Add(imgFileChk, mediaResult);
                                    }
                                }

                                img.Attributes["src"].Value = mediaResult.URL;

                                // use first image as featured image
                                if (!DontInferFeaturedImage)
                                {
                                    if (string.IsNullOrEmpty(FeaturedImageUrl))
                                    {
                                        FeaturedImageUrl = mediaResult.URL;
                                    }
                                    if (string.IsNullOrEmpty(FeatureImageId))
                                    {
                                        FeatureImageId = mediaResult.Id;
                                    }
                                }

                                if (WeblogAddinConfiguration.Current.ReplacePostImagesWithOnlineUrls)
                                {
                                    mmApp.Model.ActiveDocument.CurrentText =
                                        mmApp.Model.ActiveDocument.CurrentText
                                        .Replace($"]({origImageLink})", $"]({mediaResult.URL})")
                                        .Replace($"=\"{origImageLink}\"", $"=\"{mediaResult.URL}\"");
                                }
                            }
                        }
                        WindowUtilities.DoEvents();
                    }

                    html = doc.DocumentNode.OuterHtml;
                }
            }
            catch (Exception ex)
            {
                ErrorMessage = "Error posting images to Weblog: " + ex.GetBaseException().Message;
                mmApp.Log("Failed to post image to Weblog", ex);
                return(null);
            }

            return(html);
        }
        /// <summary>
        /// Dispatches a window message so that the appropriate events
        /// can be invoked. This is used for the Taskbar's thumbnail toolbar feature.
        /// </summary>
        /// <param name="m">The window message, typically obtained
        /// from a Windows Forms or WPF window procedure.</param>
        /// <param name="taskbarWindow">Taskbar window for which we are intercepting the messages</param>
        /// <returns>Returns true if this method handles the window message</returns>
        internal bool DispatchMessage(ref Message m, TaskbarWindow taskbarWindow)
        {
            if (taskbarWindow.EnableThumbnailToolbars)
            {
                if (m.Msg == (int)TaskbarNativeMethods.WM_TASKBARBUTTONCREATED)
                {
                    AddButtons(taskbarWindow);
                }
                else
                {
                    if (!buttonsAdded)
                    {
                        AddButtons(taskbarWindow);
                    }

                    switch (m.Msg)
                    {
                    case TaskbarNativeMethods.WM_COMMAND:
                        if (CoreNativeMethods.HIWORD(m.WParam.ToInt64(), 16) == THUMBBUTTON.THBN_CLICKED)
                        {
                            int buttonId = CoreNativeMethods.LOWORD(m.WParam.ToInt64());

                            var buttonsFound =
                                from b in taskbarWindow.ThumbnailButtons
                                where b.Id == buttonId
                                select b;

                            foreach (ThumbnailToolbarButton button in buttonsFound)
                            {
                                button.FireClick(taskbarWindow);
                            }
                        }
                        break;
                    } // End switch
                }     // End else
            }         // End if


            // If we are removed from the taskbar, ignore all the messages
            if (taskbarWindow.EnableTabbedThumbnails)
            {
                if (taskbarWindow.TabbedThumbnail.RemovedFromTaskbar)
                {
                    return(false);
                }
                else if (m.Msg == (int)TabbedThumbnailNativeMethods.WM_ACTIVATE)
                {
                    // Raise the event
                    taskbarWindow.TabbedThumbnail.OnTabbedThumbnailActivated();

                    SetActiveTab(taskbarWindow);

                    return(true);
                }
                else if (m.Msg == (int)TaskbarNativeMethods.WM_DWMSENDICONICTHUMBNAIL)
                {
                    int  width         = (int)((long)m.LParam >> 16);
                    int  height        = (int)(((long)m.LParam) & (0xFFFF));
                    Size requestedSize = new Size(width, height);

                    // Fire an event to let the user update their bitmap
                    // Raise the event
                    taskbarWindow.TabbedThumbnail.OnTabbedThumbnailBitmapRequested();

                    IntPtr hBitmap = IntPtr.Zero;

                    // Default size for the thumbnail
                    Size realWindowSize = new Size(200, 200);

                    if (taskbarWindow.TabbedThumbnail.WindowHandle != IntPtr.Zero)
                    {
                        TabbedThumbnailNativeMethods.GetClientSize(taskbarWindow.TabbedThumbnail.WindowHandle, out realWindowSize);
                    }
                    else if (taskbarWindow.TabbedThumbnail.WindowsControl != null)
                    {
                        realWindowSize = new Size(
                            Convert.ToInt32(taskbarWindow.TabbedThumbnail.WindowsControl.RenderSize.Width),
                            Convert.ToInt32(taskbarWindow.TabbedThumbnail.WindowsControl.RenderSize.Height));
                    }

                    if ((realWindowSize.Height == -1) && (realWindowSize.Width == -1))
                    {
                        realWindowSize.Width = realWindowSize.Height = 199;
                    }

                    // capture the bitmap for the given control
                    // If the user has already specified us a bitmap to use, use that.
                    if (taskbarWindow.TabbedThumbnail.ClippingRectangle != null && taskbarWindow.TabbedThumbnail.ClippingRectangle.Value != Rectangle.Empty)
                    {
                        if (taskbarWindow.TabbedThumbnail.CurrentHBitmap == IntPtr.Zero)
                        {
                            hBitmap = GrabBitmap(taskbarWindow, realWindowSize);
                        }
                        else
                        {
                            hBitmap = taskbarWindow.TabbedThumbnail.CurrentHBitmap;
                        }

                        // Clip the bitmap we just got
                        Bitmap bmp = Bitmap.FromHbitmap(hBitmap);

                        Rectangle clippingRectangle = taskbarWindow.TabbedThumbnail.ClippingRectangle.Value;

                        // If our clipping rect is out of bounds, update it
                        if (clippingRectangle.Height > requestedSize.Height)
                        {
                            clippingRectangle.Height = requestedSize.Height;
                        }
                        if (clippingRectangle.Width > requestedSize.Width)
                        {
                            clippingRectangle.Width = requestedSize.Width;
                        }

                        bmp = bmp.Clone(clippingRectangle, bmp.PixelFormat);

                        // Make sure we dispose the bitmap before assigning, otherwise we'll have a memory leak
                        if (hBitmap != IntPtr.Zero && taskbarWindow.TabbedThumbnail.CurrentHBitmap == IntPtr.Zero)
                        {
                            ShellNativeMethods.DeleteObject(hBitmap);
                        }
                        hBitmap = bmp.GetHbitmap();
                    }
                    else
                    {
                        // Else, user didn't want any clipping, if they haven't provided us a bitmap,
                        // use the screencapture utility and capture it.

                        hBitmap = taskbarWindow.TabbedThumbnail.CurrentHBitmap;

                        // If no bitmap, capture one using the utility
                        if (hBitmap == IntPtr.Zero)
                        {
                            hBitmap = GrabBitmap(taskbarWindow, realWindowSize);
                        }
                    }

                    // Only set the thumbnail if it's not null.
                    // If it's null (either we didn't get the bitmap or size was 0),
                    // let DWM handle it
                    if (hBitmap != IntPtr.Zero)
                    {
                        Bitmap temp = TabbedThumbnailScreenCapture.ResizeImageWithAspect(hBitmap, requestedSize.Width, requestedSize.Height, true);

                        if (taskbarWindow.TabbedThumbnail.CurrentHBitmap == IntPtr.Zero)
                        {
                            ShellNativeMethods.DeleteObject(hBitmap);
                        }

                        hBitmap = temp.GetHbitmap();
                        TabbedThumbnailNativeMethods.SetIconicThumbnail(taskbarWindow.WindowToTellTaskbarAbout, hBitmap);
                        temp.Dispose();
                    }

                    // If the bitmap we have is not coming from the user (i.e. we created it here),
                    // then make sure we delete it as we don't need it now.
                    if (taskbarWindow.TabbedThumbnail.CurrentHBitmap == IntPtr.Zero)
                    {
                        ShellNativeMethods.DeleteObject(hBitmap);
                    }

                    return(true);
                }
                else if (m.Msg == (int)TaskbarNativeMethods.WM_DWMSENDICONICLIVEPREVIEWBITMAP)
                {
                    // Try to get the width/height
                    int width  = (int)(((long)m.LParam) >> 16);
                    int height = (int)(((long)m.LParam) & (0xFFFF));

                    // Default size for the thumbnail
                    Size realWindowSize = new Size(200, 200);

                    if (taskbarWindow.TabbedThumbnail.WindowHandle != IntPtr.Zero)
                    {
                        TabbedThumbnailNativeMethods.GetClientSize(taskbarWindow.TabbedThumbnail.WindowHandle, out realWindowSize);
                    }
                    else if (taskbarWindow.TabbedThumbnail.WindowsControl != null)
                    {
                        realWindowSize = new Size(
                            Convert.ToInt32(taskbarWindow.TabbedThumbnail.WindowsControl.RenderSize.Width),
                            Convert.ToInt32(taskbarWindow.TabbedThumbnail.WindowsControl.RenderSize.Height));
                    }

                    // If we don't have a valid height/width, use the original window's size
                    if (width <= 0)
                    {
                        width = realWindowSize.Width;
                    }
                    if (height <= 0)
                    {
                        height = realWindowSize.Height;
                    }

                    // Fire an event to let the user update their bitmap
                    // Raise the event
                    taskbarWindow.TabbedThumbnail.OnTabbedThumbnailBitmapRequested();

                    // capture the bitmap for the given control
                    // If the user has already specified us a bitmap to use, use that.
                    IntPtr hBitmap = taskbarWindow.TabbedThumbnail.CurrentHBitmap == IntPtr.Zero ? GrabBitmap(taskbarWindow, realWindowSize) : taskbarWindow.TabbedThumbnail.CurrentHBitmap;

                    // If we have a valid parent window handle,
                    // calculate the offset so we can place the "peek" bitmap
                    // correctly on the app window
                    if (taskbarWindow.TabbedThumbnail.ParentWindowHandle != IntPtr.Zero && taskbarWindow.TabbedThumbnail.WindowHandle != IntPtr.Zero)
                    {
                        Point offset = new Point();

                        // if we don't have a offset specified already by the user...
                        if (!taskbarWindow.TabbedThumbnail.PeekOffset.HasValue)
                        {
                            offset = WindowUtilities.GetParentOffsetOfChild(taskbarWindow.TabbedThumbnail.WindowHandle, taskbarWindow.TabbedThumbnail.ParentWindowHandle);
                        }
                        else
                        {
                            offset = new Point(Convert.ToInt32(taskbarWindow.TabbedThumbnail.PeekOffset.Value.X),
                                               Convert.ToInt32(taskbarWindow.TabbedThumbnail.PeekOffset.Value.Y));
                        }

                        // Only set the peek bitmap if it's not null.
                        // If it's null (either we didn't get the bitmap or size was 0),
                        // let DWM handle it
                        if (hBitmap != IntPtr.Zero)
                        {
                            if (offset.X >= 0 && offset.Y >= 0)
                            {
                                TabbedThumbnailNativeMethods.SetPeekBitmap(taskbarWindow.WindowToTellTaskbarAbout, hBitmap, offset, taskbarWindow.TabbedThumbnail.DisplayFrameAroundBitmap);
                            }
                        }

                        // If the bitmap we have is not coming from the user (i.e. we created it here),
                        // then make sure we delete it as we don't need it now.
                        if (taskbarWindow.TabbedThumbnail.CurrentHBitmap == IntPtr.Zero)
                        {
                            ShellNativeMethods.DeleteObject(hBitmap);
                        }

                        return(true);
                    }
                    // Else, we don't have a valid window handle from the user. This is mostly likely because
                    // we have a WPF UIElement control. If that's the case, use a different screen capture method
                    // and also couple of ways to try to calculate the control's offset w.r.t it's parent.
                    else if (taskbarWindow.TabbedThumbnail.ParentWindowHandle != IntPtr.Zero &&
                             taskbarWindow.TabbedThumbnail.WindowsControl != null)
                    {
                        System.Windows.Point offset;

                        if (!taskbarWindow.TabbedThumbnail.PeekOffset.HasValue)
                        {
                            // Calculate the offset for a WPF UIElement control
                            // For hidden controls, we can't seem to perform the transform.
                            GeneralTransform objGeneralTransform = taskbarWindow.TabbedThumbnail.WindowsControl.TransformToVisual(taskbarWindow.TabbedThumbnail.WindowsControlParentWindow);
                            offset = objGeneralTransform.Transform(new System.Windows.Point(0, 0));
                        }
                        else
                        {
                            offset = new System.Windows.Point(taskbarWindow.TabbedThumbnail.PeekOffset.Value.X, taskbarWindow.TabbedThumbnail.PeekOffset.Value.Y);
                        }

                        // Only set the peek bitmap if it's not null.
                        // If it's null (either we didn't get the bitmap or size was 0),
                        // let DWM handle it
                        if (hBitmap != IntPtr.Zero)
                        {
                            if (offset.X >= 0 && offset.Y >= 0)
                            {
                                TabbedThumbnailNativeMethods.SetPeekBitmap(taskbarWindow.WindowToTellTaskbarAbout, hBitmap, new Point((int)offset.X, (int)offset.Y), taskbarWindow.TabbedThumbnail.DisplayFrameAroundBitmap);
                            }
                            else
                            {
                                TabbedThumbnailNativeMethods.SetPeekBitmap(taskbarWindow.WindowToTellTaskbarAbout, hBitmap, taskbarWindow.TabbedThumbnail.DisplayFrameAroundBitmap);
                            }
                        }

                        // If the bitmap we have is not coming from the user (i.e. we created it here),
                        // then make sure we delete it as we don't need it now.
                        if (taskbarWindow.TabbedThumbnail.CurrentHBitmap == IntPtr.Zero)
                        {
                            ShellNativeMethods.DeleteObject(hBitmap);
                        }

                        return(true);
                    }
                    else
                    {
                        // Else (no parent specified), just set the bitmap. It would take over the entire
                        // application window (would work only if you are a MDI app)

                        // Only set the peek bitmap if it's not null.
                        // If it's null (either we didn't get the bitmap or size was 0),
                        // let DWM handle it
                        if (hBitmap != null)
                        {
                            TabbedThumbnailNativeMethods.SetPeekBitmap(taskbarWindow.WindowToTellTaskbarAbout, hBitmap, taskbarWindow.TabbedThumbnail.DisplayFrameAroundBitmap);
                        }

                        // If the bitmap we have is not coming from the user (i.e. we created it here),
                        // then make sure we delete it as we don't need it now.
                        if (taskbarWindow.TabbedThumbnail.CurrentHBitmap == IntPtr.Zero)
                        {
                            ShellNativeMethods.DeleteObject(hBitmap);
                        }

                        return(true);
                    }
                }
                else if (m.Msg == (int)TabbedThumbnailNativeMethods.WM_DESTROY)
                {
                    TaskbarManager.Instance.TaskbarList.UnregisterTab(taskbarWindow.WindowToTellTaskbarAbout);

                    taskbarWindow.TabbedThumbnail.RemovedFromTaskbar = true;

                    return(true);
                }
                else if (m.Msg == (int)TabbedThumbnailNativeMethods.WM_NCDESTROY)
                {
                    // Raise the event
                    taskbarWindow.TabbedThumbnail.OnTabbedThumbnailClosed();

                    // Remove the taskbar window from our internal list
                    if (taskbarWindowList.Contains(taskbarWindow))
                    {
                        taskbarWindowList.Remove(taskbarWindow);
                    }

                    taskbarWindow.Dispose();
                    taskbarWindow = null;

                    return(true);
                }
                else if (m.Msg == (int)TabbedThumbnailNativeMethods.WM_SYSCOMMAND)
                {
                    if (((int)m.WParam) == TabbedThumbnailNativeMethods.SC_CLOSE)
                    {
                        // Raise the event
                        taskbarWindow.TabbedThumbnail.OnTabbedThumbnailClosed();

                        // Remove the taskbar window from our internal list
                        if (taskbarWindowList.Contains(taskbarWindow))
                        {
                            taskbarWindowList.Remove(taskbarWindow);
                        }

                        taskbarWindow.Dispose();
                        taskbarWindow = null;
                    }
                    else if (((int)m.WParam) == TabbedThumbnailNativeMethods.SC_MAXIMIZE)
                    {
                        // Raise the event
                        taskbarWindow.TabbedThumbnail.OnTabbedThumbnailMaximized();
                    }
                    else if (((int)m.WParam) == TabbedThumbnailNativeMethods.SC_MINIMIZE)
                    {
                        // Raise the event
                        taskbarWindow.TabbedThumbnail.OnTabbedThumbnailMinimized();
                    }

                    return(true);
                }
            }

            return(false);
        }
        /// <summary>
        /// Handle pasting and handle images
        /// </summary>
        public void PasteOperation()
        {
            if (Clipboard.ContainsImage())
            {
                string imagePath = null;

                var bmpSource = Clipboard.GetImage();
                using (var bitMap = WindowUtilities.BitmapSourceToBitmap(bmpSource))
                {
                    imagePath = AddinManager.Current.RaiseOnSaveImage(bitMap);
                }
                if (!string.IsNullOrEmpty(imagePath))
                {
                    SetSelection($"![]({imagePath})");
                    PreviewMarkdownCallback(); // force a preview refresh
                    return;
                }

                string initialFolder = null;
                if (!string.IsNullOrEmpty(MarkdownDocument.Filename) && MarkdownDocument.Filename != "untitled")
                {
                    initialFolder = Path.GetDirectoryName(MarkdownDocument.Filename);
                }

                var sd = new SaveFileDialog
                {
                    Filter           = "Image files (*.png;*.jpg;*.gif;)|*.png;*.jpg;*.jpeg;*.gif|All Files (*.*)|*.*",
                    FilterIndex      = 1,
                    Title            = "Save Image from Clipboard as",
                    InitialDirectory = initialFolder,
                    CheckFileExists  = false,
                    OverwritePrompt  = true,
                    CheckPathExists  = true,
                    RestoreDirectory = true
                };
                var result = sd.ShowDialog();
                if (result != null && result.Value)
                {
                    imagePath = sd.FileName;
                    try
                    {
                        var ext = Path.GetExtension(imagePath)?.ToLower();
                        using (var fileStream = new FileStream(imagePath, FileMode.Create))
                        {
                            BitmapEncoder encoder = null;
                            if (ext == ".png")
                            {
                                encoder = new PngBitmapEncoder();
                            }
                            else if (ext == ".jpg" || ext == ".jpeg")
                            {
                                encoder = new JpegBitmapEncoder();
                            }
                            else if (ext == ".gif")
                            {
                                encoder = new GifBitmapEncoder();
                            }

                            encoder.Frames.Add(BitmapFrame.Create(bmpSource));
                            encoder.Save(fileStream);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Couldn't copy file to new location: \r\n" + ex.Message, mmApp.ApplicationName);
                        return;
                    }

                    string relPath = Path.GetDirectoryName(sd.FileName);
                    if (initialFolder != null)
                    {
                        try
                        {
                            relPath = FileUtils.GetRelativePath(sd.FileName, initialFolder);
                        }
                        catch (Exception ex)
                        {
                            mmApp.Log($"Failed to get relative path.\r\nFile: {sd.FileName}, Path: {imagePath}", ex);
                        }
                        if (!relPath.StartsWith("..\\"))
                        {
                            imagePath = relPath;
                        }
                    }

                    if (imagePath.Contains(":\\"))
                    {
                        imagePath = "file:///" + imagePath;
                    }
                    SetSelection($"![]({imagePath})");
                    PreviewMarkdownCallback(); // force a preview refresh
                }
            }
            else if (Clipboard.ContainsText())
            {
                // just paste as is at cursor or selection
                SetSelection(Clipboard.GetText());
            }
        }
        /// <summary>
        /// Captures an image to file
        /// </summary>
        /// <returns></returns>
        public bool CaptureImageToClipboard()
        {
            var OldState = WindowState.Minimized;

            if (ActiveForm != null)
            {
                OldState = ActiveForm.WindowState;
                ActiveForm.WindowState = WindowState.Minimized;
            }

            object snagIt = SnagItCom;

            try
            {
                ReflectionUtils.SetPropertyCom(snagIt, "Input", CaptureMode);
            }
            catch
            {
                SetError("SnagIt isn't installed - COM Access failed.\r\nPlease install SnagIt from Techsmith Corporation (www.techsmith.com\\snagit).");
                return(false);
            }

            ReflectionUtils.SetPropertyCom(snagIt, "Input", CaptureMode);
            ReflectionUtils.SetPropertyCom(snagIt, "Output", 4);           // clipboard
            ReflectionUtils.SetPropertyCom(snagIt, "EnablePreviewWindow", ShowPreviewWindow);
            ReflectionUtils.SetPropertyCom(snagIt, "IncludeCursor", IncludeCursor);

            if (DelayInSeconds > 0)
            {
                ReflectionUtils.SetPropertyExCom(snagIt, "DelayOptions.EnableDelayedCapture", true);
                ReflectionUtils.SetPropertyExCom(snagIt, "DelayOptions.DelaySeconds", DelayInSeconds);
            }


            if (ActiveForm != null)
            {
                // *** Need to delay a little here so that the form has properly minimized first
                // *** especially under Vista/Win7
                for (int i = 0; i < 20; i++)
                {
                    WindowUtilities.DoEvents();
                    Thread.Sleep(5);
                }
            }

            // Works but doesn't really add anything. Won't work in .NET Core due to dynamic not working with COM
            //((dynamic) snagIt).OnStateChange += new Action<CaptureState>(SnagImg_OnStateChange);

            Clipboard.Clear();

            try
            {
                IsDone = false;
                ReflectionUtils.CallMethodCom(snagIt, "Capture");

                while (!IsDone && !HasError)
                {
                    IsDone = (bool)ReflectionUtils.GetPropertyCom(snagIt, "IsCaptureDone");
                    if (IsDone)
                    {
                        break;
                    }

                    WindowUtilities.DoEvents();
                    Thread.Sleep(5);
                }
            }
            catch (Exception ex)
            {
                ErrorMessage = "An error occurred during the image capture: " + ex.Message;
                return(false);
            }
            // *** No catch let it throw
            finally
            {
                if (ActiveForm != null)
                {
                    // Reactivate Editor
                    ActiveForm.WindowState = OldState;

                    // Make sure it pops on top of SnagIt Editors
                    ActiveForm.Topmost = true;
                    WindowUtilities.DoEvents();
                    Thread.Sleep(5);
                    ActiveForm.Topmost = false;
                }

                Marshal.ReleaseComObject(SnagItCom);
            }

            return(ClipboardHelper.ContainsImage());
        }