Ejemplo n.º 1
0
    public GUIErosion(GUIManager gm)
    {
        this.gm = gm;
        message = gm.message;

        menuWidth = gm.menuWidth;
        rightMenuOffset = gm.rightOffset;
        topOffset = gm.topOffset;
        buttonHeight = gm.smallButtonHeight;
        sideOffset = 10;
        buttonWidth = menuWidth / 2 - sideOffset - sideOffset / 2;
        smallButtonWidth = buttonWidth / 2;

        windStrength = 50;
        windEffect = 0.5f;
    }
Ejemplo n.º 2
0
  private void OnAction(Action action)
  {
    try
    {
      // hack/fix for lastactivemodulefullscreen
      // when recovering from hibernation/standby after closing with remote control somehow a F9 (keycode 120) onkeydown event is thrown from outside
      // we are currently filtering it away.
      // sometimes more than one F9 keydown event fired.
      // if these events are not filtered away the F9 context menu is shown on the restored/shown module.
      if ((action.wID == Action.ActionType.ACTION_CONTEXT_MENU || _suspended) && (showLastActiveModule))
      {
        //Log.Info("ACTION_CONTEXT_MENU, ignored = {0}, suspended = {1}", ignoreContextMenuAction, _suspended);      
        if (ignoreContextMenuAction)
        {
          ignoreContextMenuAction = false;
          lastContextMenuAction = DateTime.Now;
          return;
        }
        else if (lastContextMenuAction != DateTime.MaxValue)
        {
          TimeSpan ts = lastContextMenuAction - DateTime.Now;
          if (ts.TotalMilliseconds > -100)
          {
            ignoreContextMenuAction = false;
            lastContextMenuAction = DateTime.Now;
            return;
          }
        }
        lastContextMenuAction = DateTime.Now;
      }

      GUIWindow window;
      if (action.IsUserAction())
      {
        GUIGraphicsContext.ResetLastActivity();
      }
      switch (action.wID)
      {
          // record current tv program
        case Action.ActionType.ACTION_RECORD:
          if ((GUIGraphicsContext.IsTvWindow(GUIWindowManager.ActiveWindowEx) &&
               GUIWindowManager.ActiveWindowEx != (int)GUIWindow.Window.WINDOW_TVGUIDE) &&
              (GUIWindowManager.ActiveWindowEx != (int)GUIWindow.Window.WINDOW_DIALOG_TVGUIDE))
          {
            GUIWindow tvHome = GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_TV);
            if (tvHome != null)
            {
              if (tvHome.GetID != GUIWindowManager.ActiveWindow)
              {
                tvHome.OnAction(action);
                return;
              }
            }
          }
          break;

          //TV: zap to previous channel
        case Action.ActionType.ACTION_PREV_CHANNEL:
          if (!GUIWindowManager.IsRouted)
          {
            window = GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_TV);
            window.OnAction(action);
            return;
          }
          break;

          //TV: zap to next channel
        case Action.ActionType.ACTION_NEXT_CHANNEL:
          if (!GUIWindowManager.IsRouted)
          {
            window = GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_TV);
            window.OnAction(action);
            return;
          }
          break;

          //TV: zap to last channel viewed
        case Action.ActionType.ACTION_LAST_VIEWED_CHANNEL: // mPod
          if (!GUIWindowManager.IsRouted)
          {
            window = GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_TV);
            window.OnAction(action);
            return;
          }
          break;

          //toggle between directx windowed and exclusive mode
        case Action.ActionType.ACTION_TOGGLE_WINDOWED_FULLSCREEN:
          ToggleFullWindowed();
          return;
          //break;

          //mute or unmute audio
        case Action.ActionType.ACTION_VOLUME_MUTE:
          VolumeHandler.Instance.IsMuted = !VolumeHandler.Instance.IsMuted;
          break;

          //decrease volume 
        case Action.ActionType.ACTION_VOLUME_DOWN:
          VolumeHandler.Instance.Volume = VolumeHandler.Instance.Previous;
          break;

          //increase volume 
        case Action.ActionType.ACTION_VOLUME_UP:
          VolumeHandler.Instance.Volume = VolumeHandler.Instance.Next;
          break;

          //toggle live tv in background
        case Action.ActionType.ACTION_BACKGROUND_TOGGLE:
          //show livetv or video as background instead of the static GUI background
          // toggle livetv/video in background on/pff
          if (GUIGraphicsContext.ShowBackground)
          {
            Log.Info("Main: Using live TV as background");
            // if on, but we're not playing any video or watching tv
            if (GUIGraphicsContext.Vmr9Active)
            {
              GUIGraphicsContext.ShowBackground = false;
              //GUIGraphicsContext.Overlay = false;
            }
            else
            {
              //show warning message
              GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SHOW_WARNING, 0, 0, 0, 0, 0, 0);
              msg.Param1 = 727; //Live tv in background
              msg.Param2 = 728; //No Video/TV playing
              msg.Param3 = 729; //Make sure that something is playing
              GUIWindowManager.SendMessage(msg);
              return;
            }
          }
          else
          {
            Log.Info("Main: Using GUI as background");
            GUIGraphicsContext.ShowBackground = true;
            //GUIGraphicsContext.Overlay = true;
          }
          return;

          //switch between several home windows
        case Action.ActionType.ACTION_SWITCH_HOME:
          GUIMessage homeMsg;
          GUIWindow.Window newHome = _startWithBasicHome
                                       ? GUIWindow.Window.WINDOW_SECOND_HOME
                                       : GUIWindow.Window.WINDOW_HOME;
          // do we prefer to use only one home screen?
          if (_useOnlyOneHome)
          {
            // skip if we are already in there
            if (GUIWindowManager.ActiveWindow == (int)newHome)
            {
              return;
            }
          }
            // we like both 
          else
          {
            // if already in one home switch to the other
            if (GUIWindowManager.ActiveWindow == (int)GUIWindow.Window.WINDOW_HOME)
            {
              newHome = GUIWindow.Window.WINDOW_SECOND_HOME;
            }
            else if (GUIWindowManager.ActiveWindow == (int)GUIWindow.Window.WINDOW_SECOND_HOME)
            {
              newHome = GUIWindow.Window.WINDOW_HOME;
            }
          }
          homeMsg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_GOTO_WINDOW, 0, 0, 0, (int)newHome, 0, null);
          GUIWindowManager.SendThreadMessage(homeMsg);
          return;

          //exit mediaportal
        case Action.ActionType.ACTION_EXIT:
          Log.Info("Main: Exit requested");
          // is the minimize on gui option set?  If so, minimize to tray...
          if (_minimizeOnGuiExit && !_shuttingDown)
          {
            if (WindowState != FormWindowState.Minimized)
            {
              Log.Info("Main: Minimizing to tray on GUI exit and restoring taskbar");
            }
            WindowState = FormWindowState.Minimized;
            Hide();
            if (autoHideTaskbar)
            {
              // only re-show the startbar if MP is the one that has hidden it.
              Win32API.EnableStartBar(true);
              Win32API.ShowStartBar(true);
            }
            if (g_Player.IsVideo || g_Player.IsTV || g_Player.IsDVD)
            {
              if (g_Player.Volume > 0)
              {
                m_iVolume = g_Player.Volume;
                g_Player.Volume = 0;
              }
              if (g_Player.Paused == false && !GUIGraphicsContext.IsVMR9Exclusive)
              {
                g_Player.Pause();
              }
            }
            return;
          }
          GUIGraphicsContext.CurrentState = GUIGraphicsContext.State.STOPPING;
          return;

        case Action.ActionType.ACTION_MPRESTORE:
          {
            Log.Info("Main: Restore MP by action");
            Restore();
            if ((g_Player.IsVideo || g_Player.IsTV || g_Player.IsDVD) && m_iVolume > 0)
            {
              g_Player.Volume = m_iVolume;
              g_Player.ContinueGraph();
              if (g_Player.Paused && !GUIGraphicsContext.IsVMR9Exclusive)
              {
                g_Player.Pause();
              }
            }
          }
          return;

          //reboot pc
        case Action.ActionType.ACTION_POWER_OFF:
        case Action.ActionType.ACTION_SUSPEND:
        case Action.ActionType.ACTION_HIBERNATE:
        case Action.ActionType.ACTION_REBOOT:
          {
            //reboot
            Log.Info("Main: Reboot requested");
            bool okToChangePowermode = (action.fAmount1 == 1);

            if (!okToChangePowermode)
            {
              okToChangePowermode = PromptUserBeforeChangingPowermode(action);
            }

            if (okToChangePowermode)
            {
              switch (action.wID)
              {
                case Action.ActionType.ACTION_REBOOT:
                  restartOptions = RestartOptions.Reboot;
                  useRestartOptions = true;
                  GUIGraphicsContext.CurrentState = GUIGraphicsContext.State.STOPPING;
                  break;

                case Action.ActionType.ACTION_POWER_OFF:
                  restartOptions = RestartOptions.PowerOff;
                  useRestartOptions = true;
                  GUIGraphicsContext.CurrentState = GUIGraphicsContext.State.STOPPING;
                  base._shuttingDown = true;
                  break;

                case Action.ActionType.ACTION_SUSPEND:
                  if (IsSuspendOrHibernationAllowed())
                  {
                    restartOptions = RestartOptions.Suspend;
                    Utils.SuspendSystem(false);
                  }
                  else
                  {
                    Log.Info("Main: SUSPEND ignored since suspend graceperiod of {0} sec. is violated.", _suspendGracePeriodSec); 
                  }
                  break;

                case Action.ActionType.ACTION_HIBERNATE:
                  if (IsSuspendOrHibernationAllowed())
                  {
                    restartOptions = RestartOptions.Hibernate;
                    Utils.HibernateSystem(false);
                  }
                  else
                  {
                    Log.Info("Main: HIBERNATE ignored since hibernate graceperiod of {0} sec. is violated.", _suspendGracePeriodSec);
                  }
                  break;
              }
            }
          }
          return;

          //eject cd
        case Action.ActionType.ACTION_EJECTCD:
          Utils.EjectCDROM();
          return;

          //shutdown pc
        case Action.ActionType.ACTION_SHUTDOWN:
          {
            Log.Info("Main: Shutdown dialog");
            GUIDialogMenu dlg = (GUIDialogMenu)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_MENU);
            if (dlg != null)
            {
              dlg.Reset();
              dlg.SetHeading(GUILocalizeStrings.Get(498)); //Menu
              dlg.AddLocalizedString(1030); //PowerOff
              dlg.AddLocalizedString(1031); //Reboot
              dlg.AddLocalizedString(1032); //Suspend
              dlg.AddLocalizedString(1049); //Hibernate
              dlg.DoModal(GUIWindowManager.ActiveWindow);
              //RestartOptions option = RestartOptions.Suspend;
              if (dlg.SelectedId < 0)
              {
                GUIWindow win = GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_HOME);
                if (win != null)
                {
                  win.OnAction(new Action(Action.ActionType.ACTION_MOVE_LEFT, 0, 0));
                }
                return;
              }
              switch (dlg.SelectedId)
              {
                case 1030:
                  restartOptions = RestartOptions.PowerOff;
                  useRestartOptions = true;
                  GUIGraphicsContext.CurrentState = GUIGraphicsContext.State.STOPPING;
                  base._shuttingDown = true;
                  break;

                case 1031:
                  restartOptions = RestartOptions.Reboot;
                  useRestartOptions = true;
                  GUIGraphicsContext.CurrentState = GUIGraphicsContext.State.STOPPING;
                  base._shuttingDown = true;
                  break;

                case 1032:
                  restartOptions = RestartOptions.Suspend;
                  Utils.SuspendSystem(false);
                  break;

                case 1049:
                  restartOptions = RestartOptions.Hibernate;
                  Utils.HibernateSystem(false);
                  break;
              }
            }
            break;
          }

          //stop radio
        case Action.ActionType.ACTION_STOP:
          break;

          // Take Screenshot
        case Action.ActionType.ACTION_TAKE_SCREENSHOT:
          {
            try
            {
              string directory =
                string.Format("{0}\\MediaPortal Screenshots\\{1:0000}-{2:00}-{3:00}",
                              Environment.GetFolderPath(Environment.SpecialFolder.MyPictures),
                              DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
              if (!Directory.Exists(directory))
              {
                Log.Info("Main: Taking screenshot - Creating directory: {0}", directory);
                Directory.CreateDirectory(directory);
              }

              string fileName =
                string.Format("{0}\\{1:00}-{2:00}-{3:00}", directory, DateTime.Now.Hour,
                              DateTime.Now.Minute, DateTime.Now.Second);
              Log.Info("Main: Taking screenshot - Target: {0}.png", fileName);
              Surface backbuffer = GUIGraphicsContext.DX9Device.GetBackBuffer(0, 0, BackBufferType.Mono);
              SurfaceLoader.Save(fileName + ".png", ImageFileFormat.Png, backbuffer);
              backbuffer.Dispose();
              Log.Info("Main: Taking screenshot done");
            }
            catch (Exception ex)
            {
              Log.Info("Main: Error taking screenshot: {0}", ex.Message);
            }
          }
          break;

        case Action.ActionType.ACTION_SHOW_GUI:
          {
            // can we handle the switch to fullscreen?
            if (!GUIGraphicsContext.IsFullScreenVideo && g_Player.ShowFullScreenWindow())
            {
              return;
            }
          }
          break;
      }
      if (g_Player.Playing)
      {
        switch (action.wID)
        {
            //show DVD menu
          case Action.ActionType.ACTION_DVD_MENU:
            if (g_Player.IsDVD)
            {
              g_Player.OnAction(action);
              return;
            }
            break;

            //DVD: goto previous chapter
            //play previous item from playlist;
          case Action.ActionType.ACTION_PREV_ITEM:
          case Action.ActionType.ACTION_PREV_CHAPTER:
            if (g_Player.IsDVD || g_Player.HasChapters)
            {
              action = new Action(Action.ActionType.ACTION_PREV_CHAPTER, 0, 0);
              g_Player.OnAction(action);
              return;
            }

            if (!ActionTranslator.HasKeyMapped(GUIWindowManager.ActiveWindowEx, action.m_key))
            {
              playlistPlayer.PlayPrevious();
            }
            break;

            //play next item from playlist;
            //DVD: goto next chapter
          case Action.ActionType.ACTION_NEXT_CHAPTER:
          case Action.ActionType.ACTION_NEXT_ITEM:
            if (g_Player.IsDVD || g_Player.HasChapters)
            {
              action = new Action(Action.ActionType.ACTION_NEXT_CHAPTER, 0, 0);
              g_Player.OnAction(action);
              return;
            }

            if (!ActionTranslator.HasKeyMapped(GUIWindowManager.ActiveWindowEx, action.m_key))
            {
              playlistPlayer.PlayNext();
            }
            break;

            //stop playback
          case Action.ActionType.ACTION_STOP:

            //When MyPictures Plugin shows the pictures we want to stop the slide show only, not the player
            if (
              (GUIWindow.Window)(Enum.Parse(typeof (GUIWindow.Window), GUIWindowManager.ActiveWindow.ToString())) ==
              GUIWindow.Window.WINDOW_SLIDESHOW)
            {
              break;
            }

            if (!g_Player.IsTV || !GUIGraphicsContext.IsFullScreenVideo)
            {
              Log.Info("Main: Stopping media");
              g_Player.Stop();
              return;
            }
            break;

            //Jump to Music Now Playing
          case Action.ActionType.ACTION_JUMP_MUSIC_NOW_PLAYING:
            if (g_Player.IsMusic && GUIWindowManager.ActiveWindow != (int)GUIWindow.Window.WINDOW_MUSIC_PLAYING_NOW)
            {
              GUIWindowManager.ActivateWindow((int)GUIWindow.Window.WINDOW_MUSIC_PLAYING_NOW);
            }
            break;

            //play music
            //resume playback
          case Action.ActionType.ACTION_PLAY:
          case Action.ActionType.ACTION_MUSIC_PLAY:
            // Don't start playing from the beginning if we press play to return to normal speed
            if (g_Player.IsMusic && g_Player.Speed != 1)
            {
              // Attention: GUIMusicGenre / GUIMusicFiles need to be handled differently. we reset the speed there
              if (GUIWindowManager.ActiveWindow == (int)GUIWindow.Window.WINDOW_MUSIC_FILES ||
                  GUIWindowManager.ActiveWindow == (int)GUIWindow.Window.WINDOW_MUSIC_GENRE)
              {
                return;
              }
              g_Player.Speed = 1;
              return;
            }

            g_Player.StepNow();
            g_Player.Speed = 1;

            if (g_Player.Paused)
            {
              g_Player.Pause();
            }
            break;

            //pause (or resume playback)
          case Action.ActionType.ACTION_PAUSE:
            g_Player.Pause();
            break;

            //fast forward...
          case Action.ActionType.ACTION_FORWARD:
          case Action.ActionType.ACTION_MUSIC_FORWARD:
            {
              if (g_Player.Paused)
              {
                g_Player.Pause();
              }
              g_Player.Speed = Utils.GetNextForwardSpeed(g_Player.Speed);
              break;
            }

            //fast rewind...
          case Action.ActionType.ACTION_REWIND:
          case Action.ActionType.ACTION_MUSIC_REWIND:
            {
              if (g_Player.Paused)
              {
                g_Player.Pause();
              }
              g_Player.Speed = Utils.GetNextRewindSpeed(g_Player.Speed);
              break;
            }
        }
      }
      GUIWindowManager.OnAction(action);
    }
    catch (FileNotFoundException ex)
    {
      Log.Error(ex);
      MessageBox.Show("File not found:" + ex.FileName, "MediaPortal", MessageBoxButtons.OK, MessageBoxIcon.Error);
      Close();
    }
    catch (Exception ex)
    {
      Log.Error(ex);
      Log.Error("  exception: {0} {1} {2}", ex.Message, ex.Source, ex.StackTrace);
#if !DEBUG
      throw new Exception("exception occured", ex);
#endif
    }
  }
Ejemplo n.º 3
0
        /// <summary>
        /// Fill the list with channels
        /// </summary>
        public void FillChannelList()
        {
            List <Channel> tvChannelList = GetChannelListByGroup();

            benchClock = Stopwatch.StartNew();

            DateTime nextEPGupdate = GetNextEpgUpdate();
            Dictionary <int, NowAndNext> listNowNext = GetNowAndNext(tvChannelList, nextEPGupdate);

            benchClock.Stop();
            Log.Debug("TvMiniGuide: FillChannelList retrieved {0} programs for {1} channels in {2} ms", listNowNext.Count,
                      tvChannelList.Count, benchClock.ElapsedMilliseconds.ToString());

            GUIListItem item        = null;
            string      ChannelLogo = "";
            //List<int> RecChannels = null;
            //List<int> TSChannels = null;
            int  SelectedID        = 0;
            int  channelID         = 0;
            bool DisplayStatusInfo = true;


            Dictionary <int, ChannelState> tvChannelStatesList = null;

            if (TVHome.ShowChannelStateIcons())
            {
                benchClock.Reset();
                benchClock.Start();

                if (TVHome.Navigator.CurrentGroup.GroupName.Equals(TvConstants.TvGroupNames.AllChannels) ||
                    (!g_Player.IsTV && !g_Player.Playing))
                {
                    //we have no way of using the cached channelstates on the server in the following situations.
                    // 1) when the "all channels" group is selected - too many channels.
                    // 2) when user is not timeshifting - no user object on the server.
                    User currentUser = new User();
                    tvChannelStatesList = TVHome.TvServer.GetAllChannelStatesForGroup(TVHome.Navigator.CurrentGroup.IdGroup,
                                                                                      currentUser);
                }
                else
                {
                    // use the more speedy approach
                    // ask the server of the cached list of channel states corresponding to the user.
                    tvChannelStatesList = TVHome.TvServer.GetAllChannelStatesCached(TVHome.Card.User);

                    if (tvChannelStatesList == null)
                    {
                        //slow approach.
                        tvChannelStatesList = TVHome.TvServer.GetAllChannelStatesForGroup(TVHome.Navigator.CurrentGroup.IdGroup,
                                                                                          TVHome.Card.User);
                    }
                }

                benchClock.Stop();
                if (tvChannelStatesList != null)
                {
                    Log.Debug("TvMiniGuide: FillChannelList - {0} channel states for group retrieved in {1} ms",
                              Convert.ToString(tvChannelStatesList.Count), benchClock.ElapsedMilliseconds.ToString());
                }
            }

            for (int i = 0; i < tvChannelList.Count; i++)
            {
                Channel CurrentChan = tvChannelList[i];

                if (CurrentChan.VisibleInGuide)
                {
                    ChannelState CurrentChanState = ChannelState.tunable;
                    channelID = CurrentChan.IdChannel;
                    if (TVHome.ShowChannelStateIcons())
                    {
                        if (!tvChannelStatesList.TryGetValue(channelID, out CurrentChanState))
                        {
                            CurrentChanState = ChannelState.tunable;
                        }
                    }

                    //StringBuilder sb = new StringBuilder();
                    sb.Length = 0;
                    item      = new GUIListItem("");
                    // store here as it is not needed right now - please beat me later..
                    item.TVTag = CurrentChan;

                    sb.Append(CurrentChan.DisplayName);
                    ChannelLogo = Utils.GetCoverArt(Thumbs.TVChannel, CurrentChan.DisplayName);

                    // if we are watching this channel mark it
                    if (TVHome.Navigator != null && TVHome.Navigator.Channel != null &&
                        TVHome.Navigator.Channel.IdChannel == channelID)
                    {
                        item.IsRemote = true;
                        SelectedID    = lstChannels.Count;
                    }

                    if (!string.IsNullOrEmpty(ChannelLogo))
                    {
                        item.IconImageBig = ChannelLogo;
                        item.IconImage    = ChannelLogo;
                    }
                    else
                    {
                        item.IconImageBig = string.Empty;
                        item.IconImage    = string.Empty;
                    }

                    if (DisplayStatusInfo)
                    {
                        bool showChannelStateIcons = (TVHome.ShowChannelStateIcons() && lstChannelsWithStateIcons != null);

                        switch (CurrentChanState)
                        {
                        case ChannelState.nottunable:
                            item.IsPlayed = true;
                            if (showChannelStateIcons)
                            {
                                item.PinImage = Thumbs.TvIsUnavailableIcon;
                            }
                            else
                            {
                                sb.Append(" ");
                                sb.Append(local1056);
                            }
                            break;

                        case ChannelState.timeshifting:
                            if (showChannelStateIcons)
                            {
                                item.PinImage = Thumbs.TvIsTimeshiftingIcon;
                            }
                            else
                            {
                                sb.Append(" ");
                                sb.Append(local1055);
                            }
                            break;

                        case ChannelState.recording:
                            if (showChannelStateIcons)
                            {
                                item.PinImage = Thumbs.TvIsRecordingIcon;
                            }
                            else
                            {
                                sb.Append(" ");
                                sb.Append(local1054);
                            }
                            break;

                        default:
                            item.IsPlayed = false;
                            if (showChannelStateIcons)
                            {
                                item.PinImage = Thumbs.TvIsAvailableIcon;
                            }
                            break;
                        }
                    }
                    //StringBuilder sbTmp = new StringBuilder();
                    sbTmp.Length = 0;

                    NowAndNext currentNowAndNext = null;
                    bool       hasNowNext        = listNowNext.TryGetValue(channelID, out currentNowAndNext);

                    if (hasNowNext)
                    {
                        if (!string.IsNullOrEmpty(currentNowAndNext.TitleNow))
                        {
                            TVUtil.TitleDisplay(sbTmp, currentNowAndNext.TitleNow, currentNowAndNext.EpisodeName,
                                                currentNowAndNext.SeriesNum,
                                                currentNowAndNext.EpisodeNum, currentNowAndNext.EpisodePart);
                        }
                        else
                        {
                            sbTmp.Append(local736);
                        }
                    }
                    else
                    {
                        sbTmp.Append(local736);
                    }

                    item.Label2 = sbTmp.ToString();
                    sbTmp.Insert(0, local789);
                    item.Label3 = sbTmp.ToString();

                    sbTmp.Length = 0;

                    if (_showChannelNumber == true)
                    {
                        sb.Append(" - ");
                        if (!_byIndex)
                        {
                            sb.Append(tvChannelList[i].ChannelNumber);
                        }
                        else
                        {
                            sb.Append(i + 1);
                        }
                    }

                    if (hasNowNext)
                    {
                        // if the "Now" DB entry is in the future we set MinValue intentionally to avoid wrong percentage calculations
                        DateTime startTime = currentNowAndNext.NowStartTime;
                        if (startTime != SqlDateTime.MinValue.Value)
                        {
                            DateTime endTime = currentNowAndNext.NowEndTime;
                            sb.Append(" - ");
                            sb.Append(
                                CalculateProgress(startTime, endTime).ToString());
                            sb.Append("%");

                            if (endTime < nextEPGupdate || nextEPGupdate == DateTime.MinValue)
                            {
                                nextEPGupdate = endTime;
                                SetNextEpgUpdate(endTime);
                            }
                        }
                    }



                    if (hasNowNext && listNowNext[channelID].IdProgramNext != -1)
                    {
                        TVUtil.TitleDisplay(sbTmp, currentNowAndNext.TitleNext, currentNowAndNext.EpisodeNameNext,
                                            currentNowAndNext.SeriesNumNext,
                                            currentNowAndNext.EpisodeNumNext,
                                            currentNowAndNext.EpisodePartNext);
                    }
                    else
                    {
                        sbTmp.Append(local736);
                    }

                    item.Label2 = sb.ToString();

                    sbTmp.Insert(0, local790);

                    item.Label = sbTmp.ToString();

                    lstChannels.Add(item);
                }
            }
            benchClock.Stop();
            Log.Debug("TvMiniGuide: State check + filling completed after {0} ms", benchClock.ElapsedMilliseconds.ToString());
            lstChannels.SelectedListItemIndex = SelectedID;

            if (lstChannels.GetID == 37)
            {
                GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SETFOCUS, GetID, 0, 37, 0, 0, null);
                OnMessage(msg);
            }

            sb.Length    = 0;
            sbTmp.Length = 0;
        }
