internal DisplayInfo GetDisplayInfoForVirtualPath(string virtualPath, HttpContextBase httpContext, Func<string, bool> virtualPathExists, IDisplayMode currentDisplayMode,
                                                   bool requireConsistentDisplayMode)
 {
     IEnumerable<IDisplayMode> possibleDisplayModes = GetAvailableDisplayModesForContext(httpContext, currentDisplayMode, requireConsistentDisplayMode);
     return possibleDisplayModes.Select(mode => mode.GetDisplayInfo(httpContext, virtualPath, virtualPathExists))
         .FirstOrDefault(info => info != null);
 }
 internal static void SetDisplayMode(HttpContextBase context, IDisplayMode displayMode)
 {
     if (context != null)
     {
         context.Items[_displayModeKey] = displayMode;
     }
 }
 internal static void SetDisplayMode(HttpContextBase context, IDisplayMode displayMode)
 {
     if (context != null)
     {
         context.Items[_displayModeKey] = displayMode;
     }
 }
Пример #4
0
        internal DisplayInfo GetDisplayInfoForVirtualPath(
            string virtualPath,
            HttpContextBase httpContext,
            Func <string, bool> virtualPathExists,
            IDisplayMode currentDisplayMode,
            bool requireConsistentDisplayMode
            )
        {
            // Performance sensitive
            int first = FindFirstAvailableDisplayMode(
                currentDisplayMode,
                requireConsistentDisplayMode
                );

            for (int i = first; i < _displayModes.Count; i++)
            {
                IDisplayMode mode = _displayModes[i];
                if (mode.CanHandleContext(httpContext))
                {
                    DisplayInfo info = mode.GetDisplayInfo(
                        httpContext,
                        virtualPath,
                        virtualPathExists
                        );
                    if (info != null)
                    {
                        return(info);
                    }
                }
            }
            return(null);
        }
Пример #5
0
        public void GetAvailableDisplayModesReturnsOnlyModesThatCanHandleContext()
        {
            // Arrange
            Mock <HttpContextBase> httpContext = new Mock <HttpContextBase>(MockBehavior.Strict);
            var displayModeProvider            = new DisplayModeProvider();

            displayModeProvider.Modes.Clear();
            var displayMode1 = new Mock <IDisplayMode>(MockBehavior.Strict);

            displayMode1.Setup(d => d.CanHandleContext(It.IsAny <HttpContextBase>())).Returns(false);
            displayModeProvider.Modes.Add(displayMode1.Object);

            var displayMode2 = new Mock <IDisplayMode>(MockBehavior.Strict);

            displayMode2.Setup(d => d.CanHandleContext(It.IsAny <HttpContextBase>())).Returns(true);
            displayModeProvider.Modes.Add(displayMode2.Object);

            var displayMode3 = new Mock <IDisplayMode>(MockBehavior.Strict);

            displayMode3.Setup(d => d.CanHandleContext(It.IsAny <HttpContextBase>())).Returns(false);
            displayModeProvider.Modes.Add(displayMode3.Object);

            // Act
            var availableDisplayModes = displayModeProvider.GetAvailableDisplayModesForContext(httpContext.Object, displayMode1.Object, requireConsistentDisplayMode: false).ToList();

            // Assert
            IDisplayMode availableDisplayMode = Assert.Single(availableDisplayModes);

            Assert.Equal(displayMode2.Object, availableDisplayMode);
        }
