Exemplo n.º 1
0
        /// <summary>
        ///   Determines whether a <see cref="Wallpaper" /> object is in one of the <see cref="WallpaperCategory" /> instances or
        ///   not.
        /// </summary>
        /// <param name="wallpaper">
        ///   The <see cref="Wallpaper" /> object to check for.
        /// </param>
        /// <returns>
        ///   A <see cref="bool" /> indicating whether one of the <see cref="WallpaperCategory" /> instances contains a given
        ///   <see cref="Wallpaper" /> object or not.
        /// </returns>
        protected bool IsWallpaperInAnyCategory(Wallpaper wallpaper)
        {
            foreach (WallpaperCategory category in this)
            {
                if (category.Contains(wallpaper))
                {
                    return(true);
                }
            }

            return(false);
        }
Exemplo n.º 2
0
        /// <inheritdoc />
        public override object Clone()
        {
            Wallpaper clonedInstance = new Wallpaper(this.ImagePath);

            // Clone all fields defined by WallpaperSettingsBase.
            base.Clone(clonedInstance);

            clonedInstance.IsBlank   = this.IsBlank;
            clonedInstance.imagePath = this.ImagePath;
            clonedInstance.imageSize = this.ImageSize;

            return(clonedInstance);
        }
Exemplo n.º 3
0
        /// <summary>
        ///   Initializes a new instance of the <see cref="ScreenSettings" /> class for the screen with the given index.
        /// </summary>
        /// <param name="index">
        ///   The index of the screen of which this instance defines settings for.
        /// </param>
        public ScreenSettings(int index)
        {
            this.Index           = index;
            this.cycleRandomly   = true;
            this.staticWallpaper = null;
            this.staticWallpaper = new Wallpaper();

            this.Margins = new ScreenMargins();
            PropertyChangedEventManager.AddListener(this.Margins, this, string.Empty);

            // Cache the Bounds and BoundsWithMargin rectangles for this first time.
            this.RefreshBounds();

            this.TextOverlays = new ObservableCollection <WallpaperTextOverlay>();
        }
Exemplo n.º 4
0
        /// <summary>
        ///   Creates a new <see cref="Wallpaper" /> instance and adds it to the collection.
        /// </summary>
        /// <param name="imagePath">
        ///   The path of the wallpaper image.
        /// </param>
        /// <remarks>
        ///   <para>
        ///     The wallpaper is created asynchronously by using a <see cref="BackgroundWorker" />. If two wallpapers refering to
        ///     the same image paths are added, one of them will be automatically ignored.
        ///   </para>
        ///   <para>
        ///     If the file where <paramref name="imagePath" /> is refering to is not found, no exception will be thrown.
        ///   </para>
        /// </remarks>
        /// <exception cref="ArgumentNullException">
        ///   <paramref name="imagePath" /> is <c>null</c>.
        /// </exception>
        private void AddAsync(Path imagePath)
        {
            if (imagePath == Path.None)
            {
                throw new ArgumentException();
            }

            BackgroundWorker worker = new BackgroundWorker();

            worker.DoWork += (sender, e) => {
                Path      imagePathLocal = (Path)e.Argument;
                Wallpaper newWallpaper   = new Wallpaper(imagePathLocal);

                using (Image wallpaperImage = Image.FromFile(imagePathLocal))
                    newWallpaper.ImageSize = wallpaperImage.Size;

                e.Result = newWallpaper;
            };

            worker.RunWorkerCompleted += (sender, e) => {
                if (e.Error != null)
                {
                    // We simply ignore if the file couldn't be found or is invalid / unsupported.
                    if ((e.Error is FileNotFoundException) || (e.Error is OutOfMemoryException))
                    {
                        return;
                    }

                    throw e.Error;
                }

                if (!e.Cancelled)
                {
                    Wallpaper newWallpaperLocal = (Wallpaper)e.Result;

                    // Make sure the item wasn't already added by another thread.
                    if (this.IndexOfByImagePath(newWallpaperLocal.ImagePath) == -1)
                    {
                        base.InsertItem(this.Count, newWallpaperLocal);
                    }
                }

                ((BackgroundWorker)sender).Dispose();
            };

            // By using BackgroundWorker we make sure this operation is thread safe.
            worker.RunWorkerAsync(imagePath);
        }
Exemplo n.º 5
0
        /// <summary>
        ///   Assigns all member values of this instance to the respective members of the given instance.
        /// </summary>
        /// <param name="other">
        ///   The target instance to assign to.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///   <paramref name="other" /> is <c>null</c>.
        /// </exception>
        protected override void AssignTo(WallpaperSettingsBase other)
        {
            if (other == null)
            {
                throw new ArgumentNullException();
            }

            // Assign all members defined by WallpaperSettingsBase.
            base.AssignTo(other);

            Wallpaper wallpaperInstance = (other as Wallpaper);

            if (wallpaperInstance != null)
            {
                wallpaperInstance.ImagePath = this.ImagePath;
                wallpaperInstance.ImageSize = this.ImageSize;
            }
        }