Ejemplo n.º 4
0
        private string DownloadMainStory()
        {
            // Get the selected item
            GUIListItem item = GetSelectedItem();

            if (item == null)
            {
                return(null);
            }

            feed_details feed = (feed_details)item.MusicTag;

            // Download the story
            string text = null;

            try
            {
                string         data    = string.Empty;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(feed.m_link);
                try
                {
                    // Use the current user in case an NTLM Proxy or similar is used.
                    // request.Proxy = WebProxy.GetDefaultProxy();
                    request.Proxy.Credentials = CredentialCache.DefaultCredentials;
                }
                catch (Exception) {}

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                try
                {
                    using (Stream stream = response.GetResponseStream())
                    {
                        Encoding enc;
                        try
                        {
                            enc = Encoding.GetEncoding(response.ContentEncoding);
                        }
                        catch
                        {
                            // Using Default Encoding
                            enc = Encoding.GetEncoding(m_strSiteEncoding);
                        }
                        using (StreamReader r = new StreamReader(stream, enc))
                        {
                            data = r.ReadToEnd();
                        }
                    }
                    // Convert html to text
                    HtmlToText html = new HtmlToText(data);
                    text = html.ToString().Trim();
                }
                finally
                {
                    if (response != null)
                    {
                        response.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SHOW_WARNING, 0, 0, 0, 0, 0, 0);
                msg.Param1 = 9;   //my news
                msg.Param2 = 912; //Unable to download latest news
                msg.Param3 = 0;

                string errtxt = ex.Message;
                int    pos    = errtxt.IndexOf(":");
                if (pos != -1)
                {
                    errtxt = errtxt.Substring(pos + 1);
                }
                msg.Label3 = String.Format("{0}\n\n({1})", m_strSiteURL, errtxt);
                GUIWindowManager.SendMessage(msg);

                // Log exception
                Log.Info("ex:{0} {1} {2}", ex.Message, ex.Source, ex.StackTrace);
            }

            return(text);
        }
Ejemplo n.º 5
0
  /// <summary>
  /// 
  /// </summary>
  /// <param name="action"></param>
  /// <returns></returns>
  private static bool PromptUserBeforeChangingPowermode(Action action)
  {
    var msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_ASKYESNO, 0, 0, 0, 0, 0, 0);
    switch (action.wID)
    {
      case Action.ActionType.ACTION_REBOOT:
        msg.Param1 = 630;
        break;

      case Action.ActionType.ACTION_POWER_OFF:
        msg.Param1 = 1600;
        break;

      case Action.ActionType.ACTION_SUSPEND:
        msg.Param1 = 1601;
        break;

      case Action.ActionType.ACTION_HIBERNATE:
        msg.Param1 = 1602;
        break;
    }
    msg.Param2 = 0;
    msg.Param3 = 0;
    GUIWindowManager.SendMessage(msg);

    return (msg.Param1 == 1);
  }
Ejemplo n.º 6
0
 public void AddMessage(string text,Vector3 worldPoint, MessageType type )
 {
     GUIMessage message = new GUIMessage();
     message.destroyTime = Time.time + messageDelay;
     message.text = text;
     message.worldPoint = worldPoint;
     message.type = type;
     guiMessages.Enqueue(message);
 }
Ejemplo n.º 7
0
    void ShowErrorMessage(string message)
    {
        if (gm == null)
            gm = riverGui.gm.message;

        gm.ShowMessage(message, messageDuration);
    }
Ejemplo n.º 8
0
    void Start()
    {
        cm = GameObject.Find("MainCamera").GetComponent<CameraManager>();

        menuWidth = 200;
        rightOffset = 5;
        topOffset = 5;
        menuButtonHeight = 40;
        smallButtonHeight = 20;

        fractalNatureFlag = true;
        generalSettingsFlag = true;
        erosionMenuFlag = false;
        filterMenuFlag = false ;
        riverMenuFlag = false;
        debugMenuFlag = false;

        messageFlag = false;
        //messageEndFrame = 666;

        terrainProcessing = false;

        scaleY = cm.scaleTerrainY;
        visibleArea = cm.terrainWidth;
        //visibleArea = 100;
        patchSize = cm.patchSize;

        message = new GUIMessage(this);//has to be declared first!

        menu = new GUIMenu(this);
        cameraMenu = new GUICamera(this);
        mesh = new GUIMesh(this);
        export = new GUIExport(this);
        progress = new GUIProgress(this);
        filter = new GUIFilters(this);
        river = new GUIRiver(this);
        debug = new GUIDebug(this);
        erosion = new GUIErosion(this);

        AssignFunctions();
    }
Ejemplo n.º 9
0
        public override bool OnMessage(GUIMessage message)
        {
            switch (message.Message)
            {
            case GUIMessage.MessageType.GUI_MSG_WINDOW_DEINIT:
            {
                SetControlLabel(GetID, (int)Controls.CONTROL_HEADING, string.Empty);
                base.OnMessage(message);
                DeInitControls();
                Dispose();
                return(true);
            }

            case GUIMessage.MessageType.GUI_MSG_WINDOW_INIT:
            {
                m_bButtonPressed = false;
                base.OnMessage(message);
                _selectedLabel = -1;
                ClearControl(GetID, (int)Controls.CONTROL_LIST);

                for (int i = 0; i < m_vecList.Count; i++)
                {
                    GUIListItem pItem = (GUIListItem)m_vecList[i];
                    AddListItemControl(GetID, (int)Controls.CONTROL_LIST, pItem);
                }

                string wszText = String.Format("{0} {1}", m_vecList.Count, GUILocalizeStrings.Get(127));

                SetControlLabel(GetID, (int)Controls.CONTROL_NUMBEROFFILES, wszText);

                if (m_bButtonEnabled)
                {
                    EnableControl(GetID, (int)Controls.CONTROL_BUTTON);
                }
                else
                {
                    DisableControl(GetID, (int)Controls.CONTROL_BUTTON);
                }
            }
                return(true);

            case GUIMessage.MessageType.GUI_MSG_CLICKED:
            {
                int iControl = message.SenderControlId;
                if ((int)Controls.CONTROL_LIST == iControl)
                {
                    int iAction = message.Param1;
                    if ((int)Action.ActionType.ACTION_SELECT_ITEM == iAction)
                    {
                        _selectedLabel = GetSelectedItemNo();
                        m_strSelected  = GetSelectedItem().Label;
                        PageDestroy();
                    }
                }
                if ((int)Controls.CONTROL_BUTTON == iControl)
                {
                    _selectedLabel   = -1;
                    m_bButtonPressed = true;
                    PageDestroy();
                }
            }
            break;
            }

            return(base.OnMessage(message));
        }
Ejemplo n.º 10
0
        private void AddListItemControl(int iWindowId, int iControlId, GUIListItem item)
        {
            GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_LABEL_ADD, iWindowId, 0, iControlId, 0, 0, item);

            OnMessage(msg);
        }
Ejemplo n.º 11
0
        private void ClearControl(int iWindowId, int iControlId)
        {
            GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_LABEL_RESET, iWindowId, 0, iControlId, 0, 0, null);

            OnMessage(msg);
        }
        /// <summary> create the used COM components and get the interfaces. </summary>
        protected override bool GetInterfaces()
        {
            try
            {
                graphBuilder = (IGraphBuilder) new FilterGraph();
                _rotEntry    = new DsROTEntry((IFilterGraph)graphBuilder);
                // add preferred video & audio codecs
                int    hr;
                int    intFilters        = 0; // FlipGer: count custom filters
                string strVideoCodec     = "";
                string strH264VideoCodec = "";
                string strAudioCodec     = "";
                string strAACAudioCodec  = "";
                string strAudiorenderer  = "";
                string strFilters        = ""; // FlipGer: collect custom filters
                bool   wmvAudio;
                bool   autoloadSubtitles;
                bool   bAutoDecoderSettings = false;

                using (Settings xmlreader = new MPSettings())
                {
                    bAutoDecoderSettings = xmlreader.GetValueAsBool("movieplayer", "autodecodersettings", false);
                    strVideoCodec        = xmlreader.GetValueAsString("movieplayer", "mpeg2videocodec", "");
                    strH264VideoCodec    = xmlreader.GetValueAsString("movieplayer", "h264videocodec", "");
                    strAudioCodec        = xmlreader.GetValueAsString("movieplayer", "mpeg2audiocodec", "");
                    strAACAudioCodec     = xmlreader.GetValueAsString("movieplayer", "aacaudiocodec", "");
                    strAudiorenderer     = xmlreader.GetValueAsString("movieplayer", "audiorenderer", "Default DirectSound Device");
                    wmvAudio             = xmlreader.GetValueAsBool("movieplayer", "wmvaudio", false);
                    autoloadSubtitles    = xmlreader.GetValueAsBool("subtitles", "enabled", false);
                    // FlipGer: load infos for custom filters
                    int intCount = 0;
                    while (xmlreader.GetValueAsString("movieplayer", "filter" + intCount.ToString(), "undefined") != "undefined")
                    {
                        if (xmlreader.GetValueAsBool("movieplayer", "usefilter" + intCount.ToString(), false))
                        {
                            strFilters += xmlreader.GetValueAsString("movieplayer", "filter" + intCount.ToString(), "undefined") + ";";
                            intFilters++;
                        }
                        intCount++;
                    }
                }

                if (bAutoDecoderSettings)
                {
                    return(AutoRendering(wmvAudio));
                }

                //Manually add codecs based on file extension if not in auto-settings
                // switch back to directx fullscreen mode
                Log.Info("VideoPlayerVMR9: Enabling DX9 exclusive mode");
                GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SWITCH_FULL_WINDOWED, 0, 0, 0, 1, 0, null);
                GUIWindowManager.SendMessage(msg);

                // add the VMR9 in the graph
                // after enabeling exclusive mode, if done first it causes MediPortal to minimize if for example the "Windows key" is pressed while playing a video
                Vmr9 = new VMR9Util();
                Vmr9.AddVMR9(graphBuilder);
                Vmr9.Enable(false);

                IBaseFilter source = null;
                graphBuilder.AddSourceFilter(m_strCurrentFile, null, out source);
                string extension = Path.GetExtension(m_strCurrentFile).ToLower();

                switch (extension)
                {
                case ".wmv":
                case ".asf":
                {
                    //strVideoCodec = "WMVideo Decoder DMO"; //allow e.g. ffdshow usage
                    strH264VideoCodec = "";
                    strAudioCodec     = "WMAudio Decoder DMO"; // multichannel audio needs this filter
                    strAACAudioCodec  = "";
                    break;
                }

                case ".mkv":
                case ".m2ts":
                case ".mp4":
                {
                    strVideoCodec = "";
                    break;
                }

                default:
                    strH264VideoCodec = "";
                    strAACAudioCodec  = "";
                    break;
                }

                if (!string.IsNullOrEmpty(strVideoCodec))
                {
                    DirectShowUtil.AddFilterToGraph(graphBuilder, strVideoCodec);
                }
                if (!string.IsNullOrEmpty(strH264VideoCodec) && strVideoCodec != strH264VideoCodec)
                {
                    DirectShowUtil.AddFilterToGraph(graphBuilder, strH264VideoCodec);
                }
                if (!string.IsNullOrEmpty(strAudioCodec))
                {
                    DirectShowUtil.AddFilterToGraph(graphBuilder, strAudioCodec);
                }
                if (!string.IsNullOrEmpty(strAACAudioCodec) && strAudioCodec != strAACAudioCodec)
                {
                    DirectShowUtil.AddFilterToGraph(graphBuilder, strAACAudioCodec);
                }

                if (strAudiorenderer.Length > 0)
                {
                    DirectShowUtil.AddAudioRendererToGraph(graphBuilder, strAudiorenderer, false);
                }
                //We now add custom filters after the Audio Renderer as AC3Filter failed to connect otherwise.
                //FlipGer: add custom filters to graph
                string[] arrFilters = strFilters.Split(';');
                for (int i = 0; i < intFilters; i++)
                {
                    DirectShowUtil.AddFilterToGraph(graphBuilder, arrFilters[i]);
                }

                //Set High Resolution Output > 2 channels
                IBaseFilter baseFilter    = null;
                bool        FFDShowLoaded = false;
                graphBuilder.FindFilterByName("WMAudio Decoder DMO", out baseFilter);
                if (baseFilter != null && wmvAudio != false) //Also check configuration option enabled
                {
                    //Set the filter setting to enable more than 2 audio channels
                    const string g_wszWMACHiResOutput = "_HIRESOUTPUT";
                    object       val     = true;
                    IPropertyBag propBag = (IPropertyBag)baseFilter;
                    hr = propBag.Write(g_wszWMACHiResOutput, ref val);
                    if (hr != 0)
                    {
                        Log.Info("VideoPlayerVMR9: Unable to turn WMAudio multichannel on. Reason: {0}", hr);
                    }
                    else
                    {
                        Log.Info("VideoPlayerVMR9: WMAudio Decoder now set for > 2 audio channels");
                    }
                    if (!FFDShowLoaded)
                    {
                        IBaseFilter FFDShowAudio = DirectShowUtil.GetFilterByName(graphBuilder, FFDSHOW_AUDIO_DECODER_FILTER);
                        if (FFDShowAudio != null)
                        {
                            DirectShowUtil.ReleaseComObject(FFDShowAudio);
                            FFDShowAudio = null;
                        }
                        else
                        {
                            _FFDShowAudio = DirectShowUtil.AddFilterToGraph(graphBuilder, FFDSHOW_AUDIO_DECODER_FILTER);
                        }
                        FFDShowLoaded = true;
                    }
                    DirectShowUtil.ReleaseComObject(baseFilter);
                    baseFilter = null;
                }

                #region load external audio streams

                // check if current "File" is a file... it could also be a URL
                // Directory.Getfiles, ... will other give us an exception
                if (File.Exists(m_strCurrentFile))
                {
                    //load audio file (ac3, dts, mka, mp3) only with if the name matches partially with video file.
                    string[] audioFiles = Directory.GetFiles(Path.GetDirectoryName(m_strCurrentFile),
                                                             Path.GetFileNameWithoutExtension(m_strCurrentFile) + "*.*");
                    bool audioSwitcherLoaded = false;
                    foreach (string file in audioFiles)
                    {
                        switch (Path.GetExtension(file))
                        {
                        case ".mp3":
                        case ".dts":
                        case ".mka":
                        case ".ac3":
                            if (!audioSwitcherLoaded)
                            {
                                IBaseFilter switcher = DirectShowUtil.GetFilterByName(graphBuilder, MEDIAPORTAL_AUDIOSWITCHER_FILTER);
                                if (switcher != null)
                                {
                                    DirectShowUtil.ReleaseComObject(switcher);
                                    switcher = null;
                                }
                                else
                                {
                                    _audioSwitcher = DirectShowUtil.AddFilterToGraph(graphBuilder, MEDIAPORTAL_AUDIOSWITCHER_FILTER);
                                }
                                audioSwitcherLoaded = true;
                            }

                            _AudioSourceFilter = DirectShowUtil.AddFilterToGraph(graphBuilder, FILE_SYNC_FILTER);
                            int result = ((IFileSourceFilter)_AudioSourceFilter).Load(file, null);

                            //Force using LAVFilter
                            _AudioExtSplitterFilter = DirectShowUtil.AddFilterToGraph(graphBuilder, LAV_SPLITTER_FILTER);

                            if (result != 0 || _AudioExtSplitterFilter == null)
                            {
                                if (_AudioSourceFilter != null)
                                {
                                    graphBuilder.RemoveFilter(_AudioSourceFilter);
                                    DirectShowUtil.ReleaseComObject(_AudioSourceFilter);
                                    _AudioSourceFilter = null;
                                }
                                if (_AudioExtSplitterFilter != null)
                                {
                                    graphBuilder.RemoveFilter(_AudioExtSplitterFilter);
                                    DirectShowUtil.ReleaseComObject(_AudioExtSplitterFilter);
                                    _AudioExtSplitterFilter = null;
                                }
                                //Trying Add Audio decoder in graph
                                AddFilterToGraphAndRelease(strAudioCodec);
                                graphBuilder.RenderFile(file, string.Empty);
                                Log.Debug("VideoPlayerVMR9 : External audio file loaded \"{0}\"", file);
                                AudioExternal = true;
                                break;
                            }

                            //Add Audio decoder in graph
                            _AudioExtFilter = DirectShowUtil.AddFilterToGraph(graphBuilder, strAudioCodec);

                            //Connect Filesource with the splitter
                            IPin pinOutAudioExt1 = DsFindPin.ByDirection((IBaseFilter)_AudioSourceFilter, PinDirection.Output, 0);
                            IPin pinInAudioExt2  = DsFindPin.ByDirection((IBaseFilter)_AudioExtSplitterFilter, PinDirection.Input, 0);
                            hr = graphBuilder.Connect(pinOutAudioExt1, pinInAudioExt2);

                            //Connect Splitter with the Audio Decoder
                            IPin pinOutAudioExt3 = DsFindPin.ByDirection((IBaseFilter)_AudioExtSplitterFilter, PinDirection.Output, 0);
                            IPin pinInAudioExt4  = DsFindPin.ByDirection((IBaseFilter)_AudioExtFilter, PinDirection.Input, 0);
                            hr = graphBuilder.Connect(pinOutAudioExt3, pinInAudioExt4);

                            //Render outpin from Audio Decoder
                            DirectShowUtil.RenderUnconnectedOutputPins(graphBuilder, _AudioExtFilter);

                            //Cleanup External Audio (Release)
                            if (_AudioSourceFilter != null)
                            {
                                DirectShowUtil.ReleaseComObject(_AudioSourceFilter);
                                _AudioSourceFilter = null;
                            }
                            if (_AudioExtSplitterFilter != null)
                            {
                                DirectShowUtil.ReleaseComObject(_AudioExtSplitterFilter);
                                _AudioExtSplitterFilter = null;
                            }
                            if (_AudioExtFilter != null)
                            {
                                DirectShowUtil.ReleaseComObject(_AudioExtFilter);
                                _AudioExtFilter = null;
                            }
                            if (pinOutAudioExt1 != null)
                            {
                                DirectShowUtil.ReleaseComObject(pinOutAudioExt1);
                                pinOutAudioExt1 = null;
                            }
                            if (pinInAudioExt2 != null)
                            {
                                DirectShowUtil.ReleaseComObject(pinInAudioExt2);
                                pinInAudioExt2 = null;
                            }
                            if (pinOutAudioExt3 != null)
                            {
                                DirectShowUtil.ReleaseComObject(pinOutAudioExt3);
                                pinOutAudioExt3 = null;
                            }
                            if (pinInAudioExt4 != null)
                            {
                                DirectShowUtil.ReleaseComObject(pinInAudioExt4);
                                pinInAudioExt4 = null;
                            }

                            Log.Debug("VideoPlayerVMR9 : External audio file loaded \"{0}\"", file);
                            AudioExternal = true;
                            break;
                        }
                    }
                }

                #endregion

                DirectShowUtil.RenderUnconnectedOutputPins(graphBuilder, source);
                if (source != null)
                {
                    DirectShowUtil.ReleaseComObject(source);
                    source = null;
                }
                DirectShowUtil.RemoveUnusedFiltersFromGraph(graphBuilder);

                if (Vmr9 == null || !Vmr9.IsVMR9Connected)
                {
                    Log.Error("VideoPlayer9: Failed to render file -> vmr9");
                    mediaCtrl = null;
                    Cleanup();
                    return(false);
                }

                mediaCtrl      = (IMediaControl)graphBuilder;
                mediaEvt       = (IMediaEventEx)graphBuilder;
                mediaSeek      = (IMediaSeeking)graphBuilder;
                mediaPos       = (IMediaPosition)graphBuilder;
                basicAudio     = (IBasicAudio)graphBuilder;
                videoWin       = (IVideoWindow)graphBuilder;
                m_iVideoWidth  = Vmr9.VideoWidth;
                m_iVideoHeight = Vmr9.VideoHeight;
                Vmr9.SetDeinterlaceMode();
                return(true);
            }
            catch (Exception ex)
            {
                Error.SetError("Unable to play movie", "Unable build graph for VMR9");
                Log.Error("VideoPlayer9: Exception while creating DShow graph {0} {1}", ex.Message, ex.StackTrace);
                Cleanup();
                return(false);
            }
        }
        protected void Cleanup()
        {
            if (graphBuilder == null)
            {
                return;
            }
            int hr = 0;

            Log.Info("VideoPlayer9: Cleanup DShow graph");
            try
            {
                if (mediaCtrl != null)
                {
                    int         counter = 0;
                    FilterState state;
                    hr = mediaCtrl.Stop();
                    hr = mediaCtrl.GetState(10, out state);
                    while (state != FilterState.Stopped || GUIGraphicsContext.InVmr9Render)
                    {
                        Log.Debug("VideoPlayer9: graph still running");
                        Thread.Sleep(100);
                        hr = mediaCtrl.GetState(10, out state);
                        counter++;
                        if (counter >= 30)
                        {
                            if (state != FilterState.Stopped)
                            {
                                Log.Debug("VideoPlayer9: graph still running");
                            }
                            if (GUIGraphicsContext.InVmr9Render)
                            {
                                Log.Debug("VideoPlayer9: in renderer");
                            }
                            break;
                        }
                    }
                    mediaCtrl = null;
                }

                if (mediaEvt != null)
                {
                    hr       = mediaEvt.SetNotifyWindow(IntPtr.Zero, WM_GRAPHNOTIFY, IntPtr.Zero);
                    mediaEvt = null;
                }

                if (videoWin != null)
                {
                    hr       = videoWin.put_Visible(OABool.False);
                    hr       = videoWin.put_Owner(IntPtr.Zero);
                    videoWin = null;
                }

                mediaSeek  = null;
                mediaPos   = null;
                basicAudio = null;
                basicVideo = null;
                SubEngine.GetInstance().FreeSubtitles();
                PostProcessingEngine.GetInstance().FreePostProcess();

                if (_FFDShowAudio != null)
                {
                    DirectShowUtil.ReleaseComObject(_FFDShowAudio);
                    _FFDShowAudio = null;
                }

                if (_audioSwitcher != null)
                {
                    DirectShowUtil.ReleaseComObject(_audioSwitcher);
                    _audioSwitcher = null;
                }

                if (Vmr9 != null)
                {
                    Vmr9.Enable(false);
                    Vmr9.SafeDispose();
                    Vmr9 = null;
                }

                if (graphBuilder != null)
                {
                    DirectShowUtil.RemoveFilters(graphBuilder);
                    if (_rotEntry != null)
                    {
                        _rotEntry.SafeDispose();
                        _rotEntry = null;
                    }
                    DirectShowUtil.ReleaseComObject(graphBuilder);
                    graphBuilder = null;
                }

                GUIGraphicsContext.form.Invalidate(true);
                m_state = PlayState.Init;
            }
            catch (Exception ex)
            {
                Log.Error("VideoPlayerVMR9: Exception while cleanuping DShow graph - {0} {1}", ex.Message, ex.StackTrace);
            }
            //switch back to directx windowed mode
            Log.Info("VideoPlayerVMR9: Disabling DX9 exclusive mode");
            GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SWITCH_FULL_WINDOWED, 0, 0, 0, 0, 0, null);

            GUIWindowManager.SendMessage(msg);
        }
        private bool AutoRendering(bool wmvAudio)
        {
            try
            {
                // step 1: figure out the renderer of the graph to be removed
                int          hr = graphBuilder.RenderFile(m_strCurrentFile, string.Empty);
                IEnumFilters enumFilters;
                hr = graphBuilder.EnumFilters(out enumFilters);
                do
                {
                    int           ffetched;
                    IBaseFilter[] filters = new IBaseFilter[1];
                    hr = enumFilters.Next(1, filters, out ffetched);
                    if (hr == 0 && ffetched > 0)
                    {
                        IBasicVideo2 localBasicVideo = filters[0] as IBasicVideo2;
                        if (localBasicVideo != null)
                        {
                            graphBuilder.RemoveFilter(filters[0]);
                        }
                        DirectShowUtil.ReleaseComObject(filters[0]);
                    }
                } while (hr == 0);
                DirectShowUtil.ReleaseComObject(enumFilters);

                // switch back to directx fullscreen mode
                Log.Info("VideoPlayerVMR9: Enabling DX9 exclusive mode");
                GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SWITCH_FULL_WINDOWED, 0, 0, 0, 1, 0, null);
                GUIWindowManager.SendMessage(msg);

                // step 2: add the VMR9 in the graph
                // after enabeling exclusive mode, if done first it causes MediPortal to minimize if for example the "Windows key" is pressed while playing a video
                Vmr9 = new VMR9Util();
                Vmr9.AddVMR9(graphBuilder);
                Vmr9.Enable(false);

                // render
                DirectShowUtil.RenderGraphBuilderOutputPins(graphBuilder, null);

                if (Vmr9 == null || !Vmr9.IsVMR9Connected)
                {
                    Log.Error("VideoPlayer9: Failed to render file -> vmr9");
                    mediaCtrl = null;
                    Cleanup();
                    return(false);
                }

                mediaCtrl      = (IMediaControl)graphBuilder;
                mediaEvt       = (IMediaEventEx)graphBuilder;
                mediaSeek      = (IMediaSeeking)graphBuilder;
                mediaPos       = (IMediaPosition)graphBuilder;
                basicAudio     = (IBasicAudio)graphBuilder;
                videoWin       = (IVideoWindow)graphBuilder;
                m_iVideoWidth  = Vmr9.VideoWidth;
                m_iVideoHeight = Vmr9.VideoHeight;

                Vmr9.SetDeinterlaceMode();
                return(true);
            }
            catch (Exception ex)
            {
                Error.SetError("Unable to play movie", "Unable build graph for VMR9");
                Log.Error("VideoPlayer9: Exception while creating DShow graph {0} {1}", ex.Message, ex.StackTrace);
                Cleanup();
                return(false);
            }
        }
