Example #1
0
        private void ApplyImageDecorator(ImageDecorator decorator, Bitmap bitmap, ref bool borderNeedsReset)
        {
            if (_embedType != ImageEmbedType.Embedded &&
                (decorator.IsBorderDecorator || decorator.Id == TiltDecorator.Id))
            {
                return;
            }

            if (borderNeedsReset &&
                _embedType == ImageEmbedType.Embedded &&
                (decorator.IsBorderDecorator || decorator.Id == TiltDecorator.Id))
            {
                borderNeedsReset = false;
                //BorderMargin = ImageBorderMargin.Empty;
            }

            try
            {
                using (ApplicationPerformance.LogEvent("ApplyDecorator: " + decorator.DecoratorName))
                    using (new WaitCursor())
                    {
                        _currImage    = bitmap;
                        _currSettings = _decoratorsList.GetImageDecoratorSettings(decorator);
                        decorator.Decorate(this);
                    }
            }
            catch (Exception e)
            {
                Trace.Fail(String.Format(CultureInfo.InvariantCulture, "Failed to apply image decorator [{0}]: {1}", decorator.DecoratorName, e.ToString()));
            }
        }
Example #2
0
        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
            case (int)WM.QUERYENDSESSION:
                m.Result = new IntPtr(1);
                return;

            case (int)WM.ENDSESSION:
            {
                bool isSessionEnding = Convert.ToBoolean(m.WParam.ToInt32()) &&
                                       (((uint)m.LParam.ToInt32() | ENDSESSION.ENDSESSION_CLOSEAPP) != 0 ||
                                        ((uint)m.LParam.ToInt32() | ENDSESSION.ENDSESSION_CRITICAL) != 0 ||
                                        ((uint)m.LParam.ToInt32() | ENDSESSION.ENDSESSION_LOGOFF) != 0);

                if (isSessionEnding)
                {
                    ((ISessionHandler)_mainControl).OnEndSession();
                    m.Result = IntPtr.Zero;
                    return;
                }
            }
            break;

            case MESSAGE_PERFLOG_FLUSH:
                if (ApplicationPerformance.IsEnabled)
                {
                    ApplicationPerformance.FlushLogFile();
                }
                return;
            }

            //if (_framelessManager != null && !_framelessManager.WndProc(ref m))
            base.WndProc(ref m);
        }
Example #3
0
 private static void LogStartupPerf(object sender, EventArgs args)
 {
     Application.Idle -= LogStartupPerf;
     if (!startupLogged)
     {
         startupLogged = true;
         DateTime endTime   = DateTime.Now;
         DateTime startTime = Process.GetCurrentProcess().StartTime;
         long     millis    = (long)Math.Round((endTime - startTime).TotalMilliseconds);
         ApplicationPerformance.WriteEvent("StartupToIdle", millis);
     }
 }
Example #4
0
 void MediaInsertForm_Closing(object sender, CancelEventArgs e)
 {
     if (DialogResult == DialogResult.OK)
     {
         if (activeSource.ValidateSelection())
         {
             ApplicationPerformance.StartEvent(EventName);
             DialogResult = DialogResult.OK;
         }
         else
         {
             DialogResult = DialogResult.Abort;
             e.Cancel     = true;
         }
     }
 }
Example #5
0
 void _blogPostHtmlEditorControl_KeyPress(object o, HtmlEventArgs e)
 {
     using (ApplicationPerformance.LogEvent("PostEditorKeyPress"))
     {
         // These are important for helping to find bugs with autoreplace, but cause to much
         // noise with tests and testers even in debug mode.  They can have many 'false positives' hits
         if (Debugger.IsAttached)
         {
             Debug.Assert(_delayedAutoReplaceAction == null, "Delayed autoreplace operation wasn't null!");
             Debug.Assert(_typographicCharacterHandler == null, "Delayed typographic character operation wasn't null!");
         }
         _delayedAutoReplaceAction    = null;
         _typographicCharacterHandler = null;
         _lastActionWasReplace        = 0;
         _ignoreNextSelectionChange   = false;
         if (MaybeHandleKey(Convert.ToChar(e.htmlEvt.keyCode)))
         {
             e.Cancel();
         }
     }
 }
