Inheritance: MonoBehaviour
Beispiel #1
0
		public async Task StartAsync()
		{
			MainViewModel viewModel = new MainViewModel();
			viewModel.CloseRequested += viewModel_CloseRequested;

			EventHandler windowClosed = (sender, e) =>
			{
				viewModel.RequestClose();
			};

			SplashScreen splashScreen = new SplashScreen();  //not disposable, but I'm keeping the same structure
			{
				splashScreen.Closed += windowClosed; //if user closes splash screen, let's quit
				splashScreen.Show();

				await viewModel.InitializeAsync();

				MainWindow mainForm = new MainWindow();
				mainForm.Closed += windowClosed;
				mainForm.DataContext = viewModel;
				mainForm.Show();
				
				splashScreen.Owner = mainForm;
				splashScreen.Closed -= windowClosed;
				splashScreen.Close();
			}
		}
Beispiel #2
0
 public static void RegisterSplashScreen(SplashScreen screen)
 {
     using (LockSplashScreenList(true))
     {
         _splashScreens.Add(screen);
     }
 }
Beispiel #3
0
      public CredentialsManagerForm()
      {
         SplashScreen splashScreen = new SplashScreen(Resources.Splash);

         Thread.CurrentThread.Name = " Main UI Thread";
         m_DownloadCompletedEvent = new ManualResetEvent(false);

         InitializeComponent();
         m_ApplicationListView.SmallImageList = new ImageList();
         m_ApplicationListView.SmallImageList.Images.Add(Resources.Application);

         m_UsersListView.SmallImageList = new ImageList();
         m_UsersListView.SmallImageList.Images.Add(Resources.User);

         m_UsersToAssignListView.SmallImageList = new ImageList();
         m_UsersToAssignListView.SmallImageList.Images.Add(Resources.User);

         m_RolesListView.SmallImageList = new ImageList();
         m_RolesListView.SmallImageList.Images.Add(Resources.Role);

         m_UsersInRoleComboBox.SetImage(Resources.User);
         m_RolesForUserComboBox.SetImage(Resources.Role);

         ServiceAddress = Settings.Default.AspNetSqlProviderService;
         m_AddressTextbox.Text = ServiceAddress;
         RefreshServicePage();
         RefreshApplicationsPage();

         splashScreen.Close();
      }    
Beispiel #4
0
 public static void UnregisterSplashScreen(SplashScreen screen)
 {
     using (LockSplashScreenList(true))
     {
         _splashScreens.Remove(screen);
     }
 }
Beispiel #5
0
    void SetSplash(SplashScreen splash)
    {
        _splashTint.a = 0.0f;
        _splashMaterial.color = _splashTint;

        _splashMaterial.mainTexture = splash.SplashTexture;
    }
 public FormLogin()
 {
     InitializeComponent();
     this.Load += new EventHandler(HandleFormLoad);
     this.splashScreen = new SplashScreen();
     this.KeyPreview = true;
 }
Beispiel #7
0
 public static void ShowSplash()
 {
     ThreadPool.QueueUserWorkItem(delegate(object obj)
     {
         instance = new SplashScreen();
         instance.ShowDialog();
     });
 }
    void Start()
    {
        gameManager = GameObject.FindGameObjectWithTag ("GameManager");
        splashScreen = GameObject.FindGameObjectWithTag ("SplashScreen");

        audioSource = GetComponent<AudioSource> ();
        sScreen = splashScreen.GetComponent<SplashScreen> ();
    }
Beispiel #9
0
        public MainWindow()
        {
            InitializeComponent();
            FrameRate = 33;
            SplashScreen splash = new SplashScreen();
            onChangeView( null, splash );
            currentControl = splash;

            Application.Current.MainWindow.Closing += MainWindow_Closing;
        }
Beispiel #10
0
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            Splash = new SplashScreen();
            Splash.Show();
            AppJumpList.CreateJumpList();

            var loadtask = new Task(() =>
            {
                //here to do long stuff;
                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

                ThemeManager.DetectAppStyle(Application.Current);

                _accents = new Accent[]
                {
                ThemeManager.GetAccent("Red"), ThemeManager.GetAccent("Green"), ThemeManager.GetAccent("Blue"),
                ThemeManager.GetAccent("Purple"), ThemeManager.GetAccent("Orange"), ThemeManager.GetAccent("Lime"),
                ThemeManager.GetAccent("Emerald"), ThemeManager.GetAccent("Teal"), ThemeManager.GetAccent("Cyan"),
                ThemeManager.GetAccent("Cobalt"), ThemeManager.GetAccent("Indigo"), ThemeManager.GetAccent("Violet"),
                ThemeManager.GetAccent("Pink"), ThemeManager.GetAccent("Magenta"), ThemeManager.GetAccent("Crimson"),
                ThemeManager.GetAccent("Amber"), ThemeManager.GetAccent("Yellow"), ThemeManager.GetAccent("Brown"),
                ThemeManager.GetAccent("Olive"), ThemeManager.GetAccent("Steel"), ThemeManager.GetAccent("Mauve"),
                ThemeManager.GetAccent("Taupe"), ThemeManager.GetAccent("Sienna")
                };

                if (Settings.Default.WindowColor < 0 || Settings.Default.WindowColor > (_accents.Length - 1))
                {
                    var random = new Random();
                    _index = random.Next(0, _accents.Length);
                }
                else _index = Settings.Default.WindowColor;

                ThemeManager.ChangeAppStyle(Application.Current, _accents[_index], ThemeManager.GetAppTheme("BaseLight"));

            });
            loadtask.ContinueWith(t =>
            {
                Modules = new ModuleLoader();
                Modules.LoadFromNameSpace("ECalc.Modules");
                var mw = new MainWindow();

                var left = Settings.Default.WindowLeft;
                var top = Settings.Default.WindowTop;

                MainWindow = mw;

                if (left > 0) MainWindow.Left = left;
                if (top > 0) MainWindow.Top = top;

                mw.Show();

            }, TaskScheduler.FromCurrentSynchronizationContext());
            loadtask.Start();
        }
 private static void AddSplashEntry(JsonElementArray entries, SplashScreen splash)
 {
     if (Utils.CompareVersionNumbers(splash.minOsVersion, "7.0") <= 0)
     {
         AddSplashEntryForOSVersion(entries.AddDict(), splash, null);
     }
     if (splash.minOsVersion != null)
     {
         AddSplashEntryForOSVersion(entries.AddDict(), splash, splash.minOsVersion);
     }
 }
Beispiel #12
0
	// Update is called once per frame
	void Update () {
		if(asrc==null || ss == null){			
			asrc = Camera.current.GetComponent<AudioSource>();
			ss = Camera.current.GetComponent<SplashScreen>();
		} else {
			if(ss.CurrentStatus == SplashScreen.FadeStatus.FadeOut) {
				asrc.Play();
				this.enabled=false;
			}
		}
	}
Beispiel #13
0
 public static void ShowSplash(string title, string message)
 {
     Thread t = new Thread(
         delegate(object obj)
         {
             instance = new SplashScreen(title, message);
             instance.ShowDialog();
         });
     t.IsBackground = true;
     t.Start();
 }
Beispiel #14
0
        private void ShowSplash()
        {
            // Create the window
            Splash = new SplashScreen();

            // Show it
            Splash.Show();

            // Now that the window is created, allow the rest of the startup to run
            ResetSplashCreated.Set();
            System.Windows.Threading.Dispatcher.Run();
        }
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            SplashScreen splash = new SplashScreen();
            splash.ShowDialog();

            Application.Run(new Main());

            splash = null;
        }
Beispiel #16
0
	// Update is called once per frame
	void Update () {
		if( a == null || ss == null) {
			a = this.gameObject.GetComponent<Animator>();
			ss = Camera.current.GetComponent<SplashScreen>();
		} else {
			if(!playedOnce) {
				if(ss.CurrentStatus == SplashScreen.FadeStatus.FadeOut) {
					a.Play(Animator.StringToHash("Fade out"));
					playedOnce=true;
				}
			}
		}
	}
Beispiel #17
0
        public override async void RunGame()
        {
            using (var splashScreen = new SplashScreen(this, 3))
            {
                splashScreen.LoadResource(Content);
                await this.Play(splashScreen);
            }

            using (var level = new Level_0(this))
            {
                level.LoadResource(Content);
                await this.Play(level);
            }
        }
    public MainClass()
    {
        //display the splash screen and determine network status
        splash = new SplashScreen(this);
        splash.ShowDialog();

        try {
            game = new GameClass(fullScreen, gameFormSize, enableNetwork);
        }
        catch(DirectXException) {
            return;
        }
        if( game.CreateGraphicsSample() )
            game.Run();
    }
Beispiel #19
0
	// Update is called once per frame
	void Update () {		
		if(ss == null || asrc == null) {
			ss = Camera.current.GetComponent<SplashScreen>();
			asrc = this.gameObject.GetComponent<AudioSource>();
		}
		else {
			if(ss.CurrentStatus == SplashScreen.FadeStatus.FadeOut) {
				ss.splashLogo = SplashAfter;
				if(!playedOnce) {
					asrc.Play ();
					playedOnce=true;
				}
			}
		}
	}
        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            _splashScreen = new SplashScreen(Content, graphics);
            _splashScreen.Current = true;
            _gameScreen = new GameScreen(Content, graphics);
            _menuScreen = new MenuScreen(Content, graphics);
            _gameOverScreen = new GameOverScreen(Content, graphics);
            _creditoScreen = new CreditoScreen(Content, graphics);
            _rankingScreen = new RankingScreen(Content, graphics);

            Pontuacao();

            base.Initialize();
        }
Beispiel #21
0
        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            IsMouseVisible = true;
            // TODO: use this.Content to load your game content here

            SplashScreen Splashscreen = new SplashScreen();
            Splashscreen.BackgroundImage = ScreenManager.CurrentGame.Content.Load<Texture2D>("Logo");
            Splashscreen.ShowScreen = new MainScreen();

            Splashscreen.Show();

            if (ScreenManager.ActiveScreen != null)
                ScreenManager.ActiveScreen.LoadContent();
        }
 private static void AddSplashEntryForOSVersion(JsonElementDict entry, SplashScreen splash, string minOsVersion)
 {
     entry.SetString("orientation", !splash.isPortrait ? "landscape" : "portrait");
     entry.SetString("idiom", FileUpdaterUtils.GetDeviceIdiomForJson(splash.deviceType));
     entry.SetString("filename", splash.xcodeFile);
     if (minOsVersion != null)
     {
         entry.SetString("minimum-system-version", splash.minOsVersion);
     }
     if (splash.subtype != null)
     {
         entry.SetString("subtype", splash.subtype);
     }
     entry.SetString("extent", "full-screen");
     entry.SetString("scale", string.Format("{0}x", splash.scale));
 }