Ejemplo n.º 15
0
        public override bool Play(string strFile)
        {
            try
            {
                if (_iTunesApplication == null)
                {
                    _iTunesApplication = new iTunesAppClass();
                    _iTunesApplication.OnPlayerPlayEvent +=
                        new _IiTunesEvents_OnPlayerPlayEventEventHandler(_iTunesApplication_OnPlayerPlayEvent);
                    _iTunesApplication.OnPlayerStopEvent +=
                        new _IiTunesEvents_OnPlayerStopEventEventHandler(_iTunesApplication_OnPlayerStopEvent);
                    _iTunesApplication.OnPlayerPlayingTrackChangedEvent +=
                        new _IiTunesEvents_OnPlayerPlayingTrackChangedEventEventHandler(
                            _iTunesApplication_OnPlayerPlayingTrackChangedEvent);
                    IITPlaylist playList = null;
                    foreach (IITPlaylist pl in _iTunesApplication.LibrarySource.Playlists)
                    {
                        if (pl.Name.Equals("MediaPortalTemporaryPlaylist"))
                        {
                            playList = pl;
                            break;
                        }
                    }
                    if (playList == null)
                    {
                        _playList = (IITUserPlaylist)_iTunesApplication.CreatePlaylist("MediaPortalTemporaryPlaylist");
                    }
                    else
                    {
                        _playList = (IITUserPlaylist)playList;
                    }
                    _playList.SongRepeat = ITPlaylistRepeatMode.ITPlaylistRepeatModeOff;
                }

                // stop other media which might be active until now.
                if (g_Player.Playing)
                {
                    g_Player.Stop();
                }

                GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_PLAYBACK_STARTED, 0, 0, 0, 0, 0, null);
                msg.Label = strFile;
                GUIWindowManager.SendThreadMessage(msg);

                _started = false;
                _ended   = false;
                foreach (IITTrack track in _playList.Tracks)
                {
                    track.Delete();
                }
                _playList.AddFile(strFile);
                _playList.PlayFirstTrack();

                _playerIsPaused  = false;
                _currentFile     = strFile;
                _duration        = -1;
                _currentPosition = -1;
                _playerState     = ITPlayerState.ITPlayerStateStopped;
                _updateTimer     = DateTime.MinValue;

                UpdateStatus();
                _notifyPlaying = true;
                return(true);
            }
            catch (Exception ex)
            {
                Log.Error("ITunesPlugin.Play: Exception");
                Log.Error(ex);
                _notifyPlaying     = false;
                _iTunesApplication = null;
            }
            return(false);
        }
Ejemplo n.º 16
0
    public void AssignFunctions(GlobalTerrain globalTerrain, LocalTerrain localTerrain,
        FilterGenerator filterGenerator, FunctionMathCalculator functionMathCalculator,
        RiverGenerator riverGenerator, GridManager gridManager, GUIManager guiManager,
        ErosionGenerator erosionGenerator)
    {
        this.globalTerrain = globalTerrain;
        this.localTerrain = localTerrain;
        this.filterGenerator = filterGenerator;
        this.riverGenerator = riverGenerator;
        this.erosionGenerator = erosionGenerator;

        fmc = functionMathCalculator;

        gm = gridManager;

        rt.AssignFunctions(fmc);
        ds.AssignFunctions(localTerrain);

        this.guiManager = guiManager;
        message = guiManager.message;
    }
Ejemplo n.º 17
0
        /// <summary>
        /// Evaluates the button number, gets its mapping and executes the action
        /// </summary>
        /// <param name="btnCode">Button code (ref: XML file)</param>
        /// <param name="processID">Process-ID for close/kill commands</param>
        private bool DoMapAction(string btnCode, int processID)
        {
            if (!_isLoaded) // No mapping loaded
            {
                Log.Info("Map: No button mapping loaded");
                return(false);
            }
            Mapping map = null;

            map = GetMapping(btnCode);
            if (map == null)
            {
                return(false);
            }
#if DEBUG
            Log.Info("{0} / {1} / {2} / {3}", map.Condition, map.ConProperty, map.Command, map.CmdProperty);
#endif
            Action action;
            if (map.Sound != string.Empty)
            {
                Util.Utils.PlaySound(map.Sound, false, true);
            }
            if (map.Focus && !GUIGraphicsContext.HasFocus)
            {
                GUIGraphicsContext.ResetLastActivity();
                GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_GETFOCUS, 0, 0, 0, 0, 0, null);
                //GUIWindowManager.SendThreadMessage(msg);
                GUIGraphicsContext.SendMessage(msg);
                return(true);
            }
            switch (map.Command)
            {
            case "ACTION": // execute Action x
                Key key = new Key(map.CmdKeyChar, map.CmdKeyCode);
#if DEBUG
                Log.Info("Executing: key {0} / {1} / Action: {2} / {3}", map.CmdKeyChar, map.CmdKeyCode, map.CmdProperty,
                         ((Action.ActionType)Convert.ToInt32(map.CmdProperty)).ToString());
#endif
                action = new Action(key, (Action.ActionType)Convert.ToInt32(map.CmdProperty), 0, 0);
                GUIGraphicsContext.OnAction(action);
                break;

            case "KEY": // send Key x
                SendKeys.SendWait(map.CmdProperty);
                break;

            case "WINDOW": // activate Window x
                GUIGraphicsContext.ResetLastActivity();
                GUIMessage msg;
                if ((Convert.ToInt32(map.CmdProperty) == (int)GUIWindow.Window.WINDOW_HOME) ||
                    (Convert.ToInt32(map.CmdProperty) == (int)GUIWindow.Window.WINDOW_SECOND_HOME))
                {
                    if (_basicHome)
                    {
                        msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_GOTO_WINDOW, 0, 0, 0,
                                             (int)GUIWindow.Window.WINDOW_SECOND_HOME, 0, null);
                    }
                    else
                    {
                        msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_GOTO_WINDOW, 0, 0, 0,
                                             (int)GUIWindow.Window.WINDOW_HOME, 0, null);
                    }
                }
                else
                {
                    msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_GOTO_WINDOW, 0, 0, 0, Convert.ToInt32(map.CmdProperty),
                                         0, null);
                }

                GUIWindowManager.SendThreadMessage(msg);
                break;

            case "TOGGLE": // toggle Layer 1/2
                if (_currentLayer == 1)
                {
                    _currentLayer = 2;
                }
                else
                {
                    _currentLayer = 1;
                }
                break;

            case "POWER": // power down commands

                if ((map.CmdProperty == "STANDBY") || (map.CmdProperty == "HIBERNATE"))
                {
                    GUIGraphicsContext.ResetLastActivity();
                }

                switch (map.CmdProperty)
                {
                case "EXIT":
                    action = new Action(Action.ActionType.ACTION_EXIT, 0, 0);
                    GUIGraphicsContext.OnAction(action);
                    break;

                case "REBOOT":
                    action = new Action(Action.ActionType.ACTION_REBOOT, 0, 0);
                    GUIGraphicsContext.OnAction(action);
                    break;

                case "SHUTDOWN":
                    action = new Action(Action.ActionType.ACTION_SHUTDOWN, 0, 0);
                    GUIGraphicsContext.OnAction(action);
                    break;

                case "STANDBY":
                    action = new Action(Action.ActionType.ACTION_SUSPEND, 1, 0); //1 = ignore prompt
                    GUIGraphicsContext.OnAction(action);
                    break;

                case "HIBERNATE":
                    action = new Action(Action.ActionType.ACTION_HIBERNATE, 1, 0); //1 = ignore prompt
                    GUIGraphicsContext.OnAction(action);
                    break;

                case "POWEROFF":
                    action = new Action(Action.ActionType.ACTION_POWER_OFF, 1, 0); //1 = ignore prompt
                    GUIGraphicsContext.OnAction(action);
                    break;
                }
                break;

            case "PROCESS":
            {
                GUIGraphicsContext.ResetLastActivity();
                if (processID > 0)
                {
                    Process proc = Process.GetProcessById(processID);
                    if (null != proc)
                    {
                        switch (map.CmdProperty)
                        {
                        case "CLOSE":
                            proc.CloseMainWindow();
                            break;

                        case "KILL":
                            proc.Kill();
                            break;
                        }
                    }
                }
            }
            break;

            default:
                return(false);
            }
            return(true);
        }
Ejemplo n.º 18
0
 protected override void OnMouseMove(int cx, int cy, Action action)
 {
   for (int i = Children.Count - 1; i >= 0; i--)
   {
     GUIControl control = (GUIControl)Children[i];
     bool bFocus;
     int controlID;
     if (control.HitTest(cx, cy, out controlID, out bFocus))
     {
       if (!bFocus)
       {
         GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SETFOCUS, GetID, 0, controlID, 0, 0, null);
         OnMessage(msg);
         control.HitTest(cx, cy, out controlID, out bFocus);
       }
       control.OnAction(action);
       return;
     }
     else
     {
       // no control selected
       control.Focus = false;
     }
   }
   Focused = false;
 }
Ejemplo n.º 19
0
        private int OnPostRenderAction(Action action, GUIMessage msg, bool focus)
        {
            if (msg != null)
            {
                if (msg.Message == GUIMessage.MessageType.GUI_MSG_LOSTFOCUS ||
                    msg.Message == GUIMessage.MessageType.GUI_MSG_SETFOCUS)
                {
                    if (Focused)
                    {
                        if (DoesPostRender())
                        {
                            OnMessage(msg);
                            return((int)(Focused ? GUIWindowManager.FocusState.FOCUSED : GUIWindowManager.FocusState.NOT_FOCUSED));
                        }
                    }
                }
            }

            if (action != null)
            {
                if (action.wID == Action.ActionType.ACTION_MOVE_LEFT ||
                    action.wID == Action.ActionType.ACTION_MOVE_RIGHT ||
                    action.wID == Action.ActionType.ACTION_MOVE_UP ||
                    action.wID == Action.ActionType.ACTION_MOVE_DOWN ||
                    action.wID == Action.ActionType.ACTION_SELECT_ITEM)
                {
                    if (Focused)
                    {
                        if (DoesPostRender())
                        {
                            bool foc = Focused;
                            OnAction(action);
                            return
                                ((int)
                                 (Focused
                   ? GUIWindowManager.FocusState.FOCUSED
                   : (foc == Focused
                        ? GUIWindowManager.FocusState.NOT_FOCUSED
                        : GUIWindowManager.FocusState.JUST_LOST_FOCUS)));
                        }
                    }
                }
                if (action.wID == Action.ActionType.ACTION_MOUSE_CLICK || action.wID == Action.ActionType.ACTION_MOUSE_DOUBLECLICK)
                {
                    int x = (int)action.fAmount1;
                    int y = (int)action.fAmount2;
                    if (DoesPostRender() && InWindow(x, y))
                    {
                        OnAction(action);
                        return((int)GUIWindowManager.FocusState.FOCUSED);
                    }
                }
                if (action.wID == Action.ActionType.ACTION_MOUSE_MOVE)
                {
                    if (DoesPostRender())
                    {
                        OnAction(action);
                    }
                }
            }
            if (focus && msg == null)
            {
                if (DoesPostRender())
                {
                    if (ShouldFocus(action))
                    {
                        Focused = true;
                        return((int)GUIWindowManager.FocusState.FOCUSED);
                    }
                }
                Focused = false;
            }
            return((int)GUIWindowManager.FocusState.NOT_FOCUSED);
        }
Ejemplo n.º 20
0
 private void CheckForNewUpdate()
 {
   if (!m_bNewVersionAvailable) return;
   if (GUIWindowManager.IsRouted) return;
   g_Player.Stop();
   GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_ASKYESNO,0,0,0,0,0,0);
   msg.Param1=709;
   msg.Param2=710;
   msg.Param3=0;
   GUIWindowManager.SendMessage(msg);
   if (msg.Param1==0) 
   {
     Log.Info("Main: Update - User canceled download");
     m_bCancelVersion = true;
     m_bNewVersionAvailable = false;
     return;
   }
   m_bCancelVersion = false;
   m_bNewVersionAvailable = false;
 }
Ejemplo n.º 21
0
        public bool OnPlayDVD(String drive, int parentId)
        {
            Log.Info("SelectDVDHandler: OnPlayDVD() playing DVD {0}", drive);
            if (g_Player.Playing && g_Player.IsDVD)
            {
                if (g_Player.CurrentFile.Equals(drive + @"\VIDEO_TS\VIDEO_TS.IFO"))
                {
                    return(true);
                }
            }

            if (Util.Utils.getDriveType(drive) == 5) //cd or dvd drive
            {
                string driverLetter = drive.Substring(0, 1);
                string fileName     = String.Format(@"{0}:\VIDEO_TS\VIDEO_TS.IFO", driverLetter);
                if (!VirtualDirectories.Instance.Movies.RequestPin(fileName))
                {
                    return(false);
                }
                if (File.Exists(fileName))
                {
                    IMDBMovie movieDetails = new IMDBMovie();
                    VideoDatabase.GetMovieInfo(fileName, ref movieDetails);
                    int    idFile           = VideoDatabase.GetFileId(fileName);
                    int    idMovie          = VideoDatabase.GetMovieId(fileName);
                    int    timeMovieStopped = 0;
                    byte[] resumeData       = null;
                    if ((idMovie >= 0) && (idFile >= 0))
                    {
                        timeMovieStopped = VideoDatabase.GetMovieStopTimeAndResumeData(idFile, out resumeData, g_Player.SetResumeBDTitleState);
                        //Log.Info("GUIVideoFiles: OnPlayBackStopped for DVD - idFile={0} timeMovieStopped={1} resumeData={2}", idFile, timeMovieStopped, resumeData);
                        if (timeMovieStopped > 0)
                        {
                            string title = Path.GetFileName(fileName);
                            VideoDatabase.GetMovieInfoById(idMovie, ref movieDetails);
                            if (movieDetails.Title != string.Empty)
                            {
                                title = movieDetails.Title;
                            }

                            GUIResumeDialog.Result result =
                                GUIResumeDialog.ShowResumeDialog(title, timeMovieStopped,
                                                                 GUIResumeDialog.MediaType.DVD);

                            if (result == GUIResumeDialog.Result.Abort)
                            {
                                return(false);
                            }

                            if (result == GUIResumeDialog.Result.PlayFromBeginning)
                            {
                                timeMovieStopped = 0;
                            }
                        }
                    }

                    if (g_Player.Playing)
                    {
                        g_Player.Stop();
                    }

                    g_Player.PlayDVD(drive + @"\VIDEO_TS\VIDEO_TS.IFO");
                    g_Player.ShowFullScreenWindow();
                    if (g_Player.Playing && timeMovieStopped > 0)
                    {
                        if (g_Player.IsDVD)
                        {
                            // send resume thread async
                            var msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SET_RESUME_STATE, 0, 0, 0, 0, 0, resumeData);
                            GUIWindowManager.SendThreadMessage(msg);
                        }
                        else
                        {
                            Log.Debug("SelectDVDHandler.OnPlayDVD - skipping");
                            g_Player.SeekAbsolute(timeMovieStopped);
                        }
                    }
                    return(true);
                }
            }
            //no disc in drive...
            GUIDialogOK dlgOk = (GUIDialogOK)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_OK);

            dlgOk.SetHeading(3);   //my videos
            Log.Error("SelectDVDHandler: OnPlayDVD() Plz Insert Disk (ShowSelectDriveDialog)");
            dlgOk.SetLine(1, 219); //no disc
            dlgOk.DoModal(parentId);
            return(false);
        }
Ejemplo n.º 22
0
  /// <summary>
  /// This event is sent with the  PBT_APMRESUMEAUTOMATIC event if the system has resumed operation due to user activity.
  /// </summary>
  private void OnResumeSuspend()
  {
    // avoid screen saver after standby
    GUIGraphicsContext.ResetLastActivity();
    _ignoreContextMenuAction = false;

    // Systems without DirectX9Ex have lost graphics device in suspend/hibernate cycle
    if (!GUIGraphicsContext.IsDirectX9ExUsed())
    {
      Log.Debug("Main: OnResumeSuspend - set GUIGraphicsContext.State.LOST");
      GUIGraphicsContext.CurrentState = GUIGraphicsContext.State.LOST;
    }

    if (!_showLastActiveModule && !Utils.IsGUISettingsWindow(GUIWindowManager.GetPreviousActiveWindow())
      && GUIWindowManager.ActiveWindow != (int)GUIWindow.Window.WINDOW_HOME
      && GUIWindowManager.ActiveWindow != (int)GUIWindow.Window.WINDOW_SECOND_HOME)
    {
      if (_startWithBasicHome && File.Exists(GUIGraphicsContext.GetThemedSkinFile(@"\basichome.xml")))
      {
        Log.Info("Main: OnResumeSuspend - Switch to basic home screen");
        GUIWindowManager.ActivateWindow((int)GUIWindow.Window.WINDOW_SECOND_HOME);
      }
      else
      {
        Log.Info("Main: OnResumeSuspend - Switch to home screen");
        GUIWindowManager.ActivateWindow((int)GUIWindow.Window.WINDOW_HOME);
      }
      GUIWindowManager.ResetWindowsHistory();
    }

    GUIMessage message = new GUIMessage(GUIMessage.MessageType.GUI_MSG_ONRESUME, 0, 0, 0, 0, 0, null);
    GUIGraphicsContext.SendMessage(message); 

    RecoverDevice();

    if (GUIGraphicsContext.IsDirectX9ExUsed())
    {
      Log.Debug("Main: OnResumeSuspend - set GUIGraphicsContext.State.RUNNING");
      GUIGraphicsContext.CurrentState = GUIGraphicsContext.State.RUNNING;
    }

    Log.Debug("Main: OnResumeSuspend - Init Input Devices");
    InputDevices.Init();

    Log.Debug("Main: OnResumeSuspend - Autoplay start listening");
    AutoPlay.StartListening();

    Log.Debug("Main: OnResumeSuspend - Initializing volume handler");
    try
    {
#pragma warning disable 168
      VolumeHandler vh = VolumeHandler.Instance;
#pragma warning restore 168
    }
    catch (Exception exception)
    {
      Log.Warn("Main: OnResumeSuspend - Could not initialize volume handler: ", exception.Message);
    }

    _suspended = false;
    _lastOnresume = DateTime.Now;
    Log.Info("Main: OnResumeSuspend - Done");
  }
        private void Cleanup()
        {
            lock (lockObj)
            {
                if (_graphBuilder == null)
                {
                    return;
                }
                int hr;
                Log.Info("TSReaderPlayer: cleanup DShow graph {0}", GUIGraphicsContext.InVmr9Render);
                try
                {
                    if (_mediaCtrl != null)
                    {
                        int         counter = 0;
                        FilterState state;
                        hr = _mediaCtrl.Stop();
                        hr = _mediaCtrl.GetState(10, out state);
                        while (state != FilterState.Stopped || GUIGraphicsContext.InVmr9Render)
                        {
                            Thread.Sleep(100);
                            hr = _mediaCtrl.GetState(10, out state);
                            counter++;
                            if (counter >= 30)
                            {
                                if (state != FilterState.Stopped)
                                {
                                    Log.Error("TSReaderPlayer: graph still running");
                                }
                                if (GUIGraphicsContext.InVmr9Render)
                                {
                                    Log.Error("TSReaderPlayer: in renderer");
                                }
                                break;
                            }
                        }
                        _mediaCtrl = null;
                    }

                    if (_mediaEvt != null)
                    {
                        hr        = _mediaEvt.SetNotifyWindow(IntPtr.Zero, WM_GRAPHNOTIFY, IntPtr.Zero);
                        _mediaEvt = null;
                    }

                    _videoWin = _graphBuilder as IVideoWindow;
                    if (_videoWin != null)
                    {
                        hr        = _videoWin.put_Visible(OABool.False);
                        hr        = _videoWin.put_Owner(IntPtr.Zero);
                        _videoWin = null;
                    }

                    _mediaSeeking = null;
                    _basicAudio   = null;
                    _basicVideo   = null;
                    _ireader      = null;

                    if (_audioRendererFilter != null)
                    {
                        while (DirectShowUtil.ReleaseComObject(_audioRendererFilter) > 0)
                        {
                            ;
                        }
                        _audioRendererFilter = null;
                    }

                    if (_fileSource != null)
                    {
                        DirectShowUtil.ReleaseComObject(_fileSource, 5000);
                        _fileSource = null;
                    }

                    PostProcessingEngine.GetInstance().FreePostProcess();

                    if (_vmr9 != null)
                    {
                        _vmr9.Enable(false);
                        _vmr9.SafeDispose();
                        _vmr9 = null;
                    }

                    if (_line21Decoder != null)
                    {
                        while ((hr = DirectShowUtil.ReleaseComObject(_line21Decoder)) > 0)
                        {
                            ;
                        }
                        _line21Decoder = null;
                    }

                    if (_graphBuilder != null)
                    {
                        DirectShowUtil.RemoveFilters(_graphBuilder);
                        if (_rotEntry != null)
                        {
                            _rotEntry.SafeDispose();
                            _rotEntry = null;
                        }
                        while ((hr = DirectShowUtil.ReleaseComObject(_graphBuilder)) > 0)
                        {
                            ;
                        }
                        _graphBuilder = null;
                    }

                    if (_dvbSubRenderer != null)
                    {
                        _dvbSubRenderer.SetPlayer(null);
                        _dvbSubRenderer = null;
                    }

                    GUIGraphicsContext.form.Invalidate(true);
                    _state = PlayState.Init;
                }
                catch (Exception ex)
                {
                    Log.Error("TSReaderPlayer: Exception while cleaning DShow graph - {0} {1}", ex.Message, ex.StackTrace);
                }
                //switch back to directx windowed mode
                Log.Info("TSReaderPlayer: Disabling DX9 exclusive mode");
                GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SWITCH_FULL_WINDOWED, 0, 0, 0, 0, 0, null);
                GUIWindowManager.SendMessage(msg);
            }
        }
