예제 #1
0
        ///  GetTextMargins - checks to see if we have cached information about the current font,
        ///  returns info about it.
        ///  An MRU of Font margins was considered, but seems like overhead.
        internal static User32.DRAWTEXTPARAMS GetTextMargins(WindowsGraphics wg, WindowsFont font)
        {
            // PERF: operate on a local reference rather than party directly on the thread static one.
            CachedInfo currentCachedInfo = cachedMeasurementDCInfo;

            if (currentCachedInfo != null && currentCachedInfo.LeftTextMargin > 0 && currentCachedInfo.RightTextMargin > 0 && font == currentCachedInfo.LastUsedFont)
            {
                // we have to return clones as DrawTextEx will modify this struct
                return(new User32.DRAWTEXTPARAMS
                {
                    iLeftMargin = currentCachedInfo.LeftTextMargin,
                    iRightMargin = currentCachedInfo.RightTextMargin
                });
            }
            else if (currentCachedInfo == null)
            {
                currentCachedInfo       = new CachedInfo();
                cachedMeasurementDCInfo = currentCachedInfo;
            }
            User32.DRAWTEXTPARAMS drawTextParams = wg.GetTextMargins(font);
            currentCachedInfo.LeftTextMargin  = drawTextParams.iLeftMargin;
            currentCachedInfo.RightTextMargin = drawTextParams.iRightMargin;

            // returning a copy here to be consistent with the return value from the cache.
            return(new User32.DRAWTEXTPARAMS
            {
                iLeftMargin = currentCachedInfo.LeftTextMargin,
                iRightMargin = currentCachedInfo.RightTextMargin
            });
        }
        // Create a CachedInfo instance with every field populated from a given random number seed
        // The data doesn't have to make sense, but everything has to have a value of some sort so we can check everything is being serialized/deserialized
        static CachedInfo CreateSyntheticCachedInfo(int seed)
        {
            System.Random rnd = new System.Random(seed);

            CachedInfo cachedData = new CachedInfo();

            cachedData.Asset = CreateSyntheticCacheEntry(rnd);

            cachedData.Dependencies    = new CacheEntry[2];
            cachedData.Dependencies[0] = CreateSyntheticCacheEntry(rnd);
            cachedData.Dependencies[1] = CreateSyntheticCacheEntry(rnd);

            cachedData.Data = new object[]
            {
                CreateSyntheticAssetLoadInfo(rnd),
                CreateSyntheticBuildUsageTagSet(),
                CreateSyntheticSpriteImporterData(rnd),
                CreateSyntheticExtendedAssetData(rnd),
                CreateSyntheticObjectTypes(rnd),
                CreateSyntheticSceneDependencyInfo(rnd),
                CreateHash128(rnd),
                CreateSyntheticWriteResult(rnd),
                CreateSyntheticSerializedFileMetaData(rnd),
                CreateSyntheticBundleDetails(rnd)
            };

            return(cachedData);
        }
예제 #3
0
        CachedInfo GetCachedInfo(CacheEntry entry, IWriteOperation operation, WriteResult result)
        {
            var info = new CachedInfo();

            info.Asset = entry;

            var dependencies  = new HashSet <CacheEntry>();
            var sceneBundleOp = operation as SceneBundleWriteOperation;

            if (sceneBundleOp != null)
            {
                dependencies.Add(m_Cache.GetCacheEntry(sceneBundleOp.ProcessedScene));
            }
            var sceneDataOp = operation as SceneDataWriteOperation;

            if (sceneDataOp != null)
            {
                dependencies.Add(m_Cache.GetCacheEntry(sceneDataOp.ProcessedScene));
            }
            foreach (var serializeObject in operation.Command.serializeObjects)
            {
                dependencies.Add(m_Cache.GetCacheEntry(serializeObject.serializationObject));
            }
            info.Dependencies = dependencies.ToArray();

            info.Data = new object[] { result };

            return(info);
        }
예제 #4
0
        public void WhenLoadingStoredCachedData_CachedInfoIsValid()
        {
            StoreDataInCacheWithGUID(m_Cache, TestFile1GUID, "data");
            RecreateBuildCache();
            CachedInfo info = LoadCachedInfoForGUID(m_Cache, TestFile1GUID);

            Assert.AreEqual("data", (string)info.Data[0]);
        }
