Example #1
0
        private bool InsertSmartContentFromEmbed(string embed)
        {
            ContentSourceInfo contentSource = ContentSourceManager.FindContentSource(typeof(VideoContentSource));

            if (contentSource != null)
            {
                SmartContentSource smartSource   = contentSource.Instance as SmartContentSource;
                VideoContentSource videoSource   = smartSource as VideoContentSource;
                IExtensionData     extensionData = _contentSourceSite.CreateExtensionData(Guid.NewGuid().ToString());
                ISmartContent      smartContent  = new SmartContent(extensionData);
                videoSource.CreateContentFromEmbed(embed, smartContent);
                // generate html and insert it
                string content = videoSource.GenerateEditorHtml(smartContent, _contentSourceSite);
                if (content != null)
                {
                    _contentSourceSite.InsertContent(VideoContentSource.ID, content, extensionData);
                    return(true);
                }
                else
                {
                    Trace.Fail("Video Source content generated from embed tag was empty");
                    return(false);
                }
            }
            Trace.Fail("Cannot find the video plugin");
            return(false);
        }
Example #2
0
        private static bool TableElementIsContainedInSmartContent(MarkupRange elementRange)
        {
            // table elements inside smart content regions are not editable
            IHTMLElement parentSmartContent = elementRange.Start.GetParentElement(ContentSourceManager.CreateSmartContentElementFilter());

            return(parentSmartContent != null);
        }
        private void SelectNextControlElement(bool forward)
        {
            MarkupPointer p;

            if (forward)
            {
                p = EditorContext.Selection.SelectedMarkupRange.End.Clone();
            }
            else
            {
                p = EditorContext.Selection.SelectedMarkupRange.Start.Clone();
            }

            IHTMLElement htmlElement = GetNextElement(p, ElementRange, new IHTMLElementFilter(IsSelectableControlElement), forward);

            if (ContentSourceManager.IsSmartContent(htmlElement))
            {
                SmartContentSelection.SelectIfSmartContentElement(EditorContext, htmlElement);
            }
            else if (htmlElement is IHTMLControlElement)
            {
                _editor.SelectControlElement((IHTMLControlElement)htmlElement);
            }
            if (htmlElement != null)
            {
                htmlElement.scrollIntoView(!forward);
            }
        }
        public IExtensionData[] CalculateReferencedExtensionData(string content)
        {
            Hashtable datas = new Hashtable();

            ContentSourceManager.SmartContentPredicate predicate = new ContentSourceManager.SmartContentPredicate();
            SimpleHtmlParser p = new SimpleHtmlParser(content);

            for (Element el; null != (el = p.Next());)
            {
                if (predicate.IsMatch(el))
                {
                    BeginTag bt     = el as BeginTag;
                    Attr     idAttr = bt.GetAttribute("id");
                    if (idAttr != null) //Synchronized WP posts will strip ID attrs (bug 488143)
                    {
                        string smartContentSourceId;
                        string smartContentId;
                        string smartContentElementId = idAttr.Value;
                        ContentSourceManager.ParseContainingElementId(smartContentElementId, out smartContentSourceId, out smartContentId);
                        IExtensionData data = GetExtensionData(smartContentId);
                        if (data != null)
                        {
                            datas[smartContentId] = data;
                        }
                    }
                }
            }
            return((IExtensionData[])ArrayHelper.CollectionToArray(datas.Values, typeof(IExtensionData)));
        }
        public static ContentSourceInfo FindContentSourceForLiveClipboardFormat(LiveClipboardFormat format)
        {
            // see if the preferred content source is noted in the registry
            string contentSourceId = GetContentSourceIdForFormat(format);

            if (contentSourceId != null)
            {
                // if the content-source is still installed and active then return it
                ContentSourceInfo contentSourceInfo = ContentSourceManager.FindContentSource(contentSourceId);
                if (contentSourceInfo != null)
                {
                    return(contentSourceInfo);
                }
            }

            // didn't find a valid preconfigured entry, scan all sources to see if we've got one
            foreach (ContentSourceInfo contentSourceInfo in ContentSourceManager.ActiveContentSources)
            {
                foreach (LiveClipboardFormatHandler csFormatHandler in contentSourceInfo.LiveClipboardFormatHandlers)
                {
                    if (csFormatHandler.Format.Equals(format))
                    {
                        // note that this is now our default
                        SetContentSourceForFormat(format, contentSourceInfo.Id);

                        // return the source
                        return(contentSourceInfo);
                    }
                }
            }

            // no match found
            return(null);
        }
        /// <summary>
        /// global initialization which may show error dialogs or cause
        /// failure of the entire product to load
        /// </summary>
        public static bool Initialize()
        {
            // can show error dialog if plugin has missing or incorrect attributes
            ContentSourceManager.Initialize();

            return(true);
        }
