Esempio n. 1
0
        private static ResolutionInfo GetResolutionInfo(Document input)
        {
            var resInfo = new ResolutionInfo();

            resInfo.HeightDisplayUnit = ResolutionInfo.Unit.Inches;
            resInfo.WidthDisplayUnit  = ResolutionInfo.Unit.Inches;

            if (input.DpuUnit == MeasurementUnit.Inch)
            {
                resInfo.HResDisplayUnit = ResolutionInfo.ResUnit.PxPerInch;
                resInfo.VResDisplayUnit = ResolutionInfo.ResUnit.PxPerInch;

                resInfo.HDpi = new UFixed16_16(input.DpuX);
                resInfo.VDpi = new UFixed16_16(input.DpuY);
            }
            else
            {
                resInfo.HResDisplayUnit = ResolutionInfo.ResUnit.PxPerCm;
                resInfo.VResDisplayUnit = ResolutionInfo.ResUnit.PxPerCm;

                // Always stored as pixels/inch even if the display unit is
                // pixels/centimeter.
                resInfo.HDpi = new UFixed16_16(input.DpuX * 2.54);
                resInfo.VDpi = new UFixed16_16(input.DpuY * 2.54);
            }

            return(resInfo);
        }
Esempio n. 2
0
        private Delegate ActivateFactoryDelegate(Type type, Type[] parameterTypes, IResolutionScope resolutionScope, object name, bool nullResultAllowed)
        {
            var resolutionInfo = new ResolutionInfo(resolutionScope, this.rootScope, nullResultAllowed)
            {
                ParameterExpressions = parameterTypes.Length == 0 ? null : parameterTypes.Select(Expression.Parameter).ToArray()
            };

            var typeInfo = new TypeInformation {
                Type = type, DependencyName = name
            };
            var registration = this.containerContext.RegistrationRepository.GetRegistrationOrDefault(typeInfo);

            var initExpression = registration == null?
                                 this.resolverSelector.GetResolverExpression(this.containerContext, typeInfo, resolutionInfo) :
                                     registration.GetExpression(resolutionInfo, type);

            if (initExpression == null)
            {
                if (resolutionInfo.NullResultAllowed)
                {
                    return(null);
                }
                else
                {
                    throw new ResolutionFailedException(type);
                }
            }

            var expression = Expression.Lambda(initExpression, resolutionInfo.ParameterExpressions);

            var factory = expression.CompileDelegate(Constants.ScopeExpression);

            this.containerContext.DelegateRepository.AddFactoryDelegate(type, factory, name);
            return(factory(resolutionScope));
        }
Esempio n. 3
0
 /// <inheritdoc />
 public void Validate()
 {
     foreach (var serviceRegistration in this.registrationRepository.GetAllRegistrations())
     {
         serviceRegistration.GetExpression(ResolutionInfo.New(this, this), serviceRegistration.ServiceType);
     }
 }
        public void ImageResourceGetSetTest()
        {
            var psdFile   = new PsdFile();
            var resources = psdFile.ImageResources;

            var versionInfo1 = new VersionInfo();

            versionInfo1.Name = "VersionInfo1";
            var resolutionInfo1 = new ResolutionInfo();

            resolutionInfo1.Name = "ResolutionInfo1";
            var versionInfo2 = new VersionInfo();

            versionInfo2.Name = "VersionInfo2";

            resources.Add(versionInfo1);
            resources.Add(resolutionInfo1);
            resources.Add(versionInfo2);

            // Can retrieve an item successfully
            var gottenResolutionInfo = resources.Get(ResourceID.ResolutionInfo);

            Assert.AreEqual(resolutionInfo1.Name, gottenResolutionInfo.Name);
            var gottenThumbnail = resources.Get(ResourceID.ThumbnailRgb);

            Assert.IsNull(gottenThumbnail);

            // Set to add item.
            var thumbnail = new Thumbnail(ResourceID.ThumbnailRgb, "Thumbnail");

            resources.Set(thumbnail);
            gottenThumbnail = resources.Get(ResourceID.ThumbnailRgb);
            Assert.AreEqual(thumbnail.Name, gottenThumbnail.Name);

            // Set to change item in-place.
            var idxResolutionInfo = resources.IndexOf(resolutionInfo1);
            var resolutionInfo2   = new ResolutionInfo();

            resolutionInfo2.Name = "ResolutionInfo2";
            resources.Set(resolutionInfo2);
            gottenResolutionInfo = resources.Get(ResourceID.ResolutionInfo);
            Assert.AreEqual(resolutionInfo2.Name, gottenResolutionInfo.Name);

            // Change item that appears twice.
            var count           = resources.Count;
            var idxVersionInfo1 = resources.IndexOf(versionInfo1);
            var versionInfo3    = new VersionInfo();

            versionInfo3.Name = "VersionInfo3";
            resources.Set(versionInfo3);

            var gottenVersionInfo = resources.Get(ResourceID.VersionInfo);
            var idxVersionInfo3   = resources.IndexOf(versionInfo3);
            var versionInfoCount  = resources.Count(x => x.ID == ResourceID.VersionInfo);

            Assert.AreEqual(count - 1, resources.Count);
            Assert.AreEqual(idxVersionInfo1, idxVersionInfo3);
            Assert.AreEqual(versionInfo3.Name, gottenVersionInfo.Name);
            Assert.AreEqual(versionInfoCount, 1);
        }
Esempio n. 5
0
        public Expression CreateFillExpression(IServiceRegistration serviceRegistration, Expression instance,
                                               ResolutionInfo resolutionInfo, Type serviceType)
        {
            var block = new List <Expression>();

            if (instance.Type != serviceType)
            {
                instance = Expression.Convert(instance, serviceType);
            }

            var variable = Expression.Variable(serviceType);
            var assign   = Expression.Assign(variable, instance);

            block.Add(assign);

            if (serviceRegistration.MetaInformation.InjectionMembers.Length > 0)
            {
                block.AddRange(this.FillMembersExpression(serviceRegistration, resolutionInfo, variable));
            }

            if (serviceRegistration.MetaInformation.InjectionMethods.Length > 0 || this.containerExtensionManager.HasPostBuildExtensions)
            {
                return(this.CreatePostWorkExpressionIfAny(serviceRegistration, resolutionInfo, variable, serviceType, block, variable));
            }

            block.Add(variable); //return

            return(Expression.Block(new[] { variable }, block));
        }