Пример #6
0
        /// <summary>
        /// Attempts to create a WebPageBase instance from a virtualPath and wraps complex compiler exceptions with simpler messages
        /// </summary>
        protected virtual WebPageBase CreatePageFromVirtualPath(
            string virtualPath,
            HttpContextBase httpContext,
            Func <string, bool> virtualPathExists,
            DisplayModeProvider displayModeProvider,
            IDisplayMode displayMode
            )
        {
            try
            {
                DisplayInfo resolvedDisplayInfo = displayModeProvider.GetDisplayInfoForVirtualPath(
                    virtualPath,
                    httpContext,
                    virtualPathExists,
                    displayMode
                    );

                if (resolvedDisplayInfo != null)
                {
                    var webPage = VirtualPathFactory.CreateInstance <WebPageBase>(
                        resolvedDisplayInfo.FilePath
                        );

                    if (webPage != null)
                    {
                        // Give it its virtual path
                        webPage.VirtualPath         = virtualPath;
                        webPage.VirtualPathFactory  = VirtualPathFactory;
                        webPage.DisplayModeProvider = DisplayModeProvider;

                        return(webPage);
                    }
                }
            }
            catch (HttpException e)
            {
                // If the path uses an unregistered extension, such as Foo.txt,
                // then an error regarding build providers will be thrown.
                // Check if this is the case and throw a simpler error.
                BuildManagerExceptionUtil.ThrowIfUnsupportedExtension(virtualPath, e);

                // If the path uses an extension registered with codedom, such as Foo.js,
                // then an unfriendly compilation error might get thrown by the underlying compiler.
                // Check if this is the case and throw a simpler error.
                BuildManagerExceptionUtil.ThrowIfCodeDomDefinedExtension(virtualPath, e);

                // Rethrow any errors
                throw;
            }
            // The page is missing, could not be compiled or is of an invalid type.
            throw new HttpException(
                      String.Format(
                          CultureInfo.CurrentCulture,
                          WebPageResources.WebPage_InvalidPageType,
                          virtualPath
                          )
                      );
        }
 private int FindFirstAvailableDisplayMode(IDisplayMode currentDisplayMode, bool requireConsistentDisplayMode)
 {
     if (requireConsistentDisplayMode && currentDisplayMode != null)
     {
         int first = _displayModes.IndexOf(currentDisplayMode);
         return (first >= 0) ? first : _displayModes.Count;
     }
     return 0;
 }
 private int FindFirstAvailableDisplayMode(IDisplayMode currentDisplayMode, bool requireConsistentDisplayMode)
 {
     if (requireConsistentDisplayMode && currentDisplayMode != null)
     {
         int first = _displayModes.IndexOf(currentDisplayMode);
         return((first >= 0) ? first : _displayModes.Count);
     }
     return(0);
 }
Пример #9
0
 public void ToggleDisplayMode()
 {
     typeIndex          = typeIndex >= possibleTypes.Count - 1 ? 0 : typeIndex + 1;
     currentDisplayMode =
         (IDisplayMode)Activator.CreateInstance(possibleTypes[typeIndex]);
     currentDisplayMode.Initialize(
         WheelParts, NoteNumbers, NoteLabels, KeyOfText, chordsDisplay);
     ModeText.text = currentDisplayMode.DisplayName;
 }
Пример #10
0
 /// <summary>
 /// Returns any IDisplayMode that can handle the given request.
 /// </summary>
 public IEnumerable <IDisplayMode> GetAvailableDisplayModesForContext(
     HttpContextBase httpContext,
     IDisplayMode currentDisplayMode
     )
 {
     return(GetAvailableDisplayModesForContext(
                httpContext,
                currentDisplayMode,
                RequireConsistentDisplayMode
                ));
 }
Пример #11
0
 internal IEnumerable<IDisplayMode> GetAvailableDisplayModesForContext(HttpContextBase httpContext, IDisplayMode currentDisplayMode, bool requireConsistentDisplayMode)
 {
     int first = FindFirstAvailableDisplayMode(currentDisplayMode, requireConsistentDisplayMode);
     for (int i = first; i < _displayModes.Count; i++)
     {
         IDisplayMode mode = _displayModes[i];
         if (mode.CanHandleContext(httpContext))
         {
             yield return mode;
         }
     }
 }
        internal IEnumerable <IDisplayMode> GetAvailableDisplayModesForContext(HttpContextBase httpContext, IDisplayMode currentDisplayMode, bool requireConsistentDisplayMode)
        {
            int first = FindFirstAvailableDisplayMode(currentDisplayMode, requireConsistentDisplayMode);

            for (int i = first; i < _displayModes.Count; i++)
            {
                IDisplayMode mode = _displayModes[i];
                if (mode.CanHandleContext(httpContext))
                {
                    yield return(mode);
                }
            }
        }
        private bool TryResolveView(HttpContextBase httpContext, IDisplayMode displayMode, ref string path, ICollection <string> viewLocationsSearched)
        {
            path = NormalizeViewName(VirtualPathUtility.ToAppRelative(path)); // resolve relative path portions
            var displayInfo = displayMode.GetDisplayInfo(httpContext, path, _views.ContainsKey);

            if (displayInfo == null || displayInfo.FilePath == null)
            {
                viewLocationsSearched.Add(path);
                return(false);
            }

            path = displayInfo.FilePath;
            return(true);
        }