Example #7
0
        public void Initialize(string registrySettingsPath, IContentEditorLogger logger, IContentTarget contentTarget, ISettingsProvider settingsProvider)
        {
            try
            {
                GlobalEditorOptions.Init(contentTarget, settingsProvider);
                HtmlEditorControl.AllowCachedEditor();

                Assembly assembly = Assembly.GetExecutingAssembly();
                ApplicationEnvironment.Initialize(assembly, Path.GetDirectoryName(assembly.Location), registrySettingsPath, contentTarget.ProductName);
                ContentSourceManager.Initialize(false);

                Trace.Listeners.Clear();
                if (logger != null)
                {
                    _logger = new RedirectionLogger(logger);

                    Trace.Listeners.Add(_logger);
                }

#if DEBUG
                Trace.Listeners.Add(new DefaultTraceListener());
#endif
            }
            catch (Exception e)
            {
                Trace.Fail("Failed to initialize Shared Canvas: " + e);
                Trace.Flush();
                throw;
            }
        }
Example #8
0
        private void buttonOptions_Click(object sender, System.EventArgs e)
        {
            ContentSourceInfo selectedContentSource = GetSelectedPlugin();

            if (selectedContentSource != null)
            {
                if (selectedContentSource.WriterPluginHasEditableOptions)
                {
                    try
                    {
                        selectedContentSource.Instance.EditOptions(FindForm());
                    }
                    catch (NotImplementedException ex)
                    {
                        ContentSourceManager.DisplayContentRetreivalError(FindForm(), ex, selectedContentSource);
                    }
                    catch (Exception exception)
                    {
                        Trace.Fail(exception.ToString());
                        DisplayableException dex = new DisplayableException(
                            Res.Get(StringId.UnexpectedErrorPluginTitle),
                            string.Format(CultureInfo.CurrentCulture, Res.Get(StringId.UnexpectedErrorPluginDescription), selectedContentSource.Name, exception.Message));
                        DisplayableExceptionDisplayForm.Show(FindForm(), dex);
                    }
                }
            }
        }
        public static string GenerateContentBlock(string contentSourceId, string blockId, string content, ISmartContent sContent, IHTMLElement element)
        {
            string className = ContentSourceManager.EDITABLE_SMART_CONTENT;
            string elementId = ContentSourceManager.MakeContainingElementId(contentSourceId, blockId);
            bool   inline    = true;

            return(GenerateBlock(className, elementId, sContent, inline, content, false, element));
        }
Example #10
0
        /// <summary>Initializes the manager.</summary>
        internal static void Init(IModHelper helper, IMonitor monitor)
        {
            config = helper.ReadConfig <BetterArtisanGoodIconsConfig>();

            foreach (ArtisanGoodTextureProvider provider in ContentSourceManager.GetTextureProviders(helper, monitor))
            {
                TextureProviders.Add(provider);
            }
        }
Example #11
0
        public void SaveEditedSmartContent()
        {
            //update the element ID with the new smart content id (this preserves undo-ability)
            _smartContentElement.id = ContentSourceManager.MakeContainingElementId(_contentSourceId, _smartContentId);
            SmartContentInsertionHelper.InsertEditorHtmlIntoElement(_contentSourceContext, _contentSource, _smartContent, _smartContentElement);

            //reinit the smart content so it is re-cloned
            MakeSmartContentEditable();
        }