Ejemplo n.º 24
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);
  }
Ejemplo n.º 25
0
        /// <summary>
        /// We do not want to change neither the enum nor the previous Create overloaded calls to maintain backward compatibility
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private IPlayer Create(string aFileName, g_Player.MediaType?aMediaType)
        {
            try
            {
                // Set to anything here as it will only be passed if aMediaType is not null
                g_Player.MediaType localType = g_Player.MediaType.Video;
                if (aMediaType != null && aMediaType != g_Player.MediaType.Unknown)
                {
                    localType = (g_Player.MediaType)aMediaType;
                }

                // Get settings only once
                using (Settings xmlreader = new MPSettings())
                {
                    string strAudioPlayer   = xmlreader.GetValueAsString("audioplayer", "player", "Internal dshow player");
                    int    streamPlayer     = xmlreader.GetValueAsInt("audioscrobbler", "streamplayertype", 0);
                    bool   Vmr9Enabled      = xmlreader.GetValueAsBool("musicvideo", "useVMR9", true);
                    bool   InternalBDPlayer = xmlreader.GetValueAsBool("bdplayer", "useInternalBDPlayer", true);

                    // Free BASS to avoid problems with Digital Audio, when watching movies
                    if (BassMusicPlayer.IsDefaultMusicPlayer)
                    {
                        if (!Util.Utils.IsAudio(aFileName))
                        {
                            BassMusicPlayer.Player.FreeBass();
                        }
                    }

                    if (aFileName.ToLower().IndexOf("rtsp:") >= 0)
                    {
                        if (aMediaType != null)
                        {
                            return(new TSReaderPlayer(localType));
                        }
                        else
                        {
                            return(new TSReaderPlayer());
                        }
                    }

                    if (aFileName.StartsWith("mms:") && aFileName.EndsWith(".ymvp"))
                    {
                        if (Vmr9Enabled)
                        {
                            return(new VideoPlayerVMR9());
                        }
                        else
                        {
                            return(new AudioPlayerWMP9());
                        }
                    }

                    string extension = Path.GetExtension(aFileName).ToLower();
                    if (extension == ".bdmv")
                    {
                        if (InternalBDPlayer)
                        {
                            return(new BDPlayer());
                        }
                        else
                        {
                            return(new VideoPlayerVMR9());
                        }
                    }

                    if (extension != ".tv" && extension != ".sbe" && extension != ".dvr-ms" &&
                        aFileName.ToLower().IndexOf(".tsbuffer") < 0 && aFileName.ToLower().IndexOf("radio.tsbuffer") < 0)
                    {
                        IPlayer newPlayer = GetExternalPlayer(aFileName);
                        if (newPlayer != null)
                        {
                            Log.Info("PlayerFactory: Disabling DX9 exclusive mode");
                            GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SWITCH_FULL_WINDOWED, 0, 0, 0, 0, 0, null);
                            GUIWindowManager.SendMessage(msg);
                            return(newPlayer);
                        }
                    }

                    if (Util.Utils.IsVideo(aFileName))
                    {
                        if (extension == ".tv" || extension == ".sbe" || extension == ".dvr-ms")
                        {
                            //if (extension == ".sbe" || extension == ".dvr-ms")
                            //{
                            //  //GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_RECORDER_STOP_TIMESHIFT, 0, 0, 0, 0, 0, null);
                            //  //GUIWindowManager.SendMessage(msg);
                            //}
                            return(new StreamBufferPlayer9());
                        }
                        if (extension == ".ifo" || Util.VirtualDirectory.IsImageFile(extension))
                        {
                            return(new DVDPlayer9());
                        }
                    }

                    // Use TsReader for timeshift buffer file for TvEngine3 & .ts recordings etc.
                    if (extension == ".tsbuffer" || extension == ".ts" || extension == ".rec")
                    //new support for Topfield recordings
                    {
                        if (aFileName.ToLower().IndexOf("radio.tsbuffer") >= 0)
                        {
                            if (aMediaType != null)
                            {
                                return(new BaseTSReaderPlayer(localType));
                            }
                            else
                            {
                                return(new BaseTSReaderPlayer());
                            }
                        }
                        if (aMediaType != null)
                        {
                            return(new TSReaderPlayer(localType));
                        }
                        else
                        {
                            return(new TSReaderPlayer());
                        }
                    }

                    if (!Util.Utils.IsAVStream(aFileName) && Util.Utils.IsVideo(aFileName) && localType != g_Player.MediaType.Music)
                    {
                        if (aMediaType != null)
                        {
                            return(new VideoPlayerVMR9(localType));
                        }
                        else
                        {
                            return(new VideoPlayerVMR9());
                        }
                    }

                    if (Util.Utils.IsCDDA(aFileName))
                    {
                        // Check if, we should use BASS for CD Playback
                        if (String.Compare(strAudioPlayer, "BASS engine", true) == 0)
                        {
                            if (BassMusicPlayer.BassFreed)
                            {
                                BassMusicPlayer.Player.InitBass();
                            }

                            return(BassMusicPlayer.Player);
                        }
                        else
                        {
                            return(new AudioPlayerWMP9());
                        }
                    }

                    if (Util.Utils.IsAudio(aFileName) || localType == g_Player.MediaType.Music)
                    {
                        if (String.Compare(strAudioPlayer, "BASS engine", true) == 0)
                        {
                            if (BassMusicPlayer.BassFreed)
                            {
                                BassMusicPlayer.Player.InitBass();
                            }

                            return(BassMusicPlayer.Player);
                        }
                        else if (String.Compare(strAudioPlayer, "Windows Media Player 9", true) == 0)
                        {
                            return(new AudioPlayerWMP9());
                        }
                        else
                        {
                            return(new AudioPlayerVMR7());
                        }
                    }

                    // Use WMP Player as Default
                    return(new AudioPlayerWMP9());
                }
            }
            finally
            {
                Log.Debug("PlayerFactory: Successfully created player instance for file - {0}", aFileName);
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Evaluates the button number, gets its mapping and executes the action
        /// </summary>
        /// <param name="btnCode">Button code (ref: XML file)</param>
        /// <param name="processID">Process-ID for close/kill commands</param>
        private bool DoMapAction(string btnCode, int processID)
        {
            if (!_isLoaded) // No mapping loaded
            {
                Log.Info("Map: No button mapping loaded");
                return(false);
            }
            Mapping map = null;

            map = GetMapping(btnCode);
            if (map == null)
            {
                return(false);
            }

            Log.Debug("{0} / {1} / {2} / {3}", map.Condition, map.ConProperty, map.Command, map.CmdProperty);

            Action action;

            if (map.Sound != string.Empty) // && !g_Player.Playing)
            {
                Util.Utils.PlaySound(map.Sound, false, true);
            }
            if (map.Focus && !GUIGraphicsContext.HasFocus)
            {
                GUIGraphicsContext.ResetLastActivity();
                GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_GETFOCUS, 0, 0, 0, 0, 0, null);
                GUIWindowManager.SendThreadMessage(msg);
                return(true);
            }
            switch (map.Command)
            {
            case "ACTION": // execute Action x
                Key key = new Key(map.CmdKeyChar, map.CmdKeyCode);

                Log.Debug("Executing: key {0} / {1} / Action: {2} / {3}", map.CmdKeyChar, map.CmdKeyCode, map.CmdProperty,
                          ((Action.ActionType)Convert.ToInt32(map.CmdProperty)).ToString());

                action = new Action(key, (Action.ActionType)Convert.ToInt32(map.CmdProperty), 0, 0);
                GUIGraphicsContext.OnAction(action);
                break;

            case "KEY": // send Key x
                SendKeys.SendWait(map.CmdProperty);
                break;

            case "WINDOW": // activate Window x
                GUIGraphicsContext.ResetLastActivity();
                GUIMessage msg;
                if ((Convert.ToInt32(map.CmdProperty) == (int)GUIWindow.Window.WINDOW_HOME) ||
                    (Convert.ToInt32(map.CmdProperty) == (int)GUIWindow.Window.WINDOW_SECOND_HOME))
                {
                    if (_basicHome)
                    {
                        msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_GOTO_WINDOW, 0, 0, 0,
                                             (int)GUIWindow.Window.WINDOW_SECOND_HOME, 0, null);
                    }
                    else
                    {
                        msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_GOTO_WINDOW, 0, 0, 0,
                                             (int)GUIWindow.Window.WINDOW_HOME, 0, null);
                    }
                }
                else
                {
                    msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_GOTO_WINDOW, 0, 0, 0, Convert.ToInt32(map.CmdProperty),
                                         0, null);
                }

                GUIWindowManager.SendThreadMessage(msg);
                break;

            case "TOGGLE": // toggle Layer 1/2
                if (_currentLayer == 1)
                {
                    _currentLayer = 2;
                }
                else
                {
                    _currentLayer = 1;
                }
                break;

            case "POWER": // power down commands

                if ((map.CmdProperty == "STANDBY") || (map.CmdProperty == "HIBERNATE"))
                {
                    GUIGraphicsContext.ResetLastActivity();

                    //Stop all media before suspending or hibernating
                    if (g_Player.Playing)
                    {
                        GUIWindowManager.SendThreadCallbackAndWait(StopPlayback, 0, 0, null);
                    }

                    // this is all handled in mediaportal.cs - OnSuspend

                    /*
                     * if (_basicHome)
                     * msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_GOTO_WINDOW, 0, 0, 0, (int)GUIWindow.Window.WINDOW_SECOND_HOME, 0, null);
                     * else
                     * msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_GOTO_WINDOW, 0, 0, 0, (int)GUIWindow.Window.WINDOW_HOME, 0, null);
                     *
                     * GUIWindowManager.SendThreadMessage(msg);
                     */
                }

                switch (map.CmdProperty)
                {
                case "EXIT":
                    action = new Action(Action.ActionType.ACTION_EXIT, 0, 0);
                    GUIGraphicsContext.OnAction(action);
                    break;

                case "REBOOT":
                    action = new Action(Action.ActionType.ACTION_REBOOT, 0, 0);
                    GUIGraphicsContext.OnAction(action);
                    break;

                case "SHUTDOWN":
                    action = new Action(Action.ActionType.ACTION_SHUTDOWN, 0, 0);
                    GUIGraphicsContext.OnAction(action);
                    break;

                case "STANDBY":
                    // we need a slow standby (force=false), in order to have the onsuspend method being called on mediportal.cs
                    // this is needed in order to have "ShowLastActiveModule" working correctly.
                    // also using force=true results in a silent non critical D3DERR_DEVICELOST exception when resuming from powerstate.
                    MPControlPlugin.OnSuspend();
                    WindowsController.ExitWindows(RestartOptions.Suspend, false);
                    break;

                case "HIBERNATE":
                    // we need a slow hibernation (force=false), in order to have the onsuspend method being called on mediportal.cs
                    // this is needed in order to have "ShowLastActiveModule" working correctly.
                    // also using force=true results in a silent non critical D3DERR_DEVICELOST exception when resuming from powerstate.
                    MPControlPlugin.OnSuspend();
                    WindowsController.ExitWindows(RestartOptions.Hibernate, false);
                    break;
                }
                break;

            case "PROCESS":
            {
                GUIGraphicsContext.ResetLastActivity();
                if (processID > 0)
                {
                    Process proc = Process.GetProcessById(processID);
                    if (null != proc)
                    {
                        switch (map.CmdProperty)
                        {
                        case "CLOSE":
                            proc.CloseMainWindow();
                            break;

                        case "KILL":
                            proc.Kill();
                            break;
                        }
                    }
                }
            }
            break;

            case "BLAST":
                MPControlPlugin.ProcessCommand(map.CmdProperty, true);
                break;

            default:
                return(false);
            }
            return(true);
        }
Ejemplo n.º 27
0
        private void OnGlobalMessage(GUIMessage message)
        {
            switch (message.Message)
            {
            case GUIMessage.MessageType.GUI_MSG_NOTIFY:
                ShowNotify(message.Label, message.Label2, message.Label3);
                break;

            case GUIMessage.MessageType.GUI_MSG_ASKYESNO:
                string Head = "", Line1 = "", Line2 = "", Line3 = "", Line4 = "";
                bool   DefaultYes = false;
                if (message.Param1 != 0)
                {
                    Head = GUILocalizeStrings.Get(message.Param1);
                }
                else if (message.Label != string.Empty)
                {
                    Head = message.Label;
                }
                if (message.Param2 != 0)
                {
                    Line1 = GUILocalizeStrings.Get(message.Param2);
                }
                else if (message.Label2 != string.Empty)
                {
                    Line1 = message.Label2;
                }
                if (message.Param3 != 0)
                {
                    Line2 = GUILocalizeStrings.Get(message.Param3);
                }
                else if (message.Label3 != string.Empty)
                {
                    Line2 = message.Label3;
                }
                if (message.Param4 != 0)
                {
                    Line3 = GUILocalizeStrings.Get(message.Param4);
                }
                else if (message.Label4 != string.Empty)
                {
                    Line3 = message.Label4;
                }
                if (message.Object != null && message.Object is int && (int)message.Object != 0)
                {
                    Line4 = GUILocalizeStrings.Get((int)message.Object);
                }
                else if (message.Object != null && message.Object is string && (string)message.Object != string.Empty)
                {
                    Line4 = (string)message.Object;
                }
                if (message.Object2 != null && message.Object2 is bool)
                {
                    DefaultYes = (bool)message.Object2;
                }
                if (AskYesNo(Head, Line1, Line2, Line3, Line4, DefaultYes))
                {
                    message.Param1 = 1;
                }
                else
                {
                    message.Param1 = 0;
                }
                break;

            case GUIMessage.MessageType.GUI_MSG_SHOW_WARNING:
            {
                string strHead = "", strLine1 = "", strLine2 = "";
                if (message.Param1 != 0)
                {
                    strHead = GUILocalizeStrings.Get(message.Param1);
                }
                else if (message.Label != string.Empty)
                {
                    strHead = message.Label;
                }
                if (message.Param2 != 0)
                {
                    strLine1 = GUILocalizeStrings.Get(message.Param2);
                }
                else if (message.Label2 != string.Empty)
                {
                    strLine2 = message.Label2;
                }
                if (message.Param3 != 0)
                {
                    strLine2 = GUILocalizeStrings.Get(message.Param3);
                }
                else if (message.Label3 != string.Empty)
                {
                    strLine2 = message.Label3;
                }
                ShowInfo(strHead, strLine1, strLine2);
            }
            break;

            case GUIMessage.MessageType.GUI_MSG_GET_STRING:
                VirtualKeyboard keyboard = (VirtualKeyboard)GUIWindowManager.GetWindow((int)Window.WINDOW_VIRTUAL_KEYBOARD);
                if (null == keyboard)
                {
                    return;
                }
                keyboard.Reset();
                keyboard.Text = message.Label;
                keyboard.DoModal(GUIWindowManager.ActiveWindow);
                if (keyboard.IsConfirmed)
                {
                    message.Label = keyboard.Text;
                }
                else
                {
                    message.Label = "";
                }
                break;

            case GUIMessage.MessageType.GUI_MSG_GET_PASSWORD:
                VirtualKeyboard keyboard2 = (VirtualKeyboard)GUIWindowManager.GetWindow((int)Window.WINDOW_VIRTUAL_KEYBOARD);
                if (null == keyboard2)
                {
                    return;
                }
                keyboard2.Reset();
                keyboard2.Password = true;
                keyboard2.Text     = message.Label;
                keyboard2.DoModal(GUIWindowManager.ActiveWindow);
                if (keyboard2.IsConfirmed)
                {
                    message.Label = keyboard2.Text;
                }
                else
                {
                    message.Label = "";
                }
                break;

            case GUIMessage.MessageType.GUI_MSG_WRONG_PASSWORD:
                using (Profile.Settings xmlreader = new Profile.MPSettings()
                       )
                {
                    if (!xmlreader.GetValueAsBool("general", "hidewrongpin", false))
                    {
                        GUIDialogYesNo dlgYesNo = (GUIDialogYesNo)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_YES_NO);
                        if (dlgYesNo == null)
                        {
                            return;
                        }
                        dlgYesNo.SetHeading(771); // The entered PIN could not be accepted
                        dlgYesNo.SetLine(1, 772); // Do you want to try again?
                        dlgYesNo.SetDefaultToYes(true);
                        dlgYesNo.DoModal(GetID);
                        message.Object = dlgYesNo.IsConfirmed;
                    }
                    else
                    {
                        message.Object = false;
                    }
                }
                break;
            }
        }
Ejemplo n.º 28
0
        protected override void OnPageLoad()
        {
            Log.Info("RadioHome:OnPageLoad");

            if (!TVHome.Connected)
            {
                RemoteControl.Clear();
                GUIWindowManager.ActivateWindow((int)Window.WINDOW_SETTINGS_TVENGINE);
                return;
            }

            if (TVHome.Navigator == null)
            {
                TVHome.OnLoaded();
            }
            else if (TVHome.Navigator.Channel == null)
            {
                TVHome.m_navigator.ReLoad();
                TVHome.LoadSettings(false);
            }

            // Create the channel navigator (it will load groups and channels)
            if (TVHome.m_navigator == null)
            {
                TVHome.m_navigator = new ChannelNavigator();
            }

            // Reload ChannelGroups
            Radio radioLoad = (Radio)GUIWindowManager.GetWindow((int)Window.WINDOW_RADIO);

            radioLoad.OnAdded();

            base.OnPageLoad();
            GUIMessage msgStopRecorder = new GUIMessage(GUIMessage.MessageType.GUI_MSG_RECORDER_STOP, 0, 0, 0, 0, 0, null);

            GUIWindowManager.SendMessage(msgStopRecorder);
            switch (currentSortMethod)
            {
            case SortMethod.Name:
                btnSortBy.SelectedItem = 0;
                break;

            case SortMethod.Type:
                btnSortBy.SelectedItem = 1;
                break;

            case SortMethod.Genre:
                btnSortBy.SelectedItem = 2;
                break;

            case SortMethod.Bitrate:
                btnSortBy.SelectedItem = 3;
                break;

            case SortMethod.Number:
                btnSortBy.SelectedItem = 4;
                break;
            }

            SelectCurrentItem();
            LoadDirectory(currentFolder);

            SetLastChannel();

            if ((_autoTurnOnRadio) && !(g_Player.Playing && g_Player.IsRadio))
            {
                GUIListItem item = facadeLayout.SelectedListItem;
                if (item != null && item.Label != ".." && !item.IsFolder)
                {
                    Play(facadeLayout.SelectedListItem);
                }
            }

            btnSortBy.SortChanged += SortChanged;
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Execute the given conditional action if needed.
        /// </summary>
        /// <param name="aAction">The action we want to conditionally execute.</param>
        /// <param name="aProcessId">Process-ID for close/kill commands.</param>
        /// <returns></returns>
        public bool ExecuteActionIfNeeded(ConditionalAction aAction, int aProcessId = -1)
        {
            if (aAction == null)
            {
                return(false);
            }

            HidListener.LogInfo("Action: {0} / {1} / {2} / {3}", aAction.Condition, aAction.ConProperty, aAction.Command, aAction.CmdProperty);

            Action action;

            if (aAction.Sound != string.Empty)
            {
                Util.Utils.PlaySound(aAction.Sound, false, true);
            }
            if (aAction.Focus && !GUIGraphicsContext.HasFocus)
            {
                GUIGraphicsContext.ResetLastActivity();
                var msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_GETFOCUS, 0, 0, 0, 0, 0, null);
                //GUIWindowManager.SendThreadMessage(msg);
                GUIGraphicsContext.SendMessage(msg);
                return(true);
            }
            switch (aAction.Command)
            {
            case "ACTION": // execute Action x
                var key = new Key(aAction.CmdKeyChar, aAction.CmdKeyCode);

                HidListener.LogInfo("Executing: key {0} / {1} / Action: {2} / {3}", aAction.CmdKeyChar, aAction.CmdKeyCode,
                                    aAction.CmdProperty,
                                    ((Action.ActionType)Convert.ToInt32(aAction.CmdProperty)).ToString());

                action = new Action(key, (Action.ActionType)Convert.ToInt32(aAction.CmdProperty), 0, 0);
                GUIGraphicsContext.OnAction(action);
                break;

            case "KEY": // send Key x
                SendKeys.SendWait(aAction.CmdProperty);
                break;

            case "WINDOW": // activate Window x
                GUIGraphicsContext.ResetLastActivity();
                GUIMessage msg;
                if ((Convert.ToInt32(aAction.CmdProperty) == (int)GUIWindow.Window.WINDOW_HOME) ||
                    (Convert.ToInt32(aAction.CmdProperty) == (int)GUIWindow.Window.WINDOW_SECOND_HOME))
                {
                    if (_basicHome)
                    {
                        msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_GOTO_WINDOW, 0, 0, 0,
                                             (int)GUIWindow.Window.WINDOW_SECOND_HOME, 0, null);
                    }
                    else
                    {
                        msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_GOTO_WINDOW, 0, 0, 0,
                                             (int)GUIWindow.Window.WINDOW_HOME, 0, null);
                    }
                }
                else
                {
                    msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_GOTO_WINDOW, 0, 0, 0,
                                         Convert.ToInt32(aAction.CmdProperty),
                                         0, null);
                }

                GUIWindowManager.SendThreadMessage(msg);
                break;

            case "TOGGLE": // toggle Layer 1/2
                if (_currentLayer == 1)
                {
                    _currentLayer = 2;
                }
                else
                {
                    _currentLayer = 1;
                }
                break;

            case "POWER": // power down commands

                if ((aAction.CmdProperty == "STANDBY") || (aAction.CmdProperty == "HIBERNATE"))
                {
                    GUIGraphicsContext.ResetLastActivity();
                }

                switch (aAction.CmdProperty)
                {
                case "EXIT":
                    action = new Action(Action.ActionType.ACTION_EXIT, 0, 0);
                    GUIGraphicsContext.OnAction(action);
                    break;

                case "REBOOT":
                    action = new Action(Action.ActionType.ACTION_REBOOT, 0, 0);
                    GUIGraphicsContext.OnAction(action);
                    break;

                case "SHUTDOWN":
                    action = new Action(Action.ActionType.ACTION_SHUTDOWN, 0, 0);
                    GUIGraphicsContext.OnAction(action);
                    break;

                case "STANDBY":
                    action = new Action(Action.ActionType.ACTION_SUSPEND, 1, 0); //1 = ignore prompt
                    GUIGraphicsContext.OnAction(action);
                    break;

                case "HIBERNATE":
                    action = new Action(Action.ActionType.ACTION_HIBERNATE, 1, 0); //1 = ignore prompt
                    GUIGraphicsContext.OnAction(action);
                    break;
                }
                break;

            case "PROCESS":
            {
                GUIGraphicsContext.ResetLastActivity();
                if (aProcessId > 0)
                {
                    var proc = Process.GetProcessById(aProcessId);
                    if (null != proc)
                    {
                        switch (aAction.CmdProperty)
                        {
                        case "CLOSE":
                            proc.CloseMainWindow();
                            break;

                        case "KILL":
                            proc.Kill();
                            break;
                        }
                    }
                }
            }
            break;

            default:
                return(false);
            }
            return(true);
        }