Пример #14
0
 /// <summary>
 /// Returns DisplayInfo from the first IDisplayMode in Modes that can handle the given request and locate the virtual path.
 /// If currentDisplayMode is not null and RequireConsistentDisplayMode is set to true the search for DisplayInfo will only
 /// start with the currentDisplayMode.
 /// </summary>
 public DisplayInfo GetDisplayInfoForVirtualPath(
     string virtualPath,
     HttpContextBase httpContext,
     Func <string, bool> virtualPathExists,
     IDisplayMode currentDisplayMode
     )
 {
     return(GetDisplayInfoForVirtualPath(
                virtualPath,
                httpContext,
                virtualPathExists,
                currentDisplayMode,
                RequireConsistentDisplayMode
                ));
 }
Пример #15
0
        public DisplayInfo(string filePath, IDisplayMode displayMode)
        {
            if (filePath == null)
            {
                throw new ArgumentNullException("filePath");
            }

            if (displayMode == null)
            {
                throw new ArgumentNullException("displayMode");
            }

            FilePath = filePath;
            DisplayMode = displayMode;
        }
Пример #16
0
        public DisplayInfo(string filePath, IDisplayMode displayMode)
        {
            if (filePath == null)
            {
                throw new ArgumentNullException("filePath");
            }

            if (displayMode == null)
            {
                throw new ArgumentNullException("displayMode");
            }

            FilePath    = filePath;
            DisplayMode = displayMode;
        }
Пример #17
0
 internal DisplayInfo GetDisplayInfoForVirtualPath(string virtualPath, HttpContextBase httpContext, Func<string, bool> virtualPathExists, IDisplayMode currentDisplayMode,
                                                   bool requireConsistentDisplayMode)
 {
     // Performance sensitive
     int first = FindFirstAvailableDisplayMode(currentDisplayMode, requireConsistentDisplayMode);
     for (int i = first; i < _displayModes.Count; i++)
     {
         IDisplayMode mode = _displayModes[i];
         if (mode.CanHandleContext(httpContext))
         {
             DisplayInfo info = mode.GetDisplayInfo(httpContext, virtualPath, virtualPathExists);
             if (info != null)
             {
                 return info;
             }
         }
     }
     return null;
 }
Пример #18
0
 public LocalizedDisplayInfo(string filePath, IDisplayMode displayMode, string lang)
     : base(filePath, displayMode)
 {
     this.Lang = lang;
 }
Пример #19
0
 public SmartVideoView(List <Video> videos, IDisplayMode displayMode)
 {
     Videos      = videos;
     DisplayMode = displayMode;
 }
