Search in sources :

Example 31 with DownloadManagerState

use of com.biglybt.core.download.DownloadManagerState in project BiglyBT by BiglySoftware.

the class DiskManagerImpl method allocateFiles.

private int[] allocateFiles() {
    int[] fail_result = { -1, -1 };
    Set file_set = new HashSet();
    DMPieceMapperFile[] pm_files = piece_mapper.getFiles();
    DiskManagerFileInfoImpl[] allocated_files = new DiskManagerFileInfoImpl[pm_files.length];
    DownloadManagerState state = download_manager.getDownloadState();
    try {
        allocation_scheduler.register(this);
        setState(ALLOCATING);
        allocated = 0;
        int numNewFiles = 0;
        int notRequiredFiles = 0;
        String root_dir = download_manager.getAbsoluteSaveLocation().getParent();
        if (!torrent.isSimpleTorrent()) {
            root_dir += File.separator + download_manager.getAbsoluteSaveLocation().getName();
        }
        root_dir += File.separator;
        String[] storage_types = getStorageTypes();
        String incomplete_suffix = state.getAttribute(DownloadManagerState.AT_INCOMP_FILE_SUFFIX);
        for (int i = 0; i < pm_files.length; i++) {
            if (stopping) {
                this.errorMessage = "File allocation interrupted - download is stopping";
                setState(FAULTY);
                return (fail_result);
            }
            final DMPieceMapperFile pm_info = pm_files[i];
            final long target_length = pm_info.getLength();
            File relative_data_file = pm_info.getDataFile();
            DiskManagerFileInfoImpl fileInfo;
            try {
                int storage_type = DiskManagerUtil.convertDMStorageTypeFromString(storage_types[i]);
                fileInfo = createFileInfo(state, pm_info, i, root_dir, relative_data_file, storage_type);
                allocated_files[i] = fileInfo;
                pm_info.setFileInfo(fileInfo);
            } catch (Exception e) {
                this.errorMessage = Debug.getNestedExceptionMessage(e) + " (allocateFiles:" + relative_data_file.toString() + ")";
                setState(FAULTY);
                return (fail_result);
            }
            CacheFile cache_file = fileInfo.getCacheFile();
            File data_file = fileInfo.getFile(true);
            String file_key = data_file.getAbsolutePath();
            if (Constants.isWindows) {
                file_key = file_key.toLowerCase();
            }
            if (file_set.contains(file_key)) {
                this.errorMessage = "File occurs more than once in download: " + data_file.toString() + ".\nRename one of the files in Files view via the right-click menu.";
                setState(FAULTY);
                return (fail_result);
            }
            file_set.add(file_key);
            String ext = data_file.getName();
            if (incomplete_suffix != null && ext.endsWith(incomplete_suffix)) {
                ext = ext.substring(0, ext.length() - incomplete_suffix.length());
            }
            int separator = ext.lastIndexOf(".");
            if (separator == -1) {
                separator = 0;
            }
            fileInfo.setExtension(ext.substring(separator));
            // Added for Feature Request
            // [ 807483 ] Prioritize .nfo files in new torrents
            // Implemented a more general way of dealing with it.
            String extensions = COConfigurationManager.getStringParameter("priorityExtensions", "");
            if (!extensions.equals("")) {
                boolean bIgnoreCase = COConfigurationManager.getBooleanParameter("priorityExtensionsIgnoreCase");
                StringTokenizer st = new StringTokenizer(extensions, ";");
                while (st.hasMoreTokens()) {
                    String extension = st.nextToken();
                    extension = extension.trim();
                    if (!extension.startsWith("."))
                        extension = "." + extension;
                    boolean bHighPriority = (bIgnoreCase) ? fileInfo.getExtension().equalsIgnoreCase(extension) : fileInfo.getExtension().equals(extension);
                    if (bHighPriority)
                        fileInfo.setPriority(1);
                }
            }
            fileInfo.setDownloaded(0);
            int st = cache_file.getStorageType();
            boolean compact = st == CacheFile.CT_COMPACT || st == CacheFile.CT_PIECE_REORDER_COMPACT;
            boolean mustExistOrAllocate = (!compact) || RDResumeHandler.fileMustExist(download_manager, fileInfo);
            if (!mustExistOrAllocate && cache_file.exists()) {
                data_file.delete();
            }
            if (cache_file.exists()) {
                try {
                    // make sure the existing file length isn't too large
                    long existing_length = fileInfo.getCacheFile().getLength();
                    if (existing_length > target_length) {
                        if (COConfigurationManager.getBooleanParameter("File.truncate.if.too.large")) {
                            fileInfo.setAccessMode(DiskManagerFileInfo.WRITE);
                            cache_file.setLength(target_length);
                            fileInfo.setAccessMode(DiskManagerFileInfo.READ);
                            Debug.out("Existing data file length too large [" + existing_length + ">" + target_length + "]: " + data_file.getAbsolutePath() + ", truncating");
                        } else {
                            this.errorMessage = "Existing data file length too large [" + existing_length + ">" + target_length + "]: " + data_file.getAbsolutePath();
                            setState(FAULTY);
                            return (fail_result);
                        }
                    } else if (existing_length < target_length) {
                        if (!compact) {
                            if (!allocateFile(fileInfo, data_file, existing_length, target_length)) {
                                return (fail_result);
                            }
                        }
                    }
                } catch (Throwable e) {
                    fileAllocFailed(data_file, target_length, false, e);
                    setState(FAULTY);
                    return (fail_result);
                }
                allocated += target_length;
            } else if (mustExistOrAllocate) {
                if (download_manager.isDataAlreadyAllocated()) {
                    this.errorMessage = "Data file missing: " + data_file.getAbsolutePath();
                    setState(FAULTY);
                    return (fail_result);
                }
                try {
                    if (!allocateFile(fileInfo, data_file, -1, target_length)) {
                        return (fail_result);
                    }
                } catch (Throwable e) {
                    fileAllocFailed(data_file, target_length, true, e);
                    setState(FAULTY);
                    return (fail_result);
                }
                numNewFiles++;
            } else {
                notRequiredFiles++;
            }
        }
        // make sure that "files" doens't become visible to the rest of the world until all
        // entries have been populated
        files = allocated_files;
        fileset = new DiskManagerFileInfoSetImpl(files, this);
        loadFilePriorities();
        download_manager.setDataAlreadyAllocated(true);
        return (new int[] { numNewFiles, notRequiredFiles });
    } finally {
        allocation_scheduler.unregister(this);
        if (files == null) {
            for (int i = 0; i < allocated_files.length; i++) {
                if (allocated_files[i] != null) {
                    try {
                        allocated_files[i].getCacheFile().close();
                    } catch (Throwable e) {
                    }
                }
            }
        }
    }
}
Also used : DownloadManagerState(com.biglybt.core.download.DownloadManagerState) LocaleUtilEncodingException(com.biglybt.core.internat.LocaleUtilEncodingException) CacheFileManagerException(com.biglybt.core.diskmanager.cache.CacheFileManagerException) PlatformManagerException(com.biglybt.pif.platform.PlatformManagerException) TOTorrentException(com.biglybt.core.torrent.TOTorrentException) DownloadManagerException(com.biglybt.core.download.DownloadManagerException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) CacheFile(com.biglybt.core.diskmanager.cache.CacheFile) TOTorrentFile(com.biglybt.core.torrent.TOTorrentFile) CacheFile(com.biglybt.core.diskmanager.cache.CacheFile) File(java.io.File)