Ejemplo n.º 30
0
 protected void OnGUIMessage(string message) => GUIMessage?.Invoke(this, message);
Ejemplo n.º 31
0
        /// <summary> create the used COM components and get the interfaces. </summary>
        protected bool GetInterfaces()
        {
            VMR9Util.g_vmr9 = null;
            if (IsRadio == false)
            {
                Vmr9 = VMR9Util.g_vmr9 = new VMR9Util();

                // switch back to directx fullscreen mode
                Log.Info("RTSPPlayer: Enabling DX9 exclusive mode");
                GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SWITCH_FULL_WINDOWED, 0, 0, 0, 1, 0, null);
                GUIWindowManager.SendMessage(msg);
            }
            //Type comtype = null;
            //object comobj = null;

            DsRect rect = new DsRect();

            rect.top    = 0;
            rect.bottom = GUIGraphicsContext.form.Height;
            rect.left   = 0;
            rect.right  = GUIGraphicsContext.form.Width;


            try
            {
                graphBuilder = (IGraphBuilder) new FilterGraph();

                Log.Info("RTSPPlayer: add source filter");
                if (IsRadio == false)
                {
                    bool AddVMR9 = VMR9Util.g_vmr9 != null && VMR9Util.g_vmr9.AddVMR9(graphBuilder);
                    if (!AddVMR9)
                    {
                        Log.Error("RTSPPlayer:Failed to add VMR9 to graph");
                        return(false);
                    }
                    VMR9Util.g_vmr9.Enable(false);
                }

                _mpegDemux = (IBaseFilter) new MPEG2Demultiplexer();
                graphBuilder.AddFilter(_mpegDemux, "MPEG-2 Demultiplexer");

                _rtspSource = (IBaseFilter) new RtpSourceFilter();
                int hr = graphBuilder.AddFilter((IBaseFilter)_rtspSource, "RTSP Source Filter");
                if (hr != 0)
                {
                    Log.Error("RTSPPlayer:unable to add RTSP source filter:{0:X}", hr);
                    return(false);
                }

                // add preferred video & audio codecs
                Log.Info("RTSPPlayer: add video/audio codecs");
                string strVideoCodec               = "";
                string strAudioCodec               = "";
                string strAudiorenderer            = "";
                int    intFilters                  = 0;  // FlipGer: count custom filters
                string strFilters                  = ""; // FlipGer: collect custom filters
                string postProcessingFilterSection = "mytv";
                using (Settings xmlreader = new MPSettings())
                {
                    if (_mediaType == g_Player.MediaType.Video)
                    {
                        strVideoCodec               = xmlreader.GetValueAsString("movieplayer", "mpeg2videocodec", "");
                        strAudioCodec               = xmlreader.GetValueAsString("movieplayer", "mpeg2audiocodec", "");
                        strAudiorenderer            = xmlreader.GetValueAsString("movieplayer", "audiorenderer", "Default DirectSound Device");
                        postProcessingFilterSection = "movieplayer";
                    }
                    else
                    {
                        strVideoCodec               = xmlreader.GetValueAsString("mytv", "videocodec", "");
                        strAudioCodec               = xmlreader.GetValueAsString("mytv", "audiocodec", "");
                        strAudiorenderer            = xmlreader.GetValueAsString("mytv", "audiorenderer", "Default DirectSound Device");
                        postProcessingFilterSection = "mytv";
                    }
                    enableDvbSubtitles = xmlreader.GetValueAsBool("tvservice", "dvbsubtitles", false);
                    // FlipGer: load infos for custom filters
                    int intCount = 0;
                    while (xmlreader.GetValueAsString(postProcessingFilterSection, "filter" + intCount.ToString(), "undefined") !=
                           "undefined")
                    {
                        if (xmlreader.GetValueAsBool(postProcessingFilterSection, "usefilter" + intCount.ToString(), false))
                        {
                            strFilters +=
                                xmlreader.GetValueAsString(postProcessingFilterSection, "filter" + intCount.ToString(), "undefined") +
                                ";";
                            intFilters++;
                        }
                        intCount++;
                    }
                }
                string extension = Path.GetExtension(m_strCurrentFile).ToLowerInvariant();
                if (IsRadio == false)
                {
                    if (strVideoCodec.Length > 0)
                    {
                        DirectShowUtil.AddFilterToGraph(graphBuilder, strVideoCodec);
                    }
                }
                if (strAudioCodec.Length > 0)
                {
                    DirectShowUtil.AddFilterToGraph(graphBuilder, strAudioCodec);
                }

                if (enableDvbSubtitles == true)
                {
                    try
                    {
                        _subtitleFilter = SubtitleRenderer.GetInstance().AddSubtitleFilter(graphBuilder);
                        SubtitleRenderer.GetInstance().SetPlayer(this);
                        dvbSubRenderer = SubtitleRenderer.GetInstance();
                    }
                    catch (Exception e)
                    {
                        Log.Error(e);
                    }
                }

                Log.Debug("Is subtitle fitler null? {0}", (_subtitleFilter == null));
                // FlipGer: add custom filters to graph
                string[] arrFilters = strFilters.Split(';');
                for (int i = 0; i < intFilters; i++)
                {
                    DirectShowUtil.AddFilterToGraph(graphBuilder, arrFilters[i]);
                }
                if (strAudiorenderer.Length > 0)
                {
                    audioRendererFilter = DirectShowUtil.AddAudioRendererToGraph(graphBuilder, strAudiorenderer, false);
                }

                Log.Info("RTSPPlayer: load:{0}", m_strCurrentFile);
                IFileSourceFilter interfaceFile = (IFileSourceFilter)_rtspSource;
                if (interfaceFile == null)
                {
                    Log.Error("RTSPPlayer:Failed to get IFileSourceFilter");
                    return(false);
                }

                //Log.Info("RTSPPlayer: open file:{0}",filename);
                hr = interfaceFile.Load(m_strCurrentFile, null);
                if (hr != 0)
                {
                    Log.Error("RTSPPlayer:Failed to open file:{0} :0x{1:x}", m_strCurrentFile, hr);
                    return(false);
                }

                #region connect rtspsource->demux

                Log.Info("RTSPPlayer:connect rtspsource->mpeg2 demux");
                IPin pinTsOut = DsFindPin.ByDirection((IBaseFilter)_rtspSource, PinDirection.Output, 0);
                if (pinTsOut == null)
                {
                    Log.Info("RTSPPlayer:failed to find output pin of tsfilesource");
                    return(false);
                }
                IPin pinDemuxIn = DsFindPin.ByDirection(_mpegDemux, PinDirection.Input, 0);
                if (pinDemuxIn == null)
                {
                    Log.Info("RTSPPlayer:failed to find output pin of tsfilesource");
                    return(false);
                }

                hr = graphBuilder.Connect(pinTsOut, pinDemuxIn);
                if (hr != 0)
                {
                    Log.Info("RTSPPlayer:failed to connect rtspsource->mpeg2 demux:{0:X}", hr);
                    return(false);
                }
                DirectShowUtil.ReleaseComObject(pinTsOut);
                DirectShowUtil.ReleaseComObject(pinDemuxIn);

                #endregion

                #region render demux output pins

                if (IsRadio)
                {
                    Log.Info("RTSPPlayer:render audio demux outputs");
                    IEnumPins enumPins;
                    _mpegDemux.EnumPins(out enumPins);
                    IPin[] pins    = new IPin[2];
                    int    fetched = 0;
                    while (enumPins.Next(1, pins, out fetched) == 0)
                    {
                        if (fetched != 1)
                        {
                            break;
                        }
                        PinDirection direction;
                        pins[0].QueryDirection(out direction);
                        if (direction == PinDirection.Input)
                        {
                            continue;
                        }
                        IEnumMediaTypes enumMediaTypes;
                        pins[0].EnumMediaTypes(out enumMediaTypes);
                        AMMediaType[] mediaTypes = new AMMediaType[20];
                        int           fetchedTypes;
                        enumMediaTypes.Next(20, mediaTypes, out fetchedTypes);
                        for (int i = 0; i < fetchedTypes; ++i)
                        {
                            if (mediaTypes[i].majorType == MediaType.Audio)
                            {
                                graphBuilder.Render(pins[0]);
                                break;
                            }
                        }
                    }
                }
                else
                {
                    Log.Info("RTSPPlayer:render audio/video demux outputs");
                    IEnumPins enumPins;
                    _mpegDemux.EnumPins(out enumPins);
                    IPin[] pins    = new IPin[2];
                    int    fetched = 0;
                    while (enumPins.Next(1, pins, out fetched) == 0)
                    {
                        if (fetched != 1)
                        {
                            break;
                        }
                        PinDirection direction;
                        pins[0].QueryDirection(out direction);
                        if (direction == PinDirection.Input)
                        {
                            continue;
                        }
                        graphBuilder.Render(pins[0]);
                    }
                }

                #endregion

                // Connect DVB subtitle filter pins in the graph
                if (_mpegDemux != null && enableDvbSubtitles == true)
                {
                    IMpeg2Demultiplexer demuxer = _mpegDemux as IMpeg2Demultiplexer;
                    hr = demuxer.CreateOutputPin(GetTSMedia(), "Pcr", out _pinPcr);

                    if (hr == 0)
                    {
                        Log.Info("RTSPPlayer:_pinPcr OK");

                        IPin pDemuxerPcr  = DsFindPin.ByName(_mpegDemux, "Pcr");
                        IPin pSubtitlePcr = DsFindPin.ByName(_subtitleFilter, "Pcr");
                        hr = graphBuilder.Connect(pDemuxerPcr, pSubtitlePcr);
                    }
                    else
                    {
                        Log.Info("RTSPPlayer:Failed to create _pinPcr in demuxer:{0:X}", hr);
                    }

                    hr = demuxer.CreateOutputPin(GetTSMedia(), "Subtitle", out _pinSubtitle);
                    if (hr == 0)
                    {
                        Log.Info("RTSPPlayer:_pinSubtitle OK");

                        IPin pDemuxerSubtitle = DsFindPin.ByName(_mpegDemux, "Subtitle");
                        IPin pSubtitle        = DsFindPin.ByName(_subtitleFilter, "In");
                        hr = graphBuilder.Connect(pDemuxerSubtitle, pSubtitle);
                    }
                    else
                    {
                        Log.Info("RTSPPlayer:Failed to create _pinSubtitle in demuxer:{0:X}", hr);
                    }

                    hr = demuxer.CreateOutputPin(GetTSMedia(), "PMT", out _pinPMT);
                    if (hr == 0)
                    {
                        Log.Info("RTSPPlayer:_pinPMT OK");

                        IPin pDemuxerSubtitle = DsFindPin.ByName(_mpegDemux, "PMT");
                        IPin pSubtitle        = DsFindPin.ByName(_subtitleFilter, "PMT");
                        hr = graphBuilder.Connect(pDemuxerSubtitle, pSubtitle);
                    }
                    else
                    {
                        Log.Info("RTSPPlayer:Failed to create _pinPMT in demuxer:{0:X}", hr);
                    }
                }


                if (IsRadio == false)
                {
                    if (!VMR9Util.g_vmr9.IsVMR9Connected)
                    {
                        //VMR9 is not supported, switch to overlay
                        Log.Info("RTSPPlayer: vmr9 not connected");
                        _mediaCtrl = null;
                        Cleanup();
                        return(false);
                    }
                    VMR9Util.g_vmr9.SetDeinterlaceMode();
                }

                _mediaCtrl    = (IMediaControl)graphBuilder;
                mediaEvt      = (IMediaEventEx)graphBuilder;
                _mediaSeeking = (IMediaSeeking)graphBuilder;
                mediaPos      = (IMediaPosition)graphBuilder;
                basicAudio    = graphBuilder as IBasicAudio;
                //DirectShowUtil.SetARMode(graphBuilder,AspectRatioMode.Stretched);
                DirectShowUtil.EnableDeInterlace(graphBuilder);
                if (VMR9Util.g_vmr9 != null)
                {
                    m_iVideoWidth  = VMR9Util.g_vmr9.VideoWidth;
                    m_iVideoHeight = VMR9Util.g_vmr9.VideoHeight;
                }
                if (audioRendererFilter != null)
                {
                    Log.Info("RTSPPlayer9:set reference clock");
                    IMediaFilter    mp    = graphBuilder as IMediaFilter;
                    IReferenceClock clock = audioRendererFilter as IReferenceClock;
                    hr = mp.SetSyncSource(null);
                    hr = mp.SetSyncSource(clock);
                    Log.Info("RTSPPlayer9:set reference clock:{0:X}", hr);
                }
                Log.Info("RTSPPlayer: graph build successfull");
                return(true);
            }
            catch (Exception ex)
            {
                Error.SetError("Unable to play movie", "Unable build graph for VMR9");
                Log.Error("RTSPPlayer:exception while creating DShow graph {0} {1}", ex.Message, ex.StackTrace);
                CloseInterfaces();
                return(false);
            }
        }
        public override bool OnMessage(GUIMessage message)
        {
            switch (message.Message)
            {
            case GUIMessage.MessageType.GUI_MSG_WINDOW_INIT:
            {
                base.OnMessage(message);

                for (int i = 1; i <= 6; ++i)
                {
                    GUIControl.AddItemLabelControl(GetID, (int)Controls.CONTROL_THUMBNAILS_QUALITY, i.ToString());
                }
                GUIControl.SelectItemControl(GetID, (int)Controls.CONTROL_THUMBNAILS_QUALITY, _iQuality - 1);

                for (int i = 1; i <= 3; ++i)
                {
                    GUIControl.AddItemLabelControl(GetID, (int)Controls.CONTROL_THUMBNAILS_COLUMNS, i.ToString());
                }
                GUIControl.SelectItemControl(GetID, (int)Controls.CONTROL_THUMBNAILS_COLUMNS, _iColumns - 1);

                for (int i = 1; i <= 3; ++i)
                {
                    GUIControl.AddItemLabelControl(GetID, (int)Controls.CONTROL_THUMBNAILS_ROWS, i.ToString());
                }
                GUIControl.SelectItemControl(GetID, (int)Controls.CONTROL_THUMBNAILS_ROWS, _iRows - 1);
            }
                return(true);

            case GUIMessage.MessageType.GUI_MSG_CLICKED:
            {
                int iControl = message.SenderControlId;

                if (iControl == (int)Controls.CONTROL_THUMBNAILS_QUALITY)
                {
                    string strLabel = message.Label;
                    _iQuality = Int32.Parse(strLabel);
                    GUIGraphicsContext.ScrollSpeedHorizontal = _iQuality;
                    //settingsChanged = true;
                    ThumbQualityValueChanged();
                    SetProperties();
                }

                if (iControl == (int)Controls.CONTROL_THUMBNAILS_COLUMNS)
                {
                    string strLabel = message.Label;
                    _iColumns = Int32.Parse(strLabel);
                    GUIGraphicsContext.ScrollSpeedHorizontal = _iColumns;
                    //settingsChanged = true;
                }

                if (iControl == (int)Controls.CONTROL_THUMBNAILS_ROWS)
                {
                    string strLabel = message.Label;
                    _iRows = Int32.Parse(strLabel);
                    GUIGraphicsContext.ScrollSpeedHorizontal = _iRows;
                    //settingsChanged = true;
                }

                break;
            }
            }
            return(base.OnMessage(message));
        }
Ejemplo n.º 33
0
        private void Cleanup()
        {
            if (graphBuilder == null || (VMR9Util.g_vmr9 != null && VMR9Util.g_vmr9.isCurrentStopping))
            {
                return;
            }
            int hr;

            Log.Info("RTSPPlayer:cleanup DShow graph");
            try
            {
                if (VMR9Util.g_vmr9 != null)
                {
                    VMR9Util.g_vmr9.Vmr9MediaCtrl(_mediaCtrl);
                    VMR9Util.g_vmr9.Enable(false);
                }

                if (mediaEvt != null)
                {
                    hr = mediaEvt.SetNotifyWindow(IntPtr.Zero, WM_GRAPHNOTIFY, IntPtr.Zero);
                }

                videoWin = graphBuilder as IVideoWindow;
                if (videoWin != null && GUIGraphicsContext.VideoRenderer != GUIGraphicsContext.VideoRendererType.madVR)
                {
                    videoWin.put_Owner(IntPtr.Zero);
                    videoWin.put_Visible(OABool.False);
                }

                _mediaCtrl    = null;
                mediaEvt      = null;
                _mediaSeeking = null;
                mediaPos      = null;
                basicAudio    = null;
                basicVideo    = null;
                videoWin      = null;
                SubEngine.GetInstance().FreeSubtitles();

                if (graphBuilder != null)
                {
                    DirectShowUtil.RemoveFilters(graphBuilder);
                    if (_rotEntry != null)
                    {
                        _rotEntry.SafeDispose();
                        _rotEntry = null;
                    }
                    DirectShowUtil.FinalReleaseComObject(graphBuilder);
                    graphBuilder = null;
                }

                if (VMR9Util.g_vmr9 != null)
                {
                    VMR9Util.g_vmr9.SafeDispose();
                    VMR9Util.g_vmr9 = null;
                }

                GUIGraphicsContext.form.Invalidate(true);
                _state = PlayState.Init;

                if (_mpegDemux != null)
                {
                    Log.Info("cleanup mpegdemux");
                    DirectShowUtil.FinalReleaseComObject(_mpegDemux);
                    _mpegDemux = null;
                }
                if (_rtspSource != null)
                {
                    Log.Info("cleanup _rtspSource");
                    DirectShowUtil.FinalReleaseComObject(_rtspSource);
                    _rtspSource = null;
                }
                if (_subtitleFilter != null)
                {
                    DirectShowUtil.FinalReleaseComObject(_subtitleFilter);
                    _subtitleFilter = null;
                    if (this.dvbSubRenderer != null)
                    {
                        this.dvbSubRenderer.SetPlayer(null);
                    }
                    this.dvbSubRenderer = null;
                }

                if (vobSub != null)
                {
                    Log.Info("cleanup vobSub");
                    DirectShowUtil.FinalReleaseComObject(vobSub);
                    vobSub = null;
                }
            }
            catch (Exception ex)
            {
                if (VMR9Util.g_vmr9 != null)
                {
                    VMR9Util.g_vmr9.RestoreGuiForMadVr();
                    VMR9Util.g_vmr9.SafeDispose();
                }
                Log.Error("RTSPPlayer: Exception while cleanuping DShow graph - {0} {1}", ex.Message, ex.StackTrace);
            }

            //switch back to directx windowed mode
            Log.Info("RTSPPlayer: Disabling DX9 exclusive mode");
            GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SWITCH_FULL_WINDOWED, 0, 0, 0, 0, 0, null);

            GUIWindowManager.SendMessage(msg);
        }
Ejemplo n.º 34
0
  /// <summary>
  /// 
  /// </summary>
  /// <param name="message"></param>
  private void OnMessage(GUIMessage message)
  {
    if (!_suspended && !ExitToTray && !IsVisible)
    {
      switch (message.Message)
      {
        case GUIMessage.MessageType.GUI_MSG_GOTO_WINDOW:
        case GUIMessage.MessageType.GUI_MSG_GETFOCUS:
          Log.Debug("Main: Setting focus");
          if (Volume > 0 && (g_Player.IsVideo || g_Player.IsTV))
          {
            g_Player.Volume = Volume;
            if (g_Player.Paused)
            {
              g_Player.Pause();
            }
          }
          RestoreFromTray();
          break;
      }
    }

    if (!_suspended && AppActive)
    {
      switch (message.Message)
      {
        case GUIMessage.MessageType.GUI_MSG_RESTART_REMOTE_CONTROLS:
          Log.Info("Main: Restart remote controls");
          InputDevices.Stop();
          InputDevices.Init();
          break;

        case GUIMessage.MessageType.GUI_MSG_GOTO_WINDOW:
          GUIWindowManager.ActivateWindow(message.Param1);
          GUIGraphicsContext.IsFullScreenVideo = GUIWindowManager.ActiveWindow == (int) GUIWindow.Window.WINDOW_TVFULLSCREEN ||
                                                 GUIWindowManager.ActiveWindow == (int) GUIWindow.Window.WINDOW_FULLSCREEN_TELETEXT ||
                                                 GUIWindowManager.ActiveWindow == (int) GUIWindow.Window.WINDOW_FULLSCREEN_VIDEO ||
                                                 GUIWindowManager.ActiveWindow == (int) GUIWindow.Window.WINDOW_FULLSCREEN_MUSIC;
          break;

        case GUIMessage.MessageType.GUI_MSG_CD_INSERTED:
          AutoPlay.ExamineCD(message.Label);
          break;

        case GUIMessage.MessageType.GUI_MSG_VOLUME_INSERTED:
          AutoPlay.ExamineVolume(message.Label);
          break;

        case GUIMessage.MessageType.GUI_MSG_TUNE_EXTERNAL_CHANNEL:
          double retNum;
          bool bIsInteger = Double.TryParse(message.Label, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out retNum);
          try
          {
            if (bIsInteger)
            {
              _usbuirtdevice.ChangeTunerChannel(message.Label);
            }
          }
          // ReSharper disable EmptyGeneralCatchClause
          catch {}
          // ReSharper restore EmptyGeneralCatchClause

          try
          {
            _winlircdevice.ChangeTunerChannel(message.Label);
          }
          // ReSharper disable EmptyGeneralCatchClause
          catch { }
          // ReSharper restore EmptyGeneralCatchClause
          
          try
          {
            if (bIsInteger)
            {
              _redeyedevice.ChangeTunerChannel(message.Label);
            }
          }
          // ReSharper disable EmptyGeneralCatchClause
          catch {}
          // ReSharper restore EmptyGeneralCatchClause
          break;

        case GUIMessage.MessageType.GUI_MSG_SWITCH_FULL_WINDOWED:
          Log.Info("Main: GUI_MSG_SWITCH_FULL_WINDOWED message is obsolete.");
          break;

        case GUIMessage.MessageType.GUI_MSG_GETFOCUS:
          Log.Debug("Main: Setting focus");
          if (WindowState != FormWindowState.Minimized)
          {
            Activate();
          }
          else
          {
            if (Volume > 0 && (g_Player.IsVideo || g_Player.IsTV))
            {
              g_Player.Volume = Volume;
              if (g_Player.Paused)
              {
                g_Player.Pause();
              }
            }
            RestoreFromTray();
          }
          break;

        case GUIMessage.MessageType.GUI_MSG_CODEC_MISSING:
          var dlgOk = (GUIDialogOK) GUIWindowManager.GetWindow((int) GUIWindow.Window.WINDOW_DIALOG_OK);
          dlgOk.SetHeading(string.Empty);
          dlgOk.SetLine(1, message.Label);
          dlgOk.SetLine(2, string.Empty);
          dlgOk.SetLine(3, message.Label2);
          dlgOk.SetLine(4, message.Label3);
          dlgOk.DoModal(GUIWindowManager.ActiveWindow);
          break;

        case GUIMessage.MessageType.GUI_MSG_REFRESHRATE_CHANGED:
          var dlgNotify = (GUIDialogNotify) GUIWindowManager.GetWindow((int) GUIWindow.Window.WINDOW_DIALOG_NOTIFY);
          if (dlgNotify != null)
          {
            dlgNotify.Reset();
            dlgNotify.ClearAll();
            dlgNotify.SetHeading(message.Label);
            dlgNotify.SetText(message.Label2);
            dlgNotify.TimeOut = message.Param1;
            dlgNotify.DoModal(GUIWindowManager.ActiveWindow);
          }
          break;

        case GUIMessage.MessageType.GUI_MSG_PLAYBACK_ENDED:
        case GUIMessage.MessageType.GUI_MSG_PLAYBACK_STOPPED:
          // reset idle timer for consistent timing after end 0f playback
          SetThreadExecutionState(EXECUTION_STATE.ES_SYSTEM_REQUIRED | EXECUTION_STATE.ES_DISPLAY_REQUIRED);
          break;

        case GUIMessage.MessageType.GUI_MSG_ADD_REMOVABLE_DRIVE:
          if (!Utils.IsRemovable(message.Label))
          {
            VirtualDirectories.Instance.Movies.AddRemovableDrive(message.Label, message.Label2);
            VirtualDirectories.Instance.Music.AddRemovableDrive(message.Label, message.Label2);
            VirtualDirectories.Instance.Pictures.AddRemovableDrive(message.Label, message.Label2);
          }
          break;

        case GUIMessage.MessageType.GUI_MSG_REMOVE_REMOVABLE_DRIVE:
          if (!Utils.IsRemovable(message.Label))
          {
            VirtualDirectories.Instance.Movies.Remove(message.Label);
            VirtualDirectories.Instance.Music.Remove(message.Label);
            VirtualDirectories.Instance.Pictures.Remove(message.Label);
          }
          break;

        case GUIMessage.MessageType.GUI_MSG_DATABASE_SCAN_ENDED:
          dlgNotify = (GUIDialogNotify)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_NOTIFY);
          if (null != dlgNotify)
          {
            dlgNotify.SetHeading(GUILocalizeStrings.Get(1020)); // Information
            dlgNotify.SetText(GUILocalizeStrings.Get(300024)); // Scan finished
            dlgNotify.DoModal(GUIWindowManager.ActiveWindow);
          }
          break;

        case GUIMessage.MessageType.GUI_MSG_UNFOCUS_FOCUS:
          if (GUIGraphicsContext.VideoRenderer == GUIGraphicsContext.VideoRendererType.madVR)
          {
            // Workaround for madVR and 3D need to force a window change.
            if (!Windowed)
            {
              FormBorderStyle = FormBorderStyle.FixedSingle;
              FormBorderStyle = FormBorderStyle.None;
              Log.Debug("Main: madVR for 3D done");
              ForceMPFocus();
            }
          }
          break;
      }
    }
  }