Esempio n. 6
0
        public static ImageResource CreateImageResource(PsdBinaryReader reader)
        {
            Util.DebugMessage(reader.BaseStream, "Load, Begin, ImageResource");

            var signature     = reader.ReadAsciiChars(4);
            var resourceIdInt = reader.ReadUInt16();
            var name          = reader.ReadPascalString(2);
            var dataLength    = (int)reader.ReadUInt32();

            var dataPaddedLength = Util.RoundUp(dataLength, 2);
            var endPosition      = reader.BaseStream.Position + dataPaddedLength;

            ImageResource resource;
            var           resourceId = (ResourceID)resourceIdInt;

            switch (resourceId)
            {
            case ResourceID.ResolutionInfo:
                resource = new ResolutionInfo(reader, name);
                break;

            case ResourceID.AlphaChannelNames:
                resource = new AlphaChannelNames(reader, name, dataLength);
                break;

            case ResourceID.UnicodeAlphaNames:
                resource = new UnicodeAlphaNames(reader, name, dataLength);
                break;

            case ResourceID.VersionInfo:
                resource = new VersionInfo(reader, name);
                break;

            default:
                resource = new RawImageResource(reader, signature, resourceId, name, dataLength);
                break;
            }

            Util.DebugMessage(reader.BaseStream,
                              $"Load, End, ImageResource, {resourceId}");

            // Reposition the reader if we do not consume the full resource block.
            // This takes care of the even-padding, and also preserves forward-
            // compatibility in case a resource block is later extended with
            // additional properties.
            if (reader.BaseStream.Position < endPosition)
            {
                reader.BaseStream.Position = endPosition;
            }

            // However, overruns are definitely an error.
            if (reader.BaseStream.Position > endPosition)
            {
                throw new PsdInvalidException("Corruption detected in resource.");
            }

            return(resource);
        }
Esempio n. 7
0
        public Expression GetExpression(IServiceRegistration serviceRegistration, ResolutionInfo resolutionInfo, Type resolveType)
        {
            if (serviceRegistration.IsDecorator)
            {
                return(this.GetExpressionAndHandleDisposal(serviceRegistration, resolutionInfo, resolveType));
            }

            if (resolutionInfo.IsCurrentlyDecorating(resolveType))
            {
                return(this.GetExpressionAndHandleDisposal(serviceRegistration, resolutionInfo, resolveType));
            }

            var decorators = this.ContainerContext.DecoratorRepository.GetDecoratorsOrDefault(resolveType);

            if (decorators == null)
            {
                if (resolveType.IsClosedGenericType())
                {
                    decorators = this.ContainerContext.DecoratorRepository.GetDecoratorsOrDefault(resolveType.GetGenericTypeDefinition());
                    if (decorators == null)
                    {
                        return(this.GetExpressionAndHandleDisposal(serviceRegistration, resolutionInfo, resolveType));
                    }
                }
                else
                {
                    return(this.GetExpressionAndHandleDisposal(serviceRegistration, resolutionInfo, resolveType));
                }
            }

            resolutionInfo.AddCurrentlyDecoratingType(resolveType);
            var expression = this.GetExpressionAndHandleDisposal(serviceRegistration, resolutionInfo, resolveType);

            if (expression == null)
            {
                return(null);
            }

            var length = decorators.Length;

            for (int i = 0; i < length; i++)
            {
                var decorator = decorators[i];
                resolutionInfo.SetExpressionOverride(resolveType, expression);
                expression = decorator.Value.GetExpression(resolutionInfo, resolveType);
                if (expression == null)
                {
                    return(null);
                }
            }

            resolutionInfo.ClearCurrentlyDecoratingType(resolveType);
            return(expression);
        }
        public CircularDependencyBarrier(ResolutionInfo resolutionInfo, Type type)
        {
            resolutionInfo.AddCircularDependencyCheck(type, out bool updated);
            if (updated)
            {
                throw new CircularDependencyException(type);
            }

            this.resolutionInfo = resolutionInfo;
            this.type           = type;
        }
Esempio n. 9
0
    /// <summary>
    /// 最適な解像度を取得する
    ///
    /// 9:16 までの場合は、横720固定
    /// 9:16より縦長の場合は、縦1280固定にする
    ///
    /// </summary>
    /// <returns>The resolution.</returns>
    public static ResolutionInfo CalcResolution(int width, int height)
    {
        const int   maxWidth        = 960;
        const int   maxHeight       = 720;
        const int   superWidth      = 1440;
        const float ratio9v16       = 9.0f / 16;   // 9:16 のratio
        const float ratio9v18       = 9.0f / 18;   // 9:18 のratio
        const float baseFieldOfView = 60f;

        var r = new ResolutionInfo
        {
            OriginalWidth  = width,
            OriginalHeight = height,
            FieldOfView    = baseFieldOfView,
        };

        var ratio = 1.0f * height / width;         // 縦/横の比率

        if (ratio <= ratio9v16)
        {
            // 9:16より横長
            r.Height       = height;
            r.Width        = Mathf.RoundToInt(r.Height / ratio);
            r.UiHeight     = maxHeight;
            r.UiWidth      = maxWidth;
            r.UiViewHeight = maxHeight;
            r.UiViewWidth  = Mathf.RoundToInt(maxHeight / ratio);
            r.UiFullHeight = r.UiViewHeight;
            r.UiFullWidth  = r.UiViewWidth;
            r.FieldOfView  = baseFieldOfView * r.UiViewHeight / maxHeight;
            if (ratio <= ratio9v18)
            {
                // 9:18より横長
                r.UiViewWidth = superWidth;
            }
        }
        else
        {
            // 9:16より縦長
            r.Width        = width;
            r.Height       = Mathf.RoundToInt(width * ratio);
            r.UiHeight     = maxHeight;
            r.UiWidth      = maxWidth;
            r.UiViewHeight = Mathf.RoundToInt(maxWidth * ratio);
            r.UiViewWidth  = maxWidth;
            r.UiFullHeight = r.UiViewHeight;
            r.UiFullWidth  = r.UiViewWidth;
        }

        r.UiScale = Mathf.Min(1f * r.OriginalWidth / r.UiWidth, 1f * r.OriginalHeight / r.UiHeight);

        return(r);
    }