Example 32 with DownloadManagerState

use of com.biglybt.core.download.DownloadManagerState in project BiglyBT by BiglySoftware.

the class RDResumeHandler method clearResumeDataSupport.

protected static int clearResumeDataSupport(DownloadManager download_manager, DiskManagerFileInfo file, boolean recheck, boolean onlyClearUnsharedFirstLast) {
    DownloadManagerState download_manager_state = download_manager.getDownloadState();
    Map resume_data = getResumeData(download_manager);
    if (resume_data == null) {
        return (0);
    }
    int pieces_cleared = 0;
    // clear any affected pieces
    byte[] resume_pieces = (byte[]) resume_data.get("resume data");
    int firstPiece = file.getFirstPieceNumber();
    int lastPiece = file.getLastPieceNumber();
    if (onlyClearUnsharedFirstLast) {
        DiskManagerFileInfo[] files = download_manager.getDiskManagerFileInfo();
        boolean firstPieceShared = false;
        boolean lastPieceShared = false;
        int firstFile = findFirstFileWithPieceN(firstPiece, files);
        for (int i = firstFile; i < files.length; i++) {
            DiskManagerFileInfo currentFile = files[i];
            if (currentFile.getLastPieceNumber() < firstPiece)
                continue;
            if (currentFile.getIndex() == file.getIndex())
                continue;
            if (currentFile.getFirstPieceNumber() > lastPiece)
                break;
            if (currentFile.getFirstPieceNumber() <= firstPiece && firstPiece <= currentFile.getLastPieceNumber())
                firstPieceShared |= !currentFile.isSkipped();
            if (currentFile.getFirstPieceNumber() <= lastPiece && lastPiece <= currentFile.getLastPieceNumber())
                lastPieceShared |= !currentFile.isSkipped();
        }
        if (firstPieceShared)
            firstPiece++;
        if (lastPieceShared)
            lastPiece--;
    }
    if (resume_pieces != null) {
        for (int i = firstPiece; i <= lastPiece; i++) {
            if (i >= resume_pieces.length) {
                break;
            }
            if (resume_pieces[i] == PIECE_DONE) {
                pieces_cleared++;
            }
            resume_pieces[i] = recheck ? PIECE_RECHECK_REQUIRED : PIECE_NOT_DONE;
        }
    }
    // clear any affected partial pieces
    Map partial_pieces = (Map) resume_data.get("blocks");
    if (partial_pieces != null) {
        Iterator iter = partial_pieces.keySet().iterator();
        while (iter.hasNext()) {
            int piece_number = Integer.parseInt((String) iter.next());
            if (piece_number >= firstPiece && piece_number <= lastPiece) {
                iter.remove();
            }
        }
    }
    // either way we're valid as
    // 1) clear -> pieces are set as not done
    // 2) recheck -> pieces are set as "recheck" and will be checked on restart
    resume_data.put("valid", new Long(1));
    saveResumeData(download_manager_state, resume_data);
    return (pieces_cleared);
}
Also used : DownloadManagerState(com.biglybt.core.download.DownloadManagerState) ByteArrayHashMap(com.biglybt.core.util.ByteArrayHashMap)