Beispiel #23
0
		static async Task Init (SplashScreen splashScreen)
		{
			IProgressReport progress = splashScreen;

			try {
				bool haveCodecs = false;
				App.Current.DrawingToolkit = new CairoBackend ();
				App.Current.MultimediaToolkit = new MultimediaToolkit ();
				App.Current.GUIToolkit = GUIToolkit.Instance;
				App.Current.Navigation = GUIToolkit.Instance;
				App.Current.GUIToolkit.Register<IPlayerView, VASUi.PlayerView> (0);
				App.Current.Dialogs = VASUi.Dialogs.Instance;

				App.Current.KPIService.Init ("9dc114d23c6148719b4adbe585b811cc", "user", "email");

				Task gstInit = Task.Factory.StartNew (() => InitGStreamer (progress));

				App.Current.DependencyRegistry.Register<IFileStorage, LMDB.FileStorage> (0);
				InitAddins (progress);
				CoreServices.RegisterService (new UpdatesNotifier ());
				CoreServices.Start (App.Current.GUIToolkit, App.Current.MultimediaToolkit);
				AddinsManager.LoadDashboards (App.Current.CategoriesTemplatesProvider);
				AddinsManager.LoadImportProjectAddins (CoreServices.ProjectsImporter);

				// Migrate the old databases now that the DB and Templates services have started
				DatabaseMigration dbMigration = new DatabaseMigration (progress);
				Task dbInit = Task.Factory.StartNew (dbMigration.Start);

				// Wait for Migration and the GStreamer initialization
				try {
					await Task.WhenAll (gstInit, dbInit);
				} catch (AggregateException ae) {
					throw ae.Flatten ();
				}

				if (!AddinsManager.RegisterGStreamerPlugins ()) {
					ShowCodecsDialog ();
				}

				splashScreen.Destroy ();
				ConfigureOSXApp ();
				(GUIToolkit.Instance.MainController as MainWindow).Initialize ();
				App.Current.StateController.SetHomeTransition ("Home", null);
			} catch (Exception ex) {
				ProcessExecutionError (ex);
			}
		}
        public Form1(SplashScreen.SplashScreen splash)
        {
            mSplash = splash;

            //Set up auto detect of USB device plugged in.
            JoyConnectNotify = new DetectHIDDeviceConnect.JoystickConnectNotification(this);
            JoyConnectNotify.OnJoystickConnected += new DetectHIDDeviceConnect.JoystickConnectNotification.JoyConnectDel(JoyConnectNotify_OnJoystickConnected);

            InitializeComponent();

            this.BackColor = Color.FromArgb(137, 138, 139);

            rockBandDrumControler1.DrumPadClicked += new RockBandDrumControler.DrumPadClickedEventHandler(DrumKit_DrumPadHit);

            mSplash.SetProgress("Enabling Midi Device", 0.4);
            //start midi engine
            MidiPlayer.OpenMidi();
        }
Beispiel #25
0
        public GameScreen OpeningSplashTwo()
        {
            //Create the base object to be built
            GameScreen gameScreen = new SplashScreen();

            //Change the xmlGameManger in sceneManager to the correct type and then load the basic screen settings
            SceneManager.Instance.xmlGameScreenManager.Type = gameScreen.Type;
            gameScreen = SceneManager.Instance.xmlGameScreenManager.Load("Content/XML/GameScreens/SplashScreens/SplashTwo.xml");


            //Load all events via the xml manager, the splash screen only has the one event
            //Event manager must be switched the correct child type fist, see if can change this
            gameScreen.xmlEventManager.Type = typeof(TimerEvent);
            gameScreen.Events.Add(gameScreen.xmlEventManager.Load("Content/XML/Events/SplashTimer.xml"));


            //Return fully built GameScreen
            return gameScreen;
        }
Beispiel #26
0
		public static void Main (string [] args)
		{
			// Replace the current synchronization context with a GTK synchronization context
			// that continues tasks in the main UI thread instead of a random thread from the pool.
			SynchronizationContext.SetSynchronizationContext (new GtkSynchronizationContext ());
			GLib.ExceptionManager.UnhandledException += HandleException;
			TaskScheduler.UnobservedTaskException += HandleUnobservedTaskException;
			App.Init ();
			CoreServices.Init ();
			InitGtk ();
			var splashScreen = new SplashScreen (Resources.LoadImage (Constants.SPLASH));
			splashScreen.Show ();
			Application.Invoke (async (s, e) => await Init (splashScreen));
			Application.Run ();
			try {
				AddinsManager.ShutdownMultimediaBackends ();
			} catch (Exception e) {
				Log.Exception (e);
			}
		}
Beispiel #27
0
        public IGameUI NewGameUI()
        {
            IRandom random                        = new InjectableRandom();
            IPlayer player                        = new Player();
            SnailNameGenerator snailNameGenerator = new SnailNameGenerator(random);
            IBookie bookie                        = new Bookie();
            IGame game                            = new Game
            (
                player,
                CreateRaceLineup.DelegateCreateRaceLineup
                (
                    random,
                    40,
                    CreateRace.DelegateCreateRace()
                ),
                AggregateSnails.DelegateAggregateSnails
                (
                    CreateSnail.DelegateCreateSnail(),
                    snailNameGenerator
                ),
                bookie
            );
            DelegateCreateOutputMethod standardOutput = CreateConsoleOutput.DelegateCreateConsoleOutput();
            DelegateCreateOutputMethod bufferedOutput = CreateBufferedConsoleOutput.DelegateCreateBufferedConsoleOutput();

            ISplashScreen splashScreen   = new SplashScreen(standardOutput);
            IRaceViewer raceViewer       = new RaceViewer(100, bufferedOutput);
            IBookieInput bookieInput     = new BookieInput(CreateBet.DelegateCreateBet(), standardOutput);
            IPayoutDisplay payoutDisplay = new PayoutDisplay(standardOutput);

            return new GameUI(
                game,
                splashScreen,
                raceViewer,
                bookieInput,
                payoutDisplay
            );
        }
        protected override void OnStartup(StartupEventArgs e)
        {
            double splashDuration = 2000.0;
            #if DEBUG
            splashDuration = 100.0;
            #endif

            base.OnStartup(e);

            // start the main window hidden
            MainWindow mainWindow = new MainWindow();

            // this is called after the Splash Screen timer expires
            Action showMain = delegate
            {
                Application.Current.MainWindow = mainWindow;
                mainWindow.Show();
            };

            SplashScreen splashScreen = new SplashScreen(splashDuration, showMain);
            Application.Current.MainWindow = splashScreen;
            splashScreen.Show();
        }
Beispiel #29
0
 public ExtendedSplash(SplashScreen Screen)
 {
     Initialize(Screen);
 }
Beispiel #30
0
 public Splash(SplashScreen splashScreen)
 {
     InitializeComponent();
 }
Beispiel #31
0
        protected override void LoadContent()
        {
            var options = Services.GetService <IOptionsProvider>();

            options.Load();

            //	DebugFont = (WrappedSpriteFont) Content.Load<SpriteFont>("Alex.Resources.DebugFont.xnb");

            ResourceManager.BlockEffect    = Content.Load <Effect>("Alex.Resources.Blockshader.xnb").Clone();
            ResourceManager.LightingEffect = Content.Load <Effect>("Alex.Resources.Lightmap.xnb").Clone();
            //	ResourceManager.BlockEffect.GraphicsDevice = GraphicsDevice;

            _spriteBatch = new SpriteBatch(GraphicsDevice);
            InputManager = new InputManager(this);

            GuiRenderer = new GuiRenderer();
            //GuiRenderer.Init(GraphicsDevice);

            GuiManager = new GuiManager(this, Services, InputManager, GuiRenderer, options);
            GuiManager.Init(GraphicsDevice, Services);

            options.AlexOptions.VideoOptions.UseVsync.Bind((value, newValue) => { SetVSync(newValue); });
            if (options.AlexOptions.VideoOptions.UseVsync.Value)
            {
                SetVSync(true);
            }

            options.AlexOptions.VideoOptions.Fullscreen.Bind((value, newValue) => { SetFullscreen(newValue); });
            if (options.AlexOptions.VideoOptions.Fullscreen.Value)
            {
                SetFullscreen(true);
            }

            options.AlexOptions.VideoOptions.LimitFramerate.Bind((value, newValue) =>
            {
                SetFrameRateLimiter(newValue, options.AlexOptions.VideoOptions.MaxFramerate.Value);
            });

            options.AlexOptions.VideoOptions.MaxFramerate.Bind((value, newValue) =>
            {
                SetFrameRateLimiter(options.AlexOptions.VideoOptions.LimitFramerate.Value, newValue);
            });

            if (options.AlexOptions.VideoOptions.LimitFramerate.Value)
            {
                SetFrameRateLimiter(true, options.AlexOptions.VideoOptions.MaxFramerate.Value);
            }

            options.AlexOptions.VideoOptions.Antialiasing.Bind((value, newValue) =>
            {
                SetAntiAliasing(newValue > 0, newValue);
            });

            options.AlexOptions.MiscelaneousOptions.Language.Bind((value, newValue) =>
            {
                GuiRenderer.SetLanguage(newValue);
            });
            GuiRenderer.SetLanguage(options.AlexOptions.MiscelaneousOptions.Language);

            options.AlexOptions.VideoOptions.SmoothLighting.Bind(
                (value, newValue) =>
            {
                ResourcePackBlockModel.SmoothLighting = newValue;
            });

            ResourcePackBlockModel.SmoothLighting = options.AlexOptions.VideoOptions.SmoothLighting.Value;

            SetAntiAliasing(options.AlexOptions.VideoOptions.Antialiasing > 0,
                            options.AlexOptions.VideoOptions.Antialiasing.Value);

            GuiDebugHelper = new GuiDebugHelper(GuiManager);

            OnCharacterInput += GuiManager.FocusManager.OnTextInput;

            GameStateManager = new GameStateManager(GraphicsDevice, _spriteBatch, GuiManager);

            var splash = new SplashScreen();

            GameStateManager.AddState("splash", splash);
            GameStateManager.SetActiveState("splash");

            WindowSize = this.Window.ClientBounds.Size;
            //	Log.Info($"Initializing Alex...");
            ThreadPool.QueueUserWorkItem(() =>
            {
                try
                {
                    InitializeGame(splash);
                }
                catch (Exception ex)
                {
                    Log.Error(ex, $"Could not initialize! {ex}");
                }
            });
        }
 //--------------------------------------------------------Events:---------------------------------------------------------------------\\
 #region --Events--
 private async void SPLASH_SCREEN_Dismissed(SplashScreen sender, object args)
 {
     await SharedUtils.CallDispatcherAsync(async() => await LoadAppAsync());
 }