예제 #5
0
        static CachedInfo GetCachedInfo(IBuildCache cache, CacheEntry entry, IEnumerable <ResourceFile> resources, BundleDetails details)
        {
            var info = new CachedInfo();

            info.Asset        = entry;
            info.Dependencies = new CacheEntry[0];
            info.Data         = new object[] { details };
            return(info);
        }
예제 #6
0
        CachedInfo GetCachedInfo(CacheEntry entry, WriteResult result, SerializedFileMetaData metaData)
        {
            var info = new CachedInfo();

            info.Asset        = entry;
            info.Data         = new object[] { result, metaData };
            info.Dependencies = new CacheEntry[0];
            return(info);
        }
예제 #7
0
        /// <summary>
        /// List roles
        /// </summary>
        private void ListRoles()
        {
            tvAvailableRoles.Nodes.Clear();

            // List roles
            //
            SecurityRole rootRole = new SecurityRole();

            rootRole.Role        = "ROOT";
            rootRole.Description = "ROOT FOLDER";

            var rootRoleNode =
                new TreeNode(
                    rootRole.Role,
                    FCMConstant.Image.Folder,
                    FCMConstant.Image.Folder);

            rootRoleNode.Tag = rootRole;

            tvAvailableRoles.Nodes.Add(rootRoleNode);

            var roleList = SecurityRole.List();

            foreach (var role in roleList)
            {
                var roleNode =
                    new TreeNode(
                        role.Role,
                        FCMConstant.Image.Checked,
                        FCMConstant.Image.Checked);
                roleNode.Tag = role;

                rootRoleNode.Nodes.Add(roleNode);

                // Add screens connected to role
                //
                var respList      = BUSUserAccess.ListByRole(role.Role);
                var listOfScreens = (List <SecurityRoleScreen>)respList.Contents;

                // Get Screen Description from cache.
                //
                foreach (var screen in listOfScreens)
                {
                    var screenDescription =
                        CachedInfo.GetDescription(FCMConstant.CodeTypeString.SCREENCODE, screen.FKScreenCode);

                    var screenNode =
                        new TreeNode(
                            screenDescription,
                            FCMConstant.Image.Folder,
                            FCMConstant.Image.Folder);
                    screenNode.Tag = screen;

                    roleNode.Nodes.Add(screenNode);
                }
            }
        }
예제 #8
0
        ///  Reset
        ///  clear the current cached information about the measurement dc.
        internal static void Reset()
        {
            CachedInfo currentCachedInfo = cachedMeasurementDCInfo;

            if (currentCachedInfo != null)
            {
                currentCachedInfo.UpdateFont(null);
            }
        }
예제 #9
0
        public void WhenLoadingCachedDataForGUIDWithModifiedDependency_CachedInfoIsNull()
        {
            GUID depGuid = CreateTestTextAsset("mytext");

            StoreDataInCacheWithGUID(m_Cache, TestFile1GUID, "data", depGuid);
            ModifyTestTextAsset(depGuid, "mytext2");
            RecreateBuildCache();
            CachedInfo info = LoadCachedInfoForGUID(m_Cache, TestFile1GUID);

            Assert.IsNull(info);
        }
예제 #10
0
        public void WhenLoadingCachedDataForModifiedGUID_CachedInfoIsNull()
        {
            GUID guid = CreateTestTextAsset("mytext");

            StoreDataInCacheWithGUID(m_Cache, guid, "data");
            ModifyTestTextAsset(guid, "mytext2");
            RecreateBuildCache();
            CachedInfo info = LoadCachedInfoForGUID(m_Cache, guid);

            Assert.IsNull(info);
        }
