Example #1
0
        /// <summary>
        /// Function to start the logging for the application.
        /// </summary>
        /// <param name="args">The command line arguments.</param>
        private static void InitializeLogging(string[] args)
        {
            // Log everything.
            LoggingLevel level = LoggingLevel.Simple;

            // Logging is always active when compiled as DEBUG.
#if !DEBUG
            // Look for the log switch.
            (bool hasLogSwitch, string severity) = GetCommandLineArgument(args, "-log");

            // Logging is not active.
            if (!hasLogSwitch)
            {
                Log = GorgonApplication.Log = GorgonLog.NullLog;
                return;
            }

            if (!string.IsNullOrWhiteSpace(severity))
            {
                if (!Enum.TryParse(severity, out level))
                {
                    level = LoggingLevel.Simple;
                }
            }
#endif
            (bool hasLogTypeSwitch, string logType) = GetCommandLineArgument(args, "-logtype");

            if (!hasLogTypeSwitch)
            {
#if DEBUG
                logType = "console";
#else
                logType = "file";
#endif
            }

            try
            {
                if (string.Equals(logType, "console", StringComparison.OrdinalIgnoreCase))
                {
                    Log = GorgonApplication.Log = new GorgonLogConsole("Gorgon.Editor", typeof(Program).Assembly.GetName().Version)
                    {
                        LogFilterLevel = level
                    };
                }

                if (string.Equals(logType, "file", StringComparison.OrdinalIgnoreCase))
                {
                    Log = GorgonApplication.Log = new GorgonLog("Gorgon.Editor", @"Tape_Worm\Gorgon.Editor\Logging\", typeof(Program).Assembly.GetName().Version)
                    {
                        LogFilterLevel = level
                    };
                }
            }
            catch (Exception ex)
            {
                Debug.Print($"Couldn't open the log for the editor: {ex.Message}.");
                Log = GorgonLog.NullLog;
            }
        }
Example #2
0
        /// <summary>
        /// Function to retrieve the description of the raw input device from the registry.
        /// </summary>
        /// <param name="deviceName">Path to the registry key that holds the device description.</param>
        /// <param name="log">The debug log file to use when logging issues.</param>
        /// <returns>The device description.</returns>
        public static string GetDeviceDescription(string deviceName, IGorgonLog log)
        {
            if (string.IsNullOrWhiteSpace(deviceName))
            {
                throw new ArgumentException(Resources.GORINP_RAW_ERR_CANNOT_READ_DEVICE_DATA, nameof(deviceName));
            }

            string[] regValue = deviceName.Split('#');

            regValue[0] = regValue[0].Substring(4);

            // Don't add RDP devices.
            if ((log != null) &&
                (regValue.Length > 0) &&
                (regValue[1].StartsWith("RDP_", StringComparison.OrdinalIgnoreCase)))
            {
                log.Print("WARNING: This is an RDP device.  Raw input in Gorgon is not supported under RDP.  Skipping this device.", LoggingLevel.Verbose);
                return(string.Empty);
            }

            using (RegistryKey deviceKey = Registry.LocalMachine.OpenSubKey($@"System\CurrentControlSet\Enum\{regValue[0]}\{regValue[1]}\{regValue[2]}",
                                                                            false))
            {
                if (deviceKey?.GetValue("DeviceDesc") == null)
                {
                    return(string.Empty);
                }

                regValue = deviceKey.GetValue("DeviceDesc").ToString().Split(';');

                return(regValue[regValue.Length - 1]);
            }
        }
Example #3
0
 /// <summary>Initializes a new instance of the <see cref="T:Gorgon.Editor.SpriteEditor.Services.GorgonSpriteImporter"/> class.</summary>
 /// <param name="sourceFile">The file being imported.</param>
 /// <param name="codec">The original codec for the file.</param>
 /// <param name="renderer">The renderer used to locate the image linked to the sprite.</param>
 /// <param name="fileSystem">The file system containing the file being imported.</param>
 /// <param name="log">The log used for logging debug messages.</param>
 public GorgonSpriteImporter(FileInfo sourceFile, IGorgonSpriteCodec codec, Gorgon2D renderer, IGorgonFileSystem fileSystem, IGorgonLog log)
 {
     _log        = log ?? GorgonLog.NullLog;
     SourceFile  = sourceFile;
     _codec      = codec;
     _renderer   = renderer;
     _fileSystem = fileSystem;
 }
Example #4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="GorgonMefPlugInCache"/> class.
 /// </summary>
 /// <param name="log">[Optional] The application log file to use.</param>
 public GorgonMefPlugInCache(IGorgonLog log = null)
 {
     _builder.ForTypesDerivedFrom <GorgonPlugIn>().Export <GorgonPlugIn>(b =>
     {
         b.AddMetadata("Name", t => t.FullName);
         b.AddMetadata("Assembly", t => t.Assembly.GetName());
         b.Inherited();
     });
     Log        = log ?? GorgonLog.NullLog;
     _container = new CompositionContainer(_rootCatalog, CompositionOptions.DisableSilentRejection | CompositionOptions.IsThreadSafe);
 }
Example #5
0
        /// <summary>
        /// Function to inject dependencies for the view model.
        /// </summary>
        /// <param name="injectionParameters">The parameters to inject.</param>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="injectionParameters"/> parameter is <b>null</b>.</exception>
        /// <exception cref="ArgumentMissingException">Thrown when a required parameter is <b>null</b> or missing from the <paramref name="injectionParameters"/>.</exception>
        /// <remarks>
        /// <para>
        /// Applications should call this when setting up the view model for complex operations and/or dependency injection. The constructor should only be used for simple set up and initialization of objects.
        /// </para>
        /// </remarks>
        public void Initialize(T injectionParameters)
        {
            if (injectionParameters == null)
            {
                throw new ArgumentNullException(nameof(injectionParameters));
            }

            Log = injectionParameters.Log ?? GorgonLog.NullLog;

            OnInitialize(injectionParameters);
        }
Example #6
0
        /// <summary>
        /// Function to return the class name for the device.
        /// </summary>
        /// <param name="deviceName">The name of the device from <see cref="RawInputApi.GetDeviceName"/>.</param>
        /// <param name="log">The debug log file to use when logging issues.</param>
        /// <returns>The device class name.</returns>
        public static string GetDeviceClass(string deviceName, IGorgonLog log)
        {
            if (string.IsNullOrWhiteSpace(deviceName))
            {
                throw new ArgumentException(Resources.GORINP_RAW_ERR_CANNOT_READ_DEVICE_DATA, nameof(deviceName));
            }

            string[] regValue = deviceName.Split('#');

            regValue[0] = regValue[0].Substring(4);

            // Don't add RDP devices.
            if ((log != null) &&
                (regValue.Length > 0) &&
                (regValue[1].StartsWith("RDP_", StringComparison.OrdinalIgnoreCase)))
            {
                log.Print("WARNING: This is an RDP device.  Raw input in Gorgon is not supported under RDP.  Skipping this device.", LoggingLevel.Verbose);
                return(string.Empty);
            }

            using (RegistryKey deviceKey = Registry.LocalMachine.OpenSubKey($@"System\CurrentControlSet\Enum\{regValue[0]}\{regValue[1]}\{regValue[2]}",
                                                                            false))
            {
                if (deviceKey?.GetValue("DeviceDesc") == null)
                {
                    return(string.Empty);
                }

                if (deviceKey.GetValue("Class") != null)
                {
                    return(deviceKey.GetValue("Class").ToString());
                }

                // Windows 8 no longer has a "Class" value in this area, so we need to go elsewhere to get it.
                if (deviceKey.GetValue("ClassGUID") == null)
                {
                    return(string.Empty);
                }

                string classGUID = deviceKey.GetValue("ClassGUID").ToString();

                if (string.IsNullOrWhiteSpace(classGUID))
                {
                    return(string.Empty);
                }

                using (RegistryKey classKey = Registry.LocalMachine.OpenSubKey($@"System\CurrentControlSet\Control\Class\{classGUID}"))
                {
                    return(classKey?.GetValue("Class") == null ? string.Empty : classKey.GetValue("Class").ToString());
                }
            }
        }
        /// <summary>
        /// Function to catch and handle an exception.
        /// </summary>
        /// <typeparam name="T">The type of exception. This value must be or inherit from the <see cref="Exception"/> type.</typeparam>
        /// <param name="ex">Exception to pass to the handler.</param>
        /// <param name="handler">A method that is called to handle the exception.</param>
        /// <param name="log">[Optional] A logger that will capture the exception, or <b>null</b> to disable logging of this exception.</param>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="ex"/> parameter is <b>null</b>.</exception>
        /// <remarks>
        /// This is a convenience method used to catch an exception and then handle it with the supplied <paramref name="handler"/> method. The handler method must take a parameter
        /// that has a type that is or derives from <see cref="Exception"/>.
        /// </remarks>
        public static void Catch <T>(this T ex, Action <T> handler, IGorgonLog log = null)
            where T : Exception
        {
            if ((ex == null) ||
                (handler == null))
            {
                return;
            }

            log?.LogException(ex);

            handler(ex);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="GorgonRawInput"/> class.
        /// </summary>
        /// <param name="windowHandle">The handle to the main application window.</param>
        /// <param name="log">[Optional] The logger used for debugging.</param>
        /// <exception cref="ArgumentNullException">thrown when the <paramref name="windowHandle"/> is set to <see cref="IntPtr.Zero"/>.</exception>
        /// <remarks>
        /// <para>
        /// This constructor will allow any window handle to use a <see cref="GorgonRawInput"/> object. This allows WPF and other windowing systems to work with raw input.
        /// </para>
        /// <para>
        /// The <paramref name="windowHandle"/> parameter is required in order to set up the application to receive <c>WM_INPUT</c> messages. Ideally, this window should be the primary application window.
        /// </para>
        /// </remarks>
        public GorgonRawInput(GorgonReadOnlyPointer windowHandle, IGorgonLog log = null)
        {
            if (windowHandle.IsNull)
            {
                throw new ArgumentNullException(nameof(windowHandle));
            }

            _log = log ?? GorgonLog.NullLog;
            unsafe
            {
                _applicationWindow = new IntPtr((void *)windowHandle);
            }
            _devices       = new Dictionary <DeviceKey, IGorgonRawInputDevice>();
            _useNativeHook = true;
        }
 /// <summary>Initializes a new instance of the <see cref="T:Gorgon.Editor.ImageEditor.ImageIO"/> class.</summary>
 /// <param name="defaultCodec">The default codec used by the plug in.</param>
 /// <param name="installedCodecs">The list of installed codecs.</param>
 /// <param name="importDialog">The dialog service used to export an image.</param>
 /// <param name="busyService">The busy state service.</param>
 /// <param name="scratchArea">The file system writer used to write to the temporary area.</param>
 /// <param name="bcCompressor">The block compressor used to block (de)compress image data.</param>
 /// <param name="log">The logging interface to use.</param>
 public ImageIOService(IGorgonImageCodec defaultCodec,
                       ICodecRegistry installedCodecs,
                       IExportImageDialogService exportDialog,
                       IImportImageDialogService importDialog,
                       IBusyStateService busyService,
                       IGorgonFileSystemWriter <Stream> scratchArea,
                       TexConvCompressor bcCompressor,
                       IGorgonLog log)
 {
     _exportDialog   = exportDialog;
     _importDialog   = importDialog;
     DefaultCodec    = defaultCodec;
     InstalledCodecs = installedCodecs;
     ScratchArea     = scratchArea;
     _compressor     = bcCompressor;
     _busyState      = busyService;
     _log            = log ?? GorgonLog.NullLog;
 }
        /// <summary>
        /// Function to print device log information.
        /// </summary>
        /// <param name="device">Device to print.</param>
        /// <param name="log">The log interface to output debug messages.</param>
        private static void PrintLog(VideoAdapterInfo device, IGorgonLog log)
        {
            log.Print($"Device found: {device.Name}", LoggingLevel.Simple);
            log.Print("===================================================================", LoggingLevel.Simple);
            log.Print($"Supported feature set: {device.FeatureSet}", LoggingLevel.Simple);
            log.Print($"Video memory: {(device.Memory.Video).FormatMemory()}", LoggingLevel.Simple);
            log.Print($"System memory: {(device.Memory.System).FormatMemory()}", LoggingLevel.Intermediate);
            log.Print($"Shared memory: {(device.Memory.Shared).FormatMemory()}", LoggingLevel.Intermediate);
            log.Print($"Device ID: 0x{device.PciInfo.DeviceID.FormatHex()}", LoggingLevel.Verbose);
            log.Print($"Sub-system ID: 0x{device.PciInfo.SubSystemID.FormatHex()}", LoggingLevel.Verbose);
            log.Print($"Vendor ID: 0x{device.PciInfo.VendorID.FormatHex()}", LoggingLevel.Verbose);
            log.Print($"Revision: {device.PciInfo.Revision}", LoggingLevel.Verbose);
            log.Print($"Unique ID: 0x{device.Luid.FormatHex()}", LoggingLevel.Verbose);
            log.Print("===================================================================", LoggingLevel.Simple);

            foreach (IGorgonVideoOutputInfo output in device.Outputs)
            {
                log.Print($"Found output '{output.Name}'.", LoggingLevel.Simple);
                log.Print("===================================================================", LoggingLevel.Verbose);
                log.Print($"Output bounds: ({output.DesktopBounds.Left}x{output.DesktopBounds.Top})-({output.DesktopBounds.Right}x{output.DesktopBounds.Bottom})",
                          LoggingLevel.Verbose);
                log.Print($"Monitor handle: 0x{output.MonitorHandle.FormatHex()}", LoggingLevel.Verbose);
                log.Print($"Attached to desktop: {output.IsAttachedToDesktop}", LoggingLevel.Verbose);
                log.Print($"Monitor rotation: {output.Rotation}", LoggingLevel.Verbose);
                log.Print("===================================================================", LoggingLevel.Simple);

                log.Print($"Retrieving video modes for output '{output.Name}'...", LoggingLevel.Simple);
                log.Print("===================================================================", LoggingLevel.Simple);

                foreach (GorgonVideoMode mode in output.VideoModes)
                {
                    log.Print($"{mode.ToString().PadRight(70)}\tScaling: {mode.Scaling.ToString().PadRight(20)}Scanline Order: {mode.ScanlineOrder.ToString().PadRight(25)}Stereo: {mode.SupportsStereo}",
                              LoggingLevel.Verbose);
                }

                log.Print("===================================================================", LoggingLevel.Verbose);
                log.Print($"Found {output.VideoModes.Count} video modes for output '{output.Name}'.", LoggingLevel.Simple);
                log.Print("===================================================================", LoggingLevel.Simple);
            }
        }
Example #11
0
        private static void Main()
        {
            try
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                // Get the initial time.
                _lastTime = GorgonTiming.MillisecondsSinceStart;

                // Here we will override the log to use a console log.
                GorgonApplication.Log = _log = new GorgonLogConsole(Application.ProductName, typeof(Program).Assembly.GetName().Version);

                // Run the application context with an idle loop.
                //
                // Here we specify that we want to run an application context and an idle loop.  The idle loop
                // will kick in after the main form displays.
                GorgonApplication.Run(new Context(), Idle);
            }
            catch (Exception ex)
            {
                ex.Catch(_ => GorgonDialogs.ErrorBox(null, _), GorgonApplication.Log);
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="GorgonFileSystemProviderFactory"/> class.
 /// </summary>
 /// <param name="pluginService">The plugin service used to retrieve file system provider plugins.</param>
 /// <param name="log">[Optional] The application log file.</param>
 /// <exception cref="ArgumentNullException">Thrown when the <paramref name="pluginService"/> parameter is <b>null</b>.</exception>
 public GorgonFileSystemProviderFactory(IGorgonPlugInService pluginService, IGorgonLog log = null)
 {
     _log           = log ?? GorgonLog.NullLog;
     _pluginService = pluginService ?? throw new ArgumentNullException(nameof(pluginService));
 }
Example #13
0
        /// <summary>Function to load all the specified plug in assemblies.</summary>
        /// <param name="pluginCache">The plugin cache that will hold the plug in assembies.</param>
        /// <param name="pluginAssemblyFiles">The list of plug in assembly paths to load.</param>
        /// <param name="log">The application logging interface.</param>
        /// <returns>A list of <see cref="PlugInAssemblyState"/> objects for each plug in assembly loaded.</returns>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="pluginAssemblyFiles" /> parameter is <b>null</b></exception>
        public static IReadOnlyList <PlugInAssemblyState> ValidateAndLoadAssemblies(this GorgonMefPlugInCache pluginCache, IEnumerable <FileInfo> pluginAssemblyFiles, IGorgonLog log)
        {
            if (pluginAssemblyFiles == null)
            {
                throw new ArgumentNullException(nameof(pluginAssemblyFiles));
            }

            var records = new List <PlugInAssemblyState>();

            // We use this to determine whether the plug in can be loaded into the current platform.
            AssemblyPlatformType currentPlatform = IntPtr.Size == 8 ? AssemblyPlatformType.x64 : AssemblyPlatformType.x86;

            foreach (FileInfo file in pluginAssemblyFiles)
            {
                // If we've already got the assembly loaded into this cache, then there's no need to try and load it.
                if (pluginCache.PlugInAssemblies?.Any(item => string.Equals(item, file.FullName, StringComparison.OrdinalIgnoreCase)) ?? false)
                {
                    continue;
                }

                if (!file.Exists)
                {
                    log.Print($"[ERROR] Plug in '{file.FullName}' was not found.", LoggingLevel.Verbose);
                    records.Add(new PlugInAssemblyState(file.FullName, Resources.GOREDIT_PLUGIN_LOAD_FAIL_NOT_FOUND, false));
                    continue;
                }

                (bool isManaged, AssemblyPlatformType platformType) = GorgonMefPlugInCache.IsManagedAssembly(file.FullName);

                if ((!isManaged) || (platformType == AssemblyPlatformType.Unknown))
                {
                    log.Print($"[WARNING] Skipping '{file.FullName}'. Not a valid .NET assembly.", LoggingLevel.Verbose);
                    records.Add(new PlugInAssemblyState(file.FullName, string.Format(Resources.GOREDIT_PLUGIN_LOAD_FAIL_NOT_DOT_NET, file.Name), false));
                    continue;
                }

                // Ensure that our platform type matches (AnyCPU is exempt and will always run, and DLLs don't allow Prefer 32 bit).
                if ((currentPlatform == AssemblyPlatformType.x86) && (platformType == AssemblyPlatformType.x64))
                {
                    log.Print($"[ERROR] Cannot load assembly '{file.FullName}', currently executing in an x86 environment, but the assembly is x64.", LoggingLevel.Simple);
                    records.Add(new PlugInAssemblyState(file.FullName, string.Format(Resources.GOREDIT_PLUGIN_LOAD_FAIL_PLATFORM_MISMATCH, file.Name, platformType, currentPlatform), true));
                    continue;
                }

                if ((currentPlatform == AssemblyPlatformType.x64) && (platformType == AssemblyPlatformType.x86))
                {
                    log.Print($"[ERROR] Cannot load assembly '{file.FullName}', currently executing in an x64 environment, but the assembly is x86.", LoggingLevel.Simple);
                    records.Add(new PlugInAssemblyState(file.FullName, string.Format(Resources.GOREDIT_PLUGIN_LOAD_FAIL_PLATFORM_MISMATCH, file.Name, platformType, currentPlatform), true));
                    continue;
                }

                try
                {
                    log.Print($"Loading plug in assembly '{file.FullName}'...", LoggingLevel.Simple);
                    pluginCache.LoadPlugInAssemblies(file.DirectoryName, file.Name);

                    records.Add(new PlugInAssemblyState(file.FullName, string.Empty, true));
                }
                catch (Exception ex)
                {
                    log.Print($"ERROR: Cannot load plug in assembly '{file.FullName}'.", LoggingLevel.Simple);
                    log.LogException(ex);
                    records.Add(new PlugInAssemblyState(file.FullName, string.Format(Resources.GOREDIT_PLUGIN_LOAD_FAIL_EXCEPTION, file.Name, ex.Message), true));
                }
            }

            return(records);
        }
        /// <summary>
        /// Function to retrieve the outputs attached to a video adapter.
        /// </summary>
        /// <param name="device">The Direct 3D device used to filter display modes.</param>
        /// <param name="adapter">The adapter to retrieve the outputs from.</param>
        /// <param name="outputCount">The number of outputs for the device.</param>
        /// <param name="log">The logging interface used to capture debug messages.</param>
        /// <returns>A list if video output info values.</returns>
        private static Dictionary <string, VideoOutputInfo> GetOutputs(D3D11.Device5 device, Adapter4 adapter, int outputCount, IGorgonLog log)
        {
            var result = new Dictionary <string, VideoOutputInfo>(StringComparer.OrdinalIgnoreCase);

            // Devices created under RDP/TS do not support output selection.
            if (SystemInformation.TerminalServerSession)
            {
                log.Print("Devices under terminal services and software devices devices do not use outputs, no outputs enumerated.", LoggingLevel.Intermediate);
                return(result);
            }

            for (int i = 0; i < outputCount; ++i)
            {
                using (Output output = adapter.GetOutput(i))
                    using (Output6 output6 = output.QueryInterface <Output6>())
                    {
                        var outputInfo = new VideoOutputInfo(i, output6, GetVideoModes(device, output6));

                        if (outputInfo.VideoModes.Count == 0)
                        {
                            log.Print($"Output '{output.Description.DeviceName}' on adapter '{adapter.Description1.Description}' has no full screen video modes.",
                                      LoggingLevel.Intermediate);
                        }

                        result.Add(output.Description.DeviceName, outputInfo);
                    }
            }

            return(result);
        }
 /// <summary>Initializes a new instance of the <see cref="T:Gorgon.Editor.ImageEditor.Services.DdsImageImporter"/> class.</summary>
 /// <param name="log">The log used for logging debug messages.</param>
 public DdsImageImporter(FileInfo sourceFile, IGorgonImageCodec codec, IGorgonLog log)
 {
     _log       = log ?? GorgonLog.NullLog;
     SourceFile = sourceFile;
     _codec     = codec;
 }
        /// <summary>
        /// Function to perform an enumeration of the video adapters attached to the system and populate this list.
        /// </summary>
        /// <param name="enumerateWARPDevice"><b>true</b> to enumerate the WARP software device, or <b>false</b> to exclude it.</param>
        /// <param name="log">The log that will capture debug logging messages.</param>
        /// <remarks>
        /// <para>
        /// Use this method to populate a list with information about the video adapters installed in the system.
        /// </para>
        /// <para>
        /// You may include the WARP device, which is a software based device that emulates most of the functionality of a video adapter, by setting the <paramref name="enumerateWARPDevice"/> to <b>true</b>.
        /// </para>
        /// <para>
        /// Gorgon requires a video adapter that is capable of supporting Direct 3D 12.0 at minimum. If no suitable devices are found installed in the computer, then the resulting list will be empty.
        /// </para>
        /// </remarks>
        public static IReadOnlyList <IGorgonVideoAdapterInfo> Enumerate(bool enumerateWARPDevice, IGorgonLog log)
        {
            var devices = new List <IGorgonVideoAdapterInfo>();

            if (log == null)
            {
                log = GorgonLog.NullLog;
            }

            using (var factory2 = new Factory2(GorgonGraphics.IsDebugEnabled))
                using (Factory5 factory5 = factory2.QueryInterface <Factory5>())
                {
                    int adapterCount = factory5.GetAdapterCount1();

                    log.Print("Enumerating video adapters...", LoggingLevel.Simple);

                    // Begin gathering device information.
                    for (int i = 0; i < adapterCount; i++)
                    {
                        // Get the video adapter information.
                        using (Adapter1 adapter1 = factory5.GetAdapter1(i))
                            using (Adapter4 adapter = adapter1.QueryInterface <Adapter4>())
                            {
                                // ReSharper disable BitwiseOperatorOnEnumWithoutFlags
                                if (((adapter.Desc3.Flags & AdapterFlags3.Remote) == AdapterFlags3.Remote) ||
                                    ((adapter.Desc3.Flags & AdapterFlags3.Software) == AdapterFlags3.Software))
                                {
                                    continue;
                                }
                                // ReSharper restore BitwiseOperatorOnEnumWithoutFlags

                                D3D11.DeviceCreationFlags flags = D3D11.DeviceCreationFlags.None;

                                if (GorgonGraphics.IsDebugEnabled)
                                {
                                    flags = D3D11.DeviceCreationFlags.Debug;
                                }

                                // We create a D3D device here to filter out unsupported video modes from the format list.
                                using (var D3DDevice = new D3D11.Device(adapter, flags, D3D.FeatureLevel.Level_12_1, D3D.FeatureLevel.Level_12_0))
                                    using (D3D11.Device5 D3DDevice5 = D3DDevice.QueryInterface <D3D11.Device5>())
                                    {
                                        D3DDevice5.DebugName = "Output enumerator device.";

                                        FeatureSet?featureSet = GetFeatureLevel(D3DDevice5);

                                        // Do not enumerate this device if its feature set is not supported.
                                        if (featureSet == null)
                                        {
                                            log.Print("This video adapter is not supported by Gorgon and will be skipped.", LoggingLevel.Verbose);
                                            continue;
                                        }

                                        Dictionary <string, VideoOutputInfo> outputs = GetOutputs(D3DDevice5, adapter, adapter.GetOutputCount(), log);

                                        if (outputs.Count <= 0)
                                        {
                                            log.Print($"WARNING: Video adapter {adapter.Description1.Description.Replace("\0", string.Empty)} has no outputs. Full screen mode will not be possible.",
                                                      LoggingLevel.Verbose);
                                        }

                                        var videoAdapter = new VideoAdapterInfo(i, adapter, featureSet.Value, outputs, VideoDeviceType.Hardware);

                                        devices.Add(videoAdapter);
                                        PrintLog(videoAdapter, log);
                                    }
                            }
                    }

                    // Get software devices.
                    if (!enumerateWARPDevice)
                    {
                        return(devices);
                    }

                    VideoAdapterInfo device = GetWARPSoftwareDevice(devices.Count, factory5, log);

                    if (device != null)
                    {
                        devices.Add(device);
                    }
                }

            log.Print("Found {0} video adapters.", LoggingLevel.Simple, devices.Count);

            return(devices);
        }
Example #17
0
 /// <summary>
 /// Initializes a new instance of the <see cref="GorgonMefPlugInService"/> class.
 /// </summary>
 /// <param name="mefCache">The cache of MEF plugin assemblies.</param>
 /// <exception cref="ArgumentNullException">Thrown when the <paramref name="mefCache"/> parameter is <b>null</b>.</exception>
 public GorgonMefPlugInService(GorgonMefPlugInCache mefCache)
 {
     _cache = mefCache ?? throw new ArgumentNullException(nameof(mefCache));
     _log   = mefCache.Log ?? GorgonLog.NullLog;
 }
Example #18
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        private static void Main()
        {
            _log = new GorgonLog("FolderFileSystem", "Tape_Worm");
            _log.LogStart();

            try
            {
                Console.WindowHeight = 26.Max(Console.WindowHeight);
                Console.BufferHeight = Console.WindowHeight;

                // Create a new file system.
                _fileSystem = new GorgonFileSystem(_log);

                // Set the following directory as root on the virtual file system.
                // To mount a directory we need to put in the trailing slash.
                //
                // If we wanted to, we could mount a directory as a sub directory of
                // the root of the virtual file system.  For example, mounting the
                // directory D:\Dir with Mount(@"D:\Dir", "/VFSDir"); would mount the
                // contents of the D:\Dir directory under /VFSDir.
                //
                // It's also important to point out that the old Gorgon "file system"
                // would load files from the system into memory when mounting a
                // directory.  While this version only loads directory and file
                // information when mounting.  This is considerably more efficient.
                string physicalPath = GetResourcePath(@"FolderSystem\");
                _fileSystem.Mount(physicalPath);

                Console.ForegroundColor = ConsoleColor.White;

                Console.WriteLine("This example will mount a physical file system directory as the root of a");
                Console.WriteLine("virtual file system.  The virtual file system is capable of mounting various");
                Console.WriteLine("types of data such as a zip file, a file system folder, etc... as the root or a");
                Console.WriteLine("sub directory.  You can even mount a zip file as the root, and a physical file");
                Console.WriteLine("system directory as a virtual sub directory in the same virtual file system and");
                Console.WriteLine("access them as a single unified file system.");

                Console.Write("\nMounted: ");
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.Write("'{0}'", physicalPath.Ellipses(Console.WindowWidth - 20, true));
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write(" as ");
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("'/'\n");
                Console.ForegroundColor = ConsoleColor.White;

                // Get a count of all sub directories and files under the root directory.
                IGorgonVirtualDirectory[] directoryList = _fileSystem.FindDirectories("*").ToArray();

                // Display directories.
                Console.WriteLine("Virtual file system contents:");

                for (int i = -1; i < directoryList.Length; i++)
                {
                    IGorgonVirtualDirectory directory = _fileSystem.RootDirectory;

                    // Go into the sub directories under root.
                    if (i > -1)
                    {
                        directory = directoryList[i];
                    }

                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.WriteLine("{0}", directory.FullPath);

                    Console.ForegroundColor = ConsoleColor.Yellow;

                    foreach (IGorgonVirtualFile file in directory.Files)
                    {
                        Console.Write("   {0}", file.Name);
                        // Align the size to the same place.
                        Console.CursorLeft = 65;
                        Console.WriteLine("{0}", file.Size.FormatMemory());
                    }
                }

                Console.ResetColor();
                Console.WriteLine("\nPress any key to close.");
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                ex.Catch(_ =>
                {
                    Console.Clear();
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Exception:\n{0}\n\nStack Trace:{1}", _.Message, _.StackTrace);

                    Console.ResetColor();
#if DEBUG
                    Console.ReadKey();
#endif
                },
                         _log);
            }
            finally
            {
                _log.LogEnd();
            }
        }
        /// <summary>
        /// Function to add the WARP software device.
        /// </summary>
        /// <param name="index">Index of the device.</param>
        /// <param name="factory">The factory used to query the adapter.</param>
        /// <param name="log">The log interface used to send messages to a debug log.</param>
        /// <returns>The video adapter used for WARP software rendering.</returns>
        private static VideoAdapterInfo GetWARPSoftwareDevice(int index, Factory5 factory, IGorgonLog log)
        {
            D3D11.DeviceCreationFlags flags = D3D11.DeviceCreationFlags.None;

            if (GorgonGraphics.IsDebugEnabled)
            {
                flags = D3D11.DeviceCreationFlags.Debug;
            }

            using (Adapter warp = factory.GetWarpAdapter())
                using (Adapter4 warpAdapter4 = warp.QueryInterface <Adapter4>())
                    using (var D3DDevice = new D3D11.Device(warpAdapter4, flags))
                        using (D3D11.Device5 D3DDevice5 = D3DDevice.QueryInterface <D3D11.Device5>())
                        {
                            FeatureSet?featureSet = GetFeatureLevel(D3DDevice5);

                            if (featureSet == null)
                            {
                                log.Print("WARNING: The WARP software adapter does not support the minimum feature set of 12.0. This device will be excluded.", LoggingLevel.All);
                                return(null);
                            }

                            var result = new VideoAdapterInfo(index, warpAdapter4, featureSet.Value, new Dictionary <string, VideoOutputInfo>(), VideoDeviceType.Software);

                            PrintLog(result, log);

                            return(result);
                        }
        }
Example #20
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Triangulator"/> class.
 /// </summary>
 /// <param name="log">The log used for debug messages..</param>
 public Triangulator(IGorgonLog log) => _log = log ?? GorgonLog.NullLog;
 /// <summary>Initializes a new instance of the <see cref="ViewModelInjection"/> class.</summary>
 /// <param name="log">The log for the application.</param>
 /// <param name="busyService">The busy service for the application.</param>
 /// <param name="messageService">The message display service for the application..</param>
 /// <exception cref="ArgumentNullException">Thrown when any of the parameters are <b>null</b>.</exception>
 public ViewModelInjection(IGorgonLog log, IBusyStateService busyService, IMessageDisplayService messageService)
 {
     Log            = log ?? throw new ArgumentNullException(nameof(log));
     BusyService    = busyService ?? throw new ArgumentNullException(nameof(busyService));
     MessageDisplay = messageService ?? throw new ArgumentNullException(nameof(messageService));
 }
Example #22
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        private static void Main()
        {
            _log = new GorgonLog("ZipFileSystem", "Tape_Worm");
            _log.LogStart();

            // Create the plugin assembly cache.
            _pluginAssemblies = new GorgonMefPlugInCache(_log);
            // Create the plugin service.
            _pluginService = new GorgonMefPlugInService(_pluginAssemblies);

            try
            {
                Console.WindowHeight = 28;
                Console.BufferHeight = Console.WindowHeight;

                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("This example will mount a zip file as the root of a virtual file system.  The");
                Console.WriteLine("virtual file system is capable of mounting various types of data such as a zip,");
                Console.WriteLine("a file system folder, etc... as the root or a sub directory.  You can even");
                Console.WriteLine("mount a zip file as the root, and a physical file system directory as a virtual");
                Console.WriteLine("sub directory in the same virtual file system and access them as a single");
                Console.WriteLine("unified file system.");

                // Unlike the folder file system example, we need to load
                // a provider to handle zip files before trying to mount
                // one.
                if (!LoadZipProviderPlugIn())
                {
                    return;
                }

                // Set the following zip file as root on the virtual file system.
                //
                // If we wanted to, we could mount a zip file as a sub directory of
                // the root of the virtual file system.  For example, mounting the
                // directory D:\Dir\zipFile.zip with Mount(@"D:\Dir", "/VFSDir"); would mount
                // the contents of the D:\Dir\zipFile.zip directory under /VFSDir.
                //
                // It's also important to point out that the old Gorgon "file system"
                // would load files from the system into memory when mounting a
                // directory.  While this version only loads directory and file
                // information when mounting.  This is considerably more efficient.
                string physicalPath = GetResourcePath(@"FileSystem.zip");
                _fileSystem.Mount(physicalPath);

                Console.Write("\nMounted: ");
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.Write("'{0}'", physicalPath.Ellipses(Console.WindowWidth - 20, true));
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write(" as ");
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("'/'\n");
                Console.ForegroundColor = ConsoleColor.White;

                // Get a count of all sub directories and files under the root directory.
                IGorgonVirtualDirectory[] directoryList = _fileSystem.FindDirectories("*").ToArray();

                // Display directories.
                Console.WriteLine("Virtual file system contents:");

                for (int i = -1; i < directoryList.Length; i++)
                {
                    IGorgonVirtualDirectory directory = _fileSystem.RootDirectory;

                    // Go into the sub directories under root.
                    if (i > -1)
                    {
                        directory = directoryList[i];
                    }

                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.WriteLine("{0}", directory.FullPath);

                    Console.ForegroundColor = ConsoleColor.Yellow;

                    foreach (IGorgonVirtualFile file in directory.Files)
                    {
                        Console.Write("   {0}", file.Name);
                        // Align the size to the same place.
                        Console.CursorLeft = 65;
                        Console.WriteLine("{0}", file.Size.FormatMemory());
                    }
                }

                Console.ResetColor();
                Console.WriteLine("\nPress any key to close.");
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                ex.Catch(_ =>
                {
                    Console.Clear();
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Exception:\n{0}\n\nStack Trace:{1}", _.Message, _.StackTrace);

                    Console.ResetColor();
#if DEBUG
                    Console.ReadKey();
#endif
                });
            }
            finally
            {
                // Always dispose the cache to clean up the temporary app domain it creates.
                _pluginAssemblies.Dispose();
                _log.LogEnd();
            }
        }
Example #23
0
 /// <summary>
 /// Initializes a new instance of the <see cref="GorgonRawInput"/> class.
 /// </summary>
 /// <param name="applicationWindow">The main application window.</param>
 /// <param name="log">[Optional] The logger used for debugging.</param>
 /// <exception cref="ArgumentNullException">thrown when the <paramref name="applicationWindow"/> is set to <b>null</b>.</exception>
 /// <remarks>
 /// <para>
 /// This constructor will only allow Windows Forms controls as the main application window. For other window types, use the overloaded constructor.
 /// </para>
 /// <para>
 /// The <paramref name="applicationWindow"/> parameter is required in order to set up the application to receive <c>WM_INPUT</c> messages. Ideally, this window should be the primary application window.
 /// </para>
 /// </remarks>
 public GorgonRawInput(Control applicationWindow, IGorgonLog log = null)
 {
     _log = log ?? GorgonLog.NullLog;
     _applicationWindow = applicationWindow?.Handle ?? throw new ArgumentNullException(nameof(applicationWindow));
     _devices           = new Dictionary <DeviceKey, IGorgonRawInputDevice>();
 }
Example #24
0
 /// <summary>Initializes a new instance of the <see cref="T:Gorgon.Editor.Services.UndoService"/> class.</summary>
 /// <param name="log">The log used for debug messaging.</param>
 /// <exception cref="ArgumentNullException">Thrown when the <paramref name="log" /> parameter is <strong>null</strong>.</exception>
 public UndoService(IGorgonLog log) => _log = log ?? GorgonLog.NullLog;
 /// <summary>
 /// Initializes a new instance of the <see cref="GorgonGamingDeviceDriverFactory"/> class.
 /// </summary>
 /// <param name="plugInService">The plug in service to use when loading drivers.</param>
 /// <param name="log">[Optional] The logger used for debugging.</param>
 /// <exception cref="ArgumentNullException">Thrown when the <paramref name="plugInService"/> is <b>null</b>.</exception>
 public GorgonGamingDeviceDriverFactory(IGorgonPlugInService plugInService, IGorgonLog log = null)
 {
     _log           = log ?? GorgonLog.NullLog;
     _plugInService = plugInService;
 }
Example #26
0
 /// <summary>Initializes a new instance of the <see cref="ImageExternalEditService"/> class.</summary>
 /// <param name="log">The log used for debug messages.</param>
 public ImageExternalEditService(IGorgonLog log) => _log = log ?? GorgonLog.NullLog;
Example #27
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        private static void Main()
        {
            _log = new GorgonLog("FileSystemProviders", "Tape_Worm");
            _log.LogStart();

            // Create a plugin assembly cache to hold our plugin assemblies.
            _pluginAssemblies = new GorgonMefPlugInCache(_log);
            // Create the plugin service.
            _pluginService = new GorgonMefPlugInService(_pluginAssemblies);

            try
            {
                Console.WriteLine("Gorgon is capable of mounting virtual file systems for file access.  A virtual");
                Console.WriteLine("file system root can be a folder on a hard drive, a zip file, or any data store");
                Console.WriteLine("(assuming there's a provider for it).\n");
                Console.WriteLine("In Gorgon, the types of data that can be mounted as a virtual file system are");
                Console.WriteLine("managed by objects called providers. By default, the file system has a folder");
                Console.WriteLine("provider.  This allows a folder to be mounted as the root of a virtual file\nsystem.\n");
                Console.WriteLine("This example will show how to load extra providers that can be used in a file\nsystem.\n");

                Console.ForegroundColor = ConsoleColor.White;

                // Get our file system providers.
                Console.WriteLine("Found {0} external file system plug ins.\n", LoadFileSystemProviders());

                // Loop through each provider and print some info.
                for (int i = 0; i < _providers.Count; ++i)
                {
                    // Print some info about the file system provider.
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.WriteLine("{0}. {1}", i + 1, _providers[i].Name);

                    Console.ForegroundColor = ConsoleColor.Gray;
                    Console.WriteLine("    Description: {0}", _providers[i].Description);

                    // Gather the preferred extensions.
                    // File system providers that use a file (like a Zip file) as its root
                    // have a list of file extensions that are preferred.  For example, the
                    // Zip provider, expects to find *.zip files.  These are merely here
                    // for the convenience of the developer and are formatted like a common
                    // dialog file mask so they can be easily dropped into that control.
                    // In this case, we're going to just strip out the relevant part and
                    // concatenate each preferred extension description into a single string.
                    //
                    // Note that a provider may have multiple preferred extensions.
                    string[] extensionList = (from preferred in _providers[i].PreferredExtensions
                                              select $"*.{preferred.Extension}").ToArray();

                    if (extensionList.Length > 0)
                    {
                        Console.WriteLine("    Preferred Extensions: {0}", string.Join(", ", extensionList));
                    }
                }

                Console.ResetColor();
                Console.WriteLine("\nPress any key to close.");
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                ex.Catch(_ =>
                {
                    Console.Clear();
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Exception:\n{0}\n\nStack Trace:{1}", _.Message, _.StackTrace);
                },
                         _log);
                Console.ResetColor();
#if DEBUG
                Console.ReadKey();
#endif
            }
            finally
            {
                // Always call dispose so we can unload our temporary application domain.
                _pluginAssemblies.Dispose();

                _log.LogEnd();
            }
        }
Example #28
0
        private static void Main(string[] args)
        {
            _log = new GorgonLog("Example 004", "Tape_Worm", typeof(Program).Assembly.GetName().Version);

            // Set up the assembly cache.
            // We'll need the assemblies loaded into this object in order to load our plugin types.
            var pluginCache = new GorgonMefPlugInCache(_log);

            // Create our plugin service.
            // This takes the cache of assemblies we just created.
            IGorgonPlugInService pluginService = new GorgonMefPlugInService(pluginCache);

            try
            {
                Console.Title           = "Gorgon Example #4 - PlugIns.";
                Console.ForegroundColor = ConsoleColor.White;

                Console.WriteLine("This is an example to show how to create and use custom plugins.");
                Console.WriteLine("The plugin interface in Gorgon is quite flexible and gives the developer");
                Console.WriteLine("the ability to allow extensions to their own applications.\n");

                Console.ResetColor();

                pluginCache.LoadPlugInAssemblies(Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]).FormatDirectory(Path.DirectorySeparatorChar), "Example004.*PlugIn.dll");
                Console.WriteLine("{0} plugin assemblies found.", pluginCache.PlugInAssemblies.Count);

                if (pluginCache.PlugInAssemblies.Count == 0)
                {
                    return;
                }

                // Our text writer plugin interfaces.
                IList <TextColorWriter> writers = new List <TextColorWriter>();

                // Create our plugin instances, we'll limit to 9 entries just for giggles.
                TextColorPlugIn[] plugins = (from pluginName in pluginService.GetPlugInNames()
                                             let plugin = pluginService.GetPlugIn <TextColorPlugIn>(pluginName)
                                                          where plugin != null
                                                          select plugin).ToArray();

                // Display a list of the available plugins.
                Console.WriteLine("\n{0} Plug-ins loaded:\n", plugins.Length);
                for (int i = 0; i < plugins.Length; i++)
                {
                    // Here's where we make use of our description.
                    Console.WriteLine("{0}. {1} ({2})", i + 1, plugins[i].Description, plugins[i].GetType().FullName);

                    // Create the text writer interface and add it to the list.
                    writers.Add(plugins[i].CreateWriter());
                }

                Console.Write("0. Quit\n\nSelect a plugin:  ");

                // Loop until we quit.
                while (true)
                {
                    if (!Console.KeyAvailable)
                    {
                        continue;
                    }

                    Console.ResetColor();

                    // Remember our cursor coordinates.
                    int cursorX = Console.CursorLeft; // Cursor position.
                    int cursorY = Console.CursorTop;

                    ConsoleKeyInfo keyValue = Console.ReadKey(false);

                    if (char.IsNumber(keyValue.KeyChar))
                    {
                        if (keyValue.KeyChar == '0')
                        {
                            break;
                        }

                        // Move to the next line and clear the previous line of text.
                        Console.WriteLine();
                        Console.Write(new string(' ', Console.BufferWidth - 1));
                        Console.CursorLeft = 0;

                        // Call our text color writer to print the text in the plugin color.
                        int writerIndex = keyValue.KeyChar - '0';
                        writers[writerIndex - 1].WriteString($"You pressed #{writerIndex}.");
                    }

                    Console.CursorTop  = cursorY;
                    Console.CursorLeft = cursorX;
                }
            }
            catch (Exception ex)
            {
                ex.Catch(_ =>
                {
                    Console.Clear();
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Exception:\n{0}\n\nStack Trace:{1}", ex.Message, ex.StackTrace);
                },
                         _log);
                Console.ResetColor();
#if DEBUG
                Console.ReadKey(true);
#endif
            }
            finally
            {
                // Always call dispose so we can unload our temporary application domain.
                //pluginAssemblies.Dispose();
                pluginCache.Dispose();

                _log.LogEnd();
            }
        }