Beispiel #33
0
        private static void LoadCitiesFromXmlByXmlDocument(string fileName)
        {
            XmlDocument xmlDocument = new XmlDocument();

            List <Country_Region>   regions = new List <Country_Region>();
            List <Lishkat_Mana>     lishkot = new List <Lishkat_Mana>();
            List <Regional_Council> muacot  = new List <Regional_Council>();
            List <City>             cities  = new List <City>();

            SplashScreen.SetStatus("Loading XML " + fileName);
            xmlDocument.Load(fileName);
            SplashScreen.SetStatus(fileName + " XML Loaded");

            SplashScreen.SetStatus("Parsing XML");
            foreach (XmlNode node in xmlDocument.DocumentElement)
            {
                //foreach (XmlNode child in node.ChildNodes)
                //{
                //
                //}

                Country_Region region = new Country_Region
                {
                    Country_Region_Code = int.Parse(node.ChildNodes[4].InnerText),
                    Country_Region_Name = node.ChildNodes[5].InnerText.Trim()
                };
                if (!regions.Exists(x => x.Country_Region_Code == region.Country_Region_Code))
                {
                    regions.Add(region);
                }

                Lishkat_Mana lishka = new Lishkat_Mana
                {
                    Lishkat_Mana_Code = int.Parse(node.ChildNodes[6].InnerText),
                    Lishkat_Mana_Name = node.ChildNodes[7].InnerText.Trim()
                };
                if (!lishkot.Exists(x => x.Lishkat_Mana_Code == lishka.Lishkat_Mana_Code))
                {
                    lishkot.Add(lishka);
                }

                Regional_Council muaca = new Regional_Council
                {
                    Regional_Council_Code = int.Parse(node.ChildNodes[8].InnerText),
                    Regional_Council_Name = node.ChildNodes[9].InnerText.Trim()
                };
                if (!muacot.Exists(x => x.Regional_Council_Code == muaca.Regional_Council_Code))
                {
                    muacot.Add(muaca);
                }

                City city = new City
                {
                    //Table = node.ChildNodes[0].InnerText,
                    City_Code           = int.Parse(node.ChildNodes[1].InnerText),
                    City_Name           = node.ChildNodes[2].InnerText.Trim(),
                    City_Name_En        = node.ChildNodes[3].InnerText.Trim(),
                    Country_Region_Code = int.Parse(node.ChildNodes[4].InnerText),
                    //Region_name = node.ChildNodes[5].InnerText,
                    Lishkat_Mana_Code = int.Parse(node.ChildNodes[6].InnerText),
                    //Lishka_Name = node.ChildNodes[7].InnerText,
                    Regional_Council_Code = int.Parse(node.ChildNodes[8].InnerText),
                    //Muaca_Izorit_Name = node.ChildNodes[9].InnerText
                };
                if (!cities.Exists(x => x.City_Code == city.City_Code))
                {
                    cities.Add(city);
                }

                /*
                 * if (db.Country_Regions.Find(region.Country_Region_Code) == null)
                 *  db.Country_Regions.Add(region);
                 * //db.SaveChanges();
                 *
                 * if (db.Lishkot_Mana.Find(lishka.Lishkat_Mana_Code) == null)
                 *  db.Lishkot_Mana.Add(lishka);
                 * //db.SaveChanges();
                 *
                 * if (muaca.Regional_Council_Code != 0 || db.Regional_Councils.Find(muaca.Regional_Council_Code) == null)
                 *  db.Regional_Councils.Add(muaca);
                 * //db.SaveChanges();
                 *
                 * if (db.Cities.Find(city.City_Code) == null)
                 *  db.Cities.Add(city);
                 * //db.SaveChanges();
                 */
            }
            SplashScreen.SetStatus("XML Parsed");

            SplashScreen.SetStatus("Conecting to db");
            using (WorldGeoDataDB db = new WorldGeoDataDB())
            {
                SplashScreen.SetStatus("Ading data to DB");

                SplashScreen.SetStatus("Ading regions");
                db.Country_Regions.AddRange(regions);
                db.SaveChanges();
                SplashScreen.SetStatus("Country_Regions Added");

                SplashScreen.SetStatus("Ading lishkot");
                db.Lishkot_Mana.AddRange(lishkot);
                db.SaveChanges();
                SplashScreen.SetStatus("Lishkot_Mana Added");

                SplashScreen.SetStatus("Ading muacot");
                db.Regional_Councils.AddRange(muacot);
                db.SaveChanges();
                SplashScreen.SetStatus("Muacot Added");

                SplashScreen.SetStatus("Ading cities");
                db.Cities.AddRange(cities);
                db.SaveChanges();
                SplashScreen.SetStatus("Cities Added");
            }
        }
Beispiel #34
0
 /// <summary>
 /// Invoked when the application is launched normally by the end user.  Other entry points
 /// will be used when the application is launched to open a specific file, to display
 /// search results, and so forth.
 /// </summary>
 /// <param name="args">Details about the launch request and process.</param>
 protected override void OnLaunched(LaunchActivatedEventArgs args)
 {
     splashScreen = args.SplashScreen;
     InitializeUnity(args.Arguments);
 }
        protected override void DidActivate(bool firstActivation, bool addedToHierarchy, bool screenSystemEnabling)
        {
            if (firstActivation)
            {
                //Set up UI
                SetTitle("Game Room", ViewController.AnimationType.None);

                showBackButton = true;

                _playerDataModel             = Resources.FindObjectsOfTypeAll <PlayerDataModel>().First();
                _menuLightsManager           = Resources.FindObjectsOfTypeAll <MenuLightsManager>().First();
                _soloFreePlayFlowCoordinator = Resources.FindObjectsOfTypeAll <SoloFreePlayFlowCoordinator>().First();
                _resultsViewController       = Resources.FindObjectsOfTypeAll <ResultsViewController>().First();
                _scoreLights   = _soloFreePlayFlowCoordinator.GetField <MenuLightsPresetSO>("_resultsClearedLightsPreset");
                _defaultLights = _soloFreePlayFlowCoordinator.GetField <MenuLightsPresetSO>("_defaultLightsPreset");

                _songSelection = BeatSaberUI.CreateViewController <SongSelection>();
                _songSelection.SongSelected += songSelection_SongSelected;

                _splashScreen = BeatSaberUI.CreateViewController <SplashScreen>();

                _songDetail              = BeatSaberUI.CreateViewController <SongDetail>();
                _songDetail.PlayPressed += songDetail_didPressPlayButtonEvent;
                _songDetail.DifficultyBeatmapChanged += songDetail_didChangeDifficultyBeatmapEvent;

                _playerList = BeatSaberUI.CreateViewController <PlayerList>();
            }
            if (addedToHierarchy)
            {
                TournamentMode = Match == null;
                if (TournamentMode)
                {
                    _splashScreen.StatusText = $"Connecting to \"{Host.Name}\"...";
                    ProvideInitialViewControllers(_splashScreen);
                }
                else
                {
                    //If we're not in tournament mode, then a client connection has already been made
                    //by the room selection screen, so we can just assume Plugin.client isn't null
                    //NOTE: This is *such* a hack. Oh my god.
                    isHost = Match.Leader == Plugin.client.Self;
                    _songSelection.SetSongs(SongUtils.masterLevelList);
                    _playerList.Players      = Match.Players;
                    _splashScreen.StatusText = "Waiting for the host to select a song...";

                    if (isHost)
                    {
                        ProvideInitialViewControllers(_songSelection, _playerList);
                    }
                    else
                    {
                        ProvideInitialViewControllers(_splashScreen, _playerList);
                    }
                }
            }

            //The ancestor sets up the server event listeners
            //It would be possible to recieve an event that does a ui update after this call
            //and before the rest of the ui is set up, if we did this at the top.
            //So, we do it last
            base.DidActivate(firstActivation, addedToHierarchy, screenSystemEnabling);
        }
Beispiel #36
0
 private async void DismissedEventHandler(SplashScreen sender, object args)
 {
     dismissed = true;
     // Complete app setup operations here...
     await InitializeAsync();
 }
Beispiel #37
0
        /// <summary>
        /// By default, we are configured to use MEF
        /// </summary>
        protected override void Configure()
        {
            try
            {
                var splashScreen = new SplashScreen(Assembly.GetAssembly(typeof(AppBootstrapper)), "daxstudio-splash.png");
                splashScreen.Show(true);

                // Tell Caliburn Micro how to find controls in Fluent Ribbon

                /*
                 * defaultElementLookup = BindingScope.GetNamedElements;
                 * BindingScope.GetNamedElements = new Func<System.Windows.DependencyObject, IEnumerable<System.Windows.FrameworkElement>>(
                 *  k =>
                 *  {
                 *      List<FrameworkElement> namedElements = new List<FrameworkElement>();
                 *      namedElements.AddRange(defaultElementLookup(k));
                 *      Fluent.Ribbon ribbon = LookForRibbon(k);
                 *      if (null != ribbon)
                 *          AppendRibbonNamedItem(ribbon, namedElements);
                 *      return namedElements;
                 *  }
                 *  );
                 */

                ConventionManager.AddElementConvention <Fluent.Spinner>(Fluent.Spinner.ValueProperty, "Value", "ValueChanged");

                // TODO - do I need to replace these conventions ??
                //ConventionManager.AddElementConvention<NumericUpDownLib.DoubleUpDown>(NumericUpDownLib.DoubleUpDown.ValueProperty, "Value", "ValueChanged");

                //ConventionManager.AddElementConvention<Xceed.Wpf.Toolkit.DoubleUpDown>(Xceed.Wpf.Toolkit.DoubleUpDown.ValueProperty, "Value", "ValueChanged");
                //ConventionManager.AddElementConvention<Xceed.Wpf.Toolkit.IntegerUpDown>(Xceed.Wpf.Toolkit.IntegerUpDown.ValueProperty, "Value", "ValueChanged");
                //ConventionManager.AddElementConvention<Xceed.Wpf.Toolkit.WatermarkTextBox>(Xceed.Wpf.Toolkit.WatermarkTextBox.TextProperty, "Text", "TextChanged");

                // Add Fluent Ribbon resovler
                BindingScope.AddChildResolver <Fluent.Ribbon>(FluentRibbonChildResolver);


                // Fixes the default datetime format in the results listview
                // from: http://stackoverflow.com/questions/1993046/datetime-region-specific-formatting-in-wpf-listview
                FrameworkElement.LanguageProperty.OverrideMetadata(
                    typeof(FrameworkElement),
                    new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));

                var catalog = new AggregateCatalog(
                    AssemblySource.Instance.Select(x => new AssemblyCatalog(x)).OfType <ComposablePartCatalog>()
                    );
                //_container = new CompositionContainer(catalog,true);
                _container = new CompositionContainer(catalog);
                var batch = new CompositionBatch();



                batch.AddExportedValue <IWindowManager>(new WindowManager());
                batch.AddExportedValue <IEventAggregator>(new EventAggregator());
                batch.AddExportedValue <Func <DocumentViewModel> >(() => _container.GetExportedValue <DocumentViewModel>());
                batch.AddExportedValue <Func <IWindowManager, IEventAggregator, DocumentViewModel> >(
                    (w, e) => _container.GetExportedValue <DocumentViewModel>());
                batch.AddExportedValue(_container);
                batch.AddExportedValue(catalog);

                var settingFactory = new SettingsProviderFactory();
                ISettingProvider settingProvider = settingFactory.GetSettingProvider();

                batch.AddExportedValue <ISettingProvider>(settingProvider);

                _container.Compose(batch);

                // Add AvalonDock binding convetions
                AvalonDockConventions.Install();

                //var settingFactory = _container.GetExport<Func<ISettingProvider>>();



                ConfigureKeyBindingConvention();

                // TODO - not working
                //VisibilityBindingConvention.Install();

                // Enable Caliburn.Micro debug logging
                //LogManager.GetLog = type => new DebugLogger(type);

                // Add Application object to MEF catalog
                _container.ComposeExportedValue <Application>("System.Windows.Application", Application.Current);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
            }
        }
 internal void DismissedEventHandler(SplashScreen sender, object e)
 {
 }
Beispiel #39
0
 public MainWindow(SplashScreen splashScreen)
 {
     _splashScreen = splashScreen;
     _manager      = new AnalyticsManager();
     InitializeComponent();
 }
        // Include code to be executed when the system has transitioned from the splash screen to the extended splash screen (application's first view).
        void DismissedEventHandler(SplashScreen sender, object e)
        {
            dismissed = true;

            // Complete app setup operations here...
        }
Beispiel #41
0
 public MyApp(Platform platform, StatusBar statusBar, SplashScreen splashScreen)
 {
 }