Example 33 with DownloadManagerState

use of com.biglybt.core.download.DownloadManagerState in project BiglyBT by BiglySoftware.

the class TorrentOpenOptions method getSmartDestDir.

private String getSmartDestDir() {
    String sSmartDir = sDestDir;
    try {
        String name = getTorrentName();
        String torrentFileName = sFileName == null ? "" : new File(sFileName).getName().replaceFirst("\\.torrent$", "");
        int totalSegmentsLengths = 0;
        String[][] segments = { name.split("[^a-zA-Z]+"), torrentFileName.split("[^a-zA-Z]+") };
        List downloadManagers = CoreFactory.getSingleton().getGlobalManager().getDownloadManagers();
        for (int x = 0; x < segments.length; x++) {
            String[] segmentArray = segments[x];
            for (int i = 0; i < segmentArray.length; i++) {
                int l = segmentArray[i].length();
                if (l <= 1) {
                    continue;
                }
                segmentArray[i] = segmentArray[i].toLowerCase();
                totalSegmentsLengths += l;
            }
        }
        int maxMatches = 0;
        DownloadManager match = null;
        long scanStarted = SystemTime.getCurrentTime();
        for (Iterator iter = downloadManagers.iterator(); iter.hasNext(); ) {
            DownloadManager dm = (DownloadManager) iter.next();
            if (dm.getState() == DownloadManager.STATE_ERROR) {
                continue;
            }
            DownloadManagerState dms = dm.getDownloadState();
            if (dms.getFlag(DownloadManagerState.FLAG_LOW_NOISE) || dms.getFlag(DownloadManagerState.FLAG_METADATA_DOWNLOAD)) {
                continue;
            }
            int numMatches = 0;
            String dmName = dm.getDisplayName().toLowerCase();
            for (int x = 0; x < segments.length; x++) {
                String[] segmentArray = segments[x];
                for (int i = 0; i < segmentArray.length; i++) {
                    int l = segmentArray[i].length();
                    if (l <= 1) {
                        continue;
                    }
                    String segment = segmentArray[i];
                    if (dmName.contains(segment)) {
                        numMatches += l;
                    }
                }
            }
            if (numMatches > maxMatches) {
                maxMatches = numMatches;
                match = dm;
            }
            long scanTime = SystemTime.getCurrentTime() - scanStarted;
            if (match != null && scanTime > 500) {
                break;
            }
            if (match == null && scanTime > 1000) {
                break;
            }
        }
        if (match != null) {
            // System.out.println(match + ": " + (maxMatches * 100 / totalSegmentsLengths) + "%\n");
            int iMatchLevel = (maxMatches * 100 / totalSegmentsLengths);
            if (iMatchLevel >= 30) {
                File f = match.getSaveLocation();
                if (!f.isDirectory() || match.getDiskManagerFileInfo().length > 1) {
                    // don't place data within another torrent's data dir
                    f = f.getParentFile();
                }
                if (f != null && f.isDirectory()) {
                    sSmartDir = f.getAbsolutePath();
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (sSmartDir.length() == 0) {
        try {
            return ConfigurationDefaults.getInstance().getStringParameter(PARAM_DEFSAVEPATH);
        } catch (ConfigurationParameterNotFoundException e) {
        }
    }
    return sSmartDir;
}
Also used : ConfigurationParameterNotFoundException(com.biglybt.core.config.impl.ConfigurationParameterNotFoundException) TOTorrentFile(com.biglybt.core.torrent.TOTorrentFile) File(java.io.File) DownloadManager(com.biglybt.core.download.DownloadManager) DownloadManagerState(com.biglybt.core.download.DownloadManagerState) ConfigurationParameterNotFoundException(com.biglybt.core.config.impl.ConfigurationParameterNotFoundException)

Example 34 with DownloadManagerState

use of com.biglybt.core.download.DownloadManagerState in project BiglyBT by BiglySoftware.

the class FilesViewMenuUtil method fillMenu.

public static void fillMenu(final TableView<?> tv, String columnName, final Menu menu, final DownloadManager[] manager_list, final DiskManagerFileInfo[][] files_list) {
    Shell shell = menu.getShell();
    final List<DiskManagerFileInfo> all_files = new ArrayList<>();
    for (DiskManagerFileInfo[] files : files_list) {
        all_files.addAll(Arrays.asList(files));
    }
    boolean hasSelection = (all_files.size() > 0);
    final MenuItem itemOpen = new MenuItem(menu, SWT.PUSH);
    Messages.setLanguageText(itemOpen, "FilesView.menu.open");
    Utils.setMenuItemImage(itemOpen, "run");
    // Invoke open on enter, double click
    menu.setDefaultItem(itemOpen);
    // Explore  (Copied from MyTorrentsView)
    final boolean use_open_containing_folder = COConfigurationManager.getBooleanParameter("MyTorrentsView.menu.show_parent_folder_enabled");
    final MenuItem itemExplore = new MenuItem(menu, SWT.PUSH);
    Messages.setLanguageText(itemExplore, "MyTorrentsView.menu." + (use_open_containing_folder ? "open_parent_folder" : "explore"));
    itemExplore.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            for (int i = all_files.size() - 1; i >= 0; i--) {
                DiskManagerFileInfo info = (DiskManagerFileInfo) all_files.get(i);
                if (info != null) {
                    ManagerUtils.open(info, use_open_containing_folder);
                }
            }
        }
    });
    itemExplore.setEnabled(hasSelection);
    // open in browser
    final Menu menuBrowse = new Menu(menu.getShell(), SWT.DROP_DOWN);
    final MenuItem itemBrowse = new MenuItem(menu, SWT.CASCADE);
    Messages.setLanguageText(itemBrowse, "MyTorrentsView.menu.browse");
    itemBrowse.setMenu(menuBrowse);
    final MenuItem itemBrowsePublic = new MenuItem(menuBrowse, SWT.PUSH);
    itemBrowsePublic.setText(MessageText.getString("label.public") + "...");
    itemBrowsePublic.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            for (int i = all_files.size() - 1; i >= 0; i--) {
                DiskManagerFileInfo info = (DiskManagerFileInfo) all_files.get(i);
                if (info != null) {
                    ManagerUtils.browse(info, false, true);
                }
            }
        }
    });
    final MenuItem itemBrowseAnon = new MenuItem(menuBrowse, SWT.PUSH);
    itemBrowseAnon.setText(MessageText.getString("label.anon") + "...");
    itemBrowseAnon.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            for (int i = all_files.size() - 1; i >= 0; i--) {
                DiskManagerFileInfo info = all_files.get(i);
                if (info != null) {
                    ManagerUtils.browse(info, true, true);
                }
            }
        }
    });
    new MenuItem(menuBrowse, SWT.SEPARATOR);
    final MenuItem itemBrowseURL = new MenuItem(menuBrowse, SWT.PUSH);
    Messages.setLanguageText(itemBrowseURL, "label.copy.url.to.clip");
    itemBrowseURL.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            Utils.getOffOfSWTThread(new AERunnable() {

                @Override
                public void runSupport() {
                    String url = ManagerUtils.browse(all_files.get(0), true, false);
                    if (url != null) {
                        ClipboardCopy.copyToClipBoard(url);
                    }
                }
            });
        }
    });
    itemBrowseURL.setEnabled(all_files.size() == 1);
    itemBrowse.setEnabled(hasSelection);
    // rename/retarget
    MenuItem itemRenameOrRetarget = null, itemRenameOrRetargetBatch = null, itemRename = null, itemRetarget = null;
    // "Rename or Retarget" -- Opens up file chooser (can choose new dir and new name)
    itemRenameOrRetarget = new MenuItem(menu, SWT.PUSH);
    Messages.setLanguageText(itemRenameOrRetarget, "FilesView.menu.rename");
    itemRenameOrRetarget.setData("rename", Boolean.valueOf(true));
    itemRenameOrRetarget.setData("retarget", Boolean.valueOf(true));
    itemRenameOrRetarget.setData("batch", Boolean.valueOf(false));
    // "Rename or Retarget (Batch)"
    itemRenameOrRetargetBatch = new MenuItem(menu, SWT.PUSH);
    Messages.setLanguageText(itemRenameOrRetargetBatch, "FilesView.menu.rename.batch");
    itemRenameOrRetargetBatch.setData("rename", Boolean.valueOf(true));
    itemRenameOrRetargetBatch.setData("retarget", Boolean.valueOf(true));
    itemRenameOrRetargetBatch.setData("batch", Boolean.valueOf(true));
    // "Quick Rename" -- opens up input box with name
    itemRename = new MenuItem(menu, SWT.PUSH);
    Messages.setLanguageText(itemRename, "FilesView.menu.rename_only");
    itemRename.setData("rename", Boolean.valueOf(true));
    itemRename.setData("retarget", Boolean.valueOf(false));
    itemRename.setData("batch", Boolean.valueOf(false));
    // "Move Files" -- opens up directory chooser
    itemRetarget = new MenuItem(menu, SWT.PUSH);
    Messages.setLanguageText(itemRetarget, "FilesView.menu.retarget");
    itemRetarget.setData("rename", Boolean.valueOf(false));
    itemRetarget.setData("retarget", Boolean.valueOf(true));
    itemRename.setData("batch", Boolean.valueOf(false));
    // revert
    final MenuItem itemRevertFiles = new MenuItem(menu, SWT.PUSH);
    Messages.setLanguageText(itemRevertFiles, "MyTorrentsView.menu.revertfiles");
    // locate files
    final MenuItem itemLocateFiles = new MenuItem(menu, SWT.PUSH);
    Messages.setLanguageText(itemLocateFiles, "MyTorrentsView.menu.locatefiles");
    // find more
    final MenuItem itemfindMore = new MenuItem(menu, SWT.PUSH);
    Messages.setLanguageText(itemfindMore, "MyTorrentsView.menu.findmorelikethis");
    // clear links
    MenuItem itemClearLinks = null;
    final int userMode = COConfigurationManager.getIntParameter("User Mode");
    if (userMode > 1) {
        itemClearLinks = new MenuItem(menu, SWT.PUSH);
        Messages.setLanguageText(itemClearLinks, "FilesView.menu.clear.links");
    }
    // quick view
    final MenuItem itemQuickView = new MenuItem(menu, SWT.CHECK);
    Messages.setLanguageText(itemQuickView, "MainWindow.menu.quick_view");
    itemQuickView.setEnabled(all_files.size() == 1 && Utils.isQuickViewSupported(all_files.get(0)));
    itemQuickView.setSelection(all_files.size() == 1 && Utils.isQuickViewActive(all_files.get(0)));
    itemQuickView.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event arg) {
            Utils.setQuickViewActive(all_files.get(0), itemQuickView.getSelection());
        }
    });
    if (manager_list.length == 1) {
        // lazy for the moment
        MenuFactory.addAlertsMenu(menu, manager_list[0], files_list[0]);
    }
    // personal share
    final MenuItem itemPersonalShare = new MenuItem(menu, SWT.PUSH);
    Messages.setLanguageText(itemPersonalShare, "MyTorrentsView.menu.create_personal_share");
    // priority
    final MenuItem itemPriority = new MenuItem(menu, SWT.CASCADE);
    Messages.setLanguageText(itemPriority, "FilesView.menu.setpriority");
    final Menu menuPriority = new Menu(shell, SWT.DROP_DOWN);
    itemPriority.setMenu(menuPriority);
    final MenuItem itemHigh = new MenuItem(menuPriority, SWT.CASCADE);
    itemHigh.setData("Priority", PRIORITY_HIGH);
    Messages.setLanguageText(itemHigh, "FilesView.menu.setpriority.high");
    final MenuItem itemNormal = new MenuItem(menuPriority, SWT.CASCADE);
    itemNormal.setData("Priority", PRIORITY_NORMAL);
    Messages.setLanguageText(itemNormal, "FilesView.menu.setpriority.normal");
    final MenuItem itemLow = new MenuItem(menuPriority, SWT.CASCADE);
    itemLow.setData("Priority", PRIORITY_LOW);
    Messages.setLanguageText(itemLow, "FileItem.low");
    final MenuItem itemNumeric = new MenuItem(menuPriority, SWT.CASCADE);
    itemNumeric.setData("Priority", PRIORITY_NUMERIC);
    Messages.setLanguageText(itemNumeric, "FilesView.menu.setpriority.numeric");
    final MenuItem itemNumericAuto = new MenuItem(menuPriority, SWT.CASCADE);
    itemNumericAuto.setData("Priority", PRIORITY_NUMERIC_AUTO);
    Messages.setLanguageText(itemNumericAuto, "FilesView.menu.setpriority.numeric.auto");
    final MenuItem itemSkipped = new MenuItem(menuPriority, SWT.CASCADE);
    itemSkipped.setData("Priority", PRIORITY_SKIPPED);
    Messages.setLanguageText(itemSkipped, "FilesView.menu.setpriority.skipped");
    final MenuItem itemDelete = new MenuItem(menuPriority, SWT.CASCADE);
    itemDelete.setData("Priority", PRIORITY_DELETE);
    // lazy but we're near release
    Messages.setLanguageText(itemDelete, "wizard.multitracker.delete");
    if (all_files.size() == 1) {
        DiskManagerFileInfo file = all_files.get(0);
        final MenuItem itemSequential = new MenuItem(menu, SWT.CHECK);
        Messages.setLanguageText(itemSequential, "menu.sequential.file");
        PEPeerManager pm = file.getDownloadManager().getPeerManager();
        if (pm == null || file.getDownloaded() == file.getLength() || file.isSkipped()) {
            itemSequential.setEnabled(false);
        } else {
            PiecePicker pp = pm.getPiecePicker();
            int info = pp.getSequentialInfo();
            itemSequential.setSelection(file.getFirstPieceNumber() == info - 1);
            itemSequential.addListener(SWT.Selection, new Listener() {

                @Override
                public void handleEvent(Event arg) {
                    if (itemSequential.getSelection()) {
                        pp.setSequentialAscendingFrom(file.getFirstPieceNumber());
                    } else {
                        pp.clearSequential();
                    }
                }
            });
        }
    }
    new MenuItem(menu, SWT.SEPARATOR);
    if (!hasSelection) {
        itemOpen.setEnabled(false);
        itemPriority.setEnabled(false);
        itemRenameOrRetarget.setEnabled(false);
        itemRenameOrRetargetBatch.setEnabled(false);
        itemRename.setEnabled(false);
        itemRetarget.setEnabled(false);
        itemRevertFiles.setEnabled(false);
        itemLocateFiles.setEnabled(false);
        itemfindMore.setEnabled(false);
        if (itemClearLinks != null) {
            itemClearLinks.setEnabled(false);
        }
        itemPersonalShare.setEnabled(false);
        return;
    }
    boolean all_persistent = true;
    boolean open = true;
    boolean all_compact = true;
    boolean all_dnd_not_deleted = true;
    boolean all_high_pri = true;
    boolean all_normal_pri = true;
    boolean all_low_pri = true;
    boolean all_complete = true;
    boolean any_relocated = false;
    final List<DiskManagerFileInfo> files_with_links = new ArrayList<>();
    for (int j = 0; j < manager_list.length; j++) {
        DownloadManager manager = manager_list[j];
        int dm_file_count = manager.getNumFileInfos();
        if (!manager.isPersistent()) {
            all_persistent = false;
        }
        DiskManagerFileInfo[] files = files_list[j];
        DownloadManagerState dm_state = manager.getDownloadState();
        int[] storage_types = manager.getStorageType(files);
        for (int i = 0; i < files.length; i++) {
            DiskManagerFileInfo file_info = files[i];
            if (open && file_info.getAccessMode() != DiskManagerFileInfo.READ) {
                open = false;
            }
            boolean isCompact = storage_types[i] == DiskManagerFileInfo.ST_COMPACT || storage_types[i] == DiskManagerFileInfo.ST_REORDER_COMPACT;
            if (all_compact && !isCompact) {
                all_compact = false;
            }
            if (all_dnd_not_deleted || all_high_pri || all_normal_pri || all_low_pri) {
                if (file_info.isSkipped()) {
                    all_high_pri = all_normal_pri = all_low_pri = false;
                    if (isCompact) {
                        all_dnd_not_deleted = false;
                    }
                } else {
                    all_dnd_not_deleted = false;
                    // Only do this check if we need to.
                    if (all_high_pri || all_normal_pri || all_low_pri) {
                        int file_pri = file_info.getPriority();
                        if (file_pri == 0) {
                            all_high_pri = all_low_pri = false;
                        } else if (file_pri == 1) {
                            all_normal_pri = all_low_pri = false;
                        } else if (file_pri == -1) {
                            all_normal_pri = all_high_pri = false;
                        } else {
                            all_low_pri = all_normal_pri = all_high_pri = false;
                        }
                    }
                }
            }
            File file_link = file_info.getFile(true);
            File file_nolink = file_info.getFile(false);
            if (file_info.getDownloaded() != file_info.getLength() || file_link.length() != file_info.getLength()) {
                all_complete = false;
            }
            if (dm_file_count > 1) {
                if (!file_nolink.getAbsolutePath().equals(file_link.getAbsolutePath())) {
                    files_with_links.add(file_info);
                }
            }
            File target = dm_state.getFileLink(file_info.getIndex(), file_nolink);
            if (target != null) {
                if (target != file_nolink) {
                    if (!target.equals(file_nolink)) {
                        any_relocated = true;
                    }
                }
            }
        }
    }
    // we can only open files if they are read-only
    itemOpen.setEnabled(open);
    // can't rename files for non-persistent downloads (e.g. shares) as these
    // are managed "externally"
    itemRenameOrRetarget.setEnabled(all_persistent);
    itemRenameOrRetargetBatch.setEnabled(all_persistent);
    itemRename.setEnabled(all_persistent);
    itemRetarget.setEnabled(all_persistent);
    // only enable for single files - people prolly don't expect a multi-selection to result
    // in multiple shares, rather they would expect one share with the files they selected
    // which we don't support
    itemPersonalShare.setEnabled(all_complete && all_files.size() == 1);
    itemSkipped.setEnabled(!all_dnd_not_deleted);
    itemHigh.setEnabled(!all_high_pri);
    itemNormal.setEnabled(!all_normal_pri);
    itemLow.setEnabled(!all_low_pri);
    itemDelete.setEnabled(!all_compact);
    itemOpen.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            for (int i = 0; i < all_files.size(); i++) {
                DiskManagerFileInfo info = (DiskManagerFileInfo) all_files.get(i);
                if (info != null && info.getAccessMode() == DiskManagerFileInfo.READ) {
                    Utils.launch(info);
                }
            }
        }
    });
    Listener rename_listener = new Listener() {

        @Override
        public void handleEvent(Event event) {
            final boolean rename_it = ((Boolean) event.widget.getData("rename")).booleanValue();
            final boolean retarget_it = ((Boolean) event.widget.getData("retarget")).booleanValue();
            final boolean batch = ((Boolean) event.widget.getData("batch")).booleanValue();
            rename(tv, all_files.toArray(new Object[all_files.size()]), rename_it, retarget_it, batch);
        }
    };
    itemRenameOrRetargetBatch.addListener(SWT.Selection, rename_listener);
    itemRenameOrRetarget.addListener(SWT.Selection, rename_listener);
    itemRename.addListener(SWT.Selection, rename_listener);
    itemRetarget.addListener(SWT.Selection, rename_listener);
    itemLocateFiles.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            ManagerUtils.locateFiles(manager_list, files_list, menu.getShell());
        }
    });
    itemLocateFiles.setEnabled(true);
    if (ManagerUtils.canFindMoreLikeThis()) {
        itemfindMore.addListener(SWT.Selection, new Listener() {

            @Override
            public void handleEvent(Event event) {
                ManagerUtils.findMoreLikeThis(all_files.get(0), menu.getShell());
            }
        });
        itemfindMore.setEnabled(all_files.size() == 1);
    }
    itemRevertFiles.setEnabled(any_relocated);
    itemRevertFiles.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            revertFiles(tv, all_files);
        }
    });
    if (itemClearLinks != null) {
        itemClearLinks.setEnabled(files_with_links.size() > 0);
        itemClearLinks.addListener(SWT.Selection, new Listener() {

            @Override
            public void handleEvent(Event event) {
                for (DiskManagerFileInfo file : files_with_links) {
                    file.setLink(null);
                }
                invalidateRows(tv, files_with_links);
            }
        });
    }
    itemPersonalShare.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            Map<String, String> properties = new HashMap<>();
            properties.put(ShareManager.PR_PERSONAL, "true");
            for (int i = 0; i < all_files.size(); i++) {
                DiskManagerFileInfo file_info = all_files.get(i);
                File file = file_info.getFile(true);
                if (file.isFile()) {
                    ShareUtils.shareFile(file.getAbsolutePath(), properties);
                } else if (file.isDirectory()) {
                    ShareUtils.shareDir(file.getAbsolutePath(), properties);
                }
            }
        }
    });
    Listener priorityListener = new Listener() {

        @Override
        public void handleEvent(Event event) {
            final Object priority = event.widget.getData("Priority");
            Utils.getOffOfSWTThread(new AERunnable() {

                @Override
                public void runSupport() {
                    changePriority(priority, all_files);
                }
            });
        }
    };
    itemNumeric.addListener(SWT.Selection, priorityListener);
    itemNumericAuto.addListener(SWT.Selection, priorityListener);
    itemHigh.addListener(SWT.Selection, priorityListener);
    itemNormal.addListener(SWT.Selection, priorityListener);
    itemLow.addListener(SWT.Selection, priorityListener);
    itemSkipped.addListener(SWT.Selection, priorityListener);
    itemDelete.addListener(SWT.Selection, priorityListener);
    if (columnName.equals(ColumnUnopened.COLUMN_ID)) {
        final MenuItem toggle = new MenuItem(menu, SWT.PUSH);
        Messages.setLanguageText(toggle, "label.toggle.new.marker");
        toggle.addListener(SWT.Selection, new Listener() {

            @Override
            public void handleEvent(Event arg) {
                for (int i = 0; i < all_files.size(); i++) {
                    DiskManagerFileInfo file = all_files.get(i);
                    DownloadManager dm = file.getDownloadManager();
                    int ff = dm.getDownloadState().getFileFlags(file.getIndex());
                    ff ^= DownloadManagerState.FILE_FLAG_NOT_NEW;
                    dm.getDownloadState().setFileFlags(file.getIndex(), ff);
                }
            }
        });
        new MenuItem(menu, SWT.SEPARATOR);
    }
    com.biglybt.pif.ui.menus.MenuItem[] menu_items = MenuItemManager.getInstance().getAllAsArray(MenuManager.MENU_FILE_CONTEXT);
    if (menu_items.length > 0) {
        // plugins take com.biglybt.pif.disk.DiskManagerFileInfo
        com.biglybt.pif.disk.DiskManagerFileInfo[] fileInfos = new com.biglybt.pif.disk.DiskManagerFileInfo[all_files.size()];
        for (int i = 0; i < all_files.size(); i++) {
            fileInfos[i] = (com.biglybt.pif.disk.DiskManagerFileInfo) PluginCoreUtils.convert(all_files.get(i), false);
        }
        MenuBuildUtils.addPluginMenuItems(menu_items, menu, false, true, new MenuBuildUtils.MenuItemPluginMenuControllerImpl(fileInfos));
    }
}
Also used : UserPrompterResultListener(com.biglybt.ui.UserPrompterResultListener) UIInputReceiverListener(com.biglybt.pif.ui.UIInputReceiverListener) PiecePicker(com.biglybt.core.peermanager.piecepicker.PiecePicker) DownloadManager(com.biglybt.core.download.DownloadManager) DownloadManagerState(com.biglybt.core.download.DownloadManagerState) MessageBoxShell(com.biglybt.ui.swt.shells.MessageBoxShell) DiskManagerFileInfo(com.biglybt.core.disk.DiskManagerFileInfo) PEPeerManager(com.biglybt.core.peer.PEPeerManager) File(java.io.File) MenuBuildUtils(com.biglybt.ui.swt.MenuBuildUtils)