Esempio n. 10
0
        private object Activate(ResolutionInfo resolutionInfo, Type type, object name = null)
        {
            if (type == Constants.ResolverType)
            {
                return(resolutionInfo.ResolutionScope);
            }

            var registration = this.containerContext.RegistrationRepository.GetRegistrationOrDefault(type, name);

            if (registration != null)
            {
                var ragistrationFactory = registration.GetExpression(resolutionInfo, type)?.CompileDelegate(Constants.ScopeExpression);
                if (ragistrationFactory == null)
                {
                    if (resolutionInfo.NullResultAllowed)
                    {
                        return(null);
                    }
                    else
                    {
                        throw new ResolutionFailedException(type);
                    }
                }

                this.containerContext.DelegateRepository.AddServiceDelegate(type, ragistrationFactory, name);
                return(ragistrationFactory(resolutionInfo.ResolutionScope));
            }

            var expr = this.resolverSelector.GetResolverExpression(this.containerContext, new TypeInformation {
                Type = type, DependencyName = name
            }, resolutionInfo);

            if (expr == null)
            {
                if (resolutionInfo.NullResultAllowed)
                {
                    return(null);
                }
                else
                {
                    throw new ResolutionFailedException(type);
                }
            }

            var factory = expr.CompileDelegate(Constants.ScopeExpression);

            this.containerContext.DelegateRepository.AddServiceDelegate(type, factory, name);
            return(factory(resolutionInfo.ResolutionScope));
        }
Esempio n. 11
0
        public override void Read(HmeReader reader)
        {
            long streamId = reader.ReadInt64();

            System.Diagnostics.Debug.Assert(_rootStreamId == streamId);
            _metricsPerResolutionInfo = reader.ReadInt64();
            _currentResolution        = new ResolutionInfo(reader.ReadInt64(),
                                                           reader.ReadInt64(), reader.ReadInt64(), reader.ReadInt64());
            SkipExtraResolutionMetrics(reader);
            long count = reader.ReadInt64();

            for (int i = 0; i < count; ++i)
            {
                _supportedResolutions.Add(new ResolutionInfo(
                                              reader.ReadInt64(), reader.ReadInt64(), reader.ReadInt64(), reader.ReadInt64()));
                SkipExtraResolutionMetrics(reader);
            }
            reader.ReadTerminator();
        }
Esempio n. 12
0
        private ParameterExpression[] PrepareExtraParameters(Type wrappedType, ResolutionInfo resolutionInfo, Type[] args)
        {
            var length     = args.Length - 1;
            var parameters = new ParameterExpression[length];

            if (length <= 0)
            {
                return(parameters);
            }

            for (var i = 0; i < length; i++)
            {
                var argType = args[i];
                var argName = wrappedType.Name + argType.Name + i;
                parameters[i] = Expression.Parameter(argType, argName);
            }

            resolutionInfo.ParameterExpressions = resolutionInfo.ParameterExpressions?.Concat(parameters).ToArray() ?? parameters;

            return(parameters);
        }
Esempio n. 13
0
        public Expression CreateExpression(IServiceRegistration serviceRegistration, ResolutionInfo resolutionInfo, Type serviceType)
        {
            var initExpression = this.CreateInitExpression(serviceRegistration, resolutionInfo);

            if (initExpression == null)
            {
                return(null);
            }

            if (serviceRegistration.MetaInformation.InjectionMembers.Length > 0)
            {
                initExpression = Expression.MemberInit((NewExpression)initExpression, this.GetMemberBindings(serviceRegistration, resolutionInfo));
            }

            if (serviceRegistration.MetaInformation.InjectionMethods.Length > 0 || this.containerExtensionManager.HasPostBuildExtensions)
            {
                return(this.CreatePostWorkExpressionIfAny(serviceRegistration, resolutionInfo, initExpression, serviceType));
            }

            return(initExpression);
        }
Esempio n. 14
0
    void ResetAspect()
    {
        var ri = CalcResolution(Screen.width, Screen.height);

        Debug.LogFormat("ResolutionInfo={0}", JsonUtility.ToJson(ri));
        CurrentScreenInfo = ri;

        if (MainCam != null)
        {
            MainCam.fieldOfView = ri.FieldOfView;
        }
        if (SelfCam != null)
        {
            if (SelfCam.orthographic == false)
            {
                SelfCam.fieldOfView = ri.FieldOfView;
            }
            else
            {
                SelfCam.orthographicSize = (ri.FieldOfView / 10) - (SelfCam.orthographicSize / 10);
            }
        }
    }
Esempio n. 15
0
 private void LoadDefaultConfig()
 {
     VideoVolume      = 30;
     MicrophoneVolume = 50;
     UseMicrophoneID  = 0;
     RecordingStatusChangesAccordingToLiveBroadcastStatus = false;
     UploadCompletedAutoDeleteLocalFile = false;
     IsAutoUpload      = false;
     AutoDelayDuration = 10;
     UseResolutionInfo = new ResolutionInfo {
         ID = 2, DisplayName = "960*540", Width = 960, Height = 540
     };
     UseRateInfo = new RateInfo {
         ID = 3, DisplayName = "1500kbps", Value = 1500
     };
     UseFrameRateInfo = new FrameRateInfo {
         ID = 1, DisplayName = "25Fps", Value = 25
     };
     if (!Directory.Exists(AllDataSavePath))
     {
         Directory.CreateDirectory(AllDataSavePath);
     }
     Save();
 }
Esempio n. 16
0
 public object ExecutePostBuildExtensions(object instance, IContainerContext containerContext, ResolutionInfo resolutionInfo,
                                          IServiceRegistration serviceRegistration, Type requestedType) =>
 this.repository.OfType <IPostBuildExtension>().Aggregate(instance, (current, extension) => extension.PostBuild(current, containerContext, resolutionInfo, serviceRegistration, requestedType));