Beispiel #42
0
        private static void Main(string[] args)
        {
            // Parse command line arguments
            bool recover = false;

            foreach (string a in args)
            {
                if (a == "debug")
                {
                    System.Diagnostics.Debugger.Launch();
                }
                else if (a == "recover")
                {
                    recover = true;
                }
            }

            // Culture setup
            Thread.CurrentThread.CurrentCulture   = CultureInfo.InvariantCulture;
            Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;

            // Set up file logging
            StreamWriter        logfileWriter = null;
            TextWriterLogOutput logfileOutput = null;

            try
            {
                // If there is an existing logfile, preserve it under a different name
                if (File.Exists(DualityEditorApp.EditorLogfilePath))
                {
                    if (File.Exists(DualityEditorApp.EditorPrevLogfilePath))
                    {
                        File.Delete(DualityEditorApp.EditorPrevLogfilePath);
                    }
                    File.Move(DualityEditorApp.EditorLogfilePath, DualityEditorApp.EditorPrevLogfilePath);
                }

                // Create a new logfile
                logfileWriter           = new StreamWriter(DualityEditorApp.EditorLogfilePath);
                logfileWriter.AutoFlush = true;
                logfileOutput           = new TextWriterLogOutput(logfileWriter);
                Log.AddGlobalOutput(logfileOutput);
            }
            catch (Exception e)
            {
                Log.Core.WriteWarning("Text Logfile unavailable: {0}", Log.Exception(e));
            }

            // Winforms Setup
            Application.CurrentCulture = Thread.CurrentThread.CurrentCulture;
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.ThreadException += Application_ThreadException;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            {
                PackageManager packageManager = new PackageManager();

                // On the first install startup, display a generic license agreement for Duality
                if (packageManager.IsFirstInstall)
                {
                    LicenseAcceptDialog licenseDialog = new LicenseAcceptDialog
                    {
                        DescriptionText = GeneralRes.LicenseAcceptDialog_FirstStartGeneric,
                        LicenseUrl      = new Uri(DualityMainLicenseUrl)
                    };
                    DialogResult result = licenseDialog.ShowDialog();
                    if (result != DialogResult.OK)
                    {
                        Application.Exit();
                        return;
                    }
                }

                // Perform the initial package update - even before initializing the editor
                if (packageManager.IsPackageSyncRequired)
                {
                    Log.Editor.Write("Updating Packages...");
                    Log.Editor.PushIndent();
                    ProcessingBigTaskDialog setupDialog = new ProcessingBigTaskDialog(
                        GeneralRes.TaskInstallPackages_Caption,
                        GeneralRes.TaskInstallPackages_Desc,
                        SynchronizePackages,
                        packageManager);
                    setupDialog.ShowInTaskbar      = true;
                    setupDialog.MainThreadRequired = false;
                    setupDialog.ShowDialog();
                    Log.Editor.PopIndent();
                }
                // Restart to apply the update
                if (packageManager.ApplyUpdate())
                {
                    Application.Exit();
                    return;
                }
                // If we have nothing to apply, but still require a sync, something went wrong.
                // Should this happen on our first start, we'll remind the user that the install
                // requires an internet connection and refuse to start.
                else if (packageManager.IsPackageSyncRequired && packageManager.IsFirstInstall)
                {
                    DialogResult result = MessageBox.Show(
                        GeneralRes.Msg_ErrorFirstDualityInstall_Desc,
                        GeneralRes.Msg_ErrorFirstDualityInstall_Caption,
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Application.Exit();
                    return;
                }
            }

            // Run the editor
            SplashScreen splashScreen = new SplashScreen(recover);

            splashScreen.Show();
            Application.Run();

            // Clean up the log file
            if (logfileWriter != null)
            {
                Log.RemoveGlobalOutput(logfileOutput);
                logfileWriter.Flush();
                logfileWriter.Close();
                logfileWriter = null;
                logfileOutput = null;
            }
        }
Beispiel #43
0
        public void OnExplore(object sender, EventArgs e)
        {
            Cursor currentCursor = Cursor.Current;

            Cursor.Current = Cursors.WaitCursor;

            m_ExploreToolStripMenuItem.Enabled = m_ExploreButton.Enabled = false;

            string serviceNamespace = m_NamespaceTextBox.Text;

            if (String.IsNullOrEmpty(serviceNamespace))
            {
                MessageBox.Show("You need to provide a service namespace", "Service Bus Explorer", MessageBoxButtons.OK, MessageBoxIcon.Error);
                m_ExploreToolStripMenuItem.Enabled = m_ExploreButton.Enabled = true;

                Cursor.Current = currentCursor;

                return;
            }

            if (Graphs.ContainsKey(serviceNamespace.ToLower()) == false)
            {
                LogonDialog dialog = new LogonDialog(m_NamespaceTextBox.Text, DefaultIssuer);
                dialog.ShowDialog();

                if (dialog.Secret == null)
                {
                    m_ExploreToolStripMenuItem.Enabled = m_ExploreButton.Enabled = true;
                    Cursor.Current = currentCursor;

                    return;
                }
                try
                {
                    Graphs[serviceNamespace.ToLower()] = new ServiceBusGraph(serviceNamespace, dialog.Issuer, dialog.Secret);
                }
                catch (Exception exception)
                {
                    MessageBox.Show("Invalid namespace name: " + exception.Message, "Service Bus Explorer", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    m_ExploreToolStripMenuItem.Enabled = m_ExploreButton.Enabled = true;
                    Cursor.Current = currentCursor;
                    return;
                }
            }

            SplashScreen splash = new SplashScreen(Resources.Progress);

            try
            {
                Application.DoEvents();

                ServiceBusNode[] nodes = Graphs[serviceNamespace.ToLower()].Discover();

                AddNodesToTree(m_ServiceBusTree, nodes);

                DisplayNamespaceControl(serviceNamespace);
            }
            catch (Exception exception)
            {
                MessageBox.Show("Some error occurred discovering the service namespace: " + exception.Message, "Service Bus Explorer", MessageBoxButtons.OK, MessageBoxIcon.Error);

                for (int index = 0; index < m_ServiceBusTree.Nodes.Count; index++)
                {
                    if (m_ServiceBusTree.Nodes[index].Text == serviceNamespace)
                    {
                        m_ServiceBusTree.Nodes.Add(new NamespaceTreeNode(this, serviceNamespace, ServiceError));
                        m_ServiceBusTree.Nodes.RemoveAt(index);
                        break;
                    }
                }
            }
            finally
            {
                splash.Close();
                m_ExploreToolStripMenuItem.Enabled = m_ExploreButton.Enabled = true;
                Cursor.Current = currentCursor;
            }
        }
 /// <summary>
 /// Invoked when this page is about to be displayed in a Frame.
 /// </summary>
 /// <param name="e">Event data that describes how this page was reached.  The Parameter
 /// property is typically used to configure the page.</param>
 protected override void OnNavigatedTo(NavigationEventArgs e)
 {
     splash = (SplashScreen)e.Parameter;
     OnResize();
 }
Beispiel #45
0
 public Splash(SplashScreen splashScreen)
 {
     InitializeComponent();
     Window.Current.SizeChanged += (s, e) => Resize(splashScreen);
     Resize(splashScreen);
 }
Beispiel #46
0
    //private float m_duration1 = 4.0f;
    //private float m_duration2 = 5.0f;

    public Splash_MAINBACKGROUND(Patterns.FiniteStateMachine fsm, int id, SplashScreen menu)
        : base(fsm, id, menu)
    {
        Name = "Splash_MAINBACKGROUND";
    }
Beispiel #47
0
 public PlayAudio(FSM fsm, SplashScreen splash) : base(fsm)
 {
     m_splash = splash;
 }
Beispiel #48
0
 public Splash_FADEIN(Patterns.FiniteStateMachine fsm, int id, SplashScreen menu)
     : base(fsm, id, menu)
 {
     Name = "Splash_FADEIN";
 }
Beispiel #49
0
        /// <summary>
        /// Bootstraps this instance.
        /// </summary>
        /// <remarks>
        /// Bootstrap flow:
        /// splash
        /// ui setup
        /// loader/core update
        /// tos
        /// auth
        /// update webservice
        /// compile
        /// remoting/injection
        /// </remarks>
        /// <returns></returns>
        private async Task Bootstrap()
        {
            try
            {
                var splash = new SplashScreen("resources/splash.png");
                this.Visibility = Visibility.Hidden;
                splash.Show(false, true);

                this.Browser.Visibility             = Visibility.Hidden;
                this.TosBrowser.Visibility          = Visibility.Hidden;
                this.GeneralSettingsItem.IsSelected = true;

                PropertyDescriptor pd = DependencyPropertyDescriptor.FromProperty(
                    DataGridColumn.ActualWidthProperty,
                    typeof(DataGridColumn));

                foreach (var column in this.InstalledAssembliesDataGrid.Columns)
                {
                    pd.AddValueChanged(column, this.ColumnWidthPropertyChanged);
                }

                this.ColumnCheck.Width    = Config.Instance.ColumnCheckWidth;
                this.ColumnName.Width     = Config.Instance.ColumnNameWidth;
                this.ColumnType.Width     = Config.Instance.ColumnTypeWidth;
                this.ColumnVersion.Width  = Config.Instance.ColumnVersionWidth;
                this.ColumnLocation.Width = Config.Instance.ColumnLocationWidth;

                this.NewsTabItem.Visibility       = Visibility.Hidden;
                this.AssembliesTabItem.Visibility = Visibility.Hidden;
                this.SettingsTabItem.Visibility   = Visibility.Hidden;
                this.AssemblyDB.Visibility        = Visibility.Hidden;

                this.DevMenu.Visibility      = Config.Instance.ShowDevOptions ? Visibility.Visible : Visibility.Collapsed;
                this.Config.PropertyChanged += (o, args) =>
                {
                    if (args.PropertyName == "ShowDevOptions")
                    {
                        this.DevMenu.Visibility = Config.Instance.ShowDevOptions
                                                      ? Visibility.Visible
                                                      : Visibility.Collapsed;
                    }
                };

                await this.CheckForUpdates(true, true, false);

                if (!Config.Instance.TosAccepted)
                {
                    splash.Close(TimeSpan.FromMilliseconds(300));
                    this.Visibility = Visibility.Visible;
                    this.RightWindowCommands.Visibility = Visibility.Collapsed;
                    this.TosButton_OnClick(null, null);
                }
                else
                {
                    this.AssemblyButton_OnClick(null, null);
                }

                // wait for tos accept
                await Task.Factory.StartNew(
                    () =>
                {
                    while (Config.Instance.TosAccepted == false)
                    {
                        Thread.Sleep(100);
                    }
                });

                this.Config.PropertyChanged += this.ConfigOnSearchTextChanged;
                this.UpdateFilters();

                // Try to login with the saved credentials.
                if (!WebService.IsAuthenticated)
                {
                    splash.Close(TimeSpan.FromMilliseconds(300));

                    this.Browser.Visibility    = Visibility.Hidden;
                    this.TosBrowser.Visibility = Visibility.Hidden;

                    this.Visibility = Visibility.Visible;
                    await this.ShowLoginDialog();

                    this.NewsButton_OnClick(null, null);
                }
                else
                {
                    this.OnLogin(Config.Instance.Username);
                }

                if (Config.Instance.FirstRun)
                {
                    Config.SaveAndRestart();
                }

                this.RightWindowCommands.Visibility = Visibility.Visible;

                splash.Close(TimeSpan.FromMilliseconds(300));
                this.Visibility = Visibility.Visible;
                await Updater.UpdateRepositories();

                await Updater.UpdateWebService();

                await this.UpdateAccount();

                Utility.Log(LogStatus.Info, "Update Complete");

                var allAssemblies = new List <LeagueSharpAssembly>();

                foreach (var profile in Config.Instance.Profiles)
                {
                    allAssemblies.AddRange(profile.InstalledAssemblies);
                }

                allAssemblies = allAssemblies.Distinct().ToList();

                GitUpdater.ClearUnusedRepos(allAssemblies);
                await this.PrepareAssemblies(allAssemblies, true, true);

                Utility.Log(LogStatus.Info, "Compile Complete");

                // injection, randomizer, remoting
                this.InitSystem();
                Utility.Log(LogStatus.Info, "System Initialisation Complete");

                this.MainTabControl.SelectedIndex = TAB_ASSEMBLIES;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Bootstrap Error");
            }
        }
Beispiel #50
0
        public static void Show()
        {
            var splash = new SplashScreen(typeof(Splash).Assembly, "Splash.png");

            splash.Show(true);
        }
Beispiel #51
0
 void DismissedEventHandler(SplashScreen sender, object e)
 {
     dismissed = true;
 }
Beispiel #52
0
 /// <summary>
 ///   Load all XNA <see cref = "ContentManager" /> content
 /// </summary>
 /// <param name = "catalogue"></param>
 /// <param name = "manager">XNA content manage</param>
 public void LoadContent(IContentCatalogue catalogue, Microsoft.Xna.Framework.Content.ContentManager manager)
 {
     SplashScreen = new SplashScreen();
     SplashScreen.ShowDuringDevelopment = _showDuringDevelopment;
 }
Beispiel #53
0
        public App()
        {
            initialStartDirectory = Environment.CurrentDirectory;

            SplashScreen splashScreen = new SplashScreen("assets/markdownmonstersplash.png");

            splashScreen.Show(true);

            if (mmApp.Configuration.UseSingleWindow)
            {
                bool isOnlyInstance = false;
                Mutex = new Mutex(true, @"MarkdownMonster", out isOnlyInstance);
                if (!isOnlyInstance)
                {
                    string filesToOpen = " ";
                    var    args        = Environment.GetCommandLineArgs();
                    if (args != null && args.Length > 1)
                    {
                        StringBuilder sb = new StringBuilder();
                        for (int i = 1; i < args.Length; i++)
                        {
                            string file = args[i];

                            // check if file exists and fully qualify to
                            // pass to named pipe
                            if (!File.Exists(file))
                            {
                                file = Path.Combine(initialStartDirectory, file);
                                if (!File.Exists(file))
                                {
                                    file = null;
                                }
                            }

                            if (!string.IsNullOrEmpty(file))
                            {
                                sb.AppendLine(Path.GetFullPath(file));
                            }
                        }
                        filesToOpen = sb.ToString();
                    }
                    var manager = new NamedPipeManager("MarkdownMonster");
                    manager.Write(filesToOpen);

                    splashScreen.Close(TimeSpan.MinValue);

                    // this exits the application
                    Environment.Exit(0);
                }
            }


            AppDomain currentDomain = AppDomain.CurrentDomain;

            currentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
#if !DEBUG
            //AppDomain currentDomain = AppDomain.CurrentDomain;
            //currentDomain.UnhandledException += new UnhandledExceptionEventHandler(GlobalErrorHandler);


            DispatcherUnhandledException += App_DispatcherUnhandledException;
#endif
            mmApp.Started = DateTime.UtcNow;
        }
Beispiel #54
0
        private void ApplicationStart(object sender, StartupEventArgs e)
        {
            // unhandled exception events
            AppDomain.CurrentDomain.UnhandledException +=
                (s, exception) =>
                LogUnhandledException((Exception)exception.ExceptionObject, "AppDomain.CurrentDomain.UnhandledException");

            DispatcherUnhandledException +=
                (s, exception) =>
                LogUnhandledException(exception.Exception, "Application.Current.DispatcherUnhandledException");

            TaskScheduler.UnobservedTaskException +=
                (s, exception) =>
                LogUnhandledException(exception.Exception, "TaskScheduler.UnobservedException");


            /* is the OS x64 or x86? */
            // determine windows install drive letter
            string letter = Path.GetPathRoot(Environment.GetFolderPath(Environment.SpecialFolder.System));

            // test for /Program Files (x86)
            if (Directory.Exists(letter + @"Program Files (x86)"))
            {
                // assume this is x64
                IsX86 = false;
            }
            else
            {
                // assume x86
                IsX86 = true;
            }


            var splashScreen = new SplashScreen(@"Data\Graphics\mediconsplash-new.png");

            splashScreen.Show(false);
            Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;
            // show the initialisation window and begin checks
            ShowInitWindow();
            Thread.Sleep(1000);
            // init should have completed - run MainWindow

            // instantiate GamesList object
            //GamesList = new GameListBuilder();
            GamesLibrary = new GamesLibraryViewModel();

            MainWindow mw = new MedLaunch.MainWindow();

            Current.ShutdownMode           = ShutdownMode.OnMainWindowClose;
            Application.Current.MainWindow = mw;


            //mw.DataContext = _GamesLibraryViewModel;
            mw.Show();

            // instantiate GamesList object
            //GamesList = new GameListBuilder();



            splashScreen.Close(TimeSpan.FromSeconds(1));

            // instantiate ScrapeDB
            //ScrapedData = new ScrapeDB();
            ScrapeDB sdb = new ScrapeDB();



            // set color scheme from database
            Tuple <AppTheme, Accent> appStyle = ThemeManager.DetectAppStyle(Application.Current);

            if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + @"Data\Settings\MedLaunch.db"))
            {
                // database already exists
                var gs = GlobalSettings.GetGlobals();
                ThemeManager.ChangeAppStyle(Application.Current,
                                            ThemeManager.GetAccent(gs.colorAccent),
                                            ThemeManager.GetAppTheme(gs.colorBackground));
            }
            else
            {
                // database hasnt been generated yet - set default
                ThemeManager.ChangeAppStyle(Application.Current,
                                            ThemeManager.GetAccent("Emerald"),
                                            ThemeManager.GetAppTheme("BaseDark"));
            }
        }