예제 #11
0
        public void End()
        {
            GL.GetInteger(GetPName.Viewport, Viewport);
            ScreenWidth  = Viewport[2];
            ScreenHeight = Viewport[3];
            int stamp = Environment.TickCount;

            GL.Enable(EnableCap.Texture2D);
            GLHUDBegin();
            {
                foreach (TextItem item in textItems)
                {
                    int        hash = GetItemHash(item);
                    CachedInfo tex  = new CachedInfo()
                    {
                        TextureID = -1
                    };
                    if (Cache.ContainsKey(hash))
                    {
                        tex          = Cache[hash];
                        tex.LastUsed = stamp;
                    }
                    else
                    {
                        PrepareText(item);
                        if (item.TextureID != -1)
                        {
                            Cache[hash] = tex = new CachedInfo()
                            {
                                TextureID = item.TextureID,
                                Width     = item.ImgWidth,
                                Height    = item.ImgHeight,
                                LastUsed  = stamp
                            };
                        }
                    }
                    if (tex.TextureID == -1)
                    {
                        continue;
                    }
                    GL.Color4(item.Color);
                    GL.BindTexture(TextureTarget.Texture2D, tex.TextureID);
                    RHelp.Draw2DBox(item.Box.X, ScreenHeight - item.Box.Y - tex.Height, tex.Width, tex.Height, 0f);
                }

                GL.BindTexture(TextureTarget.Texture2D, 0);
                GL.Disable(EnableCap.Texture2D);
                GL.Color4(1f, 1f, 1f, 1f);
            }
            GLHUDEnd();

            textItems.Clear();
        }
        public void TestCachedInfoSerialises()
        {
            CachedInfo cachedInfo = CreateSyntheticCachedInfo(12478324);

            TestSerializeData(new PrimitiveValue <CachedInfo>()
            {
                m_Value = cachedInfo
            },
                              BuildCache.CustomSerializers,
                              BuildCache.ObjectFactories,
                              new DumpToText.ICustomDumper[] { new CustomDumper_BuildUsageTagSet() },
                              false); // full Equality not implemented for CachedInfo so we rely on the dumper text comparison
        }
예제 #13
0
        internal static void ResetIfIsMeasurementDC(IntPtr hdc)
        {
            WindowsGraphics sharedGraphics = WindowsGraphicsCacheManager.GetCurrentMeasurementGraphics();

            if (sharedGraphics != null && sharedGraphics.DeviceContext != null && sharedGraphics.DeviceContext.Hdc == hdc)
            {
                CachedInfo currentCachedInfo = cachedMeasurementDCInfo;
                if (currentCachedInfo != null)
                {
                    currentCachedInfo.UpdateFont(null);
                }
            }
        }
예제 #14
0
        public void WhenGlobalVersionChanges_OriginalCachedInfoDoesNotNeedRebuild()
        {
            m_Cache.OverrideGlobalHash(new Hash128(0, 1, 0, 0));

            StoreDataInCacheWithGUID(m_Cache, TestFile1GUID, "data");
            CachedInfo info1 = LoadCachedInfoForGUID(m_Cache, TestFile1GUID);

            RecreateBuildCache();
            m_Cache.OverrideGlobalHash(new Hash128(0, 2, 0, 0));
            CachedInfo info2 = LoadCachedInfoForGUID(m_Cache, TestFile1GUID);

            Assert.IsFalse(m_Cache.HasAssetOrDependencyChanged(info1)); // original info still doesn't need rebuild. Required for content update
            Assert.IsNull(info2);                                       // however the data cannot be recovered
        }
#pragma warning restore 649

        CachedInfo GetCachedInfo(GUID scene, IEnumerable<ObjectIdentifier> references, SceneDependencyInfo sceneInfo, BuildUsageTagSet usageTags, IEnumerable<CacheEntry> prefabEntries, Hash128 prefabDependency)
        {
            var info = new CachedInfo();
            info.Asset = m_Cache.GetCacheEntry(scene, Version);

            var dependencies = new HashSet<CacheEntry>();
            foreach (var reference in references)
                dependencies.Add(m_Cache.GetCacheEntry(reference));
            dependencies.UnionWith(prefabEntries);
            info.Dependencies = dependencies.ToArray();

            info.Data = new object[] { sceneInfo, usageTags, prefabDependency };

            return info;
        }