Example #12
0
        /// <summary>
        /// global initializaiton which may show error dialogs or cause
        /// failure of the entire product to load
        /// </summary>
        public static bool Initialize()
        {
            // can show error dialog if plugin has missing or incorrect attributes
            ContentSourceManager.Initialize();

            // auto-update manager
            //BlogSettingsAutoUpdateManager.Instance.Startup();

            return(true);
        }
Example #13
0
        protected override bool DoInsertData(DataAction action, MarkupPointer begin, MarkupPointer end)
        {
            // get the live clipboard data
            LiveClipboardData lcData = DataMeister.LiveClipboardData;

            if (lcData == null)
            {
                Trace.Fail("Unexpected failure to get LC data!");
                return(false);
            }

            // lookup the content-source
            ContentSourceInfo contentSource =
                LiveClipboardManager.FindContentSourceForLiveClipboard(lcData.Formats);

            if (contentSource == null)
            {
                Trace.Fail("Unexpected failure to find content soure!");
                return(false);
            }

            using (new WaitCursor())
            {
                try
                {
                    // HACK: drive the selection textRange to the caret so we can call generic
                    // content-source routines that work off the current selection
                    // Note that we do the same thing below for Images so we can use the common
                    // InsertImages method -- we may want to bake this into core marshalling
                    // or add MarkupRange parameters to the image and content-source routines
                    EditorContext.MarkupServices.CreateMarkupRange(begin, end).ToTextRange().select();

                    if (contentSource.Instance is SmartContentSource)
                    {
                        return(InsertSmartContentFromLiveClipboard(contentSource, lcData.Document));
                    }
                    else if (contentSource.Instance is ContentSource)
                    {
                        return(InsertSimpleContentFromLiveClipboard(contentSource, lcData.Document));
                    }
                    else
                    {
                        Debug.Fail("Unexpected content source type: " + contentSource.GetType());
                        return(false);
                    }
                }
                catch (Exception ex)
                {
                    ContentSourceManager.DisplayContentRetreivalError(EditorContext.FrameWindow, ex, contentSource);
                    return(false);
                }
            }
        }
Example #14
0
        protected override void OnResizeStart(Size size, bool preserveAspectRatio)
        {
            _resizeUndo = EditorContext.CreateUndoUnit();
            base.OnResizeStart(size, preserveAspectRatio);

            // save references
            _initialParentSize   = size;
            _preserveAspectRatio = preserveAspectRatio;

            // initialize smart content
            string contentSourceId;
            string contentId;

            ContentSourceManager.ParseContainingElementId(HTMLElement.id, out contentSourceId, out contentId);

            // clone the smart content for resizing so that settings changes made during the resize
            //operation are undoable
            String       newContentId = Guid.NewGuid().ToString();
            SmartContent content      = (SmartContent)_contentSourceContext.CloneSmartContent(contentId, newContentId);

            if (content == null)
            {
                Trace.WriteLine("Could not clone smart content for resize.");
                return;
            }

            HTMLElement.id = ContentSourceManager.MakeContainingElementId(contentSourceId, newContentId);

            // call sizer
            ResizeOptions resizeOptions = new ResizeOptions();

            _contentSource.OnResizeStart(content, resizeOptions);

            // determine the target size
            IHTMLElement targetSizeElement = GetResizeTargetElement(resizeOptions.ResizeableElementId);

            _initialTargetSize = new Size(targetSizeElement.offsetWidth, targetSizeElement.offsetHeight);
            // Account for areas of the smart content that are not being scaled when preserving aspect ratio.
            // For example, in YouTube plugin, label text below the image.
            UpdateResizerAspectRatioOffset(_initialParentSize - _initialTargetSize);

            // determine the aspect ratio
            if (resizeOptions.AspectRatio > 0)
            {
                _aspectRatio = resizeOptions.AspectRatio;
            }
            else
            {
                _aspectRatio = ((double)_initialTargetSize.Width) / _initialTargetSize.Height;
            }
        }