Beispiel #55
0
  public static void Main(string[] args)
  {
    Thread.CurrentThread.Name = "MPMain";
    if (args.Length > 0)
    {
      foreach (string arg in args)
      {
        if (arg == "/fullscreen")
        {
          _fullscreenOverride = true;
        }
        if (arg == "/windowed")
        {
          _windowedOverride = true;
        }
        if (arg.StartsWith("/fullscreen="))
        {
          string argValue = arg.Remove(0, 12); // remove /?= from the argument  
          _fullscreenOverride |= argValue != "no";
          _windowedOverride |= argValue.Equals("no");
        }
        if (arg == "/crashtest")
        {
          _mpCrashed = true;
        }
        if (arg.StartsWith("/screen="))
        {
          GUIGraphicsContext._useScreenSelector = true;
          string screenarg = arg.Remove(0, 8); // remove /?= from the argument          
          if (!int.TryParse(screenarg, out _screenNumberOverride))
          {
            _screenNumberOverride = -1;
          }
        }
        if (arg.StartsWith("/skin="))
        {
          string skinOverrideArg = arg.Remove(0, 6); // remove /?= from the argument
          _strSkinOverride = skinOverrideArg;
        }
        if (arg.StartsWith("/config="))
        {
          _alternateConfig = arg.Remove(0, 8); // remove /?= from the argument
          if (!Path.IsPathRooted(_alternateConfig))
          {
            _alternateConfig = Config.GetFile(Config.Dir.Config, _alternateConfig);
          }
        }
        if (arg.StartsWith("/safelist="))
        {
          _safePluginsList = arg.Remove(0, 10); // remove /?= from the argument
        }

#if !DEBUG
        _avoidVersionChecking = false;
        if (arg.ToLowerInvariant() == "/avoidversioncheck")
        {
          _avoidVersionChecking = true;
          Log.Warn("Version check is disabled by command line switch \"/avoidVersionCheck\"");
        }
#endif
      }
    }

    if (string.IsNullOrEmpty(_alternateConfig))
    {
      Log.BackupLogFiles();
    }
    else
    {
      if (File.Exists(_alternateConfig))
      {
        try
        {
          MPSettings.ConfigPathName = _alternateConfig;
          Log.BackupLogFiles();
          Log.Info("Using alternate configuration file: {0}", MPSettings.ConfigPathName);
        }
        catch (Exception ex)
        {
          Log.BackupLogFiles();
          Log.Error("Failed to change to alternate configuration file:");
          Log.Error(ex);
        }
      }
      else
      {
        Log.BackupLogFiles();
        Log.Info("Alternative configuration file was specified but the file was not found: '{0}'", _alternateConfig);
        Log.Info("Using default configuration file instead.");
      }
    }

    if (!Config.DirsFileUpdateDetected)
    {
      //check if mediaportal has been configured
      FileInfo fi = new FileInfo(MPSettings.ConfigPathName);
      if (!File.Exists(MPSettings.ConfigPathName) || (fi.Length < 10000))
      {
        //no, then start configuration.exe in wizard form
        Log.Info("MediaPortal.xml not found. Launching configuration tool and exiting...");
        try
        {
          Process.Start(Config.GetFile(Config.Dir.Base, "configuration.exe"), @"/wizard");
        }
        catch {} // no exception logging needed, since MP is now closed
        return;
      }

      bool autoHideTaskbar = true;
      bool watchdogEnabled = true;
      bool restartOnError = false;
      int restartDelay = 10;
      using (Settings xmlreader = new MPSettings())
      {
        string MPThreadPriority = xmlreader.GetValueAsString("general", "ThreadPriority", "Normal");
        if (MPThreadPriority == "AboveNormal")
        {
          Thread.CurrentThread.Priority = ThreadPriority.AboveNormal;
          Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.AboveNormal;
        }
        else if (MPThreadPriority == "High")
        {
          Thread.CurrentThread.Priority = ThreadPriority.Highest;
          Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;
        }
        else if (MPThreadPriority == "BelowNormal")
        {
          Thread.CurrentThread.Priority = ThreadPriority.BelowNormal;
          Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.BelowNormal;
        }
        autoHideTaskbar = xmlreader.GetValueAsBool("general", "hidetaskbar", false);
        _startupDelay = xmlreader.GetValueAsBool("general", "delay startup", false)
                          ? xmlreader.GetValueAsInt("general", "delay", 0)
                          : 0;
        _waitForTvServer = xmlreader.GetValueAsBool("general", "wait for tvserver", false);
        watchdogEnabled = xmlreader.GetValueAsBool("general", "watchdogEnabled", true);
        restartOnError = xmlreader.GetValueAsBool("general", "restartOnError", false);
        restartDelay = xmlreader.GetValueAsInt("general", "restart delay", 10);        

        GUIGraphicsContext._useScreenSelector |= xmlreader.GetValueAsBool("screenselector", "usescreenselector", false);
      }
#if !DEBUG
      AddExceptionHandler();
      if (watchdogEnabled)
      {
        //StreamWriter sw = new StreamWriter(Application.StartupPath + "\\mediaportal.running", false);
        // BAV: fixing mantis bug 1216: Watcher process uses a wrong folder for integrity file
        using (StreamWriter sw = new StreamWriter(Config.GetFile(Config.Dir.Config, "mediaportal.running"), false))
        {
          sw.WriteLine("running");
          sw.Close();
        }
        Log.Info("Main: Starting MPWatchDog");
        string cmdargs = "-watchdog";
        if (restartOnError)
        {
          cmdargs += " -restartMP " + restartDelay.ToString();
        }
        Process mpWatchDog = new Process();
        mpWatchDog.StartInfo.ErrorDialog = true;
        mpWatchDog.StartInfo.UseShellExecute = true;
        mpWatchDog.StartInfo.WorkingDirectory = Application.StartupPath;
        mpWatchDog.StartInfo.FileName = "WatchDog.exe";
        mpWatchDog.StartInfo.Arguments = cmdargs;
        mpWatchDog.Start();
      }
#endif
      //Log MediaPortal version build and operating system level
      FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(Application.ExecutablePath);

      Log.Info("Main: MediaPortal v" + versionInfo.FileVersion + " is starting up on " +
               OSInfo.OSInfo.GetOSDisplayVersion());
#if DEBUG
      Log.Info("Debug build: " + Application.ProductVersion);
#else
      Log.Info("Build: " + Application.ProductVersion);
#endif

      //Check for unsupported operating systems
      OSPrerequisites.OSPrerequisites.OsCheck(false);

      //Log last install of WindowsUpdate patches
      string LastSuccessTime = "NEVER !!!";
      UIntPtr res = UIntPtr.Zero;

      int options = Convert.ToInt32(Reg.RegistryRights.ReadKey);
      if (OSInfo.OSInfo.Xp64OrLater())
      {
        options = options | Convert.ToInt32(Reg.RegWow64Options.KEY_WOW64_64KEY);
      }
      UIntPtr rKey = new UIntPtr(Convert.ToUInt32(Reg.RegistryRoot.HKLM));
      int lastError = 0;
      int retval = Reg.RegOpenKeyEx(rKey,
                                    "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update\\Results\\Install",
                                    0, options, out res);
      if (retval == 0)
      {
        uint tKey;
        uint lKey = 100;
        System.Text.StringBuilder sKey = new System.Text.StringBuilder((int)lKey);
        retval = Reg.RegQueryValueEx(res, "LastSuccessTime", 0, out tKey, sKey, ref lKey);
        if (retval == 0)
        {
          LastSuccessTime = sKey.ToString();
        }
        else
        {
          lastError = Marshal.GetLastWin32Error();
          Log.Debug("RegQueryValueEx retval=<{0}>, lastError=<{1}>", retval, lastError);
        }
      }
      else
      {
        lastError = Marshal.GetLastWin32Error();
        Log.Debug("RegOpenKeyEx retval=<{0}>, lastError=<{1}>", retval, lastError);
      }
      Log.Info("Main: Last install from WindowsUpdate is dated {0}", LastSuccessTime);

      //Disable "ghosting" for WindowsVista and up
      if (OSInfo.OSInfo.VistaOrLater())
      {
        Log.Debug("Disabling process window ghosting");
        NativeMethods.DisableProcessWindowsGhosting();
      }

      //Start MediaPortal
      Log.Info("Main: Using Directories:");
      foreach (Config.Dir option in Enum.GetValues(typeof (Config.Dir)))
      {
        Log.Info("{0} - {1}", option, Config.GetFolder(option));
      }
      FileInfo mpFi = new FileInfo(Assembly.GetExecutingAssembly().Location);
      Log.Info("Main: Assembly creation time: {0} (UTC)", mpFi.LastWriteTimeUtc.ToUniversalTime());
      using (ProcessLock processLock = new ProcessLock(mpMutex))
      {
        if (processLock.AlreadyExists)
        {
          Log.Warn("Main: MediaPortal is already running");
          Win32API.ActivatePreviousInstance();
        }
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        //Set current directory
        string applicationPath = Application.ExecutablePath;
        applicationPath = Path.GetFullPath(applicationPath);
        applicationPath = Path.GetDirectoryName(applicationPath);
        Directory.SetCurrentDirectory(applicationPath);
        Log.Info("Main: Set current directory to: {0}", applicationPath);

        //Localization strings for new splashscreen and for MediaPortal itself
        LoadLanguageString();

        // Initialize the skin and theme prior to beginning the splash screen thread.  This provides for the splash screen to be used in a theme.
        string strSkin = "";
        try
        {
          using (Settings xmlreader = new MPSettings())
          {
            strSkin = _strSkinOverride.Length > 0 ? _strSkinOverride : xmlreader.GetValueAsString("skin", "name", "Default");
          }
        }
        catch (Exception)
        {
          strSkin = "Default";
        }
        Config.SkinName = strSkin;
        GUIGraphicsContext.Skin = strSkin;
        SkinSettings.Load();

        // Send a message that the skin has changed.
        GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SKIN_CHANGED, 0, 0, 0, 0, 0, null);
        GUIGraphicsContext.SendMessage(msg);

        Log.Info("Main: Skin is {0} using theme {1}", strSkin, GUIThemeManager.CurrentTheme);

#if !DEBUG
        string version = ConfigurationManager.AppSettings["version"];
        //ClientApplicationInfo clientInfo = ClientApplicationInfo.Deserialize("MediaPortal.exe.config");
        splashScreen = new SplashScreen();
        splashScreen.Version = version;
        splashScreen.Run();
        //clientInfo=null;
#endif
        Application.DoEvents();
        if (_waitForTvServer)
        {
          Log.Debug("Main: Wait for TV service requested. Checking if installed...");
          ServiceController ctrl = null;
          try
          {
            ctrl = new ServiceController("TVService");
            string name = ctrl.ServiceName;
          }
          catch (Exception)
          {
            ctrl = null;
            Log.Debug("Main: TV service not installed - proceeding...");
          }
          if (ctrl != null)
          {
            Log.Debug("Main: TV service found. Checking status...");
            if (splashScreen != null)
            {
              splashScreen.SetInformation(GUILocalizeStrings.Get(60)); // Waiting for startup of TV service...
            }
            if (ctrl.Status == ServiceControllerStatus.StartPending || ctrl.Status == ServiceControllerStatus.Stopped)
            {
              if (ctrl.Status == ServiceControllerStatus.StartPending)
              {
                Log.Info("Main: TV service start is pending. Waiting...");
              }
              if (ctrl.Status == ServiceControllerStatus.Stopped)
              {
                Log.Info("Main: TV service is stopped, so we try start it...");
                try
                {
                  ctrl.Start();
                }
                catch (Exception)
                {
                  Log.Info("TvService seems to be already starting up.");
                }
              }
              try
              {
                ctrl.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 45));
              }
              catch (Exception) {}
              if (ctrl.Status == ServiceControllerStatus.Running)
              {
                Log.Info("Main: The TV service has started successfully.");
              }
              else
              {
                Log.Info("Main: Startup of the TV service failed - current status: {0}", ctrl.Status.ToString());
              }
            }
            Log.Info("Main: TV service is in status {0} - proceeding...", ctrl.Status.ToString());
            ctrl.Close();
          }
        }
        Application.DoEvents();
        if (_startupDelay > 0)
        {
          Log.Info("Main: Waiting {0} second(s) before startup", _startupDelay);
          for (int i = _startupDelay; i > 0; i--)
          {
            if (splashScreen != null)
            {
              splashScreen.SetInformation(String.Format(GUILocalizeStrings.Get(61), i.ToString()));
              // Waiting {0} second(s) before startup...
            }
            Application.DoEvents();
            Thread.Sleep(1000);
          }
        }
        Log.Debug("Main: Checking prerequisites");
        try
        {
          // CHECK if DirectX 9.0c if installed
          Log.Debug("Main: Verifying DirectX 9");
          if (!DirectXCheck.IsInstalled())
          {
            string strLine = "Please install a newer DirectX 9.0c redist!\r\n";
            strLine = strLine + "MediaPortal cannot run without DirectX 9.0c redist (August 2008)\r\n";
            strLine = strLine + "http://install.team-mediaportal.com/DirectX";
#if !DEBUG
            if (splashScreen != null)
            {
              splashScreen.Stop();
              splashScreen = null;
            }
#endif
            MessageBox.Show(strLine, "MediaPortal", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return;
          }
          Application.DoEvents();

          // CHECK if Windows MediaPlayer 11 is installed
          string WMP_Main_Ver = "11";
          Log.Debug("Main: Verifying Windows Media Player");

          Version aParamVersion;
          if (FilterChecker.CheckFileVersion(Environment.SystemDirectory + "\\wmp.dll", WMP_Main_Ver + ".0.0000.0000",
                                             out aParamVersion))
          {
            Log.Info("Main: Windows Media Player version {0} installed", aParamVersion);
          }
          else
          {
#if !DEBUG
            if (splashScreen != null)
            {
              splashScreen.Stop();
              splashScreen = null;
            }
#endif
            string strLine = "Please install Windows Media Player " + WMP_Main_Ver + "\r\n";
            strLine = strLine + "MediaPortal cannot run without Windows Media Player " + WMP_Main_Ver;
            MessageBox.Show(strLine, "MediaPortal", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //return;
          }

#if !DEBUG
  // Check TvPlugin version
          string MpExe = Assembly.GetExecutingAssembly().Location;
          string tvPlugin = Config.GetFolder(Config.Dir.Plugins) + "\\Windows\\TvPlugin.dll";
          if (File.Exists(tvPlugin) && !_avoidVersionChecking)
          {
            string tvPluginVersion = FileVersionInfo.GetVersionInfo(tvPlugin).ProductVersion;
            string MpVersion = FileVersionInfo.GetVersionInfo(MpExe).ProductVersion;
            if (MpVersion != tvPluginVersion)
            {
              string strLine = "TvPlugin and MediaPortal don't have the same version.\r\n";
              strLine += "Please update the older component to the same version as the newer one.\r\n";
              strLine += "MediaPortal Version: " + MpVersion + "\r\n";
              strLine += "TvPlugin    Version: " + tvPluginVersion;
              if (splashScreen != null)
              {
                splashScreen.Stop();
                splashScreen = null;
              }
              MessageBox.Show(strLine, "MediaPortal", MessageBoxButtons.OK, MessageBoxIcon.Error);
              Log.Info(strLine);
              return;
            }
          }
#endif
        }
        catch (Exception) {}
        //following crashes on some pc's, dunno why
        //Log.Info("  Stop any known recording processes");
        //Utils.KillExternalTVProcesses();
#if !DEBUG
        try
        {
#endif
        Application.DoEvents();
        if (splashScreen != null)
        {
          splashScreen.SetInformation(GUILocalizeStrings.Get(62)); // Initializing DirectX...
        }

        MediaPortalApp app = new MediaPortalApp();
        Log.Debug("Main: Initializing DirectX");
        if (app.CreateGraphicsSample())
        {
          IMessageFilter filter = new ThreadMessageFilter(app);
          Application.AddMessageFilter(filter);
          // Initialize Input Devices
          if (splashScreen != null)
          {
            splashScreen.SetInformation(GUILocalizeStrings.Get(63)); // Initializing input devices...
          }
          InputDevices.Init();
          try
          {
            //app.PreRun();
            Log.Info("Main: Running");
            GUIGraphicsContext.BlankScreen = false;
            Application.Run(app);
            app.Focus();
            Debug.WriteLine("after Application.Run");
          }
            //#if !DEBUG
          catch (Exception ex)
          {
            Log.Error(ex);
            Log.Error("MediaPortal stopped due to an exception {0} {1} {2}", ex.Message, ex.Source, ex.StackTrace);
            _mpCrashed = true;
          }
            //#endif
          finally
          {
            Application.RemoveMessageFilter(filter);
          }
          app.OnExit();
        }
#if !DEBUG
        }
        catch (Exception ex)
        {
          Log.Error(ex);
          Log.Error("MediaPortal stopped due to an exception {0} {1} {2}", ex.Message, ex.Source, ex.StackTrace);
          _mpCrashed = true;
        }
#endif
#if !DEBUG
        if (splashScreen != null)
        {
          splashScreen.Stop();
          splashScreen = null;
        }
#endif
        Settings.SaveCache();

        if (autoHideTaskbar)
        {
          // only re-show the startbar if MP is the one that has hidden it.
          Win32API.EnableStartBar(true);
          Win32API.ShowStartBar(true);
        }
        if (useRestartOptions)
        {
          Log.Info("Main: Exiting Windows - {0}", restartOptions);
          if (File.Exists(Config.GetFile(Config.Dir.Config, "mediaportal.running")))
          {
            File.Delete(Config.GetFile(Config.Dir.Config, "mediaportal.running"));
          }
          WindowsController.ExitWindows(restartOptions, false);
        }
        else
        {
          if (!_mpCrashed)
          {
            if (File.Exists(Config.GetFile(Config.Dir.Config, "mediaportal.running")))
            {
              File.Delete(Config.GetFile(Config.Dir.Config, "mediaportal.running"));
            }
          }
        }
      }
    }
    else
    {
      string msg =
        "The file MediaPortalDirs.xml has been changed by a recent update in the MediaPortal application directory.\n\n";
      msg += "You have to open the file ";
      msg += Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Team MediaPortal\MediaPortalDirs.xml";
      msg +=
        " with an editor, update it with all changes and SAVE it at least once to start up MediaPortal successfully after this update.\n\n";
      msg += "If you are not using windows user profiles for MediaPortal's configuration management, ";
      msg += "just delete the whole directory mentioned above and reconfigure MediaPortal.";
      string msg2 = "\n\n\nDo you want to open your local file now?";
      Log.Error(msg);
#if !DEBUG
      if (splashScreen != null)
      {
        splashScreen.Stop();
        splashScreen = null;
      }
#endif
      DialogResult result = MessageBox.Show(msg + msg2, "MediaPortal - Update Conflict", MessageBoxButtons.YesNo,
                                            MessageBoxIcon.Stop);
      try
      {
        if (result == DialogResult.Yes)
        {
          Process.Start("notepad.exe",
                        Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +
                        @"\Team MediaPortal\MediaPortalDirs.xml");
        }
      }
      catch (Exception)
      {
        MessageBox.Show(
          "Error opening file " + Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +
          @"\Team MediaPortal\MediaPortalDirs.xml using notepad.exe", "Error", MessageBoxButtons.OK,
          MessageBoxIcon.Error);
      }
    }
    Environment.Exit(0);
  }