Ejemplo n.º 35
0
        public override bool Play(string strFile)
        {
            updateTimer = DateTime.Now;
            m_speedRate = 10000;
            GUIGraphicsContext.IsWindowVisible = false;
            m_iVolume        = 100;
            _state           = PlayState.Init;
            m_strCurrentFile = strFile;
            m_bFullScreen    = true;
            m_ar             = GUIGraphicsContext.ARType;

            VideoRendererStatistics.VideoState = VideoRendererStatistics.State.VideoPresent;
            _updateNeeded = true;
            Log.Info("RTSPPlayer:play {0}", strFile);
            //lock ( typeof(VideoPlayerVMR7) )
            {
                CloseInterfaces();
                m_bStarted = false;
                if (!GetInterfaces())
                {
                    m_strCurrentFile = "";
                    CloseInterfaces();
                    return(false);
                }
                int hr = mediaEvt.SetNotifyWindow(GUIGraphicsContext.ActiveForm, WM_GRAPHNOTIFY, IntPtr.Zero);
                if (hr < 0)
                {
                    Error.SetError("Unable to play movie", "Can not set notifications");
                    m_strCurrentFile = "";
                    CloseInterfaces();
                    return(false);
                }

                DirectShowUtil.SetARMode(graphBuilder, AspectRatioMode.Stretched);
                _rotEntry = new DsROTEntry((IFilterGraph)graphBuilder);

                // DsUtils.DumpFilters(graphBuilder);
                hr = _mediaCtrl.Run();
                if (hr < 0)
                {
                    Error.SetError("Unable to play movie", "Unable to start movie");
                    m_strCurrentFile = "";
                    CloseInterfaces();
                    return(false);
                }
                GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_PLAYBACK_STARTED, 0, 0, 0, 0, 0, null);
                msg.Label = strFile;
                GUIWindowManager.SendThreadMessage(msg);
                _state = PlayState.Playing;
                //Brutus GUIGraphicsContext.IsFullScreenVideo=true;
                m_iPositionX  = GUIGraphicsContext.VideoWindow.X;
                m_iPositionY  = GUIGraphicsContext.VideoWindow.Y;
                m_iWidth      = GUIGraphicsContext.VideoWindow.Width;
                m_iHeight     = GUIGraphicsContext.VideoWindow.Height;
                m_ar          = GUIGraphicsContext.ARType;
                _updateNeeded = true;
                SetVideoWindow();
                mediaPos.get_Duration(out _duration);
                Log.Info("RTSPPlayer:Duration:{0}", _duration);
                if (_mediaType == g_Player.MediaType.TV)
                {
                    //if (_duration < 1) _duration = 1;
                    //SeekAbsolute(_duration - 1);
                }
                else
                {
                    //SeekAbsolute(0);
                }

                OnInitialized();
            }

            // Wait for a while to wait VMR9 to get ready.
            // Implemented due to problems starting to play before VMR9 was ready resulting in black screen.
            Thread.Sleep(200);


            return(true);
        }
Ejemplo n.º 36
0
        private void ChannelTuneFailedNotifyUser(LiveStreamResult result, Channel channel)
        {
            string TuningResult = string.Empty;

            switch (result)
            {
            case LiveStreamResult.ChannelTuneFailed:
                TuningResult = (Utility.GetLocalizedText(TextId.ChannelTuneFailed));
                break;

            case LiveStreamResult.NoFreeCardFound:
                TuningResult = (Utility.GetLocalizedText(TextId.NoFreeCardFound));
                break;

            case LiveStreamResult.NotSupported:
                TuningResult = (Utility.GetLocalizedText(TextId.NotSupported));
                break;

            case LiveStreamResult.NoRetunePossible:
                TuningResult = (Utility.GetLocalizedText(TextId.NoRetunePossible));
                break;

            case LiveStreamResult.IsScrambled:
                TuningResult = (Utility.GetLocalizedText(TextId.IsScrambled));
                break;

            case LiveStreamResult.UnknownError:
                TuningResult = (Utility.GetLocalizedText(TextId.UnknownError));
                break;
            }

            if (GUIWindowManager.ActiveWindow == (int)(int)GUIWindow.Window.WINDOW_TVFULLSCREEN)
            {
                // If failed and wasPlaying TV, left screen as it is and show zaposd with error message
                GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_TV_ERROR_NOTIFY, GUIWindowManager.ActiveWindow, 0,
                                                0, 0, 0,
                                                null);

                msg.SendToTargetWindow = true;
                msg.Object             = TuningResult; // forward error info object
                msg.TargetWindowId     = (int)(int)GUIWindow.Window.WINDOW_TVFULLSCREEN;
                GUIGraphicsContext.SendMessage(msg);
            }
            else
            {
                // if not fulscreen, show notify dialog with the error message
                string caption = string.Empty;
                string tvlogo  = string.Empty;
                if (channel != null)
                {
                    _navigatorChannels[_currentChannel.ChannelType].PreviousChannel = channel;
                    _currentChannel = null;

                    tvlogo = Utility.GetLogoImage(channel);

                    if (channel.ChannelType == ChannelType.Television)
                    {
                        caption = GUILocalizeStrings.Get(605) + " - " + channel.DisplayName;
                    }
                    else
                    {
                        caption = GUILocalizeStrings.Get(665) + " - " + channel.DisplayName;
                    }
                }

                GUIDialogNotify pDlgNotify = (GUIDialogNotify)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_NOTIFY);
                if (pDlgNotify != null)
                {
                    pDlgNotify.Reset();
                    pDlgNotify.ClearAll();
                    pDlgNotify.SetHeading(caption);
                    if (!string.IsNullOrEmpty(TuningResult))
                    {
                        pDlgNotify.SetText(TuningResult);
                    }
                    pDlgNotify.SetImage(tvlogo);
                    pDlgNotify.TimeOut = 5;
                    pDlgNotify.DoModal(GUIWindowManager.ActiveWindow);
                }
            }
        }
Ejemplo n.º 37
0
        protected override void OnPageLoad()
        {
            base.OnPageLoad();

            // if hyperlink parameter is set (to string ID not actual name)
            // then load that view
            if (_loadParameter != null)
            {
                bool viewFound = false;
                foreach (ViewDefinition v in handler.Views)
                {
                    if (v.Name == _loadParameter)
                    {
                        MusicState.View = v.Name; //don't just set _currentView as this is used below
                        m_iItemSelected = -1;     //remove any selected item from previous selection
                        viewFound       = true;
                    }
                }
                if (!viewFound)
                {
                    // got here as parameter passed from hyperlinkParameter value
                    // did not match to a view name
                    Log.Error("Invalid view load parameter: {0} when loading music genres, using default view", _loadParameter);
                }
            }

            string view = MusicState.View;

            if (view == string.Empty)
            {
                view = ((ViewDefinition)handler.Views[0]).Name;
            }

            if (_currentView != null && _currentView.Name == view)
            {
                ((MusicViewHandler)handler).Restore(_currentView, _currentLevel);
            }
            else
            {
                handler.CurrentView = view;
            }


            // Set views
            if (btnViews != null)
            {
                InitViewSelections();
            }

            LoadDirectory("db_view");

            if (facadeLayout.Count <= 0)
            {
                GUIControl.FocusControl(GetID, btnLayouts.GetID);
            }

            if (_showArtist != string.Empty)
            {
                for (int i = 0; i < facadeLayout.Count; ++i)
                {
                    GUIListItem item = facadeLayout[i];
                    MusicTag    tag  = item.MusicTag as MusicTag;
                    if (tag != null)
                    {
                        if (String.Compare(tag.Artist, _showArtist, true) == 0)
                        {
                            OnClick(i);
                            break;
                        }
                    }
                }
            }
            _showArtist = string.Empty;

            using (Profile.Settings settings = new Profile.MPSettings())
            {
                playlistPlayer.RepeatPlaylist = settings.GetValueAsBool("musicfiles", "repeat", true);
            }

            // When we return from Fullscreen Music (the Visualisation screen), the page is reloaded again
            // The currently playing item will not be focused.
            // So we check here, if we have something playing and will focus the item
            if (g_Player.Playing && g_Player.IsMusic)
            {
                int          currentItem = playlistPlayer.CurrentSong;
                PlayListItem item        = playlistPlayer.GetCurrentItem();
                GUIMessage   msg         = new GUIMessage(GUIMessage.MessageType.GUI_MSG_ITEM_FOCUS, 0, 0, 0, currentItem, 0, null);
                msg.Label = item.FileName;
                GUIGraphicsContext.SendMessage(msg);
            }
        }
Ejemplo n.º 38
0
    private int OnPostRenderAction(Action action, GUIMessage msg, bool focus)
    {
      if (msg != null)
      {
        if (msg.Message == GUIMessage.MessageType.GUI_MSG_LOSTFOCUS ||
            msg.Message == GUIMessage.MessageType.GUI_MSG_SETFOCUS)
        {
          if (Focused)
          {
            if (DoesPostRender())
            {
              OnMessage(msg);
              return (int)(Focused ? GUIWindowManager.FocusState.FOCUSED : GUIWindowManager.FocusState.NOT_FOCUSED);
            }
          }
        }
      }

      if (action != null)
      {
        if (action.wID == Action.ActionType.ACTION_MOVE_LEFT ||
            action.wID == Action.ActionType.ACTION_MOVE_RIGHT ||
            action.wID == Action.ActionType.ACTION_MOVE_UP ||
            action.wID == Action.ActionType.ACTION_MOVE_DOWN ||
            action.wID == Action.ActionType.ACTION_SELECT_ITEM)
        {
          if (Focused)
          {
            if (DoesPostRender())
            {
              bool foc = Focused;
              OnAction(action);
              return
                (int)
                (Focused
                   ? GUIWindowManager.FocusState.FOCUSED
                   : (foc == Focused
                        ? GUIWindowManager.FocusState.NOT_FOCUSED
                        : GUIWindowManager.FocusState.JUST_LOST_FOCUS));
            }
          }
        }
        if (action.wID == Action.ActionType.ACTION_MOUSE_CLICK || action.wID == Action.ActionType.ACTION_MOUSE_DOUBLECLICK)
        {
          int x = (int)action.fAmount1;
          int y = (int)action.fAmount2;
          if (DoesPostRender() && InWindow(x, y))
          {
            OnAction(action);
            return (int)GUIWindowManager.FocusState.FOCUSED;
          }
        }
        if (action.wID == Action.ActionType.ACTION_MOUSE_MOVE)
        {
          if (DoesPostRender())
          {
            OnAction(action);
          }
        }
      }
      if (focus && msg == null)
      {
        if (DoesPostRender())
        {
          if (ShouldFocus(action))
          {
            Focused = true;
            return (int)GUIWindowManager.FocusState.FOCUSED;
          }
        }
        Focused = false;
      }
      return (int)GUIWindowManager.FocusState.NOT_FOCUSED;
    }
Ejemplo n.º 39
0
        /// <summary>
        /// this is actually loading a database view not a directory
        /// and this is done via view handler so parameter is not used
        /// but is needed to override method in base class
        /// </summary>
        /// <param name="strNotUsed">Used to implement method in base class but not used</param>
        protected override void LoadDirectory(string strNotUsed)
        {
            GUIWaitCursor.Show();
            GUIListItem SelectedItem = facadeLayout.SelectedListItem;

            int    previousLevel   = ((MusicViewHandler)handler).PreviousLevel;
            string strSelectedItem = string.Empty;

            if (SelectedItem != null)
            {
                // if there is an item selected and we are loading a new view
                // then store the existing value so when we navigate back up through
                // the view levels we can focus on the item we had selected
                // we can not use current level in the name for the directory history
                // as current level gets updated before LoadDirectory is called
                // therefore use previous level which is set by the music view handler
                // when that returns (ie. that will be level of the view user has
                // made selection from as it has not been cleared yet)
                if (SelectedItem.IsFolder && SelectedItem.Label != "..")
                {
                    m_history.Set(SelectedItem.Label, handler.LocalizedCurrentView + "." +
                                  previousLevel.ToString());
                }
            }

            List <Song> songs;

            if (!((MusicViewHandler)handler).Execute(out songs))
            {
                GUIWaitCursor.Hide();
                Action action = new Action();
                action.wID = Action.ActionType.ACTION_PREVIOUS_MENU;
                GUIGraphicsContext.OnAction(action);
                return;
            }

            GUIControl.ClearControl(GetID, facadeLayout.GetID);
            SwitchLayout();

            List <GUIListItem> itemsToAdd = new List <GUIListItem>();

            TimeSpan totalPlayingTime = new TimeSpan();

            if (previousLevel > handler.CurrentLevel)
            {
                // only need to lookup values when navigating back up through the view
                strSelectedItem = m_history.Get(handler.LocalizedCurrentView + "." + handler.CurrentLevel.ToString());
            }

            #region handle pin protected share

            if (songs.Count > 0) // some songs in there?
            {
                Song song = songs[0];
                if (song.FileName.Length > 0) // does a filename exits
                {
                    foreach (Share share in _shareList)
                    {
                        if (song.FileName.Contains(share.Path)) // compare it with shares
                        {
                            if (share.Pincode != -1)            // does it have a pincode?
                            {
                                GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_GET_PASSWORD, 0, 0, 0, 0, 0, 0);
                                GUIWindowManager.SendMessage(msg); // ask for the userinput
                                int iPincode = -1;
                                try
                                {
                                    iPincode = Int32.Parse(msg.Label);
                                }
                                catch (Exception) {}
                                if (iPincode != share.Pincode)
                                {
                                    songs.Clear();
                                }
                                break;
                            }
                        }
                    }
                }
            }

            #endregion

            if (handler.CurrentLevel > 0)
            {
                // add ".." folder item if not at bottom level of view
                GUIListItem pItem = new GUIListItem("..");
                pItem.Path     = string.Empty;
                pItem.IsFolder = true;
                Util.Utils.SetDefaultIcons(pItem);
                itemsToAdd.Add(pItem);
            }

            for (int i = 0; i < songs.Count; ++i)
            {
                Song        song = songs[i];
                GUIListItem item = new GUIListItem();

                MusicTag tag = new MusicTag();
                tag = song.ToMusicTag();
                item.AlbumInfoTag = song;
                item.MusicTag     = tag;

                if (handler.CurrentLevel + 1 < handler.MaxLevels)
                {
                    item.IsFolder = true;
                    item.Label    = MusicViewHandler.GetFieldValue(song, handler.CurrentLevelWhere);
                    SetSortLabel(ref item, CurrentSortMethod, handler.CurrentLevelWhere);
                }
                else
                {
                    item.IsFolder = false;
                    if (!GUIMusicBaseWindow.SetTrackLabels(ref item, CurrentSortMethod))
                    {
                        item.Label = song.Title;
                    }
                }

                if (tag != null)
                {
                    if (tag.Duration > 0)
                    {
                        totalPlayingTime = totalPlayingTime.Add(new TimeSpan(0, 0, tag.Duration));
                    }
                }

                item.Path = song.FileName;

                if (!string.IsNullOrEmpty(_currentPlaying) &&
                    item.Path.Equals(_currentPlaying, StringComparison.OrdinalIgnoreCase))
                {
                    item.Selected = true;
                }

                item.Duration        = song.Duration;
                tag.TimesPlayed      = song.TimesPlayed;
                item.Rating          = song.Rating;
                item.Year            = song.Year;
                item.OnRetrieveArt  += new GUIListItem.RetrieveCoverArtHandler(OnRetrieveCoverArt);
                item.OnItemSelected += new GUIListItem.ItemSelectedHandler(item_OnItemSelected);
                itemsToAdd.Add(item);
            }

            itemsToAdd.Sort(new MusicSort(CurrentSortMethod, CurrentSortAsc));

            int  iItem        = 0; // used to hold index of item to select
            bool itemSelected = false;
            for (int i = 0; i < itemsToAdd.Count; ++i)
            {
                if (!itemSelected && itemsToAdd[i].Label == strSelectedItem)
                {
                    iItem        = i;
                    itemSelected = true;
                }
                facadeLayout.Add(itemsToAdd[i]);
            }

            int iTotalItems = facadeLayout.Count;
            if (iTotalItems > 0)
            {
                GUIListItem rootItem = facadeLayout[0];
                if (rootItem.Label == "..")
                {
                    iTotalItems--;
                }
            }

            //set object count label, total duration
            GUIPropertyManager.SetProperty("#itemcount", Util.Utils.GetObjectCountLabel(iTotalItems));

            if (totalPlayingTime.TotalSeconds > 0)
            {
                GUIPropertyManager.SetProperty("#totalduration",
                                               Util.Utils.SecondsToHMSString((int)totalPlayingTime.TotalSeconds));
            }
            else
            {
                GUIPropertyManager.SetProperty("#totalduration", string.Empty);
            }

            if (itemSelected)
            {
                GUIControl.SelectItemControl(GetID, facadeLayout.GetID, iItem);
            }
            else if (m_iItemSelected >= 0)
            {
                GUIControl.SelectItemControl(GetID, facadeLayout.GetID, m_iItemSelected);
            }
            else
            {
                SelectCurrentItem();
            }

            UpdateButtonStates();
            GUIWaitCursor.Hide();
        }
Ejemplo n.º 40
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);
  }
Ejemplo n.º 41
0
        public override bool Play(string strFile)
        {
            updateTimer = DateTime.Now;
            m_speedRate = 10000;
            m_bVisible  = false;
            m_iVolume   = 100;
            m_state     = PlayState.Init;
            if (strFile != "http://localhost/OnlineVideo.mp4")
            {
                m_strCurrentFile = strFile;                                                // hack to get around the MP 1.3 Alpha bug with non http URLs
            }
            m_bFullScreen = true;
            m_ar          = GUIGraphicsContext.ARType;
            VideoRendererStatistics.VideoState = VideoRendererStatistics.State.VideoPresent;
            _updateNeeded = true;
            Log.Instance.Info("OnlineVideosPlayer: Play '{0}'", m_strCurrentFile);

            m_bStarted = false;
            if (!GetInterfaces())
            {
                m_strCurrentFile = "";
                CloseInterfaces();
                return(false);
            }

            // if we are playing a local file set the cache file so refresh rate adaption can happen
            Uri    uri      = new Uri(m_strCurrentFile);
            string protocol = uri.Scheme.Substring(0, Math.Min(uri.Scheme.Length, 4));

            if (protocol == "file")
            {
                cacheFile = m_strCurrentFile;
            }

            AdaptRefreshRateFromCacheFile();

            ISubEngine engine = SubEngine.GetInstance(true);

            if (!engine.LoadSubtitles(graphBuilder, string.IsNullOrEmpty(SubtitleFile) ? m_strCurrentFile : SubtitleFile))
            {
                SubEngine.engine = new SubEngine.DummyEngine();
            }
            else
            {
                engine.Enable = true;
            }

            IPostProcessingEngine postengine = PostProcessingEngine.GetInstance(true);

            if (!postengine.LoadPostProcessing(graphBuilder))
            {
                PostProcessingEngine.engine = new PostProcessingEngine.DummyEngine();
            }

            IAudioPostEngine audioEngine = AudioPostEngine.GetInstance(true);

            if (audioEngine != null && !audioEngine.LoadPostProcessing(graphBuilder))
            {
                AudioPostEngine.engine = new AudioPostEngine.DummyEngine();
            }

            AnalyseStreams();
            SelectSubtitles();
            SelectAudioLanguage();
            OnInitialized();

            int hr = mediaEvt.SetNotifyWindow(GUIGraphicsContext.ActiveForm, WM_GRAPHNOTIFY, IntPtr.Zero);

            if (hr < 0)
            {
                Error.SetError("Unable to play movie", "Can not set notifications");
                m_strCurrentFile = "";
                CloseInterfaces();
                return(false);
            }
            if (videoWin != null)
            {
                videoWin.put_WindowStyle((WindowStyle)((int)WindowStyle.Child + (int)WindowStyle.ClipChildren + (int)WindowStyle.ClipSiblings));
                videoWin.put_MessageDrain(GUIGraphicsContext.form.Handle);
            }

            DirectShowUtil.SetARMode(graphBuilder, AspectRatioMode.Stretched);

            try
            {
                if (protocol == "file")
                {
                    if (Vmr9 != null)
                    {
                        Vmr9.StartMediaCtrl(mediaCtrl);
                    }
                }
                else
                {
                    hr = mediaCtrl.Run();
                    DsError.ThrowExceptionForHR(hr);
                    if (hr == 1)
                    // S_FALSE from IMediaControl::Run means: The graph is preparing to run, but some filters have not completed the transition to a running state.
                    {
                        // wait max. 20 seconds for the graph to transition to the running state
                        DateTime    startTime = DateTime.Now;
                        FilterState filterState;
                        do
                        {
                            Thread.Sleep(100);
                            hr = mediaCtrl.GetState(100, out filterState);
                            // check with timeout max. 10 times a second if the state changed
                        } while ((hr != 0) && ((DateTime.Now - startTime).TotalSeconds <= 20));
                        if (hr != 0) // S_OK
                        {
                            DsError.ThrowExceptionForHR(hr);
                            throw new Exception(string.Format("IMediaControl.GetState after 20 seconds: 0x{0} - '{1}'",
                                                              hr.ToString("X8"), DsError.GetErrorText(hr)));
                        }
                    }
                }
            }
            catch (Exception error)
            {
                Log.Instance.Warn("OnlineVideosPlayer: Unable to play with reason: {0}", error.Message);
            }
            if (hr != 0) // S_OK
            {
                Error.SetError("Unable to play movie", "Unable to start movie");
                m_strCurrentFile = "";
                CloseInterfaces();
                return(false);
            }

            if (basicVideo != null)
            {
                basicVideo.GetVideoSize(out m_iVideoWidth, out m_iVideoHeight);
            }

            if (GoFullscreen)
            {
                GUIWindowManager.ActivateWindow(GUIOnlineVideoFullscreen.WINDOW_FULLSCREEN_ONLINEVIDEO);
            }
            GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_PLAYBACK_STARTED, 0, 0, 0, 0, 0, null);

            msg.Label = CurrentFile;
            GUIWindowManager.SendThreadMessage(msg);
            m_state       = PlayState.Playing;
            m_iPositionX  = GUIGraphicsContext.VideoWindow.X;
            m_iPositionY  = GUIGraphicsContext.VideoWindow.Y;
            m_iWidth      = GUIGraphicsContext.VideoWindow.Width;
            m_iHeight     = GUIGraphicsContext.VideoWindow.Height;
            m_ar          = GUIGraphicsContext.ARType;
            _updateNeeded = true;
            SetVideoWindow();
            mediaPos.get_Duration(out m_dDuration);
            Log.Instance.Info("OnlineVideosPlayer: Duration {0} sec", m_dDuration.ToString("F"));

            return(true);
        }