Пример #20
0
        protected virtual string GetPathFromGeneralName(ControllerContext controllerContext, List <ThemeableVirtualPathProviderViewEngine.ViewLocation> locations, string name, string controllerName, string areaName, string cacheKey, ref string[] searchedLocations)
        {
            Func <string, bool> func;
            Func <string, bool> func1 = null;
            Func <string, bool> func2 = null;
            string empty = string.Empty;

            searchedLocations = new string[locations.Count];
            int num = 0;

            while (num < locations.Count)
            {
                ThemeableVirtualPathProviderViewEngine.ViewLocation item = locations[num];
                string str = "";
                str = item.Format(name, controllerName, areaName);
                if (!File.Exists(HttpContext.Current.Server.MapPath(str)))
                {
                    str = item.Format(name, controllerName, areaName);
                }
                System.Web.WebPages.DisplayModeProvider displayModeProvider = base.DisplayModeProvider;
                string              str1        = str;
                HttpContextBase     httpContext = controllerContext.HttpContext;
                Func <string, bool> func3       = func1;
                if (func3 == null)
                {
                    Func <string, bool> func4 = (string path) => this.FileExists(controllerContext, path);
                    func  = func4;
                    func1 = func4;
                    func3 = func;
                }
                DisplayInfo displayInfoForVirtualPath = displayModeProvider.GetDisplayInfoForVirtualPath(str1, httpContext, func3, controllerContext.DisplayMode);
                if (displayInfoForVirtualPath == null)
                {
                    searchedLocations[num] = str;
                    num++;
                }
                else
                {
                    string filePath = displayInfoForVirtualPath.FilePath;
                    searchedLocations = ThemeableVirtualPathProviderViewEngine._emptyLocations;
                    empty             = filePath;
                    base.ViewLocationCache.InsertViewLocation(controllerContext.HttpContext, this.AppendDisplayModeToCacheKey(cacheKey, displayInfoForVirtualPath.DisplayMode.DisplayModeId), empty);
                    if (controllerContext.DisplayMode == null)
                    {
                        controllerContext.DisplayMode = displayInfoForVirtualPath.DisplayMode;
                    }
                    foreach (IDisplayMode mode in base.DisplayModeProvider.Modes)
                    {
                        if (mode.DisplayModeId != displayInfoForVirtualPath.DisplayMode.DisplayModeId)
                        {
                            IDisplayMode        displayMode     = mode;
                            HttpContextBase     httpContextBase = controllerContext.HttpContext;
                            string              str2            = str;
                            Func <string, bool> func5           = func2;
                            if (func5 == null)
                            {
                                Func <string, bool> func6 = (string path) => this.FileExists(controllerContext, path);
                                func  = func6;
                                func2 = func6;
                                func5 = func;
                            }
                            DisplayInfo displayInfo = displayMode.GetDisplayInfo(httpContextBase, str2, func5);
                            string      empty1      = string.Empty;
                            if ((displayInfo == null ? false : displayInfo.FilePath != null))
                            {
                                empty1 = displayInfo.FilePath;
                            }
                            base.ViewLocationCache.InsertViewLocation(controllerContext.HttpContext, this.AppendDisplayModeToCacheKey(cacheKey, mode.DisplayModeId), empty1);
                        }
                    }
                    break;
                }
            }
            return(empty);
        }
Пример #21
0
		/// <summary>
		/// Gets the browser specific theme and <see cref="System.Web.WebPages.IDisplayMode"/> and is
		/// called when the page first loads
		/// </summary>
		/// <param name="theme">The theme for the browser specific page or master</param>
		/// <param name="displayMode">The browser specific page's <see cref="System.Web.WebPages.IDisplayMode"/>,
		/// used in conjunction with <see cref="System.Web.WebPages.DisplayModeProvider.RequireConsistentDisplayMode"/></param>
		/// <param name="context">The current <see cref="System.Web.HttpContextBase"/></param>
		/// <returns>The browser specific <see cref="System.Web.WebPages.DisplayInfo"/></returns>
		protected virtual DisplayInfo GetDisplayInfoForTheme(string theme, IDisplayMode displayMode, HttpContextBase context)
		{
			DisplayInfo displayInfo = DisplayModeProvider.Instance.GetDisplayInfoForVirtualPath(theme + ".Theme", context, v => HostingEnvironment.VirtualPathProvider.DirectoryExists("~/App_Themes/" + v.Substring(0, v.Length - 6)), displayMode);
			return new DisplayInfo(displayInfo.FilePath.Substring(0, displayInfo.FilePath.Length - 6), displayInfo.DisplayMode);
		}