Exemplo n.º 6
0
        /// <summary>
        ///   Draws a wallpaper image by using the given <see cref="Graphics" /> object.
        /// </summary>
        /// <param name="destGraphics">
        ///   The <see cref="Graphics" /> object used to draw.
        /// </param>
        /// <param name="destScreenRect">
        ///   The destination screen's rectangle.
        /// </param>
        /// <param name="wallpaper">
        ///   The <see cref="Wallpaper" /> object to draw.
        /// </param>
        /// <param name="placement">
        ///   The type how the wallpaper image should be aligned.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///   <paramref name="destGraphics" /> is <c>null</c> or <paramref name="wallpaper" /> is <c>null</c>.
        /// </exception>
        /// <exception cref="ArgumentOutOfRangeException">
        ///   <paramref name="placement" /> is not a constant defined by the <see cref="WallpaperPlacement" /> enumeration.
        /// </exception>
        /// <seealso cref="Graphics">Graphics Class</seealso>
        /// <seealso cref="Wallpaper">Wallpaper Class</seealso>
        /// <seealso cref="WallpaperPlacement">WallpaperPlacement Enumeration</seealso>
        /// .
        protected static void DrawWallpaper(Graphics destGraphics, Rectangle destScreenRect, Wallpaper wallpaper, WallpaperPlacement placement)
        {
            if (destGraphics == null)
            {
                throw new ArgumentNullException();
            }
            if (wallpaper == null)
            {
                throw new ArgumentNullException();
            }
            if (!Enum.IsDefined(typeof(WallpaperPlacement), placement))
            {
                throw new ArgumentException();
            }

            using (SolidBrush backgroundBrush = new SolidBrush(wallpaper.BackgroundColor))
                destGraphics.FillRectangle(backgroundBrush, destScreenRect);

            if ((wallpaper.ImagePath != Path.None) && (File.Exists(wallpaper.ImagePath)))
            {
                Image originalImage = null;
                Image imageToDraw   = null;

                try {
                    originalImage = Image.FromFile(wallpaper.ImagePath);
                    imageToDraw   = originalImage;

                    if (wallpaper.Effects != 0)
                    {
                        #region Mirror Effect
                        // Required images to draw for the mirror effect.
                        int horizontalImages = 1;
                        int verticalImages   = 1;

                        // This values "move" the texture of the brush.
                        int          horizontalBrushTransform = 0;
                        int          verticalBrushTransform   = 0;
                        TextureBrush mirrorBrush = new TextureBrush(originalImage, WrapMode.TileFlipXY);

                        if (((wallpaper.Effects & WallpaperEffects.MirrorLeft) == WallpaperEffects.MirrorLeft))
                        {
                            horizontalImages++;
                            mirrorBrush.WrapMode = WrapMode.TileFlipX;

                            // This will make the brush start with the mirrored image.
                            horizontalBrushTransform = originalImage.Width;
                        }
                        if (((wallpaper.Effects & WallpaperEffects.MirrorRight) == WallpaperEffects.MirrorRight))
                        {
                            horizontalImages++;
                            mirrorBrush.WrapMode = WrapMode.TileFlipX;

                            if (((wallpaper.Effects & WallpaperEffects.MirrorLeft) != WallpaperEffects.MirrorLeft))
                            {
                                // This will make the brush start with the unmirrored image.
                                horizontalBrushTransform = 0;
                            }
                        }

                        if (((wallpaper.Effects & WallpaperEffects.FlipHorizontal) == WallpaperEffects.FlipHorizontal))
                        {
                            mirrorBrush.WrapMode = WrapMode.TileFlipX;

                            if (horizontalBrushTransform == 0)
                            {
                                // This will make the brush start with the mirrored image.
                                horizontalBrushTransform = originalImage.Width;
                            }
                            else
                            {
                                // This will make the brush start with the unmirrored image.
                                horizontalBrushTransform = 0;
                            }
                        }

                        if (((wallpaper.Effects & WallpaperEffects.MirrorTop) == WallpaperEffects.MirrorTop))
                        {
                            verticalImages++;

                            if (mirrorBrush.WrapMode != WrapMode.TileFlipXY)
                            {
                                if (mirrorBrush.WrapMode == WrapMode.TileFlipX)
                                {
                                    mirrorBrush.WrapMode = WrapMode.TileFlipXY;
                                }
                                else
                                {
                                    mirrorBrush.WrapMode = WrapMode.TileFlipY;
                                }
                            }

                            // This will make the brush start with the mirrored image.
                            verticalBrushTransform = originalImage.Height;
                        }
                        if (((wallpaper.Effects & WallpaperEffects.MirrorBottom) == WallpaperEffects.MirrorBottom))
                        {
                            verticalImages++;

                            if (mirrorBrush.WrapMode != WrapMode.TileFlipXY)
                            {
                                if (mirrorBrush.WrapMode == WrapMode.TileFlipX)
                                {
                                    mirrorBrush.WrapMode = WrapMode.TileFlipXY;
                                }
                                else
                                {
                                    mirrorBrush.WrapMode = WrapMode.TileFlipY;
                                }
                            }

                            if (((wallpaper.Effects & WallpaperEffects.MirrorTop) != WallpaperEffects.MirrorTop))
                            {
                                // This will make the brush start with the unmirrored image.
                                verticalBrushTransform = 0;
                            }
                        }

                        if (((wallpaper.Effects & WallpaperEffects.FlipVertical) == WallpaperEffects.FlipVertical))
                        {
                            if (mirrorBrush.WrapMode != WrapMode.TileFlipXY)
                            {
                                if (mirrorBrush.WrapMode == WrapMode.TileFlipX)
                                {
                                    mirrorBrush.WrapMode = WrapMode.TileFlipXY;
                                }
                                else
                                {
                                    mirrorBrush.WrapMode = WrapMode.TileFlipY;
                                }
                            }

                            if (verticalBrushTransform == 0)
                            {
                                // This will make the brush start with the mirrored image.
                                verticalBrushTransform = originalImage.Height;
                            }
                            else
                            {
                                // This will make the brush start with the unmirrored image.
                                verticalBrushTransform = 0;
                            }
                        }

                        mirrorBrush.TranslateTransform(horizontalBrushTransform, verticalBrushTransform);

                        Image modifiedImage = new Bitmap(originalImage.Width * horizontalImages, originalImage.Height * verticalImages);

                        Graphics modifiedImageGraphics = null;
                        try {
                            modifiedImageGraphics = Graphics.FromImage(modifiedImage);
                            modifiedImageGraphics.FillRectangle(mirrorBrush, new Rectangle(0, 0, modifiedImage.Width, modifiedImage.Height));

                            imageToDraw = modifiedImage;
                        } finally {
                            modifiedImageGraphics?.Dispose();
                        }
                        #endregion
                    }

                    GraphicsContainer graphicalContext = null;
                    try {
                        graphicalContext = destGraphics.BeginContainer();

                        // Place the origin in the center of the screen.
                        float xTranslationForScale = destScreenRect.X + (destScreenRect.Width / 2f);
                        float yTranslationForScale = destScreenRect.Y + (destScreenRect.Height / 2f);
                        destGraphics.TranslateTransform(xTranslationForScale, yTranslationForScale);
                        destGraphics.ScaleTransform((wallpaper.Scale.X + 100) / 100f, (wallpaper.Scale.Y + 100) / 100f);
                        // And reset it, that way we have a nice scaling of the image.
                        destGraphics.TranslateTransform(-xTranslationForScale, -yTranslationForScale);

                        // Now apply the offset.
                        destGraphics.TranslateTransform(wallpaper.Offset.X, wallpaper.Offset.Y);

                        destGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        destGraphics.PixelOffsetMode   = PixelOffsetMode.Half;
                        destGraphics.CompositingMode   = CompositingMode.SourceOver;

                        switch (placement)
                        {
                        case WallpaperPlacement.Uniform:
                            destGraphics.DrawImageUniformed(imageToDraw, destScreenRect);

                            break;

                        case WallpaperPlacement.UniformToFill:
                            destGraphics.DrawImageUniformedToFill(imageToDraw, destScreenRect);

                            break;

                        case WallpaperPlacement.Stretch:
                            destGraphics.DrawImage(imageToDraw, destScreenRect);

                            break;

                        case WallpaperPlacement.Center:
                            destGraphics.DrawImageCentered(imageToDraw, destScreenRect);

                            break;

                        case WallpaperPlacement.Tile:
                            destGraphics.ScaleTransform((wallpaper.Scale.X + 100) / 100f, (wallpaper.Scale.Y + 100) / 100f);
                            destGraphics.DrawImageTiled(imageToDraw, destScreenRect);

                            break;
                        }
                    } finally {
                        if (graphicalContext != null)
                        {
                            destGraphics.EndContainer(graphicalContext);
                        }
                    }
                } finally {
                    originalImage?.Dispose();
                    imageToDraw?.Dispose();
                }
            }
        }