Example #6
0
        void _blogPostHtmlEditorControl_KeyDown(object o, HtmlEventArgs e)
        {
            try
            {
                using (ApplicationPerformance.LogEvent("PostEditorKeyDown"))
                {
                    if (HandleKey && Convert.ToChar(e.htmlEvt.keyCode) == 8)
                    {
                        _linkIgnoreWord = null;
                        if (AutoLinkEnabled)
                        {
                            MarkupPointer blockBoundary;
                            string        htmlText = GetHtmlText(out blockBoundary);

                            if (blockBoundary == null)
                            {
                                return;
                            }

                            MatchUrl(htmlText, IgnoreSuggestedUrl);
                        }

                        if (_lastActionWasReplace > 0)
                        {
                            _lastActionWasReplace--;
                            _ignoreNextSelectionChange = true;
                            _blogPostHtmlEditorControl.Undo();
                            e.Cancel();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.Fail("Error while handling backspace key, suppressing autocomplete " + ex);
                _haltAutoReplace = true;
                throw;
            }
        }
Example #7
0
        private static List <NewImageInfo> ScanImages(IBlogPostHtmlEditor currentEditor, IEditorAccount editorAccount, ContentEditor editor, bool useDefaultTargetSettings)
        {
            List <NewImageInfo> newImages = new List <NewImageInfo>();

            ApplicationPerformance.ClearEvent("InsertImage");
            ApplicationPerformance.StartEvent("InsertImage");

            using (new WaitCursor())
            {
                IHTMLElement2 postBodyElement = (IHTMLElement2)((BlogPostHtmlEditorControl)currentEditor).PostBodyElement;
                if (postBodyElement != null)
                {
                    foreach (IHTMLElement imgElement in postBodyElement.getElementsByTagName("img"))
                    {
                        string imageSrc = imgElement.getAttribute("srcDelay", 2) as string;

                        if (string.IsNullOrEmpty(imageSrc))
                        {
                            imageSrc = imgElement.getAttribute("src", 2) as string;
                        }

                        // WinLive 96840 - Copying and pasting images within shared canvas should persist source
                        // decorator settings. "wlCopySrcUrl" is inserted while copy/pasting within canvas.
                        bool   copyDecoratorSettings = false;
                        string attributeCopySrcUrl   = imgElement.getAttribute("wlCopySrcUrl", 2) as string;
                        if (!string.IsNullOrEmpty(attributeCopySrcUrl))
                        {
                            copyDecoratorSettings = true;
                            imgElement.removeAttribute("wlCopySrcUrl", 0);
                        }

                        // Check if we need to apply default values for image decorators
                        bool   applyDefaultDecorator       = true;
                        string attributeNoDefaultDecorator = imgElement.getAttribute("wlNoDefaultDecorator", 2) as string;
                        if (!string.IsNullOrEmpty(attributeNoDefaultDecorator) && string.Compare(attributeNoDefaultDecorator, "TRUE", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            applyDefaultDecorator = false;
                            imgElement.removeAttribute("wlNoDefaultDecorator", 0);
                        }

                        string applyDefaultMargins = imgElement.getAttribute("wlApplyDefaultMargins", 2) as string;
                        if (!String.IsNullOrEmpty(applyDefaultMargins))
                        {
                            DefaultImageSettings defaultImageSettings = new DefaultImageSettings(editorAccount.Id, editor.DecoratorsManager);
                            MarginStyle          defaultMargin        = defaultImageSettings.GetDefaultImageMargin();
                            // Now apply it to the image
                            imgElement.style.marginTop    = String.Format(CultureInfo.InvariantCulture, "{0} px", defaultMargin.Top);
                            imgElement.style.marginLeft   = String.Format(CultureInfo.InvariantCulture, "{0} px", defaultMargin.Left);
                            imgElement.style.marginBottom = String.Format(CultureInfo.InvariantCulture, "{0} px", defaultMargin.Bottom);
                            imgElement.style.marginRight  = String.Format(CultureInfo.InvariantCulture, "{0} px", defaultMargin.Right);
                            imgElement.removeAttribute("wlApplyDefaultMargins", 0);
                        }

                        if ((UrlHelper.IsFileUrl(imageSrc) || IsFullPath(imageSrc)) && !ContentSourceManager.IsSmartContent(imgElement))
                        {
                            Uri imageSrcUri = new Uri(imageSrc);
                            try
                            {
                                BlogPostImageData imageData = BlogPostImageDataList.LookupImageDataByInlineUri(editor.ImageList, imageSrcUri);
                                Emoticon          emoticon  = EmoticonsManager.GetEmoticon(imgElement);
                                if (imageData == null && emoticon != null)
                                {
                                    // This is usually an emoticon copy/paste and needs to be cleaned up.
                                    Uri inlineImageUri = editor.EmoticonsManager.GetInlineImageUri(emoticon);
                                    imgElement.setAttribute("src", UrlHelper.SafeToAbsoluteUri(inlineImageUri), 0);
                                }
                                else if (imageData == null)
                                {
                                    if (!File.Exists(imageSrcUri.LocalPath))
                                    {
                                        throw new FileNotFoundException(imageSrcUri.LocalPath);
                                    }

                                    // WinLive 188841: Manually attach the behavior so that the image cannot be selected or resized while its loading.
                                    DisabledImageElementBehavior disabledImageBehavior = new DisabledImageElementBehavior(editor.IHtmlEditorComponentContext);
                                    disabledImageBehavior.AttachToElement(imgElement);

                                    Size sourceImageSize                      = ImageUtils.GetImageSize(imageSrcUri.LocalPath);
                                    ImagePropertiesInfo  imageInfo            = new ImagePropertiesInfo(imageSrcUri, sourceImageSize, new ImageDecoratorsList(editor.DecoratorsManager, new BlogPostSettingsBag()));
                                    DefaultImageSettings defaultImageSettings = new DefaultImageSettings(editorAccount.Id, editor.DecoratorsManager);

                                    // Make sure this is set because some imageInfo properties depend on it.
                                    imageInfo.ImgElement = imgElement;

                                    bool isMetafile = ImageHelper2.IsMetafile(imageSrcUri.LocalPath);
                                    ImageClassification imgClass = ImageHelper2.Classify(imageSrcUri.LocalPath);
                                    if (!isMetafile && ((imgClass & ImageClassification.AnimatedGif) != ImageClassification.AnimatedGif))
                                    {
                                        // WinLive 96840 - Copying and pasting images within shared canvas should persist source
                                        // decorator settings.
                                        if (copyDecoratorSettings)
                                        {
                                            // Try to look up the original copied source image.
                                            BlogPostImageData imageDataOriginal = BlogPostImageDataList.LookupImageDataByInlineUri(editor.ImageList, new Uri(attributeCopySrcUrl));
                                            if (imageDataOriginal != null && imageDataOriginal.GetImageSourceFile() != null)
                                            {
                                                // We have the original image reference, so lets make a clone of it.
                                                BlogPostSettingsBag originalBag            = (BlogPostSettingsBag)imageDataOriginal.ImageDecoratorSettings.Clone();
                                                ImageDecoratorsList originalDecoratorsList = new ImageDecoratorsList(editor.DecoratorsManager, originalBag);

                                                ImageFileData originalImageFileData = imageDataOriginal.GetImageSourceFile();
                                                Size          originalImageSize     = new Size(originalImageFileData.Width, originalImageFileData.Height);
                                                imageInfo = new ImagePropertiesInfo(originalImageFileData.Uri, originalImageSize, originalDecoratorsList);
                                            }
                                            else
                                            {
                                                // There are probably decorators applied to the image, but in a different editor so we can't access them.
                                                // We probably don't want to apply any decorators to this image, so apply blank decorators and load the
                                                // image as full size so it looks like it did before.
                                                imageInfo.ImageDecorators     = defaultImageSettings.LoadBlankLocalImageDecoratorsList();
                                                imageInfo.InlineImageSizeName = ImageSizeName.Full;
                                            }
                                        }
                                        else if (applyDefaultDecorator)
                                        {
                                            imageInfo.ImageDecorators = defaultImageSettings.LoadDefaultImageDecoratorsList();

                                            if ((imgClass & ImageClassification.TransparentGif) == ImageClassification.TransparentGif)
                                            {
                                                imageInfo.ImageDecorators.AddDecorator(NoBorderDecorator.Id);
                                            }
                                        }
                                        else
                                        {
                                            // Don't use default values for decorators
                                            imageInfo.ImageDecorators     = defaultImageSettings.LoadBlankLocalImageDecoratorsList();
                                            imageInfo.InlineImageSizeName = ImageSizeName.Full;
                                        }
                                    }
                                    else
                                    {
                                        ImageDecoratorsList decorators = new ImageDecoratorsList(editor.DecoratorsManager, new BlogPostSettingsBag());
                                        decorators.AddDecorator(editor.DecoratorsManager.GetDefaultRemoteImageDecorators());
                                        imageInfo.ImageDecorators = decorators;
                                    }

                                    imageInfo.ImgElement       = imgElement;
                                    imageInfo.DhtmlImageViewer = editorAccount.EditorOptions.DhtmlImageViewer;

                                    //discover the "natural" target settings from the DOM
                                    string linkTargetUrl = imageInfo.LinkTargetUrl;
                                    if (linkTargetUrl == imageSrc)
                                    {
                                        imageInfo.LinkTarget = LinkTargetType.IMAGE;
                                    }
                                    else if (!String.IsNullOrEmpty(linkTargetUrl) && !UrlHelper.IsFileUrl(linkTargetUrl))
                                    {
                                        imageInfo.LinkTarget = LinkTargetType.URL;
                                    }
                                    else
                                    {
                                        imageInfo.LinkTarget = LinkTargetType.NONE;
                                    }

                                    if (useDefaultTargetSettings)
                                    {
                                        if (!GlobalEditorOptions.SupportsFeature(ContentEditorFeature.SupportsImageClickThroughs) && imageInfo.DefaultLinkTarget == LinkTargetType.IMAGE)
                                        {
                                            imageInfo.DefaultLinkTarget = LinkTargetType.NONE;
                                        }

                                        if (imageInfo.LinkTarget == LinkTargetType.NONE)
                                        {
                                            imageInfo.LinkTarget = imageInfo.DefaultLinkTarget;
                                        }
                                        if (imageInfo.DefaultLinkOptions.ShowInNewWindow)
                                        {
                                            imageInfo.LinkOptions.ShowInNewWindow = true;
                                        }
                                        imageInfo.LinkOptions.UseImageViewer       = imageInfo.DefaultLinkOptions.UseImageViewer;
                                        imageInfo.LinkOptions.ImageViewerGroupName = imageInfo.DefaultLinkOptions.ImageViewerGroupName;
                                    }

                                    Size defaultImageSize = defaultImageSettings.GetDefaultInlineImageSize();
                                    Size initialSize      = ImageUtils.GetScaledImageSize(defaultImageSize.Width, defaultImageSize.Height, sourceImageSize);

                                    // add to list of new images
                                    newImages.Add(new NewImageInfo(imageInfo, imgElement, initialSize, disabledImageBehavior));
                                }
                                else
                                {
                                    // When switching blogs, try to adapt image viewer settings according to the blog settings.

                                    ImagePropertiesInfo imageInfo = new ImagePropertiesInfo(imageSrcUri, ImageUtils.GetImageSize(imageSrcUri.LocalPath), new ImageDecoratorsList(editor.DecoratorsManager, imageData.ImageDecoratorSettings));
                                    imageInfo.ImgElement = imgElement;
                                    // Make sure the new crop and tilt decorators get loaded
                                    imageInfo.ImageDecorators.MergeDecorators(DefaultImageSettings.GetImplicitLocalImageDecorators());
                                    string viewer = imageInfo.DhtmlImageViewer;
                                    if (viewer != editorAccount.EditorOptions.DhtmlImageViewer)
                                    {
                                        imageInfo.DhtmlImageViewer = editorAccount.EditorOptions.DhtmlImageViewer;
                                        imageInfo.LinkOptions      = imageInfo.DefaultLinkOptions;
                                    }

                                    // If the image is an emoticon, update the EmoticonsManager with the image's uri so that duplicate emoticons can point to the same file.
                                    if (emoticon != null)
                                    {
                                        editor.EmoticonsManager.SetInlineImageUri(emoticon, imageData.InlineImageFile.Uri);
                                    }
                                }
                            }
                            catch (ArgumentException e)
                            {
                                Trace.WriteLine("Could not initialize image: " + imageSrc);
                                Trace.WriteLine(e.ToString());
                            }
                            catch (DirectoryNotFoundException)
                            {
                                Debug.WriteLine("Image file does not exist: " + imageSrc);
                            }
                            catch (FileNotFoundException)
                            {
                                Debug.WriteLine("Image file does not exist: " + imageSrc);
                            }
                            catch (IOException e)
                            {
                                Debug.WriteLine("Image file cannot be read: " + imageSrc + " " + e);
                                DisplayMessage.Show(MessageId.FileInUse, imageSrc);
                            }
                        }
                    }
                }
            }

            return(newImages);
        }
Example #8
0
        private static void ProcessInitializedImages(List <NewImageInfo> newImages, IBlogPostHtmlEditor currentEditor, ContentEditor editor, Control owner, bool selectLastImage)
        {
            // Remove all invalid images first
            List <NewImageInfo> newImagesToUpdate = new List <NewImageInfo>();

            for (int i = 0; i < newImages.Count; i++)
            {
                NewImageInfo info = newImages[i];

                if (info.Remove)
                {
                    using (ContentEditor.EditorUndoUnit undo = new ContentEditor.EditorUndoUnit(currentEditor, true))
                    {
                        info.DisabledImageBehavior.DetachFromElement();
                        HTMLElementHelper.RemoveElement(info.Element);
                        undo.Commit();
                    }
                }
                else
                {
                    newImagesToUpdate.Add(info);
                }
            }

            // Queue up processing for any remaining valid images
            MultiTaskHelper tasks = new MultiTaskHelper(30);

            for (int i = 0; i < newImagesToUpdate.Count; i++)
            {
                bool         lastElement = i == (newImagesToUpdate.Count - 1);
                NewImageInfo info        = newImagesToUpdate[i];

                tasks.AddWork(delegate
                {
                    // WinLive 214012: If the original insertion operation is undone before we get to this point make
                    // sure we don't attempt to update the HTML. Elements that are removed via an undo, but that we
                    // still hold a reference to, are put into another document whose readyState is "uninitialized".
                    // It's also possible that the picture has already been updated if a user undoes and redoes the
                    // initial insertion multiple times.
                    IHTMLDocument2 doc = (IHTMLDocument2)info.Element.document;
                    if (doc == null || doc.readyState.Equals("uninitialized", StringComparison.OrdinalIgnoreCase) ||
                        BlogPostImageDataList.LookupImageDataByInlineUri(editor.ImageList, info.ImageData.InlineImageFile.Uri) != null)
                    {
                        info.DisabledImageBehavior.DetachFromElement();
                        return;
                    }

                    using (new QuickTimer("ProcessInitializedImage"))
                        using (ContentEditor.EditorUndoUnit undo = new ContentEditor.EditorUndoUnit(currentEditor, true))
                        {
                            editor.ImageList.AddImage(info.ImageData);

                            info.Element.setAttribute("src", UrlHelper.SafeToAbsoluteUri(info.ImageData.InlineImageFile.Uri), 0);
                            info.Element.removeAttribute("srcDelay", 0);
                            // Create the decorators
                            ImageEditingPropertyHandler.UpdateImageSource(info.ImageInfo, info.Element, editor, new ImageInsertHandler(), ImageDecoratorInvocationSource.InitialInsert);

                            // Manually detach the behavior so that the image can be selected and resized.
                            info.DisabledImageBehavior.DetachFromElement();

                            if (lastElement)
                            {
                                ApplicationPerformance.EndEvent("InsertImage");
                                HandleNewImage((BlogPostHtmlEditorControl)currentEditor, owner, info.Element, selectLastImage);
                            }

                            undo.Commit();

                            if (editor.ETWProvider != null)
                            {
                                editor.ETWProvider.WriteEvent("InlinePhotoEnd");
                            }
                        }
                });
            }

            // If there were no images to update, stop the perf timer
            if (newImagesToUpdate.Count == 0)
            {
                ApplicationPerformance.EndEvent("InsertImage");
            }

            // When the editor is closing, or changing to a new blog post we need to get rid of this object
            // which will then stop all the unfinished images from continuing to load.
            editor.DisposeOnEditorChange(tasks);
            tasks.Start();
        }
        public void ApplyOptions()
        {
            try
            {
                if (_options.IsArgPresent(ATTACHDEBUGGER))
                {
                    Debugger.Launch();
                }

                if (_options.IsArgPresent(CULTURE))
                {
                    string culture = _options.GetValue(CULTURE, null) as string;
                    if (culture != null)
                    {
                        CultureHelper.ApplyUICulture(culture);
                    }
                }

#if DEBUG
                if (_options.IsArgPresent(TESTMODE))
                {
                    ApplicationDiagnostics.TestMode = _options.GetFlagValue(TESTMODE, ApplicationDiagnostics.TestMode);
                }

                if (_options.IsArgPresent(VERBOSELOGGING))
                {
                    ApplicationDiagnostics.VerboseLogging = _options.GetFlagValue(VERBOSELOGGING, ApplicationDiagnostics.VerboseLogging);
                }

                if (_options.IsArgPresent(ALLOWUNSAFECERTIFICATES))
                {
                    ApplicationDiagnostics.AllowUnsafeCertificates = _options.GetFlagValue(ALLOWUNSAFECERTIFICATES, ApplicationDiagnostics.AllowUnsafeCertificates);
                }

                if (_options.IsArgPresent(PREFERATOM))
                {
                    ApplicationDiagnostics.PreferAtom = _options.GetFlagValue(PREFERATOM, ApplicationDiagnostics.PreferAtom);
                }

                if (_options.IsArgPresent(SUPPRESSBACKGROUNDREQUESTS))
                {
                    ApplicationDiagnostics.SuppressBackgroundRequests = _options.GetFlagValue(SUPPRESSBACKGROUNDREQUESTS, ApplicationDiagnostics.SuppressBackgroundRequests);
                }

                if (_options.IsArgPresent(PROXY))
                {
                    ApplicationDiagnostics.ProxySettingsOverride = (string)_options.GetValue(PROXY, ApplicationDiagnostics.ProxySettingsOverride);
                }

                if (_options.IsArgPresent(PERFLOG))
                {
                    ApplicationPerformance.SetLogFilePath((string)_options.GetValue(PERFLOG, null));
                }

                if (_options.IsArgPresent(AUTOMATIONMODE))
                {
                    ApplicationDiagnostics.AutomationMode = true;
                }

                if (_options.IsArgPresent(FIRSTRUN))
                {
                    ApplicationDiagnostics.SimulateFirstRun = true;
                }

                if (_options.IsArgPresent(INTAPIHOST))
                {
                    ApplicationDiagnostics.IntServerOverride = (string)_options.GetValue(INTAPIHOST, null);
                }
#endif

#if !SIGNED
                if (_options.IsArgPresent(LOCSPY))
                {
                    Res.DebugMode = true;
                }
#endif
            }
            catch (Exception e)
            {
                Debug.Fail("Unable to apply culture:\r\n\r\n" + e.ToString());
            }
        }