Пример #22
0
 private WebPageBase CreatePageFromVirtualPath(string virtualPath, HttpContextBase httpContext, Func<string, bool> virtualPathExists, DisplayModeProvider displayModeProvider, IDisplayMode displayMode)
 {
     try
       {
     DisplayInfo infoForVirtualPath = displayModeProvider.GetDisplayInfoForVirtualPath(virtualPath, httpContext, virtualPathExists, displayMode);
     if (infoForVirtualPath != null)
     {
       WebPageBase instance = VirtualPathFactoryExtensions.CreateInstance<WebPageBase>(this.VirtualPathFactory, infoForVirtualPath.FilePath);
       if (instance != null)
       {
     instance.VirtualPath = virtualPath;
     instance.VirtualPathFactory = this.VirtualPathFactory;
     instance.DisplayModeProvider = this.DisplayModeProvider;
     return instance;
       }
     }
       }
       catch (HttpException ex)
       {
     BuildManagerExceptionUtil.ThrowIfUnsupportedExtension(virtualPath, ex);
     BuildManagerExceptionUtil.ThrowIfCodeDomDefinedExtension(virtualPath, ex);
     throw;
       }
       throw new HttpException(string.Format((IFormatProvider) CultureInfo.CurrentCulture, WebPageResources.WebPage_InvalidPageType, new object[1]
       {
     (object) virtualPath
       }));
 }
 public LocalizedDisplayInfo(string filePath, IDisplayMode displayMode, string lang)
     : base(filePath, displayMode)
 {
     this.Lang = lang;
 }
        internal IEnumerable <IDisplayMode> GetAvailableDisplayModesForContext(HttpContextBase httpContext, IDisplayMode currentDisplayMode, bool requireConsistentDisplayMode)
        {
            IEnumerable <IDisplayMode> possibleDisplayModes = (requireConsistentDisplayMode && currentDisplayMode != null) ? Modes.SkipWhile(mode => mode != currentDisplayMode) : Modes;

            return(possibleDisplayModes.Where(mode => mode.CanHandleContext(httpContext)));
        }
Пример #25
0
        /// <summary>
        /// Attempts to create a WebPageBase instance from a virtualPath and wraps complex compiler exceptions with simpler messages
        /// </summary>
        private WebPageBase CreatePageFromVirtualPath(string virtualPath, HttpContextBase httpContext, Func<string, bool> virtualPathExists, DisplayModeProvider displayModeProvider, IDisplayMode displayMode)
        {
            try
            {
                DisplayInfo resolvedDisplayInfo = displayModeProvider.GetDisplayInfoForVirtualPath(virtualPath, httpContext, virtualPathExists, displayMode);

                if (resolvedDisplayInfo != null)
                {
                    var webPage = VirtualPathFactory.CreateInstance<WebPageBase>(resolvedDisplayInfo.FilePath);

                    if (webPage != null)
                    {
                        // Give it its virtual path
                        webPage.VirtualPath = virtualPath;
                        webPage.VirtualPathFactory = VirtualPathFactory;
                        webPage.DisplayModeProvider = DisplayModeProvider;

                        return webPage;
                    }
                }
            }
            catch (HttpException e)
            {
                // If the path uses an unregistered extension, such as Foo.txt,
                // then an error regarding build providers will be thrown.
                // Check if this is the case and throw a simpler error.
                BuildManagerExceptionUtil.ThrowIfUnsupportedExtension(virtualPath, e);

                // If the path uses an extension registered with codedom, such as Foo.js,
                // then an unfriendly compilation error might get thrown by the underlying compiler.
                // Check if this is the case and throw a simpler error.
                BuildManagerExceptionUtil.ThrowIfCodeDomDefinedExtension(virtualPath, e);

                // Rethrow any errors
                throw;
            }
            // The page is missing, could not be compiled or is of an invalid type.
            throw new HttpException(String.Format(CultureInfo.CurrentCulture, WebPageResources.WebPage_InvalidPageType, virtualPath));
        }
        internal DisplayInfo GetDisplayInfoForVirtualPath(string virtualPath, HttpContextBase httpContext, Func <string, bool> virtualPathExists, IDisplayMode currentDisplayMode,
                                                          bool requireConsistentDisplayMode)
        {
            IEnumerable <IDisplayMode> possibleDisplayModes = GetAvailableDisplayModesForContext(httpContext, currentDisplayMode, requireConsistentDisplayMode);

            return(possibleDisplayModes.Select(mode => mode.GetDisplayInfo(httpContext, virtualPath, virtualPathExists))
                   .FirstOrDefault(info => info != null));
        }