Exemplo n.º 7
0
        /// <summary>
        ///   Creates a multiscreen wallpaper from one <see cref="Wallpaper" /> object (from one image).
        /// </summary>
        /// <inheritdoc cref="CreateMultiscreenFromMultipleInternal" select='remarks|param|returns' />
        /// <param name="multiscreenWallpaper">
        ///   The <see cref="Wallpaper" /> object to use.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///   <paramref name="multiscreenWallpaper" /> is <c>null</c>.
        /// </exception>
        /// <exception cref="FileNotFoundException">
        ///   The image file where the <paramref name="multiscreenWallpaper" /> object refers to could not be found.
        /// </exception>
        /// <seealso cref="Wallpaper">Wallpaper Class</seealso>
        public Image CreateMultiscreenFromSingle(Wallpaper multiscreenWallpaper, float scaleFactor, bool useWindowsFix)
        {
            if (multiscreenWallpaper == null)
            {
                throw new ArgumentNullException();
            }

            Rectangle fullScreenBounds = WallpaperBuilderBase.FullScreenBounds;
            Bitmap    wallpaperImage   = new Bitmap((int)(fullScreenBounds.Width * scaleFactor), (int)(fullScreenBounds.Height * scaleFactor));

            using (Graphics graphics = Graphics.FromImage(wallpaperImage)) {
                Graphics destinationGraphics = graphics;
                Bitmap   preWallpaperImage   = null;

                try {
                    // If the fullscreenbounds rectangle has a negative x or y values, we normalize them by using 0,0 as origin and adding
                    // the difference to each drawn wallpaper later.
                    int xOriginAdd;
                    if (fullScreenBounds.X < 0)
                    {
                        xOriginAdd = Math.Abs(WallpaperBuilderBase.FullScreenBounds.X);
                    }
                    else
                    {
                        xOriginAdd = 0;
                    }

                    int yOriginAdd;
                    if (fullScreenBounds.Y < 0)
                    {
                        yOriginAdd = Math.Abs(WallpaperBuilderBase.FullScreenBounds.Y);
                    }
                    else
                    {
                        yOriginAdd = 0;
                    }

                    // Check if we have to redraw the end-wallpaper to fix it for Windows.
                    bool requiresWindowsFix = ((useWindowsFix) && ((fullScreenBounds.Left < 0) || (fullScreenBounds.Top < 0)));

                    if (requiresWindowsFix)
                    {
                        // We have to redraw it, we need another temporary image and draw on this one instead.
                        preWallpaperImage   = new Bitmap(wallpaperImage.Width, wallpaperImage.Height);
                        destinationGraphics = Graphics.FromImage(preWallpaperImage);
                    }

                    destinationGraphics.ScaleTransform(scaleFactor, scaleFactor);

                    // The rectangle of the multiscreen wallpaper should span across all screens except the ones which should display
                    // a statical wallpaper.
                    Rectangle?multiscreenWallpaperRect = null;

                    for (int i = 0; i < this.ScreensSettings.Count; i++)
                    {
                        if (this.ScreensSettings[i].CycleRandomly || !this.ScreensSettings[i].StaticWallpaper.EvaluateCycleConditions())
                        {
                            if (multiscreenWallpaperRect == null)
                            {
                                multiscreenWallpaperRect = this.ScreensSettings[i].BoundsWithMargin;
                            }
                            else
                            {
                                multiscreenWallpaperRect = Rectangle.Union(multiscreenWallpaperRect.Value, this.ScreensSettings[i].BoundsWithMargin);
                            }
                        }
                    }

                    // null would mean that all screens should display static wallpapers.
                    if (multiscreenWallpaperRect != null)
                    {
                        Rectangle multiscreenWallpaperRectValue = multiscreenWallpaperRect.Value;
                        multiscreenWallpaperRectValue.X += xOriginAdd;
                        multiscreenWallpaperRectValue.Y += yOriginAdd;

                        destinationGraphics.SetClip(multiscreenWallpaperRectValue);
                        WallpaperBuilderBase.DrawWallpaper(destinationGraphics, multiscreenWallpaperRectValue, multiscreenWallpaper, multiscreenWallpaper.Placement);
                        destinationGraphics.ResetClip();
                    }

                    // Draw or overdraw all static wallpapers and draw the Overlay Texts for all screens.
                    for (int i = 0; i < this.ScreensSettings.Count; i++)
                    {
                        destinationGraphics.SetClip(this.ScreensSettings[i].BoundsWithMargin);

                        if (!this.ScreensSettings[i].CycleRandomly && this.ScreensSettings[i].StaticWallpaper.EvaluateCycleConditions())
                        {
                            WallpaperBuilderBase.DrawWallpaper(
                                destinationGraphics,
                                this.ScreensSettings[i].BoundsWithMargin,
                                this.ScreensSettings[i].StaticWallpaper,
                                this.ScreensSettings[i].StaticWallpaper.Placement);
                        }

                        WallpaperBuilderBase.DrawOverlayTexts(
                            destinationGraphics,
                            this.ScreensSettings[i].BoundsWithMargin,
                            new[] { multiscreenWallpaper },
                            this.ScreensSettings[i].TextOverlays);
                        destinationGraphics.ResetClip();
                    }

                    if (requiresWindowsFix)
                    {
                        // Now redraw the wallpaper but fixed.
                        WallpaperBuilderBase.DrawFullWallpaperFixed(graphics, preWallpaperImage);
                    }
                } finally {
                    destinationGraphics.Dispose();
                    preWallpaperImage?.Dispose();
                }
            }

            return(wallpaperImage);
        }