Ejemplo n.º 42
0
  private void OnMessage(GUIMessage message)
  {
    if (_suspended)
    {
      return;
    }
    switch (message.Message)
    {
      case GUIMessage.MessageType.GUI_MSG_RESTART_REMOTE_CONTROLS:
        Log.Info("Main: Restart remote controls");
        InputDevices.Stop();
        InputDevices.Init();
        break;

      case GUIMessage.MessageType.GUI_MSG_GOTO_WINDOW:
        GUIWindowManager.ActivateWindow(message.Param1);
        if (GUIWindowManager.ActiveWindow == (int)GUIWindow.Window.WINDOW_TVFULLSCREEN ||
            GUIWindowManager.ActiveWindow == (int)GUIWindow.Window.WINDOW_FULLSCREEN_TELETEXT ||
            GUIWindowManager.ActiveWindow == (int)GUIWindow.Window.WINDOW_FULLSCREEN_VIDEO ||
            GUIWindowManager.ActiveWindow == (int)GUIWindow.Window.WINDOW_FULLSCREEN_MUSIC)
        {
          GUIGraphicsContext.IsFullScreenVideo = true;
        }
        else
        {
          GUIGraphicsContext.IsFullScreenVideo = false;
        }
        break;

      case GUIMessage.MessageType.GUI_MSG_CD_INSERTED:
        AutoPlay.ExamineCD(message.Label);
        break;

      case GUIMessage.MessageType.GUI_MSG_VOLUME_INSERTED:
        AutoPlay.ExamineVolume(message.Label);
        break;

      case GUIMessage.MessageType.GUI_MSG_TUNE_EXTERNAL_CHANNEL:
        bool bIsInteger;
        double retNum;
        bIsInteger =
          Double.TryParse(message.Label, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out retNum);
        try
        {
          if (bIsInteger)
          {
            usbuirtdevice.ChangeTunerChannel(message.Label);
          }
        }
        catch (Exception) {}
        try
        {
          winlircdevice.ChangeTunerChannel(message.Label);
        }
        catch (Exception) {}
        try
        {
          if (bIsInteger)
          {
            redeyedevice.ChangeTunerChannel(message.Label);
          }
        }
        catch (Exception) {}
        break;

      case GUIMessage.MessageType.GUI_MSG_SWITCH_FULL_WINDOWED:
        if (GUIGraphicsContext.IsDirectX9ExUsed() && useEnhancedVideoRenderer)
        {
          return;
        }
        bool fullscreen = (message.Param1 != 0);
        Log.Debug("Main: Received DX exclusive mode switch message. Fullscreen && maximized == {0}",
                  fullscreen && isMaximized);
        if (isMaximized == false || GUIGraphicsContext.CurrentState == GUIGraphicsContext.State.STOPPING)
        {
          return;
        }
        if (fullscreen)
        {
          //switch to fullscreen mode
          Log.Debug("Main: Goto fullscreen: {0}", GUIGraphicsContext.DX9Device.PresentationParameters.Windowed);
          if (GUIGraphicsContext.DX9Device.PresentationParameters.Windowed)
          {
            SwitchFullScreenOrWindowed(false);
          }
        }
        else
        {
          //switch to windowed mode
          Log.Debug("Main: Goto windowed mode: {0}",
                    GUIGraphicsContext.DX9Device.PresentationParameters.Windowed);
          if (!GUIGraphicsContext.DX9Device.PresentationParameters.Windowed)
          {
            SwitchFullScreenOrWindowed(true);
          }
        }
        // Must set the FVF after reset
        GUIFontManager.SetDevice();
        break;

      case GUIMessage.MessageType.GUI_MSG_GETFOCUS:
        Log.Debug("Main: Setting focus");
        if (WindowState == FormWindowState.Minimized)
        {
          if (m_iVolume > 0 && (g_Player.IsVideo || g_Player.IsTV))
          {
            g_Player.Volume = m_iVolume;
            if (g_Player.Paused)
            {
              g_Player.Pause();
            }
          }
          Restore();
        }
        else
        {
          Activate();
        }
        //Force.SetForegroundWindow(this.Handle, true);
        break;

      case GUIMessage.MessageType.GUI_MSG_CODEC_MISSING:
        GUIDialogOK dlgOk = (GUIDialogOK)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_OK);
        dlgOk.SetHeading(string.Empty);
        dlgOk.SetLine(1, message.Label);
        dlgOk.SetLine(2, string.Empty);
        dlgOk.SetLine(3, message.Label2);
        dlgOk.SetLine(4, message.Label3);
        dlgOk.DoModal(GUIWindowManager.ActiveWindow);
        break;

      case GUIMessage.MessageType.GUI_MSG_REFRESHRATE_CHANGED:

        GUIDialogNotify dlgNotify =
          (GUIDialogNotify)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_NOTIFY);
        if (dlgNotify != null)
        {
          dlgNotify.Reset();
          dlgNotify.ClearAll();
          dlgNotify.SetHeading(message.Label);
          dlgNotify.SetText(message.Label2);
          dlgNotify.TimeOut = message.Param1;
          dlgNotify.DoModal(GUIWindowManager.ActiveWindow);
        }

        break;
    }
  }
Ejemplo n.º 43
0
        private void GetCoverArt()
        {
            if (!Win32API.IsConnectedToInternet())
            {
                return;
            }

            GrabInProgress = true;
            GUICoverArtGrabberResults.CancelledByUser = false;
            _AbortedByUser = false;
            _Abort         = false;

            btnStart.Focus  = false;
            btnCancel.Focus = true;

            progCurrent.Percentage = 0;
            progOverall.Percentage = 0;

            lblCurrentAlbum.Label    = "";
            lblCurrentProgress.Label = "";
            lblFilteredSearch.Label  = "";
            lblFolderName.Label      = "";
            lblOverallProgress.Label = "";

            EnableControls(false);

            // Force a redraw...
            GUIWindowManager.Process();

            if (_MusicDatabase == null)
            {
                _MusicDatabase = MusicDatabase.Instance;
            }

            int albumCount = 0;
            int curCount   = 0;

            songs.Clear();

            try
            {
                ShowWaitCursor();
                string status = GUILocalizeStrings.Get(4503);

                if (status.Length == 0)
                {
                    status = "Getting album count. Please wait...";
                }

                lblCurrentAlbum.Label     = status;
                lblCurrentAlbum.Visible   = true;
                lblFilteredSearch.Visible = true;

                GUIWindowManager.Process();

                Log.Info("Cover art grabber:getting folder count for {0}...", _TopLevelFolderName);
                GetAlbumCount(_TopLevelFolderName, ref albumCount);
                Log.Info("Cover art grabber:{0} folders found", albumCount);
            }

            finally
            {
                HideWaitCursor();
            }

            lblFilteredSearch.Label    = "";
            lblCurrentProgress.Label   = "";
            lblCurrentProgress.Visible = true;
            ShowTotalProgressBar(true);
            GUIWindowManager.Process();

            Log.Info("Cover art grabber:getting pending cover count...");
            GetCoverArtList(_TopLevelFolderName, ref albumCount, ref curCount, _SkipIfCoverArtExists, ref songs);
            Log.Info("Cover art grabber:{0} covers queued for update", albumCount);

            if (_Abort)
            {
                Cleanup();
                return;
            }

            _CoversGrabbed = 0;
            _AbortedByUser = false;
            _AlbumCount    = songs.Count;

            try
            {
                if (_AlbumCount > 0)
                {
                    GuiCoverArtResults =
                        (GUICoverArtGrabberResults)GUIWindowManager.GetWindow((int)Window.WINDOW_MUSIC_COVERART_GRABBER_RESULTS);

                    if (null == GuiCoverArtResults)
                    {
                        return;
                    }

                    GuiCoverArtResults.SearchMode            = GUICoverArtGrabberResults.SearchDepthMode.Share;
                    GuiCoverArtResults.FindCoverArtProgress +=
                        new GUICoverArtGrabberResults.FindCoverArtProgressHandler(OnFindCoverArtProgress);
                    GuiCoverArtResults.FindCoverArtDone +=
                        new GUICoverArtGrabberResults.FindCoverArtDoneHandler(OnFindCoverArtDone);
                    GuiCoverArtResults.AlbumNotFoundRetryingFiltered +=
                        new GUICoverArtGrabberResults.AlbumNotFoundRetryingFilteredHandler(OnAlbumNotFoundRetryingFiltered);

                    ShowTotalProgressBar(true);
                    ShowCurrentProgressBar(true);

                    lblOverallProgress.Visible = true;
                    lblCurrentProgress.Visible = true;

                    GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_REFRESH, 0, 0, 0, GetID, 0, null);
                    GUIWindowManager.SendMessage(msg);

                    for (int i = 0; i < songs.Count; i++)
                    {
                        if (_Abort)
                        {
                            break;
                        }

                        lblFilteredSearch.Clear();
                        lblFilteredSearch.Visible = false;

                        Song curSong = songs[i];
                        CurrentCoverArtIndex = i + 1;
                        SetCurrentCoverArtProgressLabel(curSong.Album, 0);
                        Application.DoEvents();

                        lblCurrentAlbum.Label = string.Format(GrabbingAlbumNameFormatString, curSong.Album);
                        string progressText = GetCurrentProgressString(0, curSong.Album);
                        SetCurrentProgressPercentage(0);
                        SetCurrentCoverArtProgressLabel(progressText, 0);
                        GUIWindowManager.Process();

                        if (curSong.FileName.Length == 0)
                        {
                            continue;
                        }

                        string albumPath = Path.GetDirectoryName(curSong.FileName);
                        GuiCoverArtResults.GetAlbumCovers(curSong.Artist, curSong.Album, albumPath, GetID, true);

                        if (IsAbortedByUser())
                        {
                            break;
                        }

                        GuiCoverArtResults.DoModal(GetID);

                        if (IsAbortedByUser())
                        {
                            break;
                        }

                        if (GuiCoverArtResults.SelectedAlbum != null)
                        {
                            _CoversGrabbed++;

                            if (CoverArtSelected != null)
                            {
                                GuiCoverArtResults.SelectedAlbum.Artist = curSong.Artist;
                                GuiCoverArtResults.SelectedAlbum.Album  = curSong.Album;
                                CoverArtSelected(GuiCoverArtResults.SelectedAlbum, albumPath, _SaveImageToAlbumFolder,
                                                 _SaveImageToThumbsFolder);
                            }
                        }
                    }
                }
            }

            catch (Exception ex)
            {
                Log.Info("Cover art grabber exception:{0}", ex.ToString());
                _GrabCompletedSuccessfully = false;
            }

            finally
            {
                Cleanup();
            }

            if (CoverArtGrabDone != null)
            {
                CoverArtGrabDone(this);
            }

            ShowResultsDialog(_AbortedByUser, _GrabCompletedSuccessfully, _CoversGrabbed, GetID);
        }
Ejemplo n.º 44
0
  /// <summary>
  /// Message Pump
  /// </summary>
  /// <param name="msg"></param>
  protected override void WndProc(ref Message msg)
  {
    try
    {
      switch (msg.Msg)
      {
        case (int)ShellNotifications.WmShnotify:
          NotifyInfos info = new NotifyInfos((ShellNotifications.SHCNE)(int)msg.LParam);
          
          if (Notifications.NotificationReceipt(msg.WParam, msg.LParam, ref info))
          {
            if (info.Notification == ShellNotifications.SHCNE.SHCNE_MEDIAINSERTED)
            {
              string path = info.Item1;

              if (Utils.IsRemovable(path))
              {
                string driveName = Utils.GetDriveName(info.Item1);
                GUIMessage gmsg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_ADD_REMOVABLE_DRIVE, 0, 0, 0, 0, 0, 0);
                gmsg.Label = info.Item1;
                gmsg.Label2 = String.Format("({0}) {1}", path, driveName);
                GUIGraphicsContext.SendMessage(gmsg);
              }
            }

            if (info.Notification == ShellNotifications.SHCNE.SHCNE_MEDIAREMOVED)
            {
              string path = info.Item1;

              if (Utils.IsRemovable(path))
              {
                string driveName = Utils.GetDriveName(info.Item1);
                GUIMessage gmsg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_REMOVE_REMOVABLE_DRIVE, 0, 0, 0, 0, 0, 0);
                gmsg.Label = info.Item1;
                gmsg.Label2 = String.Format("({0}) {1}", path, driveName);
                GUIGraphicsContext.SendMessage(gmsg);
              }
            }
          }
          return;

        // power management
        case WM_POWERBROADCAST:
          OnPowerBroadcast(ref msg);
          break;

        // set maximum and minimum form size in windowed mode
        case WM_GETMINMAXINFO:
          OnGetMinMaxInfo(ref msg);
          PluginManager.WndProc(ref msg);
          break;

        case WM_ENTERSIZEMOVE:
          Log.Debug("Main: WM_ENTERSIZEMOVE");
          PluginManager.WndProc(ref msg);
          break;

        case WM_EXITSIZEMOVE:
          Log.Debug("Main: WM_EXITSIZEMOVE");
          PluginManager.WndProc(ref msg);
          break;

        // only allow window to be moved inside a valid working area
        case WM_MOVING:
          OnMoving(ref msg);
          PluginManager.WndProc(ref msg);
          break;
        
        // verify window size in case it was not resized by the user
        case WM_SIZE:
          OnSize(ref msg);
          PluginManager.WndProc(ref msg);
          break;

        // aspect ratio save window resizing
        case WM_SIZING:
          OnSizing(ref msg);
          PluginManager.WndProc(ref msg);
          break;
        
        // handle display changes
        case WM_DISPLAYCHANGE:
          OnDisplayChange(ref msg);
          PluginManager.WndProc(ref msg);
          break;
        
        // handle device changes
        case WM_DEVICECHANGE:
          OnDeviceChange(ref msg);
          PluginManager.WndProc(ref msg);
          break;

        case WM_QUERYENDSESSION:
          Log.Debug("Main: WM_QUERYENDSESSION");
          PluginManager.WndProc(ref msg);
          base.WndProc(ref msg);
          ShuttingDown = true;
          msg.Result = (IntPtr)1;
          break;

        case WM_ENDSESSION:
          Log.Info("Main: WM_ENDESSION");
          PluginManager.WndProc(ref msg);
          base.WndProc(ref msg);
          Application.ExitThread();
          Application.Exit();
          msg.Result = (IntPtr)0;
          break;
        
        // handle activation and deactivation requests
        case WM_ACTIVATE:
          OnActivate(ref msg);
          PluginManager.WndProc(ref msg);
          break;

        // handle system commands
        case WM_SYSCOMMAND:
          // do not continue with rest of method in case we aborted screen saver or display powering off
          if (!OnSysCommand(ref msg))
          {
            return;
          }
          PluginManager.WndProc(ref msg);
          break;

        // handle default commands needed for plugins
        default:
          PluginManager.WndProc(ref msg);
          break;
      }

      // TODO: extract to method and change to correct code
      // forward message to input devices
      Action action;
      char key;
      Keys keyCode;
      if (InputDevices.WndProc(ref msg, out action, out key, out keyCode))
      {
        if (msg.Result.ToInt32() != 1)
        {
          msg.Result = new IntPtr(0);
        }

        if (action != null && action.wID != Action.ActionType.ACTION_INVALID)
        {
          Log.Info("Main: Incoming action: {0}", action.wID);
          if (ActionTranslator.GetActionDetail(GUIWindowManager.ActiveWindowEx, action) && (action.SoundFileName.Length > 0 && !g_Player.Playing))
          {
            Utils.PlaySound(action.SoundFileName, false, true);
          }
          GUIGraphicsContext.ResetLastActivity();
          GUIGraphicsContext.OnAction(action);
        }

        if (keyCode != Keys.A)
        {
          Log.Info("Main: Incoming Keycode: {0}", keyCode.ToString());
          var ke = new KeyEventArgs(keyCode);
          OnKeyDown(ke);
          return; // abort WndProc()
        }

        if (key != 0)
        {
          Log.Info("Main: Incoming Key: {0}", key);
          var e = new KeyPressEventArgs(key);
          OnKeyPress(e);
          return; // abort WndProc()
        }

        return; // abort WndProc()
      }

      // forward message to player
      g_Player.WndProc(ref msg);

      // forward message to form class
      base.WndProc(ref msg);
    }

    catch (Exception ex)
    {
      Log.Error(ex);
    }
  }
Ejemplo n.º 45
0
 public override bool OnMessage(GUIMessage message)
 {
     return(base.OnMessage(message));
 }