Example 35 with DownloadManagerState

use of com.biglybt.core.download.DownloadManagerState in project BiglyBT by BiglySoftware.

the class DefaultRankCalculator method destroy.

protected void destroy() {
    DownloadManagerState dm_state = core_dm.getDownloadState();
    dm_state.removeListener(this, DownloadManagerState.AT_PARAMETERS, DownloadManagerStateAttributeListener.WRITTEN);
}
Also used : DownloadManagerState(com.biglybt.core.download.DownloadManagerState)

Aggregations

DownloadManagerState (com.biglybt.core.download.DownloadManagerState)38 File (java.io.File)14 DownloadManager (com.biglybt.core.download.DownloadManager)11 TOTorrent (com.biglybt.core.torrent.TOTorrent)9 TOTorrentFile (com.biglybt.core.torrent.TOTorrentFile)8 DiskManagerFileInfo (com.biglybt.core.disk.DiskManagerFileInfo)6 CacheFile (com.biglybt.core.diskmanager.cache.CacheFile)6 PEPeerManager (com.biglybt.core.peer.PEPeerManager)5 TOTorrentException (com.biglybt.core.torrent.TOTorrentException)5 Download (com.biglybt.pif.download.Download)4 UIInputReceiverListener (com.biglybt.pif.ui.UIInputReceiverListener)4 IOException (java.io.IOException)4 Map (java.util.Map)4 CoreRunningListener (com.biglybt.core.CoreRunningListener)3 DiskManagerFileInfoSet (com.biglybt.core.disk.DiskManagerFileInfoSet)3 Tag (com.biglybt.core.tag.Tag)3 UIFunctions (com.biglybt.ui.UIFunctions)3 List (java.util.List)3 Core (com.biglybt.core.Core)2 ParameterListener (com.biglybt.core.config.ParameterListener)2