Exemplo n.º 8
0
 /// <inheritdoc />
 protected override void SetItem(int index, Wallpaper item)
 {
     // TODO: Throwing this exception is not allowed here.
     throw new InvalidOperationException("Category is read only.");
 }
Exemplo n.º 9
0
        /// <summary>
        ///   Adds wallpaper related settings to a given <see cref="XmlElement" />.
        /// </summary>
        /// <param name="document">
        ///   The <see cref="XmlDocument" /> to add the data for.
        /// </param>
        /// <param name="element">
        ///   The <see cref="XmlElement" /> to add the data to.
        /// </param>
        /// <param name="wallpaperBaseSettings">
        ///   The wallpaper settings to add.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///   <paramref name="document" /> or <paramref name="element" /> or <paramref name="wallpaperBaseSettings" /> is
        ///   <c>null</c>.
        /// </exception>
        protected static void AddWallpaperDataToXmlElement(XmlDocument document, XmlElement element, WallpaperSettingsBase wallpaperBaseSettings)
        {
            if (document == null)
            {
                throw new ArgumentNullException();
            }
            if (element == null)
            {
                throw new ArgumentNullException();
            }
            if (wallpaperBaseSettings == null)
            {
                throw new ArgumentNullException();
            }

            Wallpaper wallpaperSettings = (wallpaperBaseSettings as Wallpaper);
            WallpaperDefaultSettings defaultSettings = (wallpaperBaseSettings as WallpaperDefaultSettings);
            XmlElement currentElement;

            if (wallpaperSettings != null)
            {
                currentElement = document.CreateElement("ImagePath");
                if (wallpaperSettings.ImagePath != Path.None)
                {
                    currentElement.InnerText = wallpaperSettings.ImagePath;
                }
                element.AppendChild(currentElement);
            }

            currentElement           = document.CreateElement("IsActivated");
            currentElement.InnerText = wallpaperBaseSettings.IsActivated.ToString();
            element.AppendChild(currentElement);

            currentElement           = document.CreateElement("IsMultiscreen");
            currentElement.InnerText = wallpaperBaseSettings.IsMultiscreen.ToString();
            element.AppendChild(currentElement);

            currentElement           = document.CreateElement("Priority");
            currentElement.InnerText = wallpaperBaseSettings.Priority.ToString(CultureInfo.InvariantCulture);
            element.AppendChild(currentElement);

            currentElement           = document.CreateElement("OnlyCycleBetweenStart");
            currentElement.InnerText = wallpaperBaseSettings.OnlyCycleBetweenStart.ToString();
            element.AppendChild(currentElement);

            currentElement           = document.CreateElement("OnlyCycleBetweenStop");
            currentElement.InnerText = wallpaperBaseSettings.OnlyCycleBetweenStop.ToString();
            element.AppendChild(currentElement);

            currentElement           = document.CreateElement("Placement");
            currentElement.InnerText = wallpaperBaseSettings.Placement.ToString();
            element.AppendChild(currentElement);

            currentElement           = document.CreateElement("HorizontalOffset");
            currentElement.InnerText = wallpaperBaseSettings.Offset.X.ToString(CultureInfo.InvariantCulture);
            element.AppendChild(currentElement);

            currentElement           = document.CreateElement("VerticalOffset");
            currentElement.InnerText = wallpaperBaseSettings.Offset.Y.ToString(CultureInfo.InvariantCulture);
            element.AppendChild(currentElement);

            currentElement           = document.CreateElement("HorizontalScale");
            currentElement.InnerText = wallpaperBaseSettings.Scale.X.ToString(CultureInfo.InvariantCulture);
            element.AppendChild(currentElement);

            currentElement           = document.CreateElement("VerticalScale");
            currentElement.InnerText = wallpaperBaseSettings.Scale.Y.ToString(CultureInfo.InvariantCulture);
            element.AppendChild(currentElement);

            currentElement           = document.CreateElement("Effects");
            currentElement.InnerText = wallpaperBaseSettings.Effects.ToString();
            element.AppendChild(currentElement);

            currentElement           = document.CreateElement("BackgroundColor");
            currentElement.InnerText = ColorTranslator.ToHtml(wallpaperBaseSettings.BackgroundColor);
            element.AppendChild(currentElement);

            currentElement = document.CreateElement("DisabledScreens");
            StringBuilder disabledScreensString = new StringBuilder(wallpaperBaseSettings.DisabledScreens.Count * 2);

            for (int i = 0; i < wallpaperBaseSettings.DisabledScreens.Count; i++)
            {
                if (i > 0)
                {
                    disabledScreensString.Append(',');
                }

                disabledScreensString.Append(wallpaperBaseSettings.DisabledScreens[i]);
            }
            currentElement.InnerText = disabledScreensString.ToString();
            element.AppendChild(currentElement);

            if (defaultSettings != null)
            {
                currentElement           = document.CreateElement("AutoDetermineIsMultiscreen");
                currentElement.InnerText = defaultSettings.AutoDetermineIsMultiscreen.ToString(CultureInfo.InvariantCulture);
                element.AppendChild(currentElement);

                currentElement           = document.CreateElement("AutoDeterminePlacement");
                currentElement.InnerText = defaultSettings.AutoDeterminePlacement.ToString(CultureInfo.InvariantCulture);
                element.AppendChild(currentElement);
            }
        }