예제 #16
0
        static CachedInfo GetCachedInfo(IBuildCache cache, GUID asset, AssetLoadInfo assetInfo, BuildUsageTagSet usageTags, SpriteImporterData importerData, ExtendedAssetData assetData)
        {
            var info = new CachedInfo();

            info.Asset = cache.GetCacheEntry(asset, kVersion);

            var uniqueTypes  = new HashSet <System.Type>();
            var objectTypes  = new List <KeyValuePair <ObjectIdentifier, System.Type[]> >();
            var dependencies = new HashSet <CacheEntry>();

            ExtensionMethods.ExtractCommonCacheData(cache, assetInfo.includedObjects, assetInfo.referencedObjects, uniqueTypes, objectTypes, dependencies);
            info.Dependencies = dependencies.ToArray();

            info.Data = new object[] { assetInfo, usageTags, importerData, assetData, objectTypes };
            return(info);
        }
예제 #17
0
        CachedInfo GetCachedInfo(CacheEntry entry, AssetLoadInfo assetInfo, BuildUsageTagSet usageTags)
        {
            var info = new CachedInfo();

            info.Asset = entry;

            var uniqueTypes  = new HashSet <Type>();
            var objectTypes  = new List <KeyValuePair <ObjectIdentifier, Type[]> >();
            var dependencies = new HashSet <CacheEntry>();

            ExtensionMethods.ExtractCommonCacheData(m_Cache, assetInfo.includedObjects, assetInfo.referencedObjects, uniqueTypes, objectTypes, dependencies);
            info.Dependencies = dependencies.ToArray();

            info.Data = new object[] { assetInfo, usageTags, objectTypes };
            return(info);
        }
 internal static IntNativeMethods.DRAWTEXTPARAMS GetTextMargins(WindowsGraphics wg, WindowsFont font)
 {
     CachedInfo cachedMeasurementDCInfo = MeasurementDCInfo.cachedMeasurementDCInfo;
     if (((cachedMeasurementDCInfo == null) || (cachedMeasurementDCInfo.LeftTextMargin <= 0)) || ((cachedMeasurementDCInfo.RightTextMargin <= 0) || (font != cachedMeasurementDCInfo.LastUsedFont)))
     {
         if (cachedMeasurementDCInfo == null)
         {
             cachedMeasurementDCInfo = new CachedInfo();
             MeasurementDCInfo.cachedMeasurementDCInfo = cachedMeasurementDCInfo;
         }
         IntNativeMethods.DRAWTEXTPARAMS textMargins = wg.GetTextMargins(font);
         cachedMeasurementDCInfo.LeftTextMargin = textMargins.iLeftMargin;
         cachedMeasurementDCInfo.RightTextMargin = textMargins.iRightMargin;
     }
     return new IntNativeMethods.DRAWTEXTPARAMS(cachedMeasurementDCInfo.LeftTextMargin, cachedMeasurementDCInfo.RightTextMargin);
 }
        internal static IntNativeMethods.DRAWTEXTPARAMS GetTextMargins(WindowsGraphics wg, WindowsFont font)
        {
            CachedInfo cachedMeasurementDCInfo = MeasurementDCInfo.cachedMeasurementDCInfo;

            if (((cachedMeasurementDCInfo == null) || (cachedMeasurementDCInfo.LeftTextMargin <= 0)) || ((cachedMeasurementDCInfo.RightTextMargin <= 0) || (font != cachedMeasurementDCInfo.LastUsedFont)))
            {
                if (cachedMeasurementDCInfo == null)
                {
                    cachedMeasurementDCInfo = new CachedInfo();
                    MeasurementDCInfo.cachedMeasurementDCInfo = cachedMeasurementDCInfo;
                }
                IntNativeMethods.DRAWTEXTPARAMS textMargins = wg.GetTextMargins(font);
                cachedMeasurementDCInfo.LeftTextMargin  = textMargins.iLeftMargin;
                cachedMeasurementDCInfo.RightTextMargin = textMargins.iRightMargin;
            }
            return(new IntNativeMethods.DRAWTEXTPARAMS(cachedMeasurementDCInfo.LeftTextMargin, cachedMeasurementDCInfo.RightTextMargin));
        }
        private bool TryGetCachedInfo(MetadataTypeReference typeReference, out CachedInfo cachedInfo)
        {
            var(assemblyReference, typeName) = NameSpec.FromMetadataTypeReference(typeReference);

            if (assemblyReference == null)
            {
                if (currentAssemblyLoader == null)
                {
                    currentAssemblyLoader = new AssemblyLazyLoader(currentAssemblyStreamFactory.Invoke());
                }

                if (currentAssemblyLoader.TryGetInfo(typeName, this, out cachedInfo))
                {
                    return(true);
                }

                // Attribute values containing enum type references serialize the string.
                // So far all mscorlib enum references I've seen include the assembly name,
                // but this is just in case.

                if (currentAssemblyMscorlibReference == null)
                {
                    currentAssemblyMscorlibReference = GetMscorlibReference(currentAssemblyStreamFactory.Invoke());
                }

                assemblyReference = currentAssemblyMscorlibReference;
            }

            var fullName = assemblyReference.FullName;

            if (!assemblyLoadersByFullName.TryGetValue(fullName, out var loader))
            {
                loader = assemblyResolver.TryGetAssemblyPath(assemblyReference, out var path) ? new AssemblyLazyLoader(File.OpenRead(path)) : null;
                assemblyLoadersByFullName.Add(fullName, loader);
            }

            if (loader == null)
            {
                // We couldn't locate the assembly.
                cachedInfo = default;
                return(false);
            }

            return(loader.TryGetInfo(typeName, this, out cachedInfo));
        }