Esempio n. 17
0
 public override Expression GetExpression(IContainerContext containerContext, TypeInformation typeInfo, ResolutionInfo resolutionInfo) =>
 Expression.Convert(Expression.Call(Constants.ScopeExpression, Constants.GetScopedInstanceMethod, Expression.Constant(typeInfo.Type)), typeInfo.Type);
Esempio n. 18
0
        public object Activate(Type type, IResolutionScope resolutionScope, object name, bool nullResultAllowed = false)
        {
            var cachedFactory = this.containerContext.DelegateRepository.GetDelegateCacheOrDefault(name);

            return(cachedFactory != null?cachedFactory(resolutionScope) : this.Activate(ResolutionInfo.New(resolutionScope, this.rootScope, nullResultAllowed), type, name));
        }
Esempio n. 19
0
        /// <inheritdoc />
        public override Expression GetExpression(IServiceRegistration serviceRegistration, IObjectBuilder objectBuilder, ResolutionInfo resolutionInfo,
                                                 Type resolveType)
        {
            if (this.expression != null)
            {
                return(this.expression);
            }
            lock (this.syncObject)
            {
                if (this.expression != null)
                {
                    return(this.expression);
                }
                var expr = base.GetExpression(serviceRegistration, objectBuilder, resolutionInfo, resolveType);
                if (expr == null)
                {
                    return(null);
                }

                var factory = expr.CompileDelegate(Constants.ScopeExpression);

                var method = GetScopedValueMethod.MakeGenericMethod(resolveType);

                this.expression = Expression.Call(method,
                                                  Constants.ScopeExpression,
                                                  Expression.Constant(factory), Expression.Constant(this.scopeId));
            }

            return(this.expression);
        }
Esempio n. 20
0
 /// <inheritdoc />
 public virtual Expression GetExpression(IServiceRegistration serviceRegistration, IObjectBuilder objectBuilder,
                                         ResolutionInfo resolutionInfo, Type resolveType) => objectBuilder.GetExpression(serviceRegistration, resolutionInfo, resolveType);
