Пример #1
0
        public static IEnumerable <Flashcard> Parse(IEnumerable <string> text, string seperator, LoadFlags mode)
        {
            Regex question = new Regex($".*?(?={seperator})");
            Regex answer   = new Regex("(?<=-).*");

            foreach (var item in text)
            {
                if (string.IsNullOrEmpty(item.Trim()))
                {
                    yield break;
                }
                string a = question.Match(item).Value.Trim();
                string b = answer.Match(item).Value.Trim();
                if (string.IsNullOrEmpty(a) || string.IsNullOrEmpty(b))
                {
                    continue;
                }
                if (mode.HasFlag(LoadFlags.Default))
                {
                    yield return(new Flashcard(a, b));
                }
                if (mode.HasFlag(LoadFlags.Invert))
                {
                    yield return(new Flashcard(b, a));
                }
            }
        }
        /// <summary>
        /// Method to create an object from a set of object attributes.
        /// </summary>
        /// <param name="obj_attributes">The object attributes to create/open from.</param>
        /// <returns>The newly created object.</returns>
        protected override object CreateObject(ObjectAttributes obj_attributes)
        {
            string key_path = Win32Path ? NtKeyUtils.Win32KeyNameToNt(KeyPath) : KeyPath;

            using (ObjectAttributes name = new ObjectAttributes(key_path, AttributeFlags.CaseInsensitive))
            {
                if (!LoadFlags.HasFlag(LoadKeyFlags.AppKey))
                {
                    using (NtToken token = NtToken.OpenProcessToken())
                    {
                        TokenPrivilege priv = token.GetPrivilege(TokenPrivilegeValue.SeRestorePrivilege);
                        if (priv == null || (priv.Attributes & PrivilegeAttributes.Enabled) == 0)
                        {
                            WriteWarning("Loading a non-app hive should require SeRestorePrivilege");
                        }
                    }
                }
                else
                {
                    if (!KeyPath.StartsWith(@"\Registry\A\", System.StringComparison.OrdinalIgnoreCase))
                    {
                        WriteWarning(@"Loading app hive outside of \Registry\A\ will fail on an up to date system.");
                    }
                }

                if (NoOpen)
                {
                    NtKey.LoadKeyNoOpen(name, obj_attributes, LoadFlags, TrustKey, Event, Token);
                    return(null);
                }
                return(NtKey.LoadKey(name, obj_attributes, LoadFlags, Access, TrustKey, Event, Token));
            }
        }
Пример #3
0
 /// <summary>Finds the type with the specified name.</summary>
 /// <param name="name">The name of the type (this can be a full type name or a full qualified name with assembly information).</param>
 /// <param name="mode">The loader mode.</param>
 /// <returns>Returns the first matching type.</returns>
 /// <exception cref="System.TypeLoadException">when type cannot be loaded.</exception>
 public static Type FindType(string name, LoadFlags mode = 0)
 {
     if (name.Contains(','))
     {
         var typeName     = name.BeforeFirst(',').Trim();
         var assemblyName = name.AfterFirst(',').Trim();
         var assembly     =
             mode.HasFlag(LoadFlags.LoadAssemblies) ?
             Assembly.Load(assemblyName) ?? throw new TypeLoadException($"Could not load assembly {assemblyName}") :
                   FindAssembly(assemblyName, true);
         return(assembly.GetType(typeName, true, false));
     }
     return(FindType(name, null, mode));
 }
Пример #4
0
        public void Load(string s, out LoadFlags flags)
        {
            flags = LoadFlags.None;
            this.FreezeAutocalc  = true;
            this._tempLoadObject = JObject.Parse(s);
            int saveVersion = this.LookupSaveVersion();

            this.State.Clear();
            switch (saveVersion)
            {
            case 1:
            {
                this.LoadV1(s);
                flags = LoadFlags.V2AdaptV1;
                break;
            }

            case 2:
            {
                this.LoadV2(s, ref flags);
                break;
            }

            default:
                throw new NotSupportedException($"The specified save file version can't be loaded - no format converter exists for version { saveVersion }.");
            }

            AppEvents.InvokeLoad(ref s);

            //HACK modifiers fix
            this.State.General.StatStr -= this.State.General.ModifiersStr.Sum(m => m.Value);
            this.State.General.StatDex -= this.State.General.ModifiersDex.Sum(m => m.Value);
            this.State.General.StatCon -= this.State.General.ModifiersCon.Sum(m => m.Value);
            this.State.General.StatCha -= this.State.General.ModifiersCha.Sum(m => m.Value);
            this.State.General.StatWis -= this.State.General.ModifiersWis.Sum(m => m.Value);
            this.State.General.StatInt -= this.State.General.ModifiersInt.Sum(m => m.Value);
            this.FreezeAutocalc         = false;
            this._ignoreLastSaveFile    = false;
            if (!flags.HasFlag(LoadFlags.KeepLoadObject))
            {
                this._tempLoadObject = null;
            }
        }
Пример #5
0
 public DubProject LoadProject(string file, Solution parentSolution, IProgressMonitor monitor, LoadFlags flags = LoadFlags.LoadReferences, DubProject superProject = null)
 {
     if (monitor != null)
     {
         monitor.BeginTask("Load dub project '" + file + "'", 1);
     }
     try
     {
         var prj = supportedDubFileFormats.First((i) => i.CanLoad(file)).Load(file, superProject, parentSolution);
         if (flags.HasFlag(LoadFlags.LoadReferences))
         {
             LoadSubProjects(prj, monitor);
         }
         return(prj);
     }
     finally
     {
         if (monitor != null)
         {
             monitor.EndTask();
         }
     }
 }
Пример #6
0
        /// <summary>
        /// Loads the storage from a <see cref="System.IO.Stream"/>.
        /// </summary>
        /// <param name="stream">
        /// The <see cref="System.IO.Stream"/> from which the storage should be loaded.
        /// </param>
        /// <param name="flags">
        /// The <see cref="DBFilesClient.NET.LoadFlags"/> to be used when loading.
        /// </param>
        public unsafe virtual void Load(Stream stream, LoadFlags flags)
        {
            GenerateLoadMethod();

            byte[] headerBytes;
            byte[] data;
            byte[] pool;

            fixed(byte *headerPtr = headerBytes = new byte[DBCHeader.Size])
            {
                if (stream.Read(headerBytes, 0, DBCHeader.Size) != DBCHeader.Size)
                {
                    throw new IOException("Failed to read the DBC header.");
                }

                var header = (DBCHeader *)headerPtr;

                if (!flags.HasFlag(LoadFlags.IgnoreWrongFourCC) && header->FourCC != 0x43424457)
                {
                    throw new ArgumentException("This is not a valid DBC file.");
                }

                if (header->RecordSize != m_entrySize)
                {
                    throw new ArgumentException("This DBC file has wrong record size ("
                                                + header->RecordSize + ", expected is " + m_entrySize + ").");
                }

                m_records = header->Records;

                int index, size;

                index = 0;
                size  = header->Records * header->RecordSize;
                data  = new byte[size];
                while (index < size)
                {
                    index += stream.Read(data, index, size - index);
                }

                index = 0;
                size  = header->StringPoolSize;
                pool  = new byte[size];
                while (index < size)
                {
                    index += stream.Read(pool, index, size - index);
                }
            }

            fixed(byte *pdata_ = data)
            {
                byte *pdata = pdata_;

                if (m_records > 0)
                {
                    uint  minId  = uint.MaxValue;
                    uint  maxId  = uint.MinValue;
                    byte *pdata2 = pdata;

                    for (int i = 0; i < m_records; i++)
                    {
                        uint id = *(uint *)pdata2;

                        if (minId > id)
                        {
                            minId = id;
                        }

                        if (maxId < id)
                        {
                            maxId = id;
                        }

                        pdata2 += m_entrySize;
                    }

                    this.Resize(minId, maxId);
                }

                fixed(byte *ppool = m_haveString?pool : null)
                {
                    sbyte *      spool     = (sbyte *)ppool;
                    int          poolLen   = pool.Length;
                    StringGetter strGetter = offset => LazyCString.LoadString(spool, poolLen, offset);

                    bool ignoreLazyCStrings = !flags.HasFlag(LoadFlags.LazyCStrings);

                    for (int i = 0; i < m_records; i++)
                    {
                        var entry = (T)m_ctor.Invoke(null);

                        m_loadMethod(pdata, pool, strGetter, entry, ignoreLazyCStrings);

                        uint id = *(uint *)pdata;
                        m_entries[id - m_minId] = entry;

                        pdata += m_entrySize;
                    }
                }
            }
        }
Пример #7
0
        public override unsafe void Load(Stream stream, LoadFlags flags)
        {
            GenerateLoadMethod();

            byte[] headerBytes;
            byte[] data;
            byte[] pool;

            fixed(byte *headerPtr = headerBytes = new byte[DB2Header.Size])
            {
                if (stream.Read(headerBytes, 0, DB2Header.Size) != DB2Header.Size)
                {
                    throw new IOException("Failed to read the DB2 header.");
                }

                var header = (DB2Header *)headerPtr;

                if (!flags.HasFlag(LoadFlags.IgnoreWrongFourCC) && header->FourCC != 0x32424457)
                {
                    throw new ArgumentException("This is not a valid DB2 file.");
                }

                if (header->RecordSize != m_entrySize)
                {
                    throw new ArgumentException("This DB2 file has wrong record size ("
                                                + m_entrySize + ", expected is " + header->RecordSize + ").");
                }

                m_records  = header->Records;
                this.Hash  = header->Hash;
                this.Build = header->Build;

                if (header->Build > 12880)
                {
                    fixed(byte *extHeaderPtr = headerBytes = new byte[DB2ExtendedHeader.Size])
                    {
                        if (stream.Read(headerBytes, 0, DB2ExtendedHeader.Size) != DB2ExtendedHeader.Size)
                        {
                            throw new IOException("Failed to read the extended DB2 header.");
                        }

                        var extHeader = (DB2ExtendedHeader *)extHeaderPtr;

                        this.Locale = extHeader->Locale;

                        if (extHeader->MaxId != 0)
                        {
                            int diff;
                            checked
                            {
                                diff = (int)(extHeader->MaxId - extHeader->MinId + 1) * 6;
                            }

                            if (stream.CanSeek)
                            {
                                stream.Seek(diff, SeekOrigin.Current);
                            }
                            else
                            {
                                var dummy = new byte[4096];
                                while (diff > 0)
                                {
                                    diff -= stream.Read(dummy, 0, Math.Min(diff, 4096));
                                }
                            }
                        }
                    }
                }

                int index, size;

                index = 0;
                size  = header->Records * header->RecordSize;
                data  = new byte[size];
                while (index < size)
                {
                    index += stream.Read(data, index, size - index);
                }

                index = 0;
                size  = header->StringPoolSize;
                pool  = new byte[size];
                while (index < size)
                {
                    index += stream.Read(pool, index, size - index);
                }
            }

            fixed(byte *pdata_ = data)
            {
                byte *pdata = pdata_;

                if (m_records > 0)
                    this.Resize(*(uint *)pdata, *(uint *)(pdata + m_entrySize * (m_records - 1)));

                fixed(byte *ppool = m_haveString?pool : null)
                {
                    sbyte *      spool     = (sbyte *)ppool;
                    int          poolLen   = pool.Length;
                    StringGetter strGetter = offset => LazyCString.LoadString(spool, poolLen, offset);

                    bool ignoreLazyCStrings = !flags.HasFlag(LoadFlags.LazyCStrings);

                    for (int i = 0; i < m_records; i++)
                    {
                        var entry = (T)m_ctor.Invoke(null);

                        m_loadMethod(pdata, pool, strGetter, entry, ignoreLazyCStrings);

                        uint id = *(uint *)pdata;
                        m_entries[id - m_minId] = entry;

                        pdata += m_entrySize;
                    }
                }
            }
        }
Пример #8
0
		public DubProject LoadProject(string file, Solution parentSolution, IProgressMonitor monitor, LoadFlags flags = LoadFlags.LoadReferences, DubProject superProject = null)
		{
			DubProject prj;

			if (FilesBeingLoaded.TryGetValue(file, out prj))
				return prj;

			using (new FilesBeingLoadedCleanser(file))
			{
				monitor.BeginTask("Load dub project '" + file + "'", 1);
				try
				{
					prj = supportedDubFileFormats.First((i) => i.CanLoad(file)).Load(file, superProject, parentSolution);
				}
				catch (Exception ex)
				{
					monitor.ReportError("Couldn't load dub package \"" + file + "\"", ex);
				}
				finally
				{
					monitor.EndTask();
				}

				if (flags.HasFlag(LoadFlags.LoadReferences))
					LoadSubProjects(prj, monitor);
			}

			return prj;
		}
Пример #9
0
        /// <summary>
        /// 從WIC Frame建立貼圖資源(非DDS)
        /// </summary>
        /// <param name="d3dContext">If a Direct3D 11 device context is provided and the current device supports it for the given pixel format, it will auto-generate mipmaps.</param>
        private static Result CreateWICTexture(Device device, DeviceContext d3dContext, BitmapFrameDecode frame, int maxsize, ResourceUsage usage, BindFlags bind, CpuAccessFlags cpuAccess, ResourceOptionFlags option, LoadFlags load, out Resource texture, out ShaderResourceView textureView)
        {
            texture     = null;
            textureView = null;

            if (frame.Size.Width <= 0 || frame.Size.Height <= 0)
            {
                return(Result.InvalidArg);
            }

            if (maxsize == 0)
            {
                switch (device.FeatureLevel)
                {
                case FeatureLevel.Level_9_1:
                case FeatureLevel.Level_9_2:
                    maxsize = 2048 /*D3D_FL9_1_REQ_TEXTURE2D_U_OR_V_DIMENSION*/;
                    break;

                case FeatureLevel.Level_9_3:
                    maxsize = 4096 /*D3D_FL9_3_REQ_TEXTURE2D_U_OR_V_DIMENSION*/;
                    break;

                case FeatureLevel.Level_10_0:
                case FeatureLevel.Level_10_1:
                    maxsize = 8192 /*D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION*/;
                    break;

                default:
                    maxsize = Resource.MaximumTexture2DSize;     /*D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION*/
                    break;
                }
            }

            Size2 frameSize = frame.Size;
            Size2 targetSize;

            if (frameSize.Width > maxsize || frameSize.Height > maxsize)
            {
                double ratio = Convert.ToDouble(frameSize.Height) / Convert.ToDouble(frameSize.Width);
                if (frameSize.Width > frameSize.Height)
                {
                    targetSize.Width  = maxsize;
                    targetSize.Height = Math.Max(1, Convert.ToInt32(maxsize * ratio));
                }
                else
                {
                    targetSize.Height = maxsize;
                    targetSize.Width  = Math.Max(1, Convert.ToInt32(maxsize / ratio));
                }
            }
            else
            {
                targetSize = frameSize;
            }

            #region Determine format
            Guid        sourceFormat = frame.PixelFormat;
            Guid        targetFormat = sourceFormat;
            DXGI.Format format       = sourceFormat.ConvertWICToDXGIFormat();
            int         bpp          = 0;

            if (format == DXGI.Format.Unknown)
            {
                if (sourceFormat == PixelFormat.Format96bppRGBFixedPoint)
                {
                    if (WIC2)
                    {
                        targetFormat = PixelFormat.Format96bppRGBFloat;
                        format       = DXGI.Format.R32G32B32_Float;
                        bpp          = 96;
                    }
                    else
                    {
                        targetFormat = PixelFormat.Format128bppRGBAFloat;
                        format       = DXGI.Format.R32G32B32A32_Float;
                        bpp          = 128;
                    }
                }
                else
                {
                    targetFormat = sourceFormat.ConvertToNearest();
                    format       = targetFormat.ConvertWICToDXGIFormat();
                    bpp          = PixelFormat.GetBitsPerPixel(targetFormat);
                }
                if (format == DXGI.Format.Unknown)
                {
                    return(Result.GetResultFromWin32Error(unchecked ((int)0x80070032)));
                }
            }
            else
            {
                bpp = PixelFormat.GetBitsPerPixel(sourceFormat);
            }

            if (format == DXGI.Format.R32G32B32_Float && d3dContext != null)
            {
                // Special case test for optional device support for autogen mipchains for R32G32B32_FLOAT
                var formatSupport = device.CheckFormatSupport(format);
                if (!formatSupport.HasFlag(FormatSupport.MipAutogen))
                {
                    targetFormat = PixelFormat.Format128bppRGBAFloat;
                    format       = DXGI.Format.R32G32B32A32_Float;
                    bpp          = 128;
                }
            }
            if (bpp == 0)
            {
                return(Result.Fail);
            }

            if (load.HasFlag(LoadFlags.ForceSrgb))
            {
                format = format.MakeSRgb();
            }
            else if (!load.HasFlag(LoadFlags.ignoreSrgb))
            {
                bool sRGB = false;
                try {
                    var metareader      = frame.MetadataQueryReader;
                    var containerFormat = metareader.ContainerFormat;

                    if (containerFormat == ContainerFormatGuids.Png)
                    {
                        // Check for sRGB chunk
                        if (metareader.TryGetMetadataByName("/sRGB/RenderingIntent", out var value) == Result.Ok)
                        {
                            sRGB = true;
                        }
                    }
                    else if (metareader.TryGetMetadataByName("System.Image.ColorSpace", out var value) == Result.Ok)
                    {
                        sRGB = true;
                    }

                    if (sRGB)
                    {
                        format = format.MakeSRgb();
                    }
                } catch (SharpDXException) {
                    // BMP, ICO are not supported.
                }
            }

            // Verify our target format is supported by the current device
            var support = device.CheckFormatSupport(format);
            if (!support.HasFlag(FormatSupport.Texture2D))
            {
                targetFormat = PixelFormat.Format32bppRGBA;
                format       = DXGI.Format.R8G8B8A8_UNorm;
                bpp          = 32;
            }
            #endregion


            int    stride    = (targetSize.Width * bpp + 7) / 8; // round
            int    imageSize = stride * targetSize.Height;
            IntPtr temp      = System.Runtime.InteropServices.Marshal.AllocCoTaskMem(imageSize);

            if (sourceFormat == targetFormat && frameSize == targetSize)   // 不需要格式轉換 且 不需要改變大小
            {
                frame.CopyPixels(stride, new DataPointer(temp, imageSize));
            }
            else if (frameSize == targetSize)     // 需要格式轉換
            {
                using (var factory = new ImagingFactory2())
                    using (var coverter = new FormatConverter(factory)) {
                        if (coverter.CanConvert(sourceFormat, targetFormat))
                        {
                            coverter.Initialize(frame, targetFormat, BitmapDitherType.ErrorDiffusion, null, 0, BitmapPaletteType.MedianCut);
                            coverter.CopyPixels(stride, new DataPointer(temp, imageSize));
                        }
                        else
                        {
                            return(Result.UnexpectedFailure);
                        }
                    }
            }
            else if (sourceFormat == targetFormat)     // 需要改變大小
            {
                using (var factory = new ImagingFactory2())
                    using (var scaler = new BitmapScaler(factory)) {
                        scaler.Initialize(frame, targetSize.Width, targetSize.Height, BitmapInterpolationMode.Fant);
                        var pfScaler = scaler.PixelFormat;
                        if (targetFormat == pfScaler)
                        {
                            scaler.CopyPixels(stride, new DataPointer(temp, imageSize));
                        }
                    }
            }
            else     // 需要格式轉換 且 需要改變大小
            {
                using (var factory = new ImagingFactory2())
                    using (var scaler = new BitmapScaler(factory))
                        using (var coverter = new FormatConverter(factory)) {
                            scaler.Initialize(frame, targetSize.Width, targetSize.Height, BitmapInterpolationMode.Fant);
                            var pfScaler = scaler.PixelFormat;

                            if (coverter.CanConvert(pfScaler, targetFormat))
                            {
                                coverter.Initialize(scaler, targetFormat, BitmapDitherType.ErrorDiffusion, null, 0, BitmapPaletteType.MedianCut);
                                coverter.CopyPixels(stride, new DataPointer(temp, imageSize));
                            }
                            else
                            {
                                return(Result.UnexpectedFailure);
                            }
                        }
            }

            var autogen = false;

            if (d3dContext != null)
            {
                var formatSupport = device.CheckFormatSupport(format);
                if (formatSupport.HasFlag(FormatSupport.MipAutogen))
                {
                    autogen = true;
                }
            }

            var texture2DDescription = new Texture2DDescription()
            {
                Width             = targetSize.Width,
                Height            = targetSize.Height,
                MipLevels         = autogen ? 0 : 1,
                ArraySize         = 1,
                Format            = format,
                SampleDescription = new DXGI.SampleDescription(1, 0),
                Usage             = usage,
                CpuAccessFlags    = cpuAccess,
            };

            if (autogen)
            {
                texture2DDescription.BindFlags   = bind | BindFlags.RenderTarget;
                texture2DDescription.OptionFlags = option | ResourceOptionFlags.GenerateMipMaps;
            }
            else
            {
                texture2DDescription.BindFlags   = bind;
                texture2DDescription.OptionFlags = option;
            }

            Result result = Result.Ok;

            // 建立Texture2D !!!
            try {
                if (autogen)
                {
                    texture = new Texture2D(device, texture2DDescription);
                }
                else
                {
                    texture = new Texture2D(device, texture2DDescription, new DataBox[] { new DataBox(temp, stride, imageSize) });
                }
            } catch (SharpDXException e) {
                System.Diagnostics.Debug.WriteLine(e.ToString());
                result = Result.Fail;
            }

            if (result.Success)
            {
                var SRVDesc = new ShaderResourceViewDescription()
                {
                    Format    = format,
                    Dimension = ShaderResourceViewDimension.Texture2D,
                    Texture2D = new ShaderResourceViewDescription.Texture2DResource()
                    {
                        MipLevels = autogen ? -1 : 1
                    },
                };

                try {
                    textureView = new ShaderResourceView(device, texture, SRVDesc);
                    if (autogen)
                    {
                        DataBox data = new DataBox(temp, stride, imageSize);
                        d3dContext.UpdateSubresource(data, texture);
                        d3dContext.GenerateMips(textureView);
                    }
                } catch (Exception e) {
                    System.Diagnostics.Debug.WriteLine(e.ToString());
                    Utilities.Dispose(ref texture);
                    result = Result.Fail;
                }
            }

            // 釋放 Unmanaged 資源
            System.Runtime.InteropServices.Marshal.FreeCoTaskMem(temp);

            return(result);
        }
Пример #10
0
 public DubProject LoadProject(string file, Solution parentSolution, IProgressMonitor monitor, LoadFlags flags = LoadFlags.LoadReferences, DubProject superProject = null)
 {
     if(monitor != null)
         monitor.BeginTask("Load dub project '" + file + "'", 1);
     try
     {
         var prj = supportedDubFileFormats.First((i) => i.CanLoad(file)).Load(file, superProject, parentSolution);
         if (flags.HasFlag(LoadFlags.LoadReferences))
             LoadSubProjects(prj, monitor);
         return prj;
     }
     finally
     {
         if (monitor != null)
             monitor.EndTask();
     }
 }