#pragma warning restore 649

        CachedInfo GetCachedInfo(GUID scene, IEnumerable <ObjectIdentifier> references, SceneDependencyInfo sceneInfo, BuildUsageTagSet usageTags)
        {
            var info = new CachedInfo();

            info.Asset = m_Cache.GetCacheEntry(scene, Version);

            var dependencies = new HashSet <CacheEntry>();

            foreach (ObjectIdentifier reference in references)
            {
                dependencies.Add(m_Cache.GetCacheEntry(reference));
            }
            info.Dependencies = dependencies.ToArray();

            info.Data = new object[] { sceneInfo, usageTags };

            return(info);
        }
예제 #22
0
#pragma warning restore 649

        CachedInfo GetCachedInfo(GUID asset, AssetLoadInfo assetInfo, BuildUsageTagSet usageTags, SpriteImporterData importerData)
        {
            var info = new CachedInfo();

            info.Asset = m_Cache.GetCacheEntry(asset);

            var dependencies = new HashSet <CacheEntry>();

            foreach (var reference in assetInfo.referencedObjects)
            {
                dependencies.Add(m_Cache.GetCacheEntry(reference));
            }
            info.Dependencies = dependencies.ToArray();

            info.Data = new object[] { assetInfo, usageTags, importerData };

            return(info);
        }
예제 #23
0
        static CachedInfo GetCachedInfo(IBuildCache cache, CacheEntry entry, IEnumerable <ResourceFile> resources, BundleDetails details)
        {
            var info = new CachedInfo();

            info.Asset = entry;

            var dependencies = new HashSet <CacheEntry>();

            foreach (var resource in resources)
            {
                dependencies.Add(cache.GetCacheEntry(resource.fileName));
            }
            info.Dependencies = dependencies.ToArray();

            info.Data = new object[] { details };

            return(info);
        }