Esempio n. 21
0
        static void Main(string[] args)
        {
            var psd = new PSDFile();

            using (var readStream = new FileStream(args[0], FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                psd.Read(readStream);
            }

            Console.WriteLine("Version: {0}", psd.Version);
            Console.WriteLine("Number of channels: {0}", psd.NumberOfChannels);
            Console.WriteLine("Width: {0}", psd.Width);
            Console.WriteLine("Height: {0}", psd.Height);
            Console.WriteLine("Depth: {0}", psd.Depth);
            Console.WriteLine("Color mode: {0}", psd.ColorMode);

            Console.WriteLine("Image resources:");
            foreach (var res in psd.ImageResources)
            {
                Console.WriteLine("  Image resource ID: {0}", res.ID);
                //Console.WriteLine("    Name: {0}", res.Name);

                if (res.ID == ResolutionInfo.ResolutionInfoResourceID)
                {
                    Console.WriteLine("    Binary data:");

                    for (int rowOffset = 0; rowOffset < res.Data.Length; rowOffset += 8)
                    {
                        Console.Write("      ");
                        for (int i = 0; i < 8 && rowOffset + i < res.Data.Length; ++i)
                        {
                            Console.Write("{0:X2} ", res.Data[rowOffset + i]);
                        }
                        Console.WriteLine();
                    }

                    Console.WriteLine("    Resolution info:");
                    var resInfo = ResolutionInfo.FromPSD(psd);
                    Console.WriteLine("      Horizontal resolution: {0} dpi", resInfo.HorizontalResolutionDPI);
                    Console.WriteLine("        Display unit:        {0}", resInfo.HorizontalResolutionDisplayUnit);
                    Console.WriteLine("      Width display unit:    {0}", resInfo.WidthDisplayUnit);
                    Console.WriteLine("      Vertical resolution:   {0} dpi", resInfo.VerticalResolutionDPI);
                    Console.WriteLine("        Display unit:        {0}", resInfo.VerticalResolutionDisplayUnit);
                    Console.WriteLine("      Height display unit:   {0}", resInfo.HeightDisplayUnit);
                }
                else if (res.ID == VersionInfo.VersionInfoResourceID)
                {
                    var verInfo = VersionInfo.FromPSD(psd);
                    Console.WriteLine("    Version info:");
                    Console.WriteLine("      Version: {0}", verInfo.Version);
                    Console.WriteLine("      {0} valid precomposed data", verInfo.HasValidPrecomposedData ? "Has" : "Does not have");
                    Console.WriteLine("      Writer: {0}", verInfo.WriterName);
                    Console.WriteLine("      Reader: {0}", verInfo.ReaderName);
                    Console.WriteLine("      File version: {0}", verInfo.FileVersion);
                }
            }

            Console.WriteLine("Layers: {0}", psd.Layers.Length);
            foreach (PSDLayer layer in psd.Layers)
            {
                Console.WriteLine("    Layer: {0}", layer.Name);
                Console.WriteLine("      Channels: {0}", layer.Channels.Length);
                foreach (PSDLayerChannel chan in layer.Channels)
                {
                    Console.WriteLine("        {0} ({1} bytes {2} from 0x{3:x})", chan.ID, chan.Data.DataLength, chan.Data.Compression, chan.Data.Offset);
                }
                Console.WriteLine("      Additional layer information: {0} entries", layer.AdditionalInformation.Count);
                foreach (PSDAdditionalLayerInformation pali in layer.AdditionalInformation)
                {
                    Console.WriteLine("        Key: {0}", pali.Key);
                    Console.WriteLine("          Data length: {0}", pali.Data.Length);
                }
            }

            if (psd.GlobalLayerMask != null)
            {
                var glm = psd.GlobalLayerMask;
                Console.WriteLine("Global layer mask:");
                Console.WriteLine("  Overlay color space: {0}", glm.OverlayColorSpace);
                Console.WriteLine("  Color components: {0}, {1}, {2}, {3}", glm.ColorComponent1, glm.ColorComponent2, glm.ColorComponent3, glm.ColorComponent4);
                Console.WriteLine("  Opacity: {0}", glm.Opacity);
                Console.WriteLine("  Kind: {0}", glm.Kind);
            }
            else
            {
                Console.WriteLine("No global layer mask");
            }

            Console.WriteLine("Additional layer information: {0} entries", psd.AdditionalLayerInformation.Count);
            foreach (PSDAdditionalLayerInformation ali in psd.AdditionalLayerInformation)
            {
                Console.WriteLine("  Key: {0}", ali.Key);
                Console.WriteLine("    Data length: {0}", ali.Data.Length);
            }

            if (psd.PrecomposedImageData == null)
            {
                Console.WriteLine("No precomposed image data");
            }
            else
            {
                Console.WriteLine("Precomposed image data: {0} from 0x{1:x}", psd.PrecomposedImageData.Compression, psd.PrecomposedImageData.Offset);
            }

            if (args.Length > 1 && args[1] == "-d")
            {
                // decode
                for (int l = 0; l < psd.Layers.Length; ++l)
                {
                    PSDLayer layer = psd.Layers[l];
                    foreach (PSDLayerChannel chan in layer.Channels)
                    {
                        Console.WriteLine("extracting layer {0} channel {1} ({2})", l, chan.ID, chan.Data.Compression);
                        string name = $"{args[0]}.l{l}c{chan.ID}.bin";

                        using (var reader = new FileStream(args[0], FileMode.Open, FileAccess.Read, FileShare.Read))
                            using (var writer = new FileStream(name, FileMode.Create, FileAccess.Write, FileShare.None))
                            {
                                reader.Seek(chan.Data.Offset, SeekOrigin.Begin);
                                switch (chan.Data.Compression)
                                {
                                case CompressionType.RawData:
                                    PixelDataDecoding.DecodeRawData(
                                        reader,
                                        writer,
                                        chan.Data.DataLength
                                        );
                                    break;

                                case CompressionType.PackBits:
                                    PixelDataDecoding.DecodePackBits(
                                        reader,
                                        writer,
                                        scanlineCount: layer.Bottom - layer.Top,
                                        fourByteLengths: psd.Version == 2
                                        );
                                    break;

                                case CompressionType.ZipWithoutPrediction:
                                    PixelDataDecoding.DecodeZip(
                                        reader,
                                        writer,
                                        chan.Data.DataLength
                                        );
                                    break;

                                case CompressionType.ZipWithPrediction:
                                    PixelDataDecoding.DecodeZipPredicted(
                                        reader,
                                        writer,
                                        chan.Data.DataLength,
                                        psd.Depth,
                                        psd.Width
                                        );
                                    break;
                                }
                            }
                    }
                }

                if (psd.PrecomposedImageData != null)
                {
                    string compositeName = $"{args[0]}.composite.bin";
                    using (var reader = new FileStream(args[0], FileMode.Open, FileAccess.Read, FileShare.Read))
                        using (var writer = new FileStream(compositeName, FileMode.Create, FileAccess.Write, FileShare.None))
                        {
                            reader.Seek(psd.PrecomposedImageData.Offset, SeekOrigin.Begin);
                            switch (psd.PrecomposedImageData.Compression)
                            {
                            case CompressionType.RawData:
                                PixelDataDecoding.DecodeRawData(
                                    reader,
                                    writer,
                                    length: null
                                    );
                                break;

                            case CompressionType.PackBits:
                                PixelDataDecoding.DecodePackBits(
                                    reader,
                                    writer,
                                    scanlineCount: psd.Height * psd.NumberOfChannels,
                                    fourByteLengths: psd.Version == 2
                                    );
                                break;

                            case CompressionType.ZipWithoutPrediction:
                                PixelDataDecoding.DecodeZip(
                                    reader,
                                    writer,
                                    length: null
                                    );
                                break;

                            case CompressionType.ZipWithPrediction:
                                PixelDataDecoding.DecodeZipPredicted(
                                    reader,
                                    writer,
                                    length: null,
                                    depth: psd.Depth,
                                    imageWidth: psd.Width
                                    );
                                break;
                            }
                        }
                }
            }
        }
Esempio n. 22
0
        public void ToBMP(string path)
        {
            int width  = MaxX / (DIAMETER * 2) - MinX / (DIAMETER * 2);
            int height = MaxY / (DIAMETER * 2) - MinY / (DIAMETER * 2);
            int depth  = MaxZ - MinZ;

            PsdFile psdFile = new PsdFile()
            {
                //-----------------------------------------------------------------------

                Rows    = height,
                Columns = width,

                // We only save in 8 bits per channel RGBA format, which corresponds to
                // Paint.NET's internal representation.
                Channels  = 4,
                ColorMode = PsdColorMode.RGB,
                Depth     = 8
            };

            //-----------------------------------------------------------------------
            // No color mode data is necessary for RGB
            //-----------------------------------------------------------------------

            ResolutionInfo resInfo = new ResolutionInfo()
            {
                HeightDisplayUnit = ResolutionInfo.Unit.In,
                WidthDisplayUnit  = ResolutionInfo.Unit.In,

                HResDisplayUnit = ResolutionInfo.ResUnit.PxPerInch,
                VResDisplayUnit = ResolutionInfo.ResUnit.PxPerInch,

                HDpi = new UFixed16_16(72),
                VDpi = new UFixed16_16(72)
            };

            psdFile.Resolution       = resInfo;
            psdFile.ImageCompression = ImageCompression.Rle;

            //-----------------------------------------------------------------------
            // Set document image data from the fully-rendered image
            //-----------------------------------------------------------------------

            int imageSize = psdFile.Rows * psdFile.Columns;

            psdFile.Layers.Clear();
            for (short i = 0; i < psdFile.Channels; i++)
            {
                var channel = new Layer.Channel(i, psdFile.BaseLayer)
                {
                    ImageData        = new byte[imageSize],
                    ImageCompression = psdFile.ImageCompression
                };
            }
            AddNewLayer(psdFile, 0);
            var alpha = psdFile.Layers[0].AlphaChannel.ImageData;

            for (int i = 0; i < psdFile.Rows * psdFile.Columns; i++)
            {
                alpha[i] = 255;
            }
            AddNewLayer(psdFile, 1);
            for (int y = MinY; y <= MaxY - (DIAMETER * 2); y += (DIAMETER * 2))
            {
                for (int x = MinX; x <= MaxX - (DIAMETER * 2); x += (DIAMETER * 2))
                {
                    int hash = CalcHash((short)x, (short)y);
                    try
                    {
                        if (values.ContainsKey(hash))
                        {
                            var points = (from p in values[hash].Keys
                                          orderby p descending
                                          select p).ToArray();
                            for (int index = 0; index < points.Length; index++)
                            {
                                int c  = (int)((((float)points[index] - MinZ) / depth) * 250 + 5);
                                int x2 = (x - MinX) / (DIAMETER * 2);
                                int y2 = (y - MinY) / (DIAMETER * 2);

                                if (index >= psdFile.Layers.Count - 1)
                                {
                                    AddNewLayer(psdFile, index + 1);
                                }

                                int pos     = x2 + width * y2;
                                var rgb     = psdFile.Layers[index + 1].ChannelsArray;
                                var alphaCh = psdFile.Layers[index + 1].AlphaChannel;
                                rgb[0].ImageData[pos]  = (byte)c;
                                rgb[1].ImageData[pos]  = (byte)c;
                                rgb[2].ImageData[pos]  = (byte)c;
                                alphaCh.ImageData[pos] = 255;
                            }
                        }
                    }
                    catch
                    {
                    }
                }
            }
            Layer l = psdFile.Layers[0];

            psdFile.Layers.RemoveAt(0);
            psdFile.Layers.Reverse();
            psdFile.Layers.Insert(0, l);
            psdFile.Save(path);
            psdFile = null;
        }
Esempio n. 23
0
        public PsdFile Load(String filename)
		{
			using (FileStream stream = new FileStream(filename, FileMode.Open))
			{
				//binary reverse reader reads data types in big-endian format.
				BinaryReverseReader reader = new BinaryReverseReader(stream);

				#region "Headers"
				//The headers area is used to check for a valid PSD file
				Debug.WriteLine("LoadHeader started at " + reader.BaseStream.Position.ToString(CultureInfo.InvariantCulture));

				String signature = new String(reader.ReadChars(4));
				if (signature != "8BPS") throw new IOException("Bad or invalid file stream supplied");

				//get the version number, should be 1 always
				if ((Version = reader.ReadInt16()) != 1) throw new IOException("Invalid version number supplied");

				//get rid of the 6 bytes reserverd in PSD format
				reader.BaseStream.Position += 6;

				//get the rest of the information from the PSD file.
				//Everytime ReadInt16() is called, it reads 2 bytes.
				//Everytime ReadInt32() is called, it reads 4 bytes.
				_channels = reader.ReadInt16();
				_rows = reader.ReadInt32();
				_columns = reader.ReadInt32();
				_depth = reader.ReadInt16();
				ColorMode = (ColorModes)reader.ReadInt16();

				//by end of headers, the reader has read 26 bytes into the file.
				#endregion //End Headers

				#region "ColorModeData"
				Debug.WriteLine("LoadColorModeData started at " + reader.BaseStream.Position.ToString(CultureInfo.InvariantCulture));

				UInt32 paletteLength = reader.ReadUInt32(); //readUint32() advances the reader 4 bytes.
				if (paletteLength > 0)
				{
					ColorModeData = reader.ReadBytes((Int32)paletteLength);
				}
				#endregion //End ColorModeData


				#region "Loading Image Resources"
				//This part takes extensive use of classes that I didn't write therefore
				//I can't document much on what they do.

				Debug.WriteLine("LoadingImageResources started at " + reader.BaseStream.Position.ToString(CultureInfo.InvariantCulture));

                _imageResources.Clear();

				UInt32 imgResLength = reader.ReadUInt32();
				if (imgResLength <= 0) return null;

				Int64 startPosition = reader.BaseStream.Position;

				while ((reader.BaseStream.Position - startPosition) < imgResLength)
				{
					ImageResource imgRes = new ImageResource(reader);

					ResourceIDs resID = (ResourceIDs)imgRes.ID;
					switch (resID)
					{
						case ResourceIDs.ResolutionInfo:
							imgRes = new ResolutionInfo(imgRes);
							break;
						case ResourceIDs.Thumbnail1:
						case ResourceIDs.Thumbnail2:
							imgRes = new Thumbnail(imgRes);
							break;
						case ResourceIDs.AlphaChannelNames:
							imgRes = new AlphaChannels(imgRes);
							break;
					}

                    _imageResources.Add(imgRes);

				}
				// make sure we are not on a wrong offset, so set the stream position 
				// manually
				reader.BaseStream.Position = startPosition + imgResLength;

				#endregion //End LoadingImageResources


				#region "Layer and Mask Info"
				//We are gonna load up all the layers and masking of the PSD now.
				Debug.WriteLine("LoadLayerAndMaskInfo - Part1 started at " + reader.BaseStream.Position.ToString(CultureInfo.InvariantCulture));
				UInt32 layersAndMaskLength = reader.ReadUInt32();

				if (layersAndMaskLength <= 0) return null;

				//new start position
				startPosition = reader.BaseStream.Position;

				//Lets start by loading up all the layers
				LoadLayers(reader);
				//we are done the layers, load up the masks
				LoadGlobalLayerMask(reader);

				// make sure we are not on a wrong offset, so set the stream position 
				// manually
				reader.BaseStream.Position = startPosition + layersAndMaskLength;
				#endregion //End Layer and Mask info

				#region "Loading Final Image"

				//we have loaded up all the information from the PSD file
				//into variables we can use later on.

				//lets finish loading the raw data that defines the image 
				//in the picture.

				Debug.WriteLine("LoadImage started at " + reader.BaseStream.Position.ToString(CultureInfo.InvariantCulture));

				ImageCompression = (ImageCompression)reader.ReadInt16();

				ImageData = new Byte[_channels][];

				//---------------------------------------------------------------

				if (ImageCompression == ImageCompression.Rle)
				{
					// The RLE-compressed data is proceeded by a 2-byte data count for each row in the data,
					// which we're going to just skip.
					reader.BaseStream.Position += _rows * _channels * 2;
				}

				//---------------------------------------------------------------

				Int32 bytesPerRow = 0;

				switch (_depth)
				{
					case 1:
						bytesPerRow = _columns;//NOT Shure
						break;
					case 8:
						bytesPerRow = _columns;
						break;
					case 16:
						bytesPerRow = _columns * 2;
						break;
				}

				//---------------------------------------------------------------

				for (Int32 ch = 0; ch < _channels; ch++)
				{
					ImageData[ch] = new Byte[_rows * bytesPerRow];

					switch (ImageCompression)
					{
						case ImageCompression.Raw:
							reader.Read(ImageData[ch], 0, ImageData[ch].Length);
							break;
						case ImageCompression.Rle:
							{
								for (Int32 i = 0; i < _rows; i++)
								{
									Int32 rowIndex = i * _columns;
									RleHelper.DecodedRow(reader.BaseStream, ImageData[ch], rowIndex, bytesPerRow);
								}
							}
							break;
					}
				}

				#endregion //End LoadingFinalImage
			}

            return this;
		} //end Load()
Esempio n. 24
0
 public override Expression[] GetExpressions(IContainerContext containerContext, TypeInformation typeInfo, ResolutionInfo resolutionInfo) =>
 containerContext.Container.ParentContainer.ContainerContext.ResolutionStrategy
 .BuildResolutionExpressions(containerContext.Container.ParentContainer.ContainerContext, resolutionInfo, typeInfo);
Esempio n. 25
0
 public override bool CanUseForResolution(IContainerContext containerContext, TypeInformation typeInfo, ResolutionInfo resolutionInfo) =>
 typeInfo.Type.GetEnumerableType() != null;
Esempio n. 26
0
        public override Expression GetExpression(IContainerContext containerContext, TypeInformation typeInfo, ResolutionInfo resolutionInfo)
        {
            var enumerableType = new TypeInformation {
                Type = typeInfo.Type.GetEnumerableType()
            };
            var expressions = containerContext.ResolutionStrategy.BuildResolutionExpressions(containerContext, resolutionInfo, enumerableType);

            return(expressions == null?Expression.NewArrayInit(enumerableType.Type) :
                       Expression.NewArrayInit(enumerableType.Type, expressions));
        }
Esempio n. 27
0
        protected override void OnSave(Document input, System.IO.Stream output,
                                       SaveConfigToken token, Surface scratchSurface, ProgressEventHandler callback)
        {
            PsdSaveConfigToken psdToken = (PsdSaveConfigToken)token;
            PsdFile            psdFile  = new PsdFile();

            //-----------------------------------------------------------------------

            psdFile.Rows    = input.Height;
            psdFile.Columns = input.Width;

            // we have an Alpha channel which will be saved,
            // we have to add this to our image resources
            psdFile.Channels = 4;

            // for now we oly save the images as RGB
            psdFile.ColorMode = PsdFile.ColorModes.RGB;

            psdFile.Depth = 8;

            //-----------------------------------------------------------------------
            // no color mode Data

            //-----------------------------------------------------------------------

            ResolutionInfo resInfo = new ResolutionInfo();

            resInfo.HeightUnit = ResolutionInfo.Unit.In;
            resInfo.WidthUnit  = ResolutionInfo.Unit.In;

            if (input.DpuUnit == MeasurementUnit.Inch)
            {
                resInfo.HResUnit = ResolutionInfo.ResUnit.PxPerInch;
                resInfo.VResUnit = ResolutionInfo.ResUnit.PxPerInch;

                resInfo.HRes = (short)input.DpuX;
                resInfo.VRes = (short)input.DpuY;
            }
            else
            {
                resInfo.HResUnit = ResolutionInfo.ResUnit.PxPerCent;
                resInfo.VResUnit = ResolutionInfo.ResUnit.PxPerCent;


                resInfo.HRes = (short)(input.DpuX / 2.54);
                resInfo.VRes = (short)(input.DpuY / 2.54);
            }

            psdFile.Resolution = resInfo;
            //-----------------------------------------------------------------------

            psdFile.ImageCompression = psdToken.RleCompress ? ImageCompression.Rle : ImageCompression.Raw;

            int size = psdFile.Rows * psdFile.Columns;

            psdFile.ImageData = new byte[psdFile.Channels][];
            for (int i = 0; i < psdFile.Channels; i++)
            {
                psdFile.ImageData[i] = new byte[size];
            }

            using (RenderArgs ra = new RenderArgs(scratchSurface))
            {
                input.Flatten(scratchSurface);
            }

            unsafe
            {
                for (int y = 0; y < psdFile.Rows; y++)
                {
                    int        rowIndex = y * psdFile.Columns;
                    ColorBgra *srcRow   = scratchSurface.GetRowAddress(y);
                    ColorBgra *srcPixel = srcRow;

                    for (int x = 0; x < psdFile.Columns; x++)
                    {
                        int pos = rowIndex + x;

                        psdFile.ImageData[0][pos] = srcPixel->R;
                        psdFile.ImageData[1][pos] = srcPixel->G;
                        psdFile.ImageData[2][pos] = srcPixel->B;
                        psdFile.ImageData[3][pos] = srcPixel->A;
                        srcPixel++;
                    }
                }
            }

            PaintDotNet.Threading.PrivateThreadPool threadPool = new PaintDotNet.Threading.PrivateThreadPool();
            foreach (BitmapLayer layer in input.Layers)
            {
                PhotoshopFile.Layer psdLayer = new PhotoshopFile.Layer(psdFile);
                BlendOpToBlendModeKey(layer.BlendOp, psdLayer);

                SaveLayerPixelsContext slc          = new SaveLayerPixelsContext(layer, psdFile, input, psdLayer, psdToken);
                WaitCallback           waitCallback = new WaitCallback(slc.SaveLayer);
                threadPool.QueueUserWorkItem(waitCallback);
            }
            threadPool.Drain();

            psdFile.Save(output);
        }
Esempio n. 28
0
 public override bool CanUseForResolution(IContainerContext containerContext, TypeInformation typeInfo, ResolutionInfo resolutionInfo) =>
 containerContext.Container.ParentContainer != null && containerContext.Container.ParentContainer.CanResolve(typeInfo.Type, typeInfo.DependencyName);
Esempio n. 29
0
 public override Expression[] GetExpressions(IContainerContext containerContext, TypeInformation typeInfo, ResolutionInfo resolutionInfo)
 {
     return(new Expression[] { Expression.Constant(new Test1()) });
 }
Esempio n. 30
0
		public void DoScanAndResolve()
		{
			//build a list of file sizes. Only those will be checked during scanning
			HashSet<long> sizes = new HashSet<long>();
			foreach (var ff in FirmwareDatabase.FirmwareFiles)
				sizes.Add(ff.size);

			using(var reader = new RealFirmwareReader())
			{
				// build a list of files under the global firmwares path, and build a hash for each of them while we're at it
				var todo = new Queue<DirectoryInfo>();
				todo.Enqueue(new DirectoryInfo(PathManager.MakeAbsolutePath(Global.Config.PathEntries.FirmwaresPathFragment, null)));
	
				while (todo.Count != 0)
				{
					var di = todo.Dequeue();

					if (!di.Exists)
						continue;

					// we're going to allow recursing into subdirectories, now. its been verified to work OK
					foreach (var disub in di.GetDirectories())
					{
						todo.Enqueue(disub);
					}
				
					foreach (var fi in di.GetFiles())
					{
						if(sizes.Contains(fi.Length))
							reader.Read(fi);
					}
				}

				// now, for each firmware record, try to resolve it
				foreach (var fr in FirmwareDatabase.FirmwareRecords)
				{
					// clear previous resolution results
					_resolutionDictionary.Remove(fr);

					// get all options for this firmware (in order)
					var fr1 = fr;
					var options =
						from fo in FirmwareDatabase.FirmwareOptions
						where fo.systemId == fr1.systemId && fo.firmwareId == fr1.firmwareId && fo.IsAcceptableOrIdeal
						select fo;

					// try each option
					foreach (var fo in options)
					{
						var hash = fo.hash;

						// did we find this firmware?
						if (reader.dict.ContainsKey(hash))
						{
							// rad! then we can use it
							var ri = new ResolutionInfo
								{
									FilePath = reader.dict[hash].FileInfo.FullName,
									KnownFirmwareFile = FirmwareDatabase.FirmwareFilesByHash[hash],
									Hash = hash,
									Size = fo.size
								};
							_resolutionDictionary[fr] = ri;
							goto DONE_FIRMWARE;
						}
					}

				DONE_FIRMWARE: ;

				}

				// apply user overrides
				foreach (var fr in FirmwareDatabase.FirmwareRecords)
				{
					string userSpec;

					// do we have a user specification for this firmware record?
					if (Global.Config.FirmwareUserSpecifications.TryGetValue(fr.ConfigKey, out userSpec))
					{
						// flag it as user specified
						ResolutionInfo ri;
						if (!_resolutionDictionary.TryGetValue(fr, out ri))
						{
							ri = new ResolutionInfo();
							_resolutionDictionary[fr] = ri;
						}
						ri.UserSpecified = true;
						ri.KnownFirmwareFile = null;
						ri.FilePath = userSpec;
						ri.Hash = null;

						// check whether it exists
						var fi = new FileInfo(userSpec);
						if (!fi.Exists)
						{
							ri.Missing = true;
							continue;
						}

						// compute its hash 
						var rff = reader.Read(fi);
						ri.Size = fi.Length;
						ri.Hash = rff.Hash;

						// check whether it was a known file anyway, and go ahead and bind to the known file, as a perk (the firmwares config doesnt really use this information right now)
						FirmwareDatabase.FirmwareFile ff;
						if (FirmwareDatabase.FirmwareFilesByHash.TryGetValue(rff.Hash, out ff))
						{
							ri.KnownFirmwareFile = ff;

							// if the known firmware file is for a different firmware, flag it so we can show a warning
							var option =
								(from fo in FirmwareDatabase.FirmwareOptions
								 where fo.hash == rff.Hash && fo.ConfigKey != fr.ConfigKey
								 select fr).FirstOrDefault();

							if (option != null)
							{
								ri.KnownMismatching = true;
							}
						}
					}

				} //foreach(firmware record)
			} //using(new RealFirmwareReader())
		} //DoScanAndResolve()
Esempio n. 31
0
        /// <inheritdoc />
        public TTo BuildUp <TTo>(TTo instance)
        {
            var typeTo       = instance.GetType();
            var registration = this.serviceRegistrator.PrepareContext(typeTo, typeTo);
            var expr         = this.expressionBuilder.CreateFillExpression(registration.CreateServiceRegistration(false),
                                                                           Expression.Constant(instance), ResolutionInfo.New(this, this.rootScope), typeTo);
            var factory = expr.CompileDelegate(Constants.ScopeExpression);

            return((TTo)factory(this));
        }
Esempio n. 32
0
 public override bool CanUseForResolution(IContainerContext containerContext, TypeInformation typeInfo, ResolutionInfo resolutionInfo)
 {
     return(typeInfo.Type == typeof(ITest1));
 }
Esempio n. 33
0
        ///////////////////////////////////////////////////////////////////////////
        private void LoadImageResources(BinaryReverseReader reader)
        {
            Debug.WriteLine("LoadImageResources started at " + reader.BaseStream.Position.ToString());

              m_imageResources.Clear();

              uint imgResLength = reader.ReadUInt32();
              if (imgResLength <= 0)
            return;

              long startPosition = reader.BaseStream.Position;

              while ((reader.BaseStream.Position - startPosition) < imgResLength)
              {
            ImageResource imgRes = new ImageResource(reader);

            ResourceIDs resID = (ResourceIDs)imgRes.ID;
            switch (resID)
            {
              case ResourceIDs.ResolutionInfo:
            imgRes = new ResolutionInfo(imgRes);
            break;
              case ResourceIDs.Thumbnail1:
              case ResourceIDs.Thumbnail2:
            imgRes = new Thumbnail(imgRes);
            break;
              case ResourceIDs.AlphaChannelNames:
            imgRes = new AlphaChannels(imgRes);
            break;
            }

            m_imageResources.Add(imgRes);

              }

              //-----------------------------------------------------------------------
              // make shure we are not on a wrong offset, so set the stream position
              // manually
              reader.BaseStream.Position = startPosition + imgResLength;
        }