Пример #27
0
		/// <summary>
		/// Gets the browser specific master and <see cref="System.Web.WebPages.IDisplayMode"/> and is
		/// called when the page first loads
		/// </summary>
		/// <param name="master">The master for the browser specific page or master</param>
		/// <param name="displayMode">The browser specific page's <see cref="System.Web.WebPages.IDisplayMode"/>,
		/// used in conjunction with <see cref="System.Web.WebPages.DisplayModeProvider.RequireConsistentDisplayMode"/></param>
		/// <param name="context">The current <see cref="System.Web.HttpContextBase"/></param>
		/// <returns>The browser specific <see cref="System.Web.WebPages.DisplayInfo"/></returns>
		protected virtual DisplayInfo GetDisplayInfoForMaster(string master, IDisplayMode displayMode, HttpContextBase context)
		{
			return DisplayModeProvider.Instance.GetDisplayInfoForVirtualPath(master, context, v => HostingEnvironment.VirtualPathProvider.FileExists(v), displayMode);
		}
 /// <summary>
 /// Returns any IDisplayMode that can handle the given request.
 /// </summary>
 public IEnumerable<IDisplayMode> GetAvailableDisplayModesForContext(HttpContextBase httpContext, IDisplayMode currentDisplayMode)
 {
     return GetAvailableDisplayModesForContext(httpContext, currentDisplayMode, RequireConsistentDisplayMode).ToList();
 }
 internal IEnumerable<IDisplayMode> GetAvailableDisplayModesForContext(HttpContextBase httpContext, IDisplayMode currentDisplayMode, bool requireConsistentDisplayMode)
 {
     IEnumerable<IDisplayMode> possibleDisplayModes = (requireConsistentDisplayMode && currentDisplayMode != null) ? Modes.SkipWhile(mode => mode != currentDisplayMode) : Modes;
     return possibleDisplayModes.Where(mode => mode.CanHandleContext(httpContext));
 }
 /// <summary>
 /// Returns DisplayInfo from the first IDisplayMode in Modes that can handle the given request and locate the virtual path.
 /// If currentDisplayMode is not null and RequireConsistentDisplayMode is set to true the search for DisplayInfo will only
 /// start with the currentDisplayMode.
 /// </summary>
 public DisplayInfo GetDisplayInfoForVirtualPath(string virtualPath, HttpContextBase httpContext, Func<string, bool> virtualPathExists, IDisplayMode currentDisplayMode)
 {
     return GetDisplayInfoForVirtualPath(virtualPath, httpContext, virtualPathExists, currentDisplayMode, RequireConsistentDisplayMode);
 }
Пример #31
0
        private string GetPathFromGeneralName(ControllerContext controllerContext, IEnumerable <ViewLocation> locations, IDisplayMode displayMode, string name, string controllerName, string areaName, string cacheKey, out IList <string> searchedLocations)
        {
            searchedLocations = new List <string>();

            // Iterate through the locations.

            foreach (var location in locations)
            {
                var virtualPath = location.Format(name, controllerName, areaName);

                var virtualPathDisplayInfo = DisplayModeProvider.GetDisplayInfoForVirtualPath(virtualPath, controllerContext.HttpContext, path => FileExists(controllerContext, path), controllerContext.DisplayMode);
                if (virtualPathDisplayInfo != null)
                {
                    // Found a path for a view for a display mode.  Cache it against the most specific display mode.

                    var resolvedVirtualPath = virtualPathDisplayInfo.FilePath;
                    ViewLocationCache.InsertViewLocation(controllerContext.HttpContext, AppendDisplayModeToCacheKey(cacheKey, displayMode.DisplayModeId), resolvedVirtualPath);

                    if (controllerContext.DisplayMode == null)
                    {
                        controllerContext.DisplayMode = virtualPathDisplayInfo.DisplayMode;
                    }

                    searchedLocations.Clear();
                    return(resolvedVirtualPath);
                }

                searchedLocations.Add(virtualPath);
            }

            // Even though it does not exist add it to the cache so that all subsequent lookups don't have to check again.

            ViewLocationCache.InsertViewLocation(controllerContext.HttpContext, AppendDisplayModeToCacheKey(cacheKey, displayMode.DisplayModeId), DoesNotExist);
            return(string.Empty);
        }