예제 #24
0
        /// <summary>
        /// Performs operations upon the current request.
        /// </summary>
        /// <param name="context">The current HTTP request context</param>
        /// <returns>The <see cref="Task"/></returns>
        public async Task Invoke(HttpContext context)
        {
            IDictionary <string, string> commands = this.requestParser.ParseRequestCommands(context)
                                                    .Where(kvp => this.knownCommands.Contains(kvp.Key))
                                                    .ToDictionary(p => p.Key, p => p.Value);

            this.options.OnValidate?.Invoke(new ImageValidationContext(context, commands, CommandParser.Instance));

            if (!commands.Any())
            {
                // Nothing to do. call the next delegate/middleware in the pipeline
                await this.next(context);

                return;
            }

            // Create a cache key based on all the components of the requested url
            string uri = $"{context.Request.Host.ToString().ToLowerInvariant()}/{context.Request.PathBase.ToString().ToLowerInvariant()}/{context.Request.Path}{QueryString.Create(commands)}";
            string key = this.cacheHash.Create(uri, this.options.CachedNameLength);

            // Prevent identical requests from running at the same time
            // This reduces the overheads of unnecessary processing plus avoids file locks
            bool processRequest = true;

            using (await this.asyncKeyLock.LockAsync(key))
            {
                // Get the correct service for the request.
                IImageResolver resolver = this.resolvers.FirstOrDefault(r => r.Match(context));

                if (resolver == null || !await resolver.IsValidRequestAsync(context, this.logger))
                {
                    // Nothing to do. Call the next delegate/middleware in the pipeline
                    processRequest = false;
                }

                if (processRequest)
                {
                    CachedInfo info = await this.cache.IsExpiredAsync(context, key, DateTime.UtcNow.AddDays(-this.options.MaxCacheDays));

                    var imageContext = new ImageContext(context, this.options);

                    if (info.Equals(default))
예제 #25
0
#pragma warning restore 649

        CachedInfo GetCachedInfo(GUID scene, IEnumerable <ObjectIdentifier> references, SceneDependencyInfo sceneInfo, BuildUsageTagSet usageTags, IEnumerable <CacheEntry> prefabEntries, Hash128 prefabDependency)
        {
            var info = new CachedInfo();

            info.Asset = m_Cache.GetCacheEntry(scene, Version);

#if ENABLE_TYPE_HASHING || UNITY_2020_1_OR_NEWER
            var uniqueTypes = new HashSet <System.Type>(sceneInfo.includedTypes);
#else
            var uniqueTypes = new HashSet <System.Type>();
#endif
            var objectTypes  = new List <KeyValuePair <ObjectIdentifier, System.Type[]> >();
            var dependencies = new HashSet <CacheEntry>(prefabEntries);
            ExtensionMethods.ExtractCommonCacheData(m_Cache, null, references, uniqueTypes, objectTypes, dependencies);
            info.Dependencies = dependencies.ToArray();

            info.Data = new object[] { sceneInfo, usageTags, prefabDependency, objectTypes };

            return(info);
        }
예제 #26
0
        static CachedInfo CalculateTargetCachedInfo(CacheEntry entry, BuildTarget target, TypeDB typeDB = null)
        {
            var cache = new BuildCache();
            List <ObjectIdentifier> objects = new List <ObjectIdentifier>();

            objects.AddRange(ContentBuildInterface.GetPlayerObjectIdentifiersInAsset(entry.Guid, target));
            objects.AddRange(ContentBuildInterface.GetPlayerDependenciesForObjects(objects.ToArray(), target, typeDB));

            var cachedInfo = new CachedInfo();

            cachedInfo.Asset = entry;
            cachedInfo.Data  = new[] { objects };

            // TODO: Handle built-in objects, might require some low level build changes like an option to ignore the hideFlags
            var dependencies = objects.Select(x => x.guid).Where(x => !x.Empty() && x != entry.Guid && x != k_UnityBuiltinResources).Distinct();

            cachedInfo.Dependencies = dependencies.Select(cache.GetCacheEntry).ToArray();
            // cache.SaveCachedData(new List<CachedInfo> { cachedInfo }); // TODO: Disabled because we have file contention as "Save" is async only with no wait functionality
            return(cachedInfo);
        }
#pragma warning restore 649

        CachedInfo GetCachedInfo(GUID scene, IEnumerable <ObjectIdentifier> references, SceneDependencyInfo sceneInfo, BuildUsageTagSet usageTags)
        {
            var info = new CachedInfo();

            info.Asset = m_Cache.GetCacheEntry(scene, Version);

            var dependencies = new HashSet <CacheEntry>();

            foreach (var reference in references)
            {
                dependencies.Add(m_Cache.GetCacheEntry(reference));
            }
            var prefabEntries = AssetDatabase.GetDependencies(AssetDatabase.GUIDToAssetPath(scene.ToString())).Where(path => path.EndsWith(".prefab")).Select(m_Cache.GetCacheEntry);

            dependencies.UnionWith(prefabEntries);
            info.Dependencies = dependencies.ToArray();

            info.Data = new object[] { sceneInfo, usageTags };

            return(info);
        }
예제 #28
0
        static protected void StoreDataInCacheWithGUID(BuildCache cache, GUID guid, object data, GUID depGUID = new GUID())
        {
            List <CacheEntry> deps = new List <CacheEntry>();

            if (!depGUID.Empty())
            {
                deps.Add(cache.GetCacheEntry(depGUID));
            }

            CacheEntry entry1 = cache.GetCacheEntry(guid);
            CachedInfo info   = new CachedInfo();

            info.Asset        = entry1;
            info.Dependencies = deps.ToArray();
            info.Data         = new object[] { data };
            cache.SaveCachedData(new List <CachedInfo>()
            {
                info
            });
            cache.SyncPendingSaves();
        }
예제 #29
0
       /// GetTextMargins - checks to see if we have cached information about the current font,
       /// returns info about it.
       /// An MRU of Font margins was considered, but seems like overhead.
       internal static IntNativeMethods.DRAWTEXTPARAMS GetTextMargins(WindowsGraphics wg, WindowsFont font) {

            // PERF: operate on a local reference rather than party directly on the thread static one.
            CachedInfo currentCachedInfo = cachedMeasurementDCInfo;
            
            if (currentCachedInfo != null && currentCachedInfo.LeftTextMargin >0 && currentCachedInfo.RightTextMargin >0 && font == currentCachedInfo.LastUsedFont) 
            {
                // we have to return clones as DrawTextEx will modify this struct
                return new IntNativeMethods.DRAWTEXTPARAMS(currentCachedInfo.LeftTextMargin,currentCachedInfo.RightTextMargin);                    
            }
            else if (currentCachedInfo == null) 
            {
                currentCachedInfo = new CachedInfo();
                cachedMeasurementDCInfo = currentCachedInfo;
            }
            IntNativeMethods.DRAWTEXTPARAMS drawTextParams = wg.GetTextMargins(font);
            currentCachedInfo.LeftTextMargin = drawTextParams.iLeftMargin;
            currentCachedInfo.RightTextMargin = drawTextParams.iRightMargin;
            
            // returning a copy here to be consistent with the return value from the cache.
            return new IntNativeMethods.DRAWTEXTPARAMS(currentCachedInfo.LeftTextMargin,currentCachedInfo.RightTextMargin);
            
       }
예제 #30
0
        private bool TryGetCacheValue(SqlConnectionStringBuilder builder, out CachedInfo value)
        {
            CacheKey key = new CacheKey(builder);

            return(_cache.TryGetValue(key, out value));
        }
예제 #31
0
        /// <summary>
        /// Performs operations upon the current request.
        /// </summary>
        /// <param name="context">The current HTTP request context.</param>
        /// <returns>The <see cref="Task"/>.</returns>
        public async Task Invoke(HttpContext context)
        {
            IDictionary <string, string> commands = this.requestParser.ParseRequestCommands(context)
                                                    .Where(kvp => this.knownCommands.Contains(kvp.Key))
                                                    .ToDictionary(p => p.Key, p => p.Value);

            this.options.OnParseCommands?.Invoke(new ImageCommandContext(context, commands, CommandParser.Instance));

            // Get the correct service for the request.
            IImageProvider provider = this.resolvers.FirstOrDefault(r => r.Match(context));

            if (provider?.IsValidRequest(context) != true)
            {
                // Nothing to do. call the next delegate/middleware in the pipeline
                await this.next(context).ConfigureAwait(false);

                return;
            }

            // Create a cache key based on all the components of the requested url
            string uri = GetUri(context, commands);
            string key = this.cacheHash.Create(uri, this.options.CachedNameLength);

            bool           processRequest = true;
            var            imageContext   = new ImageContext(context, this.options);
            IImageResolver resolvedImage  = provider.Get(context);

            if (resolvedImage == null)
            {
                // Log the error but let the pipeline handle the 404
                this.logger.LogImageResolveFailed(imageContext.GetDisplayUrl());
                processRequest = false;
            }

            if (processRequest)
            {
                // Lock any reads when a write is being done for the same key to prevent potential file locks.
                using (await AsyncLock.ReaderLockAsync(key).ConfigureAwait(false))
                {
                    DateTime lastWriteTimeUtc = await resolvedImage.GetLastWriteTimeUtcAsync().ConfigureAwait(false);

                    CachedInfo info = await this.cache.IsExpiredAsync(context, key, lastWriteTimeUtc, DateTime.UtcNow.AddDays(-this.options.MaxCacheDays)).ConfigureAwait(false);

                    if (!info.Expired)
                    {
                        // We're pulling the image from the cache.
                        IImageResolver cachedImage = this.cache.Get(key);
                        using (Stream cachedBuffer = await cachedImage.OpenReadAsync().ConfigureAwait(false))
                        {
                            // Image is a cached image. Return the correct response now.
                            await this.SendResponse(imageContext, key, info.LastModifiedUtc, cachedBuffer).ConfigureAwait(false);
                        }

                        return;
                    }
                }

                // Not cached? Let's get it from the image resolver.
                ChunkedMemoryStream outStream = null;
                try
                {
                    if (processRequest)
                    {
                        // Enter a write lock which locks writing and any reads for the same request.
                        // This reduces the overheads of unnecessary processing plus avoids file locks.
                        using (await AsyncLock.WriterLockAsync(key).ConfigureAwait(false))
                        {
                            // No allocations here for inStream since we are passing the raw input stream.
                            // outStream allocation depends on the memory allocator used.
                            outStream = new ChunkedMemoryStream(this.memoryAllocator);
                            using (Stream inStream = await resolvedImage.OpenReadAsync().ConfigureAwait(false))
                                using (var image = FormattedImage.Load(this.options.Configuration, inStream))
                                {
                                    image.Process(this.logger, this.processors, commands);
                                    this.options.OnBeforeSave?.Invoke(image);
                                    image.Save(outStream);
                                }

                            // Allow for any further optimization of the image. Always reset the position just in case.
                            outStream.Position = 0;
                            this.options.OnProcessed?.Invoke(new ImageProcessingContext(context, outStream, commands, Path.GetExtension(key)));
                            outStream.Position = 0;

                            DateTimeOffset cachedDate = await this.cache.SetAsync(key, outStream).ConfigureAwait(false);

                            await this.SendResponse(imageContext, key, cachedDate, outStream).ConfigureAwait(false);
                        }
                    }
                }
                catch (Exception ex)
                {
                    // Log the error internally then rethrow.
                    // We don't call next here, the pipeline will automatically handle it
                    this.logger.LogImageProcessingFailed(imageContext.GetDisplayUrl(), ex);
                    throw;
                }
                finally
                {
                    outStream?.Dispose();
                }
            }

            if (!processRequest)
            {
                // Call the next delegate/middleware in the pipeline
                await this.next(context).ConfigureAwait(false);
            }
        }
예제 #32
0
        public void End()
        {
            GL.GetInteger(GetPName.Viewport, Viewport);
            ScreenWidth = Viewport[2];
            ScreenHeight = Viewport[3];
            int stamp = Environment.TickCount;

            GL.Enable(EnableCap.Texture2D);
            GLHUDBegin();
            {
                foreach (TextItem item in textItems)
                {
                    int hash = GetItemHash(item);
                    CachedInfo tex = new CachedInfo() { TextureID = -1 };
                    if (Cache.ContainsKey(hash))
                    {
                        tex = Cache[hash];
                        tex.LastUsed = stamp;
                    }
                    else
                    {
                        PrepareText(item);
                        if (item.TextureID != -1)
                        {
                            Cache[hash] = tex = new CachedInfo()
                            {
                                TextureID = item.TextureID,
                                Width = item.ImgWidth,
                                Height = item.ImgHeight,
                                LastUsed = stamp
                            };
                        }
                    }
                    if (tex.TextureID == -1) continue;
                    GL.Color4(item.Color);
                    GL.BindTexture(TextureTarget.Texture2D, tex.TextureID);
                    RHelp.Draw2DBox(item.Box.X, ScreenHeight - item.Box.Y - tex.Height, tex.Width, tex.Height, 0f);
                }

                GL.BindTexture(TextureTarget.Texture2D, 0);
                GL.Disable(EnableCap.Texture2D);
                GL.Color4(1f, 1f, 1f, 1f);
            }
            GLHUDEnd();

            textItems.Clear();
        }
예제 #33
0
        public void WhenLoadingUncachedData_CachedInfoIsNull()
        {
            CachedInfo info = LoadCachedInfoForGUID(m_Cache, UncachedGUID);

            Assert.IsNull(info);
        }