Exemplo n.º 10
0
        /// <summary>
        ///   Gets wallpaper related settings from a given <see cref="XmlElement" />.
        /// </summary>
        /// <param name="element">
        ///   The <see cref="XmlElement" /> to get the data from.
        /// </param>
        /// <param name="wallpaperSettingsType">
        ///   The type of the wallpaper settings to read.
        /// </param>
        /// <returns>
        ///   An instance of a type inherited from <see cref="WallpaperSettingsBase" /> containing the data get from the
        ///   <see cref="XmlElement" />.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        ///   <paramref name="element" /> or <paramref name="wallpaperSettingsType" /> is <c>null</c>.
        /// </exception>
        /// <exception cref="XmlException">
        ///   The XML Data are invalid.
        /// </exception>
        protected static WallpaperSettingsBase GetWallpaperDataFromXmlElement(XmlElement element, Type wallpaperSettingsType)
        {
            if (element == null)
            {
                throw new ArgumentNullException();
            }
            if (wallpaperSettingsType == null)
            {
                throw new ArgumentNullException();
            }

            WallpaperSettingsBase    settings        = null;
            WallpaperDefaultSettings defaultSettings = null;
            XmlElement subElement;

            if (wallpaperSettingsType == typeof(Wallpaper))
            {
                subElement = element["ImagePath"];
                if (subElement != null)
                {
                    Wallpaper wallpaper;

                    if (subElement.InnerText.Length > 0)
                    {
                        wallpaper = new Wallpaper(new Path(subElement.InnerText));
                    }
                    else
                    {
                        wallpaper = new Wallpaper();
                    }

                    wallpaper.SuggestIsMultiscreen = false;
                    wallpaper.SuggestPlacement     = false;
                    settings = wallpaper;
                }
            }
            else if (wallpaperSettingsType == typeof(WallpaperDefaultSettings))
            {
                defaultSettings = new WallpaperDefaultSettings();
                settings        = defaultSettings;
            }

            if (settings == null)
            {
                throw new XmlException("A wallpaper setting node is missing.");
            }

            subElement = element["IsActivated"];
            if (subElement != null)
            {
                settings.IsActivated = bool.Parse(subElement.InnerText);
            }

            subElement = element["IsMultiscreen"];
            if (subElement != null)
            {
                settings.IsMultiscreen = bool.Parse(subElement.InnerText);
            }

            subElement = element["Priority"];
            if (subElement != null)
            {
                settings.Priority = byte.Parse(subElement.InnerText, CultureInfo.InvariantCulture);
            }

            subElement = element["OnlyCycleBetweenStart"];
            if (subElement != null)
            {
                settings.OnlyCycleBetweenStart = TimeSpan.Parse(subElement.InnerText, CultureInfo.InvariantCulture);
            }

            subElement = element["OnlyCycleBetweenStop"];
            if (subElement != null)
            {
                settings.OnlyCycleBetweenStop = TimeSpan.Parse(subElement.InnerText, CultureInfo.InvariantCulture);
            }

            subElement = element["Placement"];
            if (subElement != null)
            {
                settings.Placement = (WallpaperPlacement)Enum.Parse(typeof(WallpaperPlacement), subElement.InnerText);
            }

            subElement = element["HorizontalOffset"];
            if (subElement != null)
            {
                int horizontalOffset = int.Parse(subElement.InnerText, CultureInfo.InvariantCulture);

                subElement = element["VerticalOffset"];
                if (subElement != null)
                {
                    settings.Offset = new Point(horizontalOffset, int.Parse(subElement.InnerText, CultureInfo.InvariantCulture));
                }
            }

            subElement = element["HorizontalScale"];
            if (subElement != null)
            {
                int horizontalScale = int.Parse(subElement.InnerText, CultureInfo.InvariantCulture);

                subElement = element["VerticalScale"];
                if (subElement != null)
                {
                    settings.Offset = new Point(horizontalScale, int.Parse(subElement.InnerText, CultureInfo.InvariantCulture));
                }
            }

            subElement = element["Effects"];
            if (subElement != null)
            {
                settings.Effects = (WallpaperEffects)Enum.Parse(typeof(WallpaperEffects), subElement.InnerText);
            }

            subElement = element["BackgroundColor"];
            if (subElement != null)
            {
                settings.BackgroundColor = ColorTranslator.FromHtml(subElement.InnerText);
            }

            subElement = element["DisabledScreens"];
            if (subElement != null)
            {
                string[] disabledScreens = subElement.InnerText.Split(',');

                for (int i = 0; i < disabledScreens.Length; i++)
                {
                    string disabledScreenString = disabledScreens[i].Trim();

                    if (disabledScreens[i].Length != 0)
                    {
                        settings.DisabledScreens.Add(int.Parse(disabledScreenString, CultureInfo.InvariantCulture));
                    }
                }
            }

            if (defaultSettings != null)
            {
                subElement = element["AutoDetermineIsMultiscreen"];
                if (subElement != null)
                {
                    defaultSettings.AutoDetermineIsMultiscreen = bool.Parse(subElement.InnerText);
                }

                subElement = element["AutoDeterminePlacement"];
                if (subElement != null)
                {
                    defaultSettings.AutoDeterminePlacement = bool.Parse(subElement.InnerText);
                }
            }

            return(settings);
        }