Ejemplo n.º 46
0
  /// <summary>
  /// 
  /// </summary>
  /// <param name="action"></param>
  private void OnAction(Action action)
  {
    try
    {
      // hack/fix for lastactivemodulefullscreen
      // when recovering from hibernation/standby after closing with remote control somehow a F9 (keycode 120) onkeydown event is thrown from outside
      // we are currently filtering it away.
      // sometimes more than one F9 keydown event fired.
      // if these events are not filtered away the F9 context menu is shown on the restored/shown module.
      if ((action.wID == Action.ActionType.ACTION_CONTEXT_MENU || _suspended) && (_showLastActiveModule))
      {
        if (_ignoreContextMenuAction)
        {
          _ignoreContextMenuAction = false;
          _lastContextMenuAction = DateTime.Now;
          return;
        }
        
        if (_lastContextMenuAction != DateTime.MaxValue)
        {
          TimeSpan ts = _lastContextMenuAction - DateTime.Now;
          if (ts.TotalMilliseconds > -100)
          {
            _ignoreContextMenuAction = false;
            _lastContextMenuAction = DateTime.Now;
            return;
          }
        }
        _lastContextMenuAction = DateTime.Now;
      }

      GUIWindow window;
      if (action.IsUserAction())
      {
        GUIGraphicsContext.ResetLastActivity();
      }

      switch (action.wID)
      {
        // record current tv program
        case Action.ActionType.ACTION_RECORD:
          if ((GUIGraphicsContext.IsTvWindow(GUIWindowManager.ActiveWindowEx) &&
               GUIWindowManager.ActiveWindowEx != (int)GUIWindow.Window.WINDOW_TVGUIDE) &&
              (GUIWindowManager.ActiveWindowEx != (int)GUIWindow.Window.WINDOW_DIALOG_TVGUIDE))
          {
            GUIWindow tvHome = GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_TV);
            if (tvHome != null && tvHome.GetID != GUIWindowManager.ActiveWindow)
            {
              tvHome.OnAction(action);
              return;
            }
          }
          break;

        // TV: zap to previous channel
        case Action.ActionType.ACTION_PREV_CHANNEL:
          if (!GUIWindowManager.IsRouted)
          {
            window = GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_TV);
            window.OnAction(action);
            return;
          }
          break;

        // TV: zap to next channel
        case Action.ActionType.ACTION_NEXT_CHANNEL:
          if (!GUIWindowManager.IsRouted)
          {
            window = GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_TV);
            window.OnAction(action);
            return;
          }
          break;

        // TV: zap to last channel viewed
        case Action.ActionType.ACTION_LAST_VIEWED_CHANNEL: // mPod
          if (!GUIWindowManager.IsRouted)
          {
            window = GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_TV);
            window.OnAction(action);
            return;
          }
          break;

        // toggle between windowed and fullscreen mode
        case Action.ActionType.ACTION_TOGGLE_WINDOWED_FULLSCREEN:
          ToggleFullscreen();
          return;

        // mute or unmute audio
        case Action.ActionType.ACTION_VOLUME_MUTE:
          VolumeHandler.Instance.IsMuted = !VolumeHandler.Instance.IsMuted;
          break;

        // decrease volume 
        case Action.ActionType.ACTION_VOLUME_DOWN:
          VolumeHandler.Instance.Volume = VolumeHandler.Instance.Previous;
          break;

        // increase volume 
        case Action.ActionType.ACTION_VOLUME_UP:
          VolumeHandler.Instance.Volume = VolumeHandler.Instance.Next;
          break;

        // toggle live tv in background
        case Action.ActionType.ACTION_BACKGROUND_TOGGLE:
          // show livetv or video as background instead of the static GUI background
          // toggle livetv/video in background on/off
          if (GUIGraphicsContext.ShowBackground)
          {
            Log.Info("Main: Using live TV as background");
            // if on, but we're not playing any video or watching tv
            if (GUIGraphicsContext.Vmr9Active)
            {
              GUIGraphicsContext.ShowBackground = false;
            }
            else
            {
              // show warning message
              var msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SHOW_WARNING, 0, 0, 0, 0, 0, 0) {Param1 = 727, Param2 = 728, Param3 = 729};
              GUIWindowManager.SendMessage(msg);
              return;
            }
          }
          else
          {
            Log.Info("Main: Using GUI as background");
            GUIGraphicsContext.ShowBackground = true;
          }
          break;

        // switch between several home windows
        case Action.ActionType.ACTION_SWITCH_HOME:
          GUIWindow.Window newHome = _startWithBasicHome
                                       ? GUIWindow.Window.WINDOW_SECOND_HOME
                                       : GUIWindow.Window.WINDOW_HOME;
          // do we prefer to use only one home screen?
          if (_useOnlyOneHome)
          {
            // skip if we are already in there
            if (GUIWindowManager.ActiveWindow == (int)newHome)
            {
              break;
            }
          }
          // we like both 
          else
          {
            // if already in one home switch to the other
            switch (GUIWindowManager.ActiveWindow)
            {
              case (int)GUIWindow.Window.WINDOW_HOME:
                newHome = GUIWindow.Window.WINDOW_SECOND_HOME;
                break;

              case (int)GUIWindow.Window.WINDOW_SECOND_HOME:
                newHome = GUIWindow.Window.WINDOW_HOME;
                break;
            }
          }
          var homeMsg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_GOTO_WINDOW, 0, 0, 0, (int)newHome, 0, null);
          GUIWindowManager.SendThreadMessage(homeMsg);
          // Stop Video for MyPictures when going to home
          if (g_Player.IsPicture)
          {
            GUISlideShow._slideDirection = 0;
            g_Player.Stop();
          }
          break;

        case Action.ActionType.ACTION_MPRESTORE:
          Log.Info("Main: Restore MP by action");
          RestoreFromTray();
          if ((g_Player.IsVideo || g_Player.IsTV || g_Player.IsDVD) && Volume > 0)
          {
            g_Player.Volume = Volume;
            g_Player.ContinueGraph();
            if (g_Player.Paused && !GUIGraphicsContext.IsVMR9Exclusive)
            {
              g_Player.Pause();
            }
          }
          break;

        // reboot pc
        case Action.ActionType.ACTION_POWER_OFF:
        case Action.ActionType.ACTION_SUSPEND:
        case Action.ActionType.ACTION_HIBERNATE:
        case Action.ActionType.ACTION_REBOOT:
          // reboot
          Log.Info("Main: Reboot requested");
          bool okToChangePowermode = (Math.Abs(action.fAmount1 - 1) < float.Epsilon);

          if (!okToChangePowermode)
          {
            okToChangePowermode = PromptUserBeforeChangingPowermode(action);
          }

          if (okToChangePowermode)
          {
            switch (action.wID)
            {
              case Action.ActionType.ACTION_REBOOT:
                _restartOptions = RestartOptions.Reboot;
                _useRestartOptions = true;
                GUIGraphicsContext.CurrentState = GUIGraphicsContext.State.STOPPING;
                break;

              case Action.ActionType.ACTION_POWER_OFF:
                _restartOptions = RestartOptions.PowerOff;
                _useRestartOptions = true;
                GUIGraphicsContext.CurrentState = GUIGraphicsContext.State.STOPPING;
                ShuttingDown = true;
                break;

              case Action.ActionType.ACTION_SUSPEND:
                if (IsSuspendOrHibernationAllowed())
                {
                  _restartOptions = RestartOptions.Suspend;
                  Utils.SuspendSystem(false);
                }
                else
                {
                  Log.Info("Main: SUSPEND ignored since suspend graceperiod of {0} sec. is violated.", _suspendGracePeriodSec); 
                }
                break;

              case Action.ActionType.ACTION_HIBERNATE:
                if (IsSuspendOrHibernationAllowed())
                {
                  _restartOptions = RestartOptions.Hibernate;
                  Utils.HibernateSystem(false);
                }
                else
                {
                  Log.Info("Main: HIBERNATE ignored since hibernate graceperiod of {0} sec. is violated.", _suspendGracePeriodSec);
                }
                break;
            }
          }
          break;

        // eject cd
        case Action.ActionType.ACTION_EJECTCD:
          Utils.EjectCDROM();
          break;

        // shutdown pc
        case Action.ActionType.ACTION_SHUTDOWN:
          Log.Info("Main: Shutdown dialog");
          var dlg = (GUIDialogMenu)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_MENU);
          if (dlg != null)
          {
            dlg.Reset();
            dlg.SetHeading(GUILocalizeStrings.Get(498)); //Menu
            dlg.AddLocalizedString(1057); //Exit MediaPortal
            dlg.AddLocalizedString(1058); //Restart MediaPortal
            dlg.AddLocalizedString(1032); //Suspend
            dlg.AddLocalizedString(1049); //Hibernate
            dlg.AddLocalizedString(1031); //Reboot
            dlg.AddLocalizedString(1030); //PowerOff
            dlg.DoModal(GUIWindowManager.ActiveWindow);

            if (dlg.SelectedId >= 0)
            {
              switch (dlg.SelectedId)
              {
                case 1057:
                  ExitMP();
                  return;

                case 1058:
                  GUIGraphicsContext.CurrentState = GUIGraphicsContext.State.STOPPING;
                  Utils.RestartMePo();
                  break;

                case 1030:
                  _restartOptions = RestartOptions.PowerOff;
                  _useRestartOptions = true;
                  GUIGraphicsContext.CurrentState = GUIGraphicsContext.State.STOPPING;
                  ShuttingDown = true;
                  break;

                case 1031:
                  _restartOptions = RestartOptions.Reboot;
                  _useRestartOptions = true;
                  GUIGraphicsContext.CurrentState = GUIGraphicsContext.State.STOPPING;
                  ShuttingDown = true;
                  break;

                case 1032:
                  _restartOptions = RestartOptions.Suspend;
                  Utils.SuspendSystem(false);
                  break;

                case 1049:
                  _restartOptions = RestartOptions.Hibernate;
                  Utils.HibernateSystem(false);
                  break;
              }
            }
            else
            {
              GUIWindow win = GUIWindowManager.GetWindow((int) GUIWindow.Window.WINDOW_HOME);
              if (win != null)
              {
                win.OnAction(new Action(Action.ActionType.ACTION_MOVE_LEFT, 0, 0));
              }
            }
          }
          break;

        // exit Mediaportal
        case Action.ActionType.ACTION_EXIT:
          ExitMP();
          break;

        // stop radio
        case Action.ActionType.ACTION_STOP:
          break;

        // Take Screen shot
        case Action.ActionType.ACTION_TAKE_SCREENSHOT:
          try
          {
            string directory = string.Format("{0}\\MediaPortal Screenshots\\{1:0000}-{2:00}-{3:00}",
                                             Environment.GetFolderPath(Environment.SpecialFolder.MyPictures),
                                             DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
            if (!Directory.Exists(directory))
            {
              Log.Info("Main: Taking screenshot - Creating directory: {0}", directory);
              Directory.CreateDirectory(directory);
            }

            string fileName = string.Format("{0}\\{1:00}-{2:00}-{3:00}", directory, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
            Log.Info("Main: Taking screenshot - Target: {0}.png", fileName);
            Surface backbuffer = GUIGraphicsContext.DX9Device.GetBackBuffer(0, 0, BackBufferType.Mono);
            SurfaceLoader.Save(fileName + ".png", ImageFileFormat.Png, backbuffer);
            backbuffer.Dispose();
            Log.Info("Main: Taking screenshot done");
          }
          catch (Exception ex)
          {
            Log.Info("Main: Error taking screenshot: {0}", ex.Message);
          }
          break;

        case Action.ActionType.ACTION_SHOW_GUI:
          // can we handle the switch to fullscreen?
          if (!GUIGraphicsContext.IsFullScreenVideo && g_Player.ShowFullScreenWindow())
          {
            return;
          }
          break;
      }

      if (g_Player.Playing)
      {
        string activeWindowName;
        GUIWindow.Window activeWindow;

        switch (action.wID)
        {
          // show DVD menu
          case Action.ActionType.ACTION_DVD_MENU:
            if (g_Player.IsDVD)
            {
              g_Player.OnAction(action);
              return;
            }
            break;

          // DVD: goto previous chapter
          // play previous item from playlist;
          case Action.ActionType.ACTION_PREV_ITEM:
          case Action.ActionType.ACTION_PREV_CHAPTER:
            if (g_Player.IsDVD || g_Player.HasChapters)
            {
              action = new Action(Action.ActionType.ACTION_PREV_CHAPTER, 0, 0);
              g_Player.OnAction(action);
              break;
            }
            // When MyPictures Plugin shows the pictures/videos we don't want to change music track
            activeWindowName = GUIWindowManager.ActiveWindow.ToString(CultureInfo.InvariantCulture);
            activeWindow = (GUIWindow.Window) Enum.Parse(typeof(GUIWindow.Window), activeWindowName);
            if (!ActionTranslator.HasKeyMapped(GUIWindowManager.ActiveWindowEx, action.m_key) &&
                (activeWindow != GUIWindow.Window.WINDOW_SLIDESHOW && !g_Player.IsPicture))
            {
              PlaylistPlayer.PlayPrevious();
            }
            break;

          // play next item from playlist;
          // DVD: goto next chapter
          case Action.ActionType.ACTION_NEXT_CHAPTER:
          case Action.ActionType.ACTION_NEXT_ITEM:
            if (g_Player.IsDVD || g_Player.HasChapters)
            {
              action = new Action(Action.ActionType.ACTION_NEXT_CHAPTER, 0, 0);
              g_Player.OnAction(action);
              break;
            }
            // When MyPictures Plugin shows the pictures/videos we don't want to change music track
            activeWindowName = GUIWindowManager.ActiveWindow.ToString(CultureInfo.InvariantCulture);
            activeWindow = (GUIWindow.Window) Enum.Parse(typeof(GUIWindow.Window), activeWindowName);
            if (!ActionTranslator.HasKeyMapped(GUIWindowManager.ActiveWindowEx, action.m_key) && (activeWindow != GUIWindow.Window.WINDOW_SLIDESHOW && !g_Player.IsPicture))
            {
              PlaylistPlayer.PlayNext();
            }
            break;

          // stop playback
          case Action.ActionType.ACTION_STOP:
            // When MyPictures Plugin shows the pictures we want to stop the slide show only, not the player
            activeWindowName = GUIWindowManager.ActiveWindow.ToString(CultureInfo.InvariantCulture);
            activeWindow = (GUIWindow.Window)Enum.Parse(typeof(GUIWindow.Window), activeWindowName);
            if ((activeWindow == GUIWindow.Window.WINDOW_SLIDESHOW) || (activeWindow == GUIWindow.Window.WINDOW_FULLSCREEN_VIDEO && g_Player.IsPicture) && g_Player.Playing)
            {
              break;
            }

            if (!g_Player.IsTV || !GUIGraphicsContext.IsFullScreenVideo)
            {
              Log.Info("Main: Stopping media");
              if (g_Player.IsPicture)
              {
                GUISlideShow._slideDirection = 0;
              }
              g_Player.Stop();
            }
            break;

          // Jump to Music Now Playing
          case Action.ActionType.ACTION_JUMP_MUSIC_NOW_PLAYING:
            if (g_Player.IsMusic)
            {
              if (GUIWindowManager.ActiveWindow == (int)GUIWindow.Window.WINDOW_MUSIC_PLAYING_NOW)
              {
                GUIWindowManager.ShowPreviousWindow();
            }
              else
              {
                GUIWindowManager.ActivateWindow((int) GUIWindow.Window.WINDOW_MUSIC_PLAYING_NOW);
              }
            }
            break;

          // play music
          // resume playback
          case Action.ActionType.ACTION_PLAY:
          case Action.ActionType.ACTION_MUSIC_PLAY:
            // Don't start playing from the beginning if we press play to return to normal speed
            if (g_Player.IsMusic && g_Player.Speed != 1 &&
                (GUIWindowManager.ActiveWindow != (int) GUIWindow.Window.WINDOW_MUSIC_FILES &&
                 GUIWindowManager.ActiveWindow != (int) GUIWindow.Window.WINDOW_MUSIC_GENRE))
            {
              g_Player.Speed = 1;
              break;
            }

            g_Player.StepNow();
            g_Player.Speed = 1;

            if (g_Player.Paused)
            {
              g_Player.Pause();
            }
            break;

          // pause (or resume playback)
          case Action.ActionType.ACTION_PAUSE:
            // When MyPictures Plugin shows the pictures we want to pause the slide show only, not the player
            activeWindowName = GUIWindowManager.ActiveWindow.ToString(CultureInfo.InvariantCulture);
            activeWindow = (GUIWindow.Window)Enum.Parse(typeof(GUIWindow.Window), activeWindowName);
            if ((activeWindow == GUIWindow.Window.WINDOW_SLIDESHOW) ||
                (activeWindow == GUIWindow.Window.WINDOW_FULLSCREEN_VIDEO && g_Player.IsPicture) && g_Player.Playing && !g_Player.IsVideo)
            {
              break;
            }
            g_Player.Pause();

            break;

          // fast forward...
          case Action.ActionType.ACTION_FORWARD:
            {
              if (g_Player.Paused)
              {
                g_Player.Pause();
              }
              g_Player.Speed = Utils.GetNextForwardSpeed(g_Player.Speed);
              break;
            }

          // Decide if we want to have CD style of FF or Skip steps
          case Action.ActionType.ACTION_MUSIC_FORWARD:
            // When MyPictures Plugin shows the pictures/videos we don't want to change music track
            activeWindowName = GUIWindowManager.ActiveWindow.ToString(CultureInfo.InvariantCulture);
            activeWindow = (GUIWindow.Window) Enum.Parse(typeof(GUIWindow.Window), activeWindowName);
            if (!ActionTranslator.HasKeyMapped(GUIWindowManager.ActiveWindowEx, action.m_key) && (activeWindow != GUIWindow.Window.WINDOW_SLIDESHOW && !g_Player.IsPicture || g_Player.IsVideo))
            {
              if (g_Player.Paused)
              {
                g_Player.Pause();
              }
              if (!MediaPortal.MusicPlayer.BASS.Config.UseSkipSteps)
              {
                g_Player.Speed = Utils.GetNextForwardSpeed(g_Player.Speed);
              }
            }
            break;
 
          // fast rewind...
          case Action.ActionType.ACTION_REWIND:
            {
              if (g_Player.Paused)
              {
                g_Player.Pause();
              }
              g_Player.Speed = Utils.GetNextRewindSpeed(g_Player.Speed);
              break;
            }

          // Decide if we want to have CD style of Rew or Skip steps
          case Action.ActionType.ACTION_MUSIC_REWIND:
            // When MyPictures Plugin shows the pictures/videos we don't want to change music track
            activeWindowName = GUIWindowManager.ActiveWindow.ToString(CultureInfo.InvariantCulture);
            activeWindow = (GUIWindow.Window) Enum.Parse(typeof(GUIWindow.Window), activeWindowName);
            if (!ActionTranslator.HasKeyMapped(GUIWindowManager.ActiveWindowEx, action.m_key) && (activeWindow != GUIWindow.Window.WINDOW_SLIDESHOW && !g_Player.IsPicture || g_Player.IsVideo))
            {
              if (g_Player.Paused)
              {
                g_Player.Pause();
              }
              if (!MediaPortal.MusicPlayer.BASS.Config.UseSkipSteps)
              {
                g_Player.Speed = Utils.GetNextRewindSpeed(g_Player.Speed);
              }
            }
            break;
         }
      }
      GUIWindowManager.OnAction(action);
    }
    catch (FileNotFoundException ex)
    {
      Log.Error(ex);
      // ReSharper disable LocalizableElement
      MessageBox.Show("File not found:" + ex.FileName, "MediaPortal", MessageBoxButtons.OK, MessageBoxIcon.Error);
      // ReSharper restore LocalizableElement
      Close();
    }
    catch (Exception ex)
    {
      Log.Error(ex);
      Log.Error("Exception: {0} {1} {2}", ex.Message, ex.Source, ex.StackTrace);
      #if !DEBUG
      throw new Exception("exception occurred", ex);
      #endif
    }
  }
Ejemplo n.º 47
0
    protected override void OnDefaultAction(Action action)
    {
      if (currentSelection == Selection.Down || currentSelection == Selection.Up)
      {
        // don't send the messages to a dialog menu
        if ((WindowId != (int)GUIWindow.Window.WINDOW_DIALOG_MENU) ||
            (action.wID == Action.ActionType.ACTION_SELECT_ITEM))
        {
          GUIMessage.MessageType msgType = GUIMessage.MessageType.GUI_MSG_CLICKED_UP;
          if (currentSelection == Selection.Down)
          {
            msgType = GUIMessage.MessageType.GUI_MSG_CLICKED_DOWN;
          }

          GUIMessage msg = new GUIMessage(msgType, WindowId, GetID, ParentID, (int)action.wID, 0, null);
          GUIGraphicsContext.SendMessage(msg);
        }
      }
      else
      {
        base.OnDefaultAction(action);
      }
    }
Ejemplo n.º 48
0
  /// <summary>
  /// 
  /// </summary>
  /// <param name="message"></param>
  private void OnMessage(GUIMessage message)
  {
    if (!_suspended && AppActive)
    {
      switch (message.Message)
      {
        case GUIMessage.MessageType.GUI_MSG_RESTART_REMOTE_CONTROLS:
          Log.Info("Main: Restart remote controls");
          InputDevices.Stop();
          InputDevices.Init();
          break;

        case GUIMessage.MessageType.GUI_MSG_GOTO_WINDOW:
          GUIWindowManager.ActivateWindow(message.Param1);
          GUIGraphicsContext.IsFullScreenVideo = GUIWindowManager.ActiveWindow == (int) GUIWindow.Window.WINDOW_TVFULLSCREEN ||
                                                 GUIWindowManager.ActiveWindow == (int) GUIWindow.Window.WINDOW_FULLSCREEN_TELETEXT ||
                                                 GUIWindowManager.ActiveWindow == (int) GUIWindow.Window.WINDOW_FULLSCREEN_VIDEO ||
                                                 GUIWindowManager.ActiveWindow == (int) GUIWindow.Window.WINDOW_FULLSCREEN_MUSIC;
          break;

        case GUIMessage.MessageType.GUI_MSG_CD_INSERTED:
          AutoPlay.ExamineCD(message.Label);
          break;

        case GUIMessage.MessageType.GUI_MSG_VOLUME_INSERTED:
          AutoPlay.ExamineVolume(message.Label);
          break;

        case GUIMessage.MessageType.GUI_MSG_TUNE_EXTERNAL_CHANNEL:
          double retNum;
          bool bIsInteger = Double.TryParse(message.Label, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out retNum);
          try
          {
            if (bIsInteger)
            {
              _usbuirtdevice.ChangeTunerChannel(message.Label);
            }
          }
          // ReSharper disable EmptyGeneralCatchClause
          catch {}
          // ReSharper restore EmptyGeneralCatchClause

          try
          {
            _winlircdevice.ChangeTunerChannel(message.Label);
          }
          // ReSharper disable EmptyGeneralCatchClause
          catch { }
          // ReSharper restore EmptyGeneralCatchClause
          
          try
          {
            if (bIsInteger)
            {
              _redeyedevice.ChangeTunerChannel(message.Label);
            }
          }
          // ReSharper disable EmptyGeneralCatchClause
          catch {}
          // ReSharper restore EmptyGeneralCatchClause
          break;

        case GUIMessage.MessageType.GUI_MSG_SWITCH_FULL_WINDOWED:
          Log.Info("Main: GUI_MSG_SWITCH_FULL_WINDOWED message is obsolete.");
          break;

        case GUIMessage.MessageType.GUI_MSG_GETFOCUS:
          Log.Debug("Main: Setting focus");
          if (WindowState != FormWindowState.Minimized)
          {
            Activate();
          }
          else
          {
            if (Volume > 0 && (g_Player.IsVideo || g_Player.IsTV))
            {
              g_Player.Volume = Volume;
              if (g_Player.Paused)
              {
                g_Player.Pause();
              }
            }
            RestoreFromTray();
          }
          break;

        case GUIMessage.MessageType.GUI_MSG_CODEC_MISSING:
          var dlgOk = (GUIDialogOK) GUIWindowManager.GetWindow((int) GUIWindow.Window.WINDOW_DIALOG_OK);
          dlgOk.SetHeading(string.Empty);
          dlgOk.SetLine(1, message.Label);
          dlgOk.SetLine(2, string.Empty);
          dlgOk.SetLine(3, message.Label2);
          dlgOk.SetLine(4, message.Label3);
          dlgOk.DoModal(GUIWindowManager.ActiveWindow);
          break;

        case GUIMessage.MessageType.GUI_MSG_REFRESHRATE_CHANGED:
          var dlgNotify = (GUIDialogNotify) GUIWindowManager.GetWindow((int) GUIWindow.Window.WINDOW_DIALOG_NOTIFY);
          if (dlgNotify != null)
          {
            dlgNotify.Reset();
            dlgNotify.ClearAll();
            dlgNotify.SetHeading(message.Label);
            dlgNotify.SetText(message.Label2);
            dlgNotify.TimeOut = message.Param1;
            dlgNotify.DoModal(GUIWindowManager.ActiveWindow);
          }
          break;

        case GUIMessage.MessageType.GUI_MSG_PLAYBACK_ENDED:
        case GUIMessage.MessageType.GUI_MSG_PLAYBACK_STOPPED:
          // reset idle timer for consistent timing after end 0f playback
          SetThreadExecutionState(EXECUTION_STATE.ES_SYSTEM_REQUIRED | EXECUTION_STATE.ES_DISPLAY_REQUIRED);
          break;
      }
    }
  }
Ejemplo n.º 49
0
 public override bool OnMessage(GUIMessage message)
 {
   bool result = base.OnMessage(message);
   if (message.Message == GUIMessage.MessageType.GUI_MSG_ITEM_SELECT)
   {
     UpdateUpDownControls();
   }
   return result;
 }
Ejemplo n.º 50
0
  /// <summary>
  /// 
  /// </summary>
  protected void CheckSkinVersion()
  {
    bool ignoreErrors;
    using (Settings xmlreader = new MPSettings())
    {
      ignoreErrors = xmlreader.GetValueAsBool("general", "dontshowskinversion", false);
    }

    if (!ignoreErrors)
    {
      Version versionSkin = null;
      string filename = GUIGraphicsContext.GetThemedSkinFile(@"\references.xml");
      if (File.Exists(filename))
      {
        var doc = new XmlDocument();
        doc.Load(filename);
        XmlNode node = doc.SelectSingleNode("/controls/skin/version");
        if (node != null)
        {
          versionSkin = new Version(node.InnerText);
        }
      }

      if (CompatibilityManager.SkinVersion != versionSkin)
      {
        _outdatedSkinName = GUIGraphicsContext.SkinName;
        float screenHeight = GUIGraphicsContext.currentScreen.Bounds.Height;
        float screenWidth = GUIGraphicsContext.currentScreen.Bounds.Width;
        float screenRatio = (screenWidth/screenHeight);
        GUIGraphicsContext.Skin = screenRatio > 1.5 ? "Titan" : "Default";
        Config.SkinName = GUIGraphicsContext.SkinName;
        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: User skin is not compatible, using skin {0} with theme {1}", GUIGraphicsContext.SkinName, GUIThemeManager.CurrentTheme);
      }
    }
  }
Ejemplo n.º 51
0
        public override bool OnMessage(GUIMessage message)
        {
            switch (message.Message)
            {
            case GUIMessage.MessageType.GUI_MSG_WINDOW_INIT:
            {
                for (int j = 0; j < NUM_STORIES; j++)
                {
                    m_feed_details[j].m_site        = "";
                    m_feed_details[j].m_title       = "";
                    m_feed_details[j].m_description = "";
                }

                base.OnMessage(message);
                LoadSettings();
                m_pSiteImage = (GUIImage)GetControl((int)Controls.CONTROL_IMAGELOGO);

                UpdateNews(true);

                return(true);
            }

            case GUIMessage.MessageType.GUI_MSG_WINDOW_DEINIT:
            {
                SaveSettings();
            }
            break;

            case GUIMessage.MessageType.GUI_MSG_ITEM_FOCUS_CHANGED:
            {
                int iControl = message.SenderControlId;
                if (iControl == (int)Controls.CONTROL_LIST)
                {
                    UpdateDetails();
                }
            }
            break;

            case GUIMessage.MessageType.GUI_MSG_CLICKED:
            {
                int iControl = message.SenderControlId;
                if (iControl == (int)Controls.CONTROL_BTNREFRESH)
                {
                    UpdateNews(true);
                }

                if (iControl == (int)Controls.CONTROL_LIST)
                {
                    String story = DownloadMainStory();

                    if (story != null)
                    {
                        GUIDialogText dlg = (GUIDialogText)GUIWindowManager.GetWindow((int)Window.WINDOW_DIALOG_TEXT);
                        if (dlg != null)
                        {
                            dlg.Reset();
                            dlg.ResetAllControls();
                            dlg.SetHeading("Story");
                            dlg.SetText(story);
                            dlg.DoModal(GetID);
                        }
                    }
                }

                if (iControl == (int)Controls.CONTROL_BTNCHANNEL)
                {
                    OnSelectFeed();

                    return(true);
                }
            }
            break;
            }
            return(base.OnMessage(message));
        }