Example #15
0
        /// <summary>
        /// Clones active smart content contained in the provided HTML, and disables unknown smart content.
        /// </summary>
        public static string PrepareSmartContentHtmlForEditorInsertion(string html, IContentSourceSidebarContext sourceContext)
        {
            StringBuilder output = new StringBuilder();

            ContentSourceManager.SmartContentPredicate predicate = new ContentSourceManager.SmartContentPredicate();
            SimpleHtmlParser p = new SimpleHtmlParser(html);

            for (Element el; null != (el = p.Next());)
            {
                if (predicate.IsMatch(el))
                {
                    BeginTag bt     = el as BeginTag;
                    Attr     idAttr = bt.GetAttribute("id");

                    String contentSourceId, contentItemId;
                    ContentSourceManager.ParseContainingElementId(idAttr.Value, out contentSourceId, out contentItemId);
                    ISmartContent smartContent = sourceContext.FindSmartContent(contentItemId);
                    if (smartContent != null)
                    {
                        String newId = Guid.NewGuid().ToString();
                        sourceContext.CloneSmartContent(contentItemId, newId);

                        if (RefreshableContentManager.ContentSourcesWithRefreshableContent.Contains(contentSourceId))
                        {
                            IExtensionData extensionData = sourceContext.FindExtentsionData(newId);
                            Debug.Assert(extensionData != null);

                            // Since we just made a new id for the smart content just about to be inserted
                            // we want to give it a chance to get a callback because its callback might have happened while
                            // it was on the clipboard(in the event of cut).  This means the refreshable content manager doesnt know
                            // to watch out for this smart content on paste, it only knows to look out for who created it.   Thus
                            // we just force the callback, and if it didnt need it, nothing will happen.
                            if (extensionData.RefreshCallBack == null)
                            {
                                extensionData.RefreshCallBack = DateTime.UtcNow;
                            }
                        }


                        idAttr.Value = ContentSourceManager.MakeContainingElementId(contentSourceId, newId);
                    }
                    else
                    {
                        ContentSourceManager.RemoveSmartContentAttributes(bt);
                    }
                }
                output.Append(el.ToString());
            }
            return(output.ToString());
        }
Example #16
0
        public static SmartContentSelection SelectIfSmartContentElement(IHtmlEditorComponentContext editorComponentContext, IHTMLElement e, SmartContentState contentState)
        {
            if (e != null)
            {
                IHTMLElement smartContent = ContentSourceManager.GetContainingSmartContent(e);
                if (smartContent == null)
                {
                    return(null);
                }

                return(SelectElement(editorComponentContext, smartContent, contentState));
            }
            return(null);
        }
    private static void ContentSourceManagerGetTextureProvidersPostfix(IModHelper helper, IMonitor monitor)
    {
        var providers = helper.ContentPacks.GetOwned()
                        .Select(pack => ContentSourceManager.TryLoadContentSource(new ContentPackSource(pack), monitor));

        var textureProviders = (IList)"BetterArtisanGoodIcons.ArtisanGoodsManager".ToType().RequireField("TextureProviders")
                               .GetValue(null) !;

        foreach (var provider in providers)
        {
            if (provider is not null)
                textureProviders.Add(provider);
        }
    }
 public LiveClipboardComponentDisplay(ContentSourceInfo contentSource)
 {
     // if this format handler is "built-in" then override the content-source to
     // list it as "windows-live writer"
     if (ContentSourceManager.ContentSourceIsPlugin(contentSource.Id))
     {
         _icon = contentSource.Image;
         _name = contentSource.Name;
     }
     else
     {
         _icon = _writerLogoBitmap;
         _name = ApplicationEnvironment.ProductName;
     }
 }
