/** Launches the associated applications for each selected file in the library if it can. */
  void launch(boolean playMedia) {
    int[] rows = TABLE.getSelectedRows();
    if (rows.length == 0) {
      return;
    }

    File selectedFile = DATA_MODEL.getFile(rows[0]);

    if (OSUtils.isWindows()) {
      if (selectedFile.isDirectory()) {
        GUIMediator.launchExplorer(selectedFile);
        return;
      } else if (!MediaPlayer.isPlayableFile(selectedFile)) {
        GUIMediator.launchFile(selectedFile);
        return;
      }
    }

    LaunchableProvider[] providers = new LaunchableProvider[rows.length];
    for (int i = 0; i < rows.length; i++) {
      providers[i] = new FileProvider(DATA_MODEL.getFile(rows[i]));
    }
    if (!playMedia) {
      MediaPlayer.instance().stop();
    }

    if (playMedia) {
      GUILauncher.launch(providers);
    } else {
      GUIMediator.launchFile(selectedFile);
    }
  }
  public void handleActionKey() {
    LibraryFilesTableDataLine line = DATA_MODEL.get(TABLE.getSelectedRow());
    if (line == null || line.getFile() == null) {
      return;
    }
    if (getMediaType().equals(MediaType.getAudioMediaType())
        && MediaPlayer.isPlayableFile(line.getFile())) {
      MediaPlayer.instance()
          .asyncLoadMedia(new MediaSource(line.getFile()), true, false, true, null, getFilesView());
      UXStats.instance().log(UXAction.LIBRARY_PLAY_AUDIO_FROM_FILE);
      return;
    }

    int[] rows = TABLE.getSelectedRows();
    // LibraryTableModel ltm = DATA_MODEL;
    // File file;
    for (int i = 0; i < rows.length; i++) {
      // file = ltm.getFile(rows[i]);
      // if it's a directory try to select it in the library tree
      // if it could be selected return
      //			if (file.isDirectory()
      //				&& LibraryMediator.setSelectedDirectory(file))
      //				return;
    }

    launch(true);
  }
 private void resetAudioPlayerFileView() {
   Playlist playlist = MediaPlayer.instance().getCurrentPlaylist();
   if (playlist != null && playlist.equals(currentPlaylist)) {
     if (MediaPlayer.instance().getPlaylistFilesView() != null) {
       MediaPlayer.instance().setPlaylistFilesView(getFilesView());
     }
   }
 }
  private void playMedia() {
    LibraryPlaylistsTableDataLine line = DATA_MODEL.get(TABLE.getSelectedRow());
    if (line == null || line.getPlayListItem() == null) {
      return;
    }

    MediaSource mediaSource = new MediaSource(line.getPlayListItem());
    if (MediaPlayer.isPlayableFile(mediaSource)) {
      MediaPlayer.instance()
          .asyncLoadMedia(mediaSource, true, true, currentPlaylist, getFilesView());
    }
  }
  /** Launches the associated applications for each selected file in the library if it can. */
  void launch(boolean playAudio) {
    int[] rows = TABLE.getSelectedRows();
    if (rows.length == 0) {
      return;
    }

    File selectedFile = DATA_MODEL.getFile(rows[0]);

    if (OSUtils.isWindows()) {
      if (selectedFile.isDirectory()) {
        GUIMediator.launchExplorer(selectedFile);
        return;
      } else if (!MediaPlayer.isPlayableFile(selectedFile)) {
        String extension = FilenameUtils.getExtension(selectedFile.getName());
        if (extension != null && extension.equals("torrent")) {
          GUIMediator.instance().openTorrentFile(selectedFile, true);
        } else {
          GUIMediator.launchFile(selectedFile);
        }
        return;
      }
    }

    LaunchableProvider[] providers = new LaunchableProvider[rows.length];
    boolean stopAudio = false;
    for (int i = 0; i < rows.length; i++) {
      try {
        MediaType mt =
            MediaType.getMediaTypeForExtension(
                FilenameUtils.getExtension(DATA_MODEL.getFile(rows[i]).getName()));
        if (mt.equals(MediaType.getVideoMediaType())) {
          stopAudio = true;
        }
      } catch (Throwable e) {
        // ignore
      }
      providers[i] = new FileProvider(DATA_MODEL.getFile(rows[i]));
    }
    if (stopAudio || !playAudio) {
      MediaPlayer.instance().stop();
    }

    if (playAudio) {
      GUILauncher.launch(providers);
      UXStats.instance()
          .log(stopAudio ? UXAction.LIBRARY_VIDEO_PLAY : UXAction.LIBRARY_PLAY_AUDIO_FROM_FILE);
    } else {
      GUIMediator.launchFile(selectedFile);
    }
  }
    @Override
    public void actionPerformed(ActionEvent e) {
      File file = BTDownloadMediator.instance().getSelectedDownloaders()[0].getSaveLocation();

      if (file.isDirectory() && LibraryUtils.directoryContainsASinglePlayableFile(file, 4)) {
        try {
          file = file.listFiles()[0];
        } catch (Throwable t) {
          file = null;
        }
      }

      if (file != null && MediaPlayer.isPlayableFile(file)) {
        MediaPlayer.instance().loadMedia(new MediaSource(file), true, false, false);
      }
    }
  private boolean isPlaying() {
    if (initializer != null) {
      return MediaPlayer.instance().isThisBeingPlayed(initializer);
    }

    return false;
  }
  public void refreshSelection() {

    LibraryPlaylistsListCell cell = (LibraryPlaylistsListCell) _list.getSelectedValue();

    if (cell == null) {
      // handle special case
      if (_model.getSize() == 2 && MediaPlayer.instance().getCurrentPlaylist() == null) {
        _list.setSelectedIndex(1);
      }
      return;
    }

    Playlist playlist = cell.getPlaylist();

    if (playlist != null) {
      playlist.refresh();
      LibraryMediator.instance().updateTableItems(playlist);
      String status =
          LibraryUtils.getPlaylistDurationInDDHHMMSS(playlist)
              + ", "
              + playlist.getItems().size()
              + " "
              + I18n.tr("tracks");
      LibraryMediator.instance().getLibrarySearch().setStatus(status);
    }

    executePendingRunnables();
  }
  private boolean isStreamableSourceBeingPlayed(UISearchResult sr) {
    if (!(sr instanceof StreamableSearchResult)) {
      return false;
    }

    StreamableSearchResult ssr = (StreamableSearchResult) sr;
    return MediaPlayer.instance().isThisBeingPlayed(ssr.getStreamUrl());
  }
 @Override
 protected MediaSource createMediaSource(LibraryFilesTableDataLine line) {
   if (MediaPlayer.isPlayableFile(line.getInitializeObject())) {
     return new MediaSource(line.getInitializeObject());
   } else {
     return null;
   }
 }
  /**
   * Handles the selection rows in the library window, enabling or disabling buttons and chat menu
   * items depending on the values in the selected rows.
   *
   * @param row the index of the first row that is selected
   */
  public void handleSelection(int row) {
    int[] sel = TABLE.getSelectedRows();
    if (sel.length == 0) {
      handleNoSelection();
      return;
    }

    File selectedFile = getFile(sel[0]);

    //  always turn on Launch, Delete, Magnet Lookup, Bitzi Lookup
    LAUNCH_ACTION.setEnabled(true);
    LAUNCH_OS_ACTION.setEnabled(true);
    DELETE_ACTION.setEnabled(true);

    if (selectedFile != null && !selectedFile.getName().endsWith(".torrent")) {
      CREATE_TORRENT_ACTION.setEnabled(sel.length == 1);
    }

    if (selectedFile != null) {
      SEND_TO_FRIEND_ACTION.setEnabled(sel.length == 1);

      if (getMediaType().equals(MediaType.getAnyTypeMediaType())) {
        boolean atLeastOneIsPlayable = false;

        for (int i : sel) {
          File f = getFile(i);
          if (MediaPlayer.isPlayableFile(f) || hasExtension(f.getAbsolutePath(), "mp4")) {
            atLeastOneIsPlayable = true;
            break;
          }
        }

        SEND_TO_ITUNES_ACTION.setEnabled(atLeastOneIsPlayable);
      } else {
        SEND_TO_ITUNES_ACTION.setEnabled(
            getMediaType().equals(MediaType.getAudioMediaType())
                || hasExtension(selectedFile.getAbsolutePath(), "mp4"));
      }
    }

    if (sel.length == 1 && selectedFile.isFile() && selectedFile.getParentFile() != null) {
      OPEN_IN_FOLDER_ACTION.setEnabled(true);
    } else {
      OPEN_IN_FOLDER_ACTION.setEnabled(false);
    }

    if (sel.length == 1) {
      LibraryMediator.instance().getLibraryCoverArt().setFile(selectedFile);
    }

    //        boolean anyBeingShared = isAnyBeingShared();
    //        WIFI_SHARE_ACTION.setEnabled(!anyBeingShared);
    //        WIFI_UNSHARE_ACTION.setEnabled(!anyBeingShared);
  }
 private boolean areAllSelectedFilesPlayable() {
   boolean selectionIsAllAudio = true;
   int[] selectedRows = TABLE.getSelectedRows();
   for (int i : selectedRows) {
     if (!MediaPlayer.isPlayableFile(DATA_MODEL.get(i).getInitializeObject())) {
       selectionIsAllAudio = false;
       break;
     }
   }
   return selectionIsAllAudio;
 }
 public List<MediaSource> getFilesView() {
   int size = DATA_MODEL.getRowCount();
   List<MediaSource> result = new ArrayList<MediaSource>(size);
   for (int i = 0; i < size; i++) {
     try {
       File file = DATA_MODEL.get(i).getFile();
       if (MediaPlayer.isPlayableFile(file)) {
         result.add(new MediaSource(DATA_MODEL.get(i).getFile()));
       }
     } catch (Exception e) {
       return Collections.emptyList();
     }
   }
   return result;
 }
    @Override
    public void onComplete(HttpClient client) {
      if (state != TransferState.REDIRECTING) {
        if (!setAlbumArt(tempAudio.getAbsolutePath(), completeFile.getAbsolutePath())) {
          boolean renameTo = tempAudio.renameTo(completeFile);

          if (!renameTo) {
            if (!MediaPlayer.instance().isThisBeingPlayed(tempAudio)) {
              state = TransferState.ERROR_MOVING_INCOMPLETE;
              cleanupIncomplete();
              return;
            } else {
              boolean copiedTo = copyPlayingTemp(tempAudio, completeFile);
              if (!copiedTo) {
                state = TransferState.ERROR_MOVING_INCOMPLETE;
                cleanupIncomplete();
                return;
              }
            }
            state = TransferState.ERROR_MOVING_INCOMPLETE;
            cleanupIncomplete();
            return;
          }
        }
        state = TransferState.FINISHED;

        if (iTunesSettings.ITUNES_SUPPORT_ENABLED.getValue()
            && !iTunesMediator.instance().isScanned(completeFile)) {
          if ((OSUtils.isMacOSX() || OSUtils.isWindows())) {
            iTunesMediator.instance().scanForSongs(completeFile);
          }
        }

        cleanupIncomplete();
      }
    }
  public void selectCurrentMedia() {
    // Select current playlist.
    Playlist currentPlaylist = MediaPlayer.instance().getCurrentPlaylist();
    final MediaSource currentMedia = MediaPlayer.instance().getCurrentMedia();

    // If the current song is being played from a playlist.
    if (currentPlaylist != null && currentMedia != null && currentMedia.getPlaylistItem() != null) {
      if (currentPlaylist.getId() != LibraryDatabase.STARRED_PLAYLIST_ID) {

        // select the song once it's available on the right hand side
        getLibraryPlaylists()
            .enqueueRunnable(
                new Runnable() {
                  public void run() {
                    GUIMediator.safeInvokeLater(
                        new Runnable() {
                          public void run() {
                            LibraryPlaylistsTableMediator.instance()
                                .setItemSelected(currentMedia.getPlaylistItem());
                          }
                        });
                  }
                });

        // select the playlist
        getLibraryPlaylists().selectPlaylist(currentPlaylist);
      } else {
        LibraryExplorer libraryFiles = getLibraryExplorer();

        // select the song once it's available on the right hand side
        libraryFiles.enqueueRunnable(
            new Runnable() {
              public void run() {
                GUIMediator.safeInvokeLater(
                    new Runnable() {
                      public void run() {
                        LibraryPlaylistsTableMediator.instance()
                            .setItemSelected(currentMedia.getPlaylistItem());
                      }
                    });
              }
            });

        libraryFiles.selectStarred();
      }

    } else if (currentMedia != null && currentMedia.getFile() != null) {
      // selects the audio node at the top
      LibraryExplorer libraryFiles = getLibraryExplorer();

      // select the song once it's available on the right hand side
      libraryFiles.enqueueRunnable(
          new Runnable() {
            public void run() {
              GUIMediator.safeInvokeLater(
                  new Runnable() {
                    public void run() {
                      LibraryFilesTableMediator.instance().setFileSelected(currentMedia.getFile());
                    }
                  });
            }
          });

      libraryFiles.selectAudio();
    } else if (currentMedia instanceof InternetRadioAudioSource) {
      // selects the audio node at the top
      LibraryExplorer libraryFiles = getLibraryExplorer();

      // select the song once it's available on the right hand side
      libraryFiles.enqueueRunnable(
          new Runnable() {
            public void run() {
              GUIMediator.safeInvokeLater(
                  new Runnable() {
                    public void run() {
                      LibraryInternetRadioTableMediator.instance()
                          .setItemSelected(
                              ((InternetRadioAudioSource) currentMedia).getInternetRadioStation());
                    }
                  });
            }
          });

      libraryFiles.selectRadio();
    } else if (currentMedia instanceof DeviceMediaSource) {
      // selects the audio node at the top
      LibraryExplorer libraryFiles = getLibraryExplorer();

      // select the song once it's available on the right hand side
      libraryFiles.enqueueRunnable(
          new Runnable() {
            public void run() {
              GUIMediator.safeInvokeLater(
                  new Runnable() {
                    public void run() {
                      LibraryDeviceTableMediator.instance()
                          .setItemSelected(((DeviceMediaSource) currentMedia).getFileDescriptor());
                    }
                  });
            }
          });

      libraryFiles.selectDeviceFileType(
          ((DeviceMediaSource) currentMedia).getDevice(),
          ((DeviceMediaSource) currentMedia).getFileDescriptor().fileType);
    }

    // Scroll to current song.
  }
 public void resetAudioPlayerFileView() {
   Playlist playlist = MediaPlayer.instance().getCurrentPlaylist();
   if (playlist == null) {
     MediaPlayer.instance().setPlaylistFilesView(getFilesView());
   }
 }
  /**
   * Override the default removal so we can actually stop sharing and delete the file. Deletes the
   * selected rows in the table. CAUTION: THIS WILL DELETE THE FILE FROM THE DISK.
   */
  public void removeSelection() {
    int[] rows = TABLE.getSelectedRows();
    if (rows.length == 0) return;

    if (TABLE.isEditing()) {
      TableCellEditor editor = TABLE.getCellEditor();
      editor.cancelCellEditing();
    }

    List<File> files = new ArrayList<File>(rows.length);

    // sort row indices and go backwards so list indices don't change when
    // removing the files from the model list
    Arrays.sort(rows);
    for (int i = rows.length - 1; i >= 0; i--) {
      File file = DATA_MODEL.getFile(rows[i]);
      files.add(file);
    }

    CheckBoxListPanel<File> listPanel =
        new CheckBoxListPanel<File>(files, new FileTextProvider(), true);
    listPanel.getList().setVisibleRowCount(4);

    // display list of files that should be deleted
    Object[] message =
        new Object[] {
          new MultiLineLabel(
              I18n.tr(
                  "Are you sure you want to delete the selected file(s), thus removing it from your computer?"),
              400),
          Box.createVerticalStrut(ButtonRow.BUTTON_SEP),
          listPanel,
          Box.createVerticalStrut(ButtonRow.BUTTON_SEP)
        };

    // get platform dependent options which are displayed as buttons in the dialog
    Object[] removeOptions = createRemoveOptions();

    int option =
        JOptionPane.showOptionDialog(
            MessageService.getParentComponent(),
            message,
            I18n.tr("Message"),
            JOptionPane.YES_NO_OPTION,
            JOptionPane.QUESTION_MESSAGE,
            null,
            removeOptions,
            removeOptions[0] /* default option */);

    if (option == removeOptions.length - 1 /* "cancel" option index */
        || option == JOptionPane.CLOSED_OPTION) {
      return;
    }

    // remove still selected files
    List<File> selected = listPanel.getSelectedElements();
    List<String> undeletedFileNames = new ArrayList<String>();

    boolean somethingWasRemoved = false;

    for (File file : selected) {
      // stop seeding if seeding
      BittorrentDownload dm = null;
      if ((dm = TorrentUtil.getDownloadManager(file)) != null) {
        dm.setDeleteDataWhenRemove(false);
        dm.setDeleteTorrentWhenRemove(false);
        BTDownloadMediator.instance().remove(dm);
      }

      // close media player if still playing
      if (MediaPlayer.instance().isThisBeingPlayed(file)) {
        MediaPlayer.instance().stop();
        MPlayerMediator.instance().showPlayerWindow(false);
      }

      // removeOptions > 2 => OS offers trash options
      boolean removed =
          FileUtils.delete(
              file, removeOptions.length > 2 && option == 0 /* "move to trash" option index */);
      if (removed) {
        somethingWasRemoved = true;
        DATA_MODEL.remove(DATA_MODEL.getRow(file));
      } else {
        undeletedFileNames.add(getCompleteFileName(file));
      }
    }

    clearSelection();

    if (somethingWasRemoved) {
      LibraryMediator.instance().getLibraryExplorer().refreshSelection(true);
    }

    if (undeletedFileNames.isEmpty()) {
      return;
    }

    // display list of files that could not be deleted
    message =
        new Object[] {
          new MultiLineLabel(
              I18n.tr(
                  "The following files could not be deleted. They may be in use by another application or are currently being downloaded to."),
              400),
          Box.createVerticalStrut(ButtonRow.BUTTON_SEP),
          new JScrollPane(createFileList(undeletedFileNames))
        };

    JOptionPane.showMessageDialog(
        MessageService.getParentComponent(), message, I18n.tr("Error"), JOptionPane.ERROR_MESSAGE);

    super.removeSelection();
  }