Beispiel #56
0
 public LoadingSplash()
 {
     _splash = new SplashScreen(Assembly.GetAssembly(typeof(LoadingSplash)), "loading.png");
     _splash.Show(false, true);
 }
Beispiel #57
0
        protected override void OnStartup(StartupEventArgs e)
        {
            if (e.Args.Contains("WAIT"))
            {
                Thread.Sleep(5000);
            }

            SplashScreen appSplash = null;

            Fap.Foundation.SafeObservableStatic.Dispatcher = System.Windows.Application.Current.Dispatcher;
            SafeObservingCollectionManager.Start();
            this.DispatcherUnhandledException += new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);
            FrameworkElement.LanguageProperty.OverrideMetadata(typeof(FrameworkElement), new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));

            base.OnStartup(e);
            if (Compose())
            {
                if (e.Args.Length == 1 && e.Args[0] == "WAIT")
                {
                    //Delay the application starting up, used when restarting.
                    Thread.Sleep(3000);
                }

                ApplicationCore core = container.Resolve <ApplicationCore>();

                if (!core.CheckSingleInstance())
                {
                    //An instance of fap is already running.

                    //If we got a download url then forward onto the runing instance of FAP
                    if (e.Args.Length == 2 && e.Args[0] == "-url")
                    {
                        Model model = new Model();
                        model.Load();

                        Client      client = new Client(model.LocalNode);
                        AddDownload verb   = new AddDownload();
                        verb.URL = e.Args[1];
                        if (client.Execute(verb, model.LocalNode))
                        {
                            //Download sent successfully
                            Shutdown(0);
                            return;
                        }
                        else
                        {
                            //Unsuccessful - Notify user
                            WPFMessageBox.Show("FAP", "Failed to add download via RPC!");
                            Shutdown(1);
                            return;
                        }
                    }
                    else
                    {
                        //Inform the user they cannot run multiple instances
                        WPFMessageBox.Show("FAP", "An instance of FAP is already running");
                        Shutdown(1);
                        return;
                    }
                }

                string img = GetImage();
                appSplash = new SplashScreen(img);
                appSplash.Show(true);

                if (core.Load(false))
                {
                    core.StartClient();
                    core.StartGUI(!(e.Args.Contains("STARTUP")));
                    //Was a url passed on startup?
                    if (e.Args.Length == 2 && e.Args[0] == "-url")
                    {
                        core.AddDownloadUrlWhenConnected(e.Args[1]);
                    }
                }
                else
                {
                    Shutdown(1);
                }
            }
            else
            {
                Shutdown(1);
            }
            if (null != appSplash)
            {
                appSplash.Close(TimeSpan.FromSeconds(0));
            }
        }