Example #19
0
        public static new bool CanCreateFrom(DataObjectMeister data)
        {
            if (!GlobalEditorOptions.SupportsFeature(ContentEditorFeature.UrlContentSourcePaste))
            {
                return(false);
            }

            if (HasUrl(data))
            {
                return(ContentSourceManager.FindContentSourceForUrl(ExtractUrl(data)) != null);
            }
            else
            {
                return(false);
            }
        }
Example #20
0
        public EditableSmartContent(IContentSourceSidebarContext context, SmartContentSource contentSource, IHTMLElement smartContentElement)
        {
            GC.SuppressFinalize(this);
            _contentSourceContext = context;
            _contentSource        = contentSource;
            _smartContentElement  = smartContentElement;

            ContentSourceManager.ParseContainingElementId(_smartContentElement.id, out _contentSourceId, out _smartContentId);

            _smartContent  = _contentSourceContext.FindSmartContent(_smartContentId);
            _extensionData = _contentSourceContext.FindExtentsionData(_smartContentId);

            _properties      = new EditableRootProperties();
            _layout          = new EditableLayoutStyle();
            _supportingFiles = new EditableSupportingFiles();
            MakeSmartContentEditable();
        }
Example #21
0
        public static bool ExecuteSimpleContentRetreival(
            IWin32Window dialogOwner, ContentSourceInfo contentSourceInfo, string url, ref string title, ref string newContent)
        {
            try
            {
                // if there is progress requested then just do it on the main UI thread
                if (contentSourceInfo.UrlContentSourceRequiresProgress)
                {
                    // create the progress dialog and the async operation
                    UrlContentRetreivalWithProgressDialog progressDialog = new UrlContentRetreivalWithProgressDialog(contentSourceInfo);
                    progressDialog.CreateControl();
                    SimpleUrlContentRetreivalAsyncOperation asyncOperation = new SimpleUrlContentRetreivalAsyncOperation(progressDialog, contentSourceInfo.Instance as ContentSource, url, title);

                    // execute and retrieve results
                    if (ExecuteWithProgress(dialogOwner, progressDialog, asyncOperation, contentSourceInfo))
                    {
                        title      = asyncOperation.Title;
                        newContent = asyncOperation.NewContent;
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
                else
                {
                    try
                    {
                        (contentSourceInfo.Instance as ContentSource).CreateContentFromUrl(url, ref title, ref newContent);
                        return(true);
                    }
                    catch (Exception ex)
                    {
                        ContentSourceManager.DisplayContentRetreivalError(dialogOwner, ex, contentSourceInfo);
                        return(false);
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.Fail("Unexpected exception executing network operation for content source: " + ex.ToString());
                return(false);
            }
        }
Example #22
0
        protected override void OnElementAttached()
        {
            base.OnElementAttached();
            (HTMLElement as IHTMLElement3).contentEditable = "false";

            string sourceId;
            string contentId;

            if (HTMLElement.id != null)
            {
                try
                {
                    if (HTMLElement.className == HtmlPreserver.PRESERVE_CLASS)
                    {
                        _contentState = SmartContentState.Preserve;
                    }
                    else
                    {
                        ContentSourceManager.ParseContainingElementId(HTMLElement.id, out sourceId, out contentId);
                        if (sourceId == null || contentId == null)
                        {
                            _contentState = SmartContentState.Broken;
                        }
                        else
                        {
                            if (_contentSourceContext.FindSmartContent(contentId) == null)
                            {
                                _contentState = SmartContentState.Broken;
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    _contentState = SmartContentState.Broken;
                }
            }
            else
            {
                _contentState = SmartContentState.Broken;
            }
        }
Example #23
0
        protected override bool DoInsertData(DataAction action, MarkupPointer begin, MarkupPointer end)
        {
            // lookup the content-source
            ContentSourceInfo contentSource = ContentSourceManager.FindContentSourceForUrl(Url);

            if (contentSource != null)
            {
                // HACK: drive the selection textRange to the caret so we can call generic
                // content-source routines that work off the current selection
                // Note that we do the same thing below for Images so we can use the common
                // InsertImages method -- we may want to bake this into core marshalling
                // or add MarkupRange parameters to the image and content-source routines
                EditorContext.MarkupServices.CreateMarkupRange(begin, end).ToTextRange().select();

                try
                {
                    if (contentSource.Instance is SmartContentSource)
                    {
                        return(InsertSmartContentFromUrl(contentSource, Url));
                    }
                    else if (contentSource.Instance is ContentSource)
                    {
                        return(InsertSimpleContentFromUrl(contentSource, Url));
                    }
                    else
                    {
                        Debug.Fail("Unexpected content source type: " + contentSource.GetType());
                        return(false);
                    }
                }
                catch (Exception ex)
                {
                    Trace.Fail("Unexpected exception inserting content: " + ex.ToString());
                    return(false);
                }
            }
            else
            {
                Debug.Fail("No content source found during marshalling!");
                return(false);
            }
        }
        private void UpdatePluginList()
        {
            BlogPublishingPluginSettings settings = TemporaryBlogSettings.PublishingPluginSettings;

            List <ContentSourceInfo> plugins = new List <ContentSourceInfo>(
                Join(ContentSourceManager.EnabledPublishNotificationPlugins, ContentSourceManager.EnabledHeaderFooterPlugins));

            plugins.Sort(ContentSourceManager.CreateComparison(settings));

            listViewPlugins.BeginUpdate();
            try
            {
                listViewPlugins.Items.Clear();
                imgListPlugins.Images.Clear();

                foreach (ContentSourceInfo csi in plugins)
                {
                    imgListPlugins.Images.Add(BidiHelper.Mirror(csi.Image));
                    ListViewItem item = new ListViewItem();
                    item.Tag        = csi;
                    item.Text       = " " + csi.Name;
                    item.ImageIndex = imgListPlugins.Images.Count - 1;
                    item.Checked    = settings.IsEnabled(csi.Id) ?? false;
                    listViewPlugins.Items.Add(item);
                }

                if (listViewPlugins.Items.Count > 0)
                {
                    listViewPlugins.Items[0].Selected = true;
                }
            }
            finally
            {
                listViewPlugins.EndUpdate();
            }

            ManageMoveButtons();
        }
Example #25
0
        private static bool ExecuteWithProgress(
            IWin32Window dialogOwner,
            UrlContentRetreivalWithProgressDialog progressDialog,
            UrlContentRetreivalAsyncOperation asyncOperation,
            ContentSourceInfo contentSourceInfo)
        {
            try
            {
                // show the progress dialog
                using (progressDialog)
                {
                    asyncOperation.Start();
                    progressDialog.ShowProgress(dialogOwner, asyncOperation);
                }

                //  handle the result
                if (asyncOperation.Error != null)
                {
                    ContentSourceManager.DisplayContentRetreivalError(dialogOwner, asyncOperation.Error, contentSourceInfo);
                    return(false);
                }
                else if (asyncOperation.WasCancelled)
                {
                    return(false);
                }
                else
                {
                    return(true);
                }
            }
            catch (Exception ex)
            {
                Trace.Fail("Unexpected exception executing network operation for content source: " + ex.ToString());
                return(false);
            }
        }
        public static void InsertContentIntoElement(string content, ISmartContent sContent, IContentSourceSidebarContext contentSourceContext, IHTMLElement element)
        {
            MshtmlMarkupServices MarkupServices = new MshtmlMarkupServices((IMarkupServicesRaw)element.document);

            //Note: undo/redo disabled for smart content since undo causes the HTML to get out of sync
            //with the inserter's settings state, so undo changes will be blown away the next time the
            //the inserter's HTML is regenerated.  Also note that making this insertion without wrapping it
            //in an undo clears the undo/redo stack, which is what we want for beta.
            //string undoId = Guid.NewGuid().ToString();

            MarkupRange htmlRange = MarkupServices.CreateMarkupRange(element, false);

            htmlRange.Start.PushCling(true);
            htmlRange.End.PushCling(true);
            MarkupServices.Remove(htmlRange.Start, htmlRange.End);
            htmlRange.Start.PopCling();
            htmlRange.End.PopCling();

            element.style.padding = ToPaddingString(sContent.Layout);

            if (sContent.Layout.Alignment == Alignment.None ||
                sContent.Layout.Alignment == Alignment.Right ||
                sContent.Layout.Alignment == Alignment.Left)
            {
                element.style.display     = "inline";
                element.style.marginLeft  = "0px";
                element.style.marginRight = "0px";
                element.style.styleFloat  = sContent.Layout.Alignment.ToString().ToLower(CultureInfo.InvariantCulture);
            }
            else if (sContent.Layout.Alignment == Alignment.Center)
            {
                element.style.styleFloat  = Alignment.None.ToString().ToLower(CultureInfo.InvariantCulture);
                element.style.display     = "block";
                element.style.marginLeft  = "auto";
                element.style.marginRight = "auto";
            }

            // Clear out any width on the overall smart content block, if the element is centered, we will add the width back in later
            // after we calcuate it from the childern, the current width value is stale.
            element.style.width = "";

            //Note: we use MarkupServices to insert the content so that IE doesn't try to fix up URLs.
            //Element.insertAdjacentHTML() is a no-no because it rewrites relaive URLs to include
            //the fullpath from the local filesytem.

            //MarkupServices.ParseString() doesn't attempt to fix up URLs, so its safe to use.
            //We will now stage the new content into a MarkupContainer, and then move it into
            //the working document.
            MarkupPointer sc1 = MarkupServices.CreateMarkupPointer();
            MarkupPointer sc2 = MarkupServices.CreateMarkupPointer();

            //Create a temporary document from the html and set the start/end pointers to the
            //start and end of the document.
            MarkupServices.ParseString(content, sc1, sc2);
            IHTMLDocument2 doc          = sc1.GetDocument();
            MarkupRange    stagingRange = MarkupServices.CreateMarkupRange(sc1, sc2);

            stagingRange.MoveToElement(doc.body, false);

            //IE7 hack: fixes bug 305512.  Note that this will destroy the inner content of the element,
            //so make sure it is called before the refreshed content is inserted.
            BeforeInsertInvalidateHackForIE7(element);

            //move the content from the staging area into the actual insertion point.
            MarkupServices.Move(stagingRange.Start, stagingRange.End, htmlRange.End);

            if (sContent.Layout.Alignment == Alignment.Center)
            {
                MarkupContext mc    = htmlRange.End.Right(false);
                MarkupRange   range = MarkupServices.CreateMarkupRange(mc.Element, false);

                IHTMLElement[] childern = range.GetTopLevelElements(MarkupRange.FilterNone);

                int maxWidth = 0;
                foreach (IHTMLElement child in childern)
                {
                    maxWidth = Math.Max(maxWidth, child.offsetWidth);
                }

                if (maxWidth != 0)
                {
                    mc.Element.style.width = maxWidth;
                }
            }

            // Let the context provider know the smart content was edited.
            string contentSourceId, contentId;

            ContentSourceManager.ParseContainingElementId(element.id, out contentSourceId, out contentId);
            contentSourceContext.OnSmartContentEdited(contentId);
        }
Example #27
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 #28
0
 /// <summary>
 /// Only edit tables that are not contained within SmartContent blocks and which
 /// are marked with the "unselectable"  attribute. Since this is an attribute which
 /// applies only to editing scenarios it is almost certain never to enter the editor
 /// "from the wild" so it is a  reasonable way to determine whether we created the
 /// table (and thus can guarantee that it conforms to our editing capabilities). The
 /// only other reasonable choice would be to mark the table up with some other
 /// pseudo-hidden metadata, which seems even more undesirable.
 /// </summary>
 public static bool TableElementIsEditable(IHTMLElement element)
 {
     return(TableElementContainsWriterEditingMark(element) &&
            !ContentSourceManager.IsSmartContent(element));
 }
Example #29
0
        public override void UpdateView(object htmlSelection, bool force)
        {
            if (htmlSelection == null) //true when the a non-smartcontent element is selected
            {
                //reset the selected smart content (fixes bug 492456)
                _selectedElement        = null;
                _selectedSmartContentId = null;
                UnloadCurrentEditor();
                return;
            }

            Debug.Assert(htmlSelection is SmartContentSelection || (htmlSelection is IHtmlEditorSelection && InlineEditField.IsEditField(htmlSelection)));


            IHTMLElement          selectedElement       = null;
            SmartContentSelection smartContentSelection = htmlSelection as SmartContentSelection;

            if (smartContentSelection != null && smartContentSelection.ContentState == SmartContentState.Enabled)
            {
                selectedElement = smartContentSelection.HTMLElement;
            }
            else if (htmlSelection is IHtmlEditorSelection)
            {
                selectedElement = ContentSourceManager.GetContainingSmartContent(
                    ((IHtmlEditorSelection)(htmlSelection)).SelectedMarkupRange.ParentElement());
            }


            _currentSelection = htmlSelection;
            if (selectedElement != null)
            {
                //if the selected element id is still the same, then the sidebar is currently
                //in synch with the smart content.
                //Note: the element id will change each time an edit is made to the smart content
                if (!force && _selectedElement != null && _selectedSmartContentId != null && selectedElement.id == _selectedSmartContentId)
                {
                    return;
                }
                else
                {
                    _selectedElement        = selectedElement;
                    _selectedSmartContentId = selectedElement.id;

                    if (_currentEditor != null)
                    {
                        UnloadCurrentEditor();
                    }
                }

                ContentSourceManager.ParseContainingElementId(_selectedElement.id, out _contentSourceId, out _contentItemId);

                SmartContentEditor editor        = (SmartContentEditor)_contentSourceControls[_contentSourceId];
                ContentSourceInfo  contentSource = _contentSourceContext.FindContentSource(_contentSourceId);
                if (contentSource != null && contentSource.Instance is SmartContentSource)
                {
                    _contentSource = (SmartContentSource)contentSource.Instance;

                    if (_editableSmartContent != null)
                    {
                        _editableSmartContent.Dispose();
                    }
                    _editableSmartContent = new EditableSmartContent(_contentSourceContext, _contentSource, _selectedElement);

                    if (editor == null)
                    {
                        editor = _contentSource.CreateEditor(this);

                        if (editor is IActiveSmartContentEditor)
                        {
                            ((IActiveSmartContentEditor)editor).ForceContentEdited += new EventHandler(ContentSourceSidebarControl_ForceContentEdited);
                        }

                        //apply the current scale the new control
                        if (editor != null)
                        {
                            editor.Scale(new SizeF(scale.Width, scale.Height));
                        }
                        _contentSourceControls[_contentSourceId] = editor;
                    }

                    if (editor != null)
                    {
                        editor.ContentEdited  += new EventHandler(_editor_ContentEdited);
                        editor.SelectedContent = _editableSmartContent;

                        EnableableSmartContentEditor enableableSmartContentEditor = editor as EnableableSmartContentEditor;
                        if (enableableSmartContentEditor != null)
                        {
                            enableableSmartContentEditor.ContentEnabled = true;
                        }

                        if (editor != _currentEditor)
                        {
                            if (enableableSmartContentEditor != null)
                            {
                                Controls.Clear();
                            }
                            else
                            {
                                //load the new editor
                                editor.Dock  = DockStyle.Fill;
                                editor.Width = Width - DockPadding.Left - DockPadding.Right;
                                this.Controls.Add(editor);
                            }

                            // set the title caption
                            // Text = String.Format( CultureInfo.CurrentCulture, Res.Get(StringId.PluginSidebarTitle), contentSource.InsertableContentSourceSidebarText ) ;
                        }
                    }
                }
                _currentEditor = editor;
            }
            else
            {
                _currentEditor = null;
            }
        }
 private bool IsSelectableControlElement(IHTMLElement e)
 {
     return(ElementFilters.IsImageElement(e) || ContentSourceManager.IsSmartContent(e));
 }