Exemplo n.º 11
0
        // TODO: Use XmlSerializer for reading and writing the config.
        // TODO: Extract Read/Write functionality into a new class (and interface perhaps)
        /// <summary>
        ///   Creates a new <see cref="Configuration" /> instance by reading the data from a <see cref="Stream" />.
        /// </summary>
        /// <remarks>
        ///   This method reads Wallpaper Manager configuration files (version 1.0, 1.1 and 1.2) by using
        ///   <see cref="XmlDocument" />.
        /// </remarks>
        /// <param name="sourceStream">
        ///   The source <see cref="Stream" /> to read from.
        /// </param>
        /// <returns>
        ///   A new <see cref="Configuration" /> instance containing the read data.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        ///   <paramref name="sourceStream" /> is <c>null</c>.
        /// </exception>
        /// <exception cref="IOException">
        ///   <paramref name="sourceStream" /> is not readable.
        /// </exception>
        /// <exception cref="XmlException">
        ///   There is a load or parse error in the XML-Data.
        /// </exception>
        /// <exception cref="InvalidOperationException">
        ///   Error while deserializing. Refer to the object returned by the  <see cref="Exception.InnerException" /> property
        ///   for details.
        /// </exception>
        /// <overloads>
        ///   <summary>
        ///     Creates a new <see cref="Configuration" /> instance by reading the data from a data source.
        ///   </summary>
        ///   <returns>
        ///     A new <see cref="Configuration" /> instance containing the read data.
        ///   </returns>
        /// </overloads>
        /// <seealso cref="Stream">Stream Class</seealso>
        public static Configuration Read(Stream sourceStream)
        {
            if (sourceStream == null)
            {
                throw new ArgumentNullException();
            }
            if (!sourceStream.CanRead)
            {
                throw new IOException();
            }

            XmlDocument document = new XmlDocument();

            document.Load(sourceStream);

            if ((document.DocumentElement == null) || (document.DocumentElement.Name != Configuration.RootNodeName))
            {
                throw new XmlException("The configuration file has an invalid root element.");
            }

            XmlAttribute versionAttribute = document.DocumentElement.Attributes["Version"];
            Version      configVersion;

            if ((versionAttribute == null) || (!Version.TryParse(versionAttribute.InnerText, out configVersion)))
            {
                throw new XmlException("The configuration file has an invalid root element.");
            }

            Configuration configuration = new Configuration();

            #region <General>
            XmlElement generalElement = document.DocumentElement["General"];
            if (generalElement == null)
            {
                throw new XmlException("The configuration file does not contain expected element 'General'.");
            }

            XmlElement element = generalElement["CycleAfterStartup"];
            if (element != null)
            {
                configuration.General.CycleAfterStartup = bool.Parse(element.InnerText);
            }

            element = generalElement["TerminateAfterStartup"];
            if (element != null)
            {
                configuration.General.TerminateAfterStartup = bool.Parse(element.InnerText);
            }

            element = (generalElement["MinimizeAfterStart"] ?? generalElement["MinimizeAfterStartup"]);
            if (element != null)
            {
                configuration.General.MinimizeAfterStartup = bool.Parse(element.InnerText);
            }

            element = generalElement["StartAutoCyclingAfterStartup"];
            if (element != null)
            {
                configuration.General.StartAutocyclingAfterStartup = bool.Parse(element.InnerText);
            }

            element = generalElement["WallpaperChangeType"];
            if (element != null)
            {
                configuration.General.WallpaperChangeType = (WallpaperChangeType)Enum.Parse(typeof(WallpaperChangeType), element.InnerText);
            }

            element = generalElement["AutoCycleInterval"];
            if (element != null)
            {
                configuration.General.AutocycleInterval = TimeSpan.Parse(element.InnerText, CultureInfo.InvariantCulture);
            }

            element = generalElement["LastActiveListSize"];
            if (element != null)
            {
                configuration.General.LastActiveListSize = byte.Parse(element.InnerText, CultureInfo.InvariantCulture);
            }

            element = generalElement["CycleAfterDisplaySettingsChanged"];
            if (element != null)
            {
                configuration.General.CycleAfterDisplaySettingsChanged = bool.Parse(element.InnerText);
            }

            element = generalElement["MinimizeOnClose"];
            if (element != null)
            {
                configuration.General.MinimizeOnClose = bool.Parse(element.InnerText);
            }

            element = generalElement["DisplayCycleTimeAsIconOverlay"];
            if (element != null)
            {
                configuration.General.DisplayCycleTimeAsIconOverlay = bool.Parse(element.InnerText);
            }

            element = generalElement["WallpaperDoubleClickAction"];
            if (element != null)
            {
                configuration.General.WallpaperDoubleClickAction = (WallpaperClickAction)Enum.Parse(typeof(WallpaperClickAction), element.InnerText);
            }

            element = generalElement["TrayIconSingleClickAction"];
            if (element != null)
            {
                configuration.General.TrayIconSingleClickAction = (TrayIconClickAction)Enum.Parse(typeof(TrayIconClickAction), element.InnerText);
            }

            element = generalElement["TrayIconDoubleClickAction"];
            if (element != null)
            {
                configuration.General.TrayIconDoubleClickAction = (TrayIconClickAction)Enum.Parse(typeof(TrayIconClickAction), element.InnerText);
            }
            #endregion

            #region <ScreensSettings>
            XmlElement screensSettingsElement = document.DocumentElement["ScreensSettings"];
            if (screensSettingsElement != null)
            {
                int settingsCounter = 0;
                var screensSettings = new List <ScreenSettings>();

                foreach (XmlElement screenSettingsElement in screensSettingsElement)
                {
                    if (screenSettingsElement.Name != "ScreenSettings")
                    {
                        continue;
                    }

                    // Make sure there aren't too many screen settings in the configuration.
                    if (settingsCounter >= Screen.AllScreens.Length)
                    {
                        break;
                    }

                    ScreenSettings screenSettings = new ScreenSettings(settingsCounter);
                    element = screenSettingsElement["CycleRandomly"];
                    if (element != null)
                    {
                        screenSettings.CycleRandomly = bool.Parse(element.InnerText);
                    }

                    element = screenSettingsElement["MarginLeft"];
                    if (element != null)
                    {
                        screenSettings.Margins.Left = int.Parse(element.InnerText, CultureInfo.InvariantCulture);
                    }

                    element = screenSettingsElement["MarginRight"];
                    if (element != null)
                    {
                        screenSettings.Margins.Right = int.Parse(element.InnerText, CultureInfo.InvariantCulture);
                    }

                    element = screenSettingsElement["MarginTop"];
                    if (element != null)
                    {
                        screenSettings.Margins.Top = int.Parse(element.InnerText, CultureInfo.InvariantCulture);
                    }

                    element = screenSettingsElement["MarginBottom"];
                    if (element != null)
                    {
                        screenSettings.Margins.Bottom = int.Parse(element.InnerText, CultureInfo.InvariantCulture);
                    }

                    #region <OverlayTexts>
                    XmlElement overlayTextsElement = screenSettingsElement["OverlayTexts"];
                    if (overlayTextsElement != null)
                    {
                        foreach (XmlElement overlayTextElement in overlayTextsElement)
                        {
                            if (overlayTextElement.Name != "OverlayText")
                            {
                                continue;
                            }
                            WallpaperTextOverlay textOverlay = new WallpaperTextOverlay();

                            element = overlayTextElement["Format"];
                            if (element != null)
                            {
                                textOverlay.Format = element.InnerText;
                            }

                            element = overlayTextElement["Position"];
                            if (element != null)
                            {
                                textOverlay.Position = (TextOverlayPosition)Enum.Parse(typeof(TextOverlayPosition), element.InnerText);
                            }

                            element = overlayTextElement["FontName"];
                            if (element != null)
                            {
                                textOverlay.FontName = element.InnerText;
                            }

                            element = overlayTextElement["FontSize"];
                            if (element != null)
                            {
                                textOverlay.FontSize = float.Parse(element.InnerText, CultureInfo.InvariantCulture);
                            }

                            element = overlayTextElement["FontStyle"];
                            if (element != null)
                            {
                                textOverlay.FontStyle = (FontStyle)Enum.Parse(typeof(FontStyle), element.InnerText);
                            }

                            element = overlayTextElement["ForeColor"];
                            if (element != null)
                            {
                                textOverlay.ForeColor = ColorTranslator.FromHtml(element.InnerText);
                            }

                            element = overlayTextElement["BorderColor"];
                            if (element != null)
                            {
                                textOverlay.BorderColor = ColorTranslator.FromHtml(element.InnerText);
                            }

                            element = overlayTextElement["HorizontalOffset"];
                            if (element != null)
                            {
                                textOverlay.HorizontalOffset = int.Parse(element.InnerText, CultureInfo.InvariantCulture);
                            }

                            element = overlayTextElement["VerticalOffset"];
                            if (element != null)
                            {
                                textOverlay.VerticalOffset = int.Parse(element.InnerText, CultureInfo.InvariantCulture);
                            }

                            screenSettings.TextOverlays.Add(textOverlay);
                        }
                    }
                    #endregion

                    #region <StaticWallpaper>
                    XmlElement staticWallpaperElement = screenSettingsElement["StaticWallpaper"];
                    if (staticWallpaperElement != null)
                    {
                        screenSettings.StaticWallpaper = (Wallpaper)Configuration.GetWallpaperDataFromXmlElement(staticWallpaperElement, typeof(Wallpaper));
                    }
                    #endregion

                    screensSettings.Add(screenSettings);
                    settingsCounter++;
                }

                configuration.General.ScreensSettings = new ScreenSettingsCollection(screensSettings);
            }
            #endregion

            #region <WallpaperCategories>
            XmlElement wallpaperCategoriesElement = document.DocumentElement["WallpaperCategories"];
            if (wallpaperCategoriesElement != null)
            {
                foreach (XmlElement wallpaperCategoryElement in wallpaperCategoriesElement)
                {
                    if (
                        wallpaperCategoryElement.Name != "Category" &&
                        wallpaperCategoryElement.Name != "SynchronizedFolder" &&
                        wallpaperCategoryElement.Name != "WatchedCategory" /* Version 1.1 name for synchronized folders. */
                        )
                    {
                        continue;
                    }

                    element = wallpaperCategoryElement["Name"];
                    if (element == null)
                    {
                        continue;
                    }
                    string categoryName = element.InnerText;

                    WallpaperDefaultSettings defaultSettings = null;
                    element = wallpaperCategoryElement["WallpaperDefaultSettings"];
                    if (element != null)
                    {
                        defaultSettings = (WallpaperDefaultSettings)Configuration.GetWallpaperDataFromXmlElement(element, typeof(WallpaperDefaultSettings));
                    }

                    #region <Wallpapers>
                    List <Wallpaper> wallpapers;

                    XmlElement wallpapersElement = wallpaperCategoryElement["Wallpapers"];
                    if (wallpapersElement != null)
                    {
                        wallpapers = new List <Wallpaper>(wallpapersElement.ChildNodes.Count);

                        foreach (XmlElement wallpaperElement in wallpapersElement)
                        {
                            if (wallpaperElement.Name != "Wallpaper")
                            {
                                continue;
                            }

                            Wallpaper wallpaper = (Wallpaper)Configuration.GetWallpaperDataFromXmlElement(wallpaperElement, typeof(Wallpaper));
                            wallpapers.Add(wallpaper);
                        }
                    }
                    else
                    {
                        wallpapers = new List <Wallpaper>(0);
                    }
                    #endregion

                    bool isSynchronizedFolder = ((wallpaperCategoryElement.Name == "SynchronizedFolder") || (wallpaperCategoryElement.Name == "WatchedCategory"));
                    WallpaperCategory category;
                    if (isSynchronizedFolder)
                    {
                        element = (wallpaperCategoryElement["SynchronizedFolderPath"] ?? wallpaperCategoryElement["WatchedDirectoryPath"]);
                        if (element == null)
                        {
                            continue;
                        }
                        Path synchronizedDirPath = new Path(element.InnerText);

                        if (!Directory.Exists(synchronizedDirPath))
                        {
                            continue;
                        }

                        category = new SynchronizedWallpaperCategory(categoryName, synchronizedDirPath, wallpapers);
                    }
                    else
                    {
                        category = new WallpaperCategory(categoryName, wallpapers);
                    }

                    category.WallpaperDefaultSettings = defaultSettings;
                    configuration.WallpaperCategories.Add(category);
                }
            }
            #endregion

            return(configuration);
        }