Beispiel #58
0
 private void OnSplashScreenDismissed(SplashScreen sender, object args)
 {
     splashScreen.Dismissed -= OnSplashScreenDismissed;
     dismissed = true;
 }
Beispiel #59
0
  public static void Main(string[] args)
  {
    Thread.CurrentThread.Name = "MPMain";

    #if !DEBUG
    // TODO: work on the handlers to take over more Watchdog capabilities, current use for Area51 builds as needed only
    //AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
    //Application.ThreadException += OnThreadException;
    #endif  

    SkinOverride         = string.Empty;
    WindowedOverride     = false;
    FullscreenOverride   = false;
    ScreenNumberOverride = -1;

    if (args.Length > 0)
    {
      foreach (string arg in args)
      {
        if (arg == "/fullscreen")
        {
          FullscreenOverride = true;
        }

        if (arg == "/windowed")
        {
          WindowedOverride = true;
        }

        if (arg.StartsWith("/fullscreen="))
        {
          string argValue = arg.Remove(0, 12); // remove /?= from the argument  
          FullscreenOverride |= argValue != "no";
          WindowedOverride |= argValue.Equals("no");
        }

        if (arg == "/crashtest")
        {
          _mpCrashed = true;
        }

        if (arg.StartsWith("/screen="))
        {
          string screenarg = arg.Remove(0, 8); // remove /?= from the argument          
          if (!int.TryParse(screenarg, out ScreenNumberOverride))
          {
            ScreenNumberOverride = -1;
          }
        }

        if (arg.StartsWith("/skin="))
        {
          string skinOverrideArg = arg.Remove(0, 6); // remove /?= from the argument
          SkinOverride = skinOverrideArg;
        }

        if (arg.StartsWith("/config="))
        {
          _alternateConfig = arg.Remove(0, 8); // remove /?= from the argument
          if (!Path.IsPathRooted(_alternateConfig))
          {
            _alternateConfig = Config.GetFile(Config.Dir.Config, _alternateConfig);
          }
        }

        if (arg.StartsWith("/safelist="))
        {
          _safePluginsList = arg.Remove(0, 10); // remove /?= from the argument
        }

        #if !DEBUG
        _avoidVersionChecking = arg.ToLowerInvariant() == "/avoidversioncheck";
        #endif
      }
    }

    // check if MediaPotal is already running
    using (var processLock = new ProcessLock(MPMutex))
    {
      if (processLock.AlreadyExists)
      {
        Log.Warn("Main: MediaPortal is already running");
        Win32API.ActivatePreviousInstance();
      }
    }
   
    if (string.IsNullOrEmpty(_alternateConfig))
    {
      Log.BackupLogFiles();
    }
    else
    {
      if (File.Exists(_alternateConfig))
      {
        try
        {
          MPSettings.ConfigPathName = _alternateConfig;
          Log.BackupLogFiles();
          Log.Info("Using alternate configuration file: {0}", MPSettings.ConfigPathName);
        }
        catch (Exception ex)
        {
          Log.BackupLogFiles();
          Log.Error("Failed to change to alternate configuration file:");
          Log.Error(ex);
        }
      }
      else
      {
        Log.BackupLogFiles();
        Log.Info("Alternative configuration file was specified but the file was not found: '{0}'", _alternateConfig);
        Log.Info("Using default configuration file instead.");
      }
    }

    if (!Config.DirsFileUpdateDetected)
    {
      // check if Mediaportal has been configured
      var fi = new FileInfo(MPSettings.ConfigPathName);
      if (!File.Exists(MPSettings.ConfigPathName) || (fi.Length < 10000))
      {
        // no, then start configuration.exe in wizard form
        Log.Info("MediaPortal.xml not found. Launching configuration tool and exiting...");
        try
        {
          Process.Start(Config.GetFile(Config.Dir.Base, "configuration.exe"), @"/wizard");
        }
        // ReSharper disable EmptyGeneralCatchClause
        catch {} // no exception logging needed, since MP is now closed
        // ReSharper restore EmptyGeneralCatchClause
        return;
      }

      // TODO: check if config is valid. If you create a config file > 10000 bytes full of spaces MP will crash as Utils.dll does nearly no error checking

      using (Settings xmlreader = new MPSettings())
      {
        string threadPriority = xmlreader.GetValueAsString("general", "ThreadPriority", "Normal");
        switch (threadPriority)
        {
          case "AboveNormal":
            Thread.CurrentThread.Priority = ThreadPriority.AboveNormal;
            Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.AboveNormal;
            break;
          case "High":
            Thread.CurrentThread.Priority = ThreadPriority.Highest;
            Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;
            break;
          case "BelowNormal":
            Thread.CurrentThread.Priority = ThreadPriority.BelowNormal;
            Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.BelowNormal;
            break;
        }
        _startupDelay    = xmlreader.GetValueAsBool("general", "delay startup", false) ? xmlreader.GetValueAsInt("general", "delay", 0): 0;
        _waitForTvServer = xmlreader.GetValueAsBool("general", "wait for tvserver", false);
      }

      #if !DEBUG
      bool watchdogEnabled;
      bool restartOnError;
      int restartDelay;
      using (Settings xmlreader = new MPSettings())
      {
        watchdogEnabled = xmlreader.GetValueAsBool("general", "watchdogEnabled", true);
        restartOnError  = xmlreader.GetValueAsBool("general", "restartOnError", false);
        restartDelay    = xmlreader.GetValueAsInt("general", "restart delay", 10);        
      }

      AddExceptionHandler();
      if (watchdogEnabled)
      {
        using (var sw = new StreamWriter(Config.GetFile(Config.Dir.Config, "mediaportal.running"), false))
        {
          sw.WriteLine("running");
          sw.Close();
        }

        Log.Info("Main: Starting MPWatchDog");
        string cmdargs = "-watchdog";
        if (restartOnError)
        {
          cmdargs += " -restartMP " + restartDelay.ToString(CultureInfo.InvariantCulture);
        }
        var mpWatchDog = new Process
                           {
                             StartInfo =
                               {
                                 ErrorDialog      = true,
                                 UseShellExecute  = true,
                                 WorkingDirectory = Application.StartupPath,
                                 FileName         = "WatchDog.exe",
                                 Arguments        = cmdargs
                               }
                           };
        mpWatchDog.Start();
      }
      #endif

      // Log MediaPortal version build and operating system level
      FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(Application.ExecutablePath);

      Log.Info("Main: MediaPortal v" + versionInfo.FileVersion + " is starting up on " + OSInfo.OSInfo.GetOSDisplayVersion());

      #if DEBUG
      Log.Info("Debug Build: " + Application.ProductVersion);
      #else
      Log.Info("Build: " + Application.ProductVersion);
      #endif

      // setting minimum worker threads
      int minWorker, minIOC;
      ThreadPool.GetMinThreads(out minWorker, out minIOC);
      ThreadPool.SetMinThreads(minWorker * 2, minIOC * 1);
      ThreadPool.GetMinThreads(out minWorker, out minIOC);
      Log.Info("Main: Minimum number of worker threads to {0}/{1}", minWorker, minIOC);

      // Check for unsupported operating systems
      OSPrerequisites.OSPrerequisites.OsCheck(false);

      // Log last install of WindowsUpdate patches
      string lastSuccessTime = "NEVER !!!";
      UIntPtr res;

      int options = Convert.ToInt32(Reg.RegistryRights.ReadKey);
      if (OSInfo.OSInfo.Xp64OrLater())
      {
        options = options | Convert.ToInt32(Reg.RegWow64Options.KEY_WOW64_64KEY);
      }
      var rKey = new UIntPtr(Convert.ToUInt32(Reg.RegistryRoot.HKLM));
      int lastError;
      int retval = Reg.RegOpenKeyEx(rKey, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update\\Results\\Install", 0, options, out res);
      if (retval == 0)
      {
        uint tKey;
        uint lKey = 100;
        var sKey = new StringBuilder((int)lKey);
        retval = Reg.RegQueryValueEx(res, "LastSuccessTime", 0, out tKey, sKey, ref lKey);
        if (retval == 0)
        {
          lastSuccessTime = sKey.ToString();
        }
        else
        {
          lastError = Marshal.GetLastWin32Error();
          Log.Debug("RegQueryValueEx retval=<{0}>, lastError=<{1}>", retval, lastError);
        }
      }
      else
      {
        lastError = Marshal.GetLastWin32Error();
        Log.Debug("RegOpenKeyEx retval=<{0}>, lastError=<{1}>", retval, lastError);
      }
      Log.Info("Main: Last install from WindowsUpdate is dated {0}", lastSuccessTime);

      Log.Debug("Disabling process window ghosting");
      DisableProcessWindowsGhosting();

      // Start MediaPortal
      Log.Info("Main: Using Directories:");
      foreach (Config.Dir option in Enum.GetValues(typeof (Config.Dir)))
      {
        Log.Info("{0} - {1}", option, Config.GetFolder(option));
      }

      var mpFi = new FileInfo(Assembly.GetExecutingAssembly().Location);
      Log.Info("Main: Assembly creation time: {0} (UTC)", mpFi.LastWriteTimeUtc.ToUniversalTime());

      #pragma warning disable 168
      using (var processLock = new ProcessLock(MPMutex))
      #pragma warning restore 168
      {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        // Set current directory
        string applicationPath = Application.ExecutablePath;
        applicationPath = Path.GetFullPath(applicationPath);
        applicationPath = Path.GetDirectoryName(applicationPath);
        if (!String.IsNullOrEmpty(applicationPath))
        {
          Directory.SetCurrentDirectory(applicationPath);
          Log.Info("Main: Set current directory to: {0}", applicationPath);
        }
        else
        {
          Log.Error("Main: Cannot set current directory to {0}", applicationPath);
        }

        // log  about available displays
        foreach (var screen in Screen.AllScreens)
        {
          Log.Debug("Display: {0} - IsPrimary: {1} - BitsPerPixel: {2} - Bounds: {3}x{4} @ {5},{6} - WorkingArea: {7}x{8} @ {9},{10}",
            GetCleanDisplayName(screen), screen.Primary, screen.BitsPerPixel,
            screen.Bounds.Width, screen.Bounds.Height, screen.Bounds.X, screen.Bounds.Y,
            screen.WorkingArea.Width, screen.WorkingArea.Height, screen.WorkingArea.X, screen.WorkingArea.Y);
        }

        // log information about available adapters
        var enumeration = new D3DEnumeration();
        enumeration.Enumerate();
        foreach (GraphicsAdapterInfo ai in enumeration.AdapterInfoList)
        {
          Log.Debug("Adapter #{0}: {1} - Driver: {2} ({3}) - DeviceName: {4}",
            ai.AdapterOrdinal, ai.AdapterDetails.Description, ai.AdapterDetails.DriverName, ai.AdapterDetails.DriverVersion, ai.AdapterDetails.DeviceName);
        }

        // Localization strings for new splash screen and for MediaPortal itself
        LoadLanguageString();

        // Initialize the skin and theme prior to beginning the splash screen thread.  This provides for the splash screen to be used in a theme.
        string skin;
        try
        {
          using (Settings xmlreader = new MPSettings())
          {
            skin = string.IsNullOrEmpty(SkinOverride) ? xmlreader.GetValueAsString("skin", "name", "Default") : SkinOverride;
          }
        }
        catch (Exception)
        {
           skin = "Default";
        }

        Config.SkinName = skin;
        GUIGraphicsContext.Skin = skin;
        SkinSettings.Load();

        // Send a message that the skin has changed.
        var msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SKIN_CHANGED, 0, 0, 0, 0, 0, null);
        GUIGraphicsContext.SendMessage(msg);

        Log.Info("Main: Skin is {0} using theme {1}", skin, GUIThemeManager.CurrentTheme);

        // Start Splash Screen
        string version = ConfigurationManager.AppSettings["version"];
        SplashScreen = new SplashScreen {Version = version};

        #if !DEBUG
        SplashScreen.Run();
        #endif

        Application.DoEvents(); // process message queue
        
        if (_waitForTvServer)
        {
          Log.Debug("Main: Wait for TV service requested");
          ServiceController ctrl;
          try
          {
            ctrl = new ServiceController("TVService");
          }
          catch (Exception)
          {
            ctrl = null;
            Log.Debug("Main: Create ServiceController for TV service failed - proceeding...");
          }

          if (ctrl != null)
          {
            //Sanity check for existance of TV service
            ServiceControllerStatus status = ServiceControllerStatus.Stopped;
            try
            {
              status = ctrl.Status;
            }
            catch (Exception)
            {
              Log.Debug("Main: Failed to retrieve TV service status");
              ctrl.Close();
              ctrl = null;
            }
          }

          if (ctrl != null)
          {
            Log.Debug("Main: TV service found. Checking status...");
            UpdateSplashScreenMessage(GUILocalizeStrings.Get(60)); // Waiting for startup of TV service...
            if (ctrl.Status == ServiceControllerStatus.StartPending || ctrl.Status == ServiceControllerStatus.Stopped)
            {
              if (ctrl.Status == ServiceControllerStatus.StartPending)
              {
                Log.Info("Main: TV service start is pending. Waiting...");
              }

              if (ctrl.Status == ServiceControllerStatus.Stopped)
              {
                Log.Info("Main: TV service is stopped, so we try start it...");
                try
                {
                  ctrl.Start();
                }
                catch (Exception)
                {
                  Log.Info("TvService seems to be already starting up.");
                }
              }

              try
              {
                ctrl.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 45));
              }
              // ReSharper disable EmptyGeneralCatchClause
              catch (Exception) {}
              // ReSharper restore EmptyGeneralCatchClause
              
              if (ctrl.Status == ServiceControllerStatus.Running)
              {
                Log.Info("Main: The TV service has started successfully.");
              }
              else
              {
                Log.Info("Main: Startup of the TV service failed - current status: {0}", ctrl.Status.ToString());
              }
            }
            Log.Info("Main: TV service is in status {0} - proceeding...", ctrl.Status.ToString());
            ctrl.Close();
          }
        }

        Application.DoEvents(); // process message queue

        if (_startupDelay > 0)
        {
          Log.Info("Main: Waiting {0} second(s) before startup", _startupDelay);
          for (int i = _startupDelay; i > 0; i--)
          {
            UpdateSplashScreenMessage(String.Format(GUILocalizeStrings.Get(61), i.ToString(CultureInfo.InvariantCulture)));
            Thread.Sleep(1000);
            Application.DoEvents();
          }
        }

        Log.Debug("Main: Checking prerequisites");
        try
        {
          // check if DirectX 9.0c if installed
          Log.Debug("Main: Verifying DirectX 9");
          if (!DirectXCheck.IsInstalled())
          {
            DisableSplashScreen();
            string strLine = "Please install a newer DirectX 9.0c redist!\r\n";
            strLine = strLine + "MediaPortal cannot run without DirectX 9.0c redist (August 2008)\r\n";
            strLine = strLine + "http://install.team-mediaportal.com/DirectX";
            // ReSharper disable LocalizableElement
            MessageBox.Show(strLine, "MediaPortal", MessageBoxButtons.OK, MessageBoxIcon.Error);
            // ReSharper restore LocalizableElement
            return;
          }

          Application.DoEvents(); // process message queue

          #if !DEBUG
          // Check TvPlugin version
          string mpExe    = Assembly.GetExecutingAssembly().Location;
          string tvPlugin = Config.GetFolder(Config.Dir.Plugins) + "\\Windows\\TvPlugin.dll";
          if (File.Exists(tvPlugin) && !_avoidVersionChecking)
          {
            string tvPluginVersion = FileVersionInfo.GetVersionInfo(tvPlugin).ProductVersion;
            string mpVersion       = FileVersionInfo.GetVersionInfo(mpExe).ProductVersion;

            if (mpVersion != tvPluginVersion)
            {
              string strLine = "TvPlugin and MediaPortal don't have the same version.\r\n";
              strLine       += "Please update the older component to the same version as the newer one.\r\n";
              strLine       += "MediaPortal Version: " + mpVersion + "\r\n";
              strLine       += "TvPlugin    Version: " + tvPluginVersion;
              DisableSplashScreen();
              // ReSharper disable LocalizableElement
              MessageBox.Show(strLine, "MediaPortal", MessageBoxButtons.OK, MessageBoxIcon.Error);
              // ReSharper restore LocalizableElement
              Log.Info(strLine);
              return;
            }
          }
          #endif

        }
        // ReSharper disable EmptyGeneralCatchClause
        catch (Exception) {}
        // ReSharper restore EmptyGeneralCatchClause

        Application.DoEvents(); // process message queue
        
        try
        {
          UpdateSplashScreenMessage(GUILocalizeStrings.Get(62));
          Log.Debug("Main: Initializing DirectX");

          var app = new MediaPortalApp();
          if (app.Init())
          {
            try
            {
              Log.Info("Main: Running");
              GUIGraphicsContext.BlankScreen = false;
              Application.Run(app);
              app.Focus();
            }
            catch (Exception ex)
            {
              Log.Error(ex);
              Log.Error("MediaPortal stopped due to an exception {0} {1} {2}", ex.Message, ex.Source, ex.StackTrace);
              _mpCrashed = true;
            }
            app.OnExit();
          }

        }
        catch (Exception ex)
        {
          Log.Error(ex);
          Log.Error("MediaPortal stopped due to an exception {0} {1} {2}", ex.Message, ex.Source, ex.StackTrace);
          _mpCrashed = true;
        }

        DisableSplashScreen();
        
        Settings.SaveCache();

        // only re-show the task bar if MP is the one that has hidden it.
        using (Settings xmlreader = new MPSettings())
        {
          if (xmlreader.GetValueAsBool("general", "hidetaskbar", false))
          {
            HideTaskBar(false);
          }
        }

        if (_useRestartOptions)
        {
          Log.Info("Main: Exiting Windows - {0}", _restartOptions);
          if (File.Exists(Config.GetFile(Config.Dir.Config, "mediaportal.running")))
          {
            File.Delete(Config.GetFile(Config.Dir.Config, "mediaportal.running"));
          }
          WindowsController.ExitWindows(_restartOptions, false);
        }
        else
        {
          if (!_mpCrashed && File.Exists(Config.GetFile(Config.Dir.Config, "mediaportal.running")))
          {
            File.Delete(Config.GetFile(Config.Dir.Config, "mediaportal.running"));
          }
        }
      }
    }
    else
    {
      DisableSplashScreen();
      string msg = "The file MediaPortalDirs.xml has been changed by a recent update in the MediaPortal application directory.\n\n";
      msg       += "You have to open the file ";
      msg       += Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Team MediaPortal\MediaPortalDirs.xml";
      msg       += " with an editor, update it with all changes and SAVE it at least once to start up MediaPortal successfully after this update.\n\n";
      msg       += "If you are not using windows user profiles for MediaPortal's configuration management, ";
      msg       += "just delete the whole directory mentioned above and reconfigure MediaPortal.";
      msg       += "\n\n\n";
      msg       += "Do you want to open your local file now?";
      Log.Error(msg);
      
      // ReSharper disable LocalizableElement
      DialogResult result = MessageBox.Show(msg, "MediaPortal - Update Conflict", MessageBoxButtons.YesNo, MessageBoxIcon.Stop);
      // ReSharper restore LocalizableElement
      try
      {
        if (result == DialogResult.Yes)
        {
          Process.Start("notepad.exe",
                        Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +
                        @"\Team MediaPortal\MediaPortalDirs.xml");
        }
      }
      catch (Exception)
      {
        // ReSharper disable LocalizableElement
        MessageBox.Show(
          "Error opening file " + Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +
          @"\Team MediaPortal\MediaPortalDirs.xml using notepad.exe", "Error", MessageBoxButtons.OK,
          MessageBoxIcon.Error);
        // ReSharper restore LocalizableElement
      }
    }
    Environment.Exit(0);
  }
 public MainMenuState_FADEOUT(Patterns.FiniteStateMachine fsm, int id, SplashScreen menu)
     : base(fsm, id, menu)
 {
     Name = "MainMenuState_FADEOUT";
 }