Пример #32
0
        public static void Run()
        {
            int initialVSyncSetting = 0;

            try {
                initialVSyncSetting = GL.GetBufferSwapInterval();
                GameConfig.Load();

                GameDebugger.EngineLog(LogLevel.Debug, "Running application specific configuration event handlers");
                if (ConfigureEvent != null)
                {
                    ConfigureEvent();
                }

                GameDebugger.EngineLog(LogLevel.Debug, "Opening display device '{0}'", GameConfig.DisplayDevice);
                IDisplayDevice cur_dev = API.GetDisplayDevice(GameConfig.DisplayDevice);
                // GameDebugger.Log("Primary display device {0}", cur_dev.ToString());
                if (GameConfig.DisplayDevice != null && !GameConfig.DisplayDevice.Equals(cur_dev.Id))
                {
                    GameConfig.DisplayDevice = null;                     // needed to save a "primary display device" setting since the one in config was not found
                }
                List <IMonitor> monitors = cur_dev.GetMonitors();
                if (monitors == null || monitors.Count == 0)
                {
                    throw new UserFriendlyException("No monitors could be found on the selected device. Could there be a bug somewhere?", "Failed initializing graphics");
                }
                IMonitor first_monitor = monitors[0];
                // foreach( Rectangle mon in monitors )
                //	GameDebugger.Log("\tMonitor at {0}", mon.ToString());

                // Thanks to someone in Microsoft determining current refresh rate and bits per pixel of a monitor is quite a pain in the ass
                int current_width        = first_monitor.Width;
                int current_height       = first_monitor.Height;
                int current_bpp          = first_monitor.BitsPerPixel;
                int current_refresh_rate = first_monitor.RefreshRate;

                int cfg_width        = (GameConfig.ResX <= 0 || GameConfig.ResY <= 0) ? current_width : GameConfig.ResX;
                int cfg_height       = (GameConfig.ResX <= 0 || GameConfig.ResY <= 0) ? current_height : GameConfig.ResY;
                int cfg_bpp          = (GameConfig.BitsPerPixel <= 0) ? current_bpp : GameConfig.BitsPerPixel;
                int cfg_refresh_rate = (GameConfig.RefreshRate <= 0) ? current_refresh_rate : GameConfig.RefreshRate;

                // GameDebugger.Log("Searching for {0}bit {1}x{2} @{3}", GameConfig.BitsPerPixel, GameConfig.ResX, GameConfig.ResY, GameConfig.RefreshRate);

                if (GameConfig.FullScreen)
                {
                    List <IDisplayMode> modes = cur_dev.GetModes();
                    if (modes == null || modes.Count == 0)
                    {
                        throw new Exception(String.Format("Device {0} is invalid and has no modes suitable for graphics", cur_dev.ToString()));
                    }

                    IDisplayMode selected_mode = null;
                    foreach (IDisplayMode mode in modes)
                    {
                        // GameDebugger.Log("\t{0}", mode.ToString()); // Uncomment this to log all supported video modes for the chosen display device
                        if (cfg_width == mode.Width &&
                            cfg_height == mode.Height &&
                            cfg_bpp == mode.BitsPerPixel &&
                            cfg_refresh_rate == mode.RefreshRate)
                        {
                            selected_mode = mode;
                            // GameDebugger.Log("Selected mode: {0}", selected_mode.ToString());
                            //break;
                        }
                    }

                    if (selected_mode == null)
                    {
                        // in case the mode in the config is specified incorrectly we try to use current screen settings. also reset config so later it won't try this bothersome thing
                        GameConfig.ResX         = -1;
                        GameConfig.ResY         = -1;
                        GameConfig.BitsPerPixel = -1;
                        GameConfig.RefreshRate  = -1;
                        foreach (IDisplayMode mode in modes)
                        {
                            //GameDebugger.Log("\t{0}", mode.ToString());
                            if (current_width == mode.Width &&
                                current_height == mode.Height &&
                                current_bpp == mode.BitsPerPixel &&
                                current_refresh_rate == mode.RefreshRate)
                            {
                                selected_mode = mode;
                                break;
                            }
                        }
                    }

                    if (selected_mode == null)
                    {
                        // this should not happen but still ... if no current resolution we deperately search for any 1024x768x32 mode (should be present on all computers by now)
                        foreach (IDisplayMode mode in modes)
                        {
                            //GameDebugger.Log("\t{0}", mode.ToString());
                            if (1024 == mode.Width &&
                                768 == mode.Height &&
                                32 == mode.BitsPerPixel)
                            {
                                selected_mode = mode;
                                break;
                            }
                        }
                    }

                    //
                    if (selected_mode == null)
                    {
                        // OMG this is totally f****d up! just pick out the first one :|
                        selected_mode = modes[0];
                    }

                    if (selected_mode.Width != current_width ||
                        selected_mode.Height != current_height ||
                        selected_mode.BitsPerPixel != current_bpp ||
                        selected_mode.RefreshRate != current_refresh_rate)
                    {
                        // TODO: add support for non full screen modes
                        if (selected_mode.Set(true))
                        {
                            current_width        = selected_mode.Width;
                            current_height       = selected_mode.Height;
                            current_bpp          = selected_mode.BitsPerPixel;
                            current_refresh_rate = selected_mode.RefreshRate;
                        }

                        // After changing resolution monitor positions will change so we have to read them again!
                        monitors = cur_dev.GetMonitors();
                        if (monitors == null || monitors.Count == 0)
                        {
                            throw new Exception("No monitors could be found on the selected device. Could there be a bug somewhere?");
                        }
                        first_monitor = monitors[0];
                    }
                }
                else
                {
                    Size2 size = API.AdjustWindowSize(cfg_width, cfg_height);
                    current_width  = size.Width;
                    current_height = size.Height;
                }

                // GameDebugger.Log("{0},{1}-{2},{3}", first_monitor.X, first_monitor.Y, current_width, current_height);

                using (IOpenGLWindow window = GL.CreateWindow(null, first_monitor.X, first_monitor.Y, current_width, current_height)) {
                    m_Window = window;
                    window.BeforeRenderFrameEvent += OnBeforeFrame;
                    window.RenderFrameEvent       += OnFrame;
                    window.AfterRenderFrameEvent  += OnAfterFrame;
                    window.ResizeEvent            += OnResize;

                    m_Keyboard = IL.FirstKeyboardDevice;

                    Mouse         = IL.FirstMouseDevice;
                    Mouse.Window  = window;                    // mouse must be attached to window before showing since it watches move and resize events
                    Mouse.Visible = GameConfig.ShowHardwareCursor;
                    Mouse.Clipped = GameConfig.ClipMouseCursor;

                    window.Show();

                    GL.SetBufferSwapInterval(GameConfig.VSync ? 1 : 0);
                    GameConfig.VSyncChangedEvent += OnVSyncSettingChanged;

                    OnLoad();
                    if (LoadEvent != null)
                    {
                        LoadEvent();
                    }
                    // GameDebugger.Log("Running main loop at last");
                    Application.Run();
                    // GameDebugger.Log("ByeBye!");
                }
            }

            catch (Exception ex) {
                GameDebugger.EngineLog(LogLevel.Error, "IGE or application has crashed!");
                GameDebugger.EngineLog(LogLevel.Error, ex);
            }

            finally {
                try {
                    CacheableObject.DisposeAll();
                }
                catch (Exception ex) {
                    GameDebugger.EngineLog(LogLevel.Error, "IGE automatic resource unloading has crashed!");
                    GameDebugger.EngineLog(LogLevel.Error, ex);
                }

                try {
                    if (UnloadEvent != null)
                    {
                        UnloadEvent();
                    }
                }
                catch (Exception ex) {
                    GameDebugger.Log(LogLevel.Error, "Application has crashed on UnloadEvent!");
                    GameDebugger.Log(LogLevel.Error, ex);
                }

                try {
                    OnUnload();
                }
                catch (Exception ex) {
                    GameDebugger.EngineLog(LogLevel.Error, "IGE final unloading has crashed!");
                    GameDebugger.EngineLog(LogLevel.Error, ex);
                }

                try {
                    GameConfig.Save();
                }
                catch (Exception ex) {
                    GameDebugger.EngineLog(LogLevel.Error, "IGE could not automatically save the configuration!");
                    GameDebugger.EngineLog(LogLevel.Error, ex);
                }

                try { GameConfig.VSyncChangedEvent -= OnVSyncSettingChanged; } catch {}

                GL.SetBufferSwapInterval(initialVSyncSetting);
                m_Window = null;
            }
        }