Search in sources :

Example 1 with TextViewerWindow

use of com.biglybt.ui.swt.TextViewerWindow in project BiglyBT by BiglySoftware.

the class TorrentListViewsUtils method openInEMP.

/**
 * New version accepts map with ASX parameters. If the params are null then is uses the
 * old version to start the player. If the
 *
 * @param dm - DownloadManager
 * @return - int: 0 = ok, 1 = fail, 2 = abandon, installation in progress
 * @since 3.0.4.4 -
 */
private static int openInEMP(final DownloadManager dm, final int _file_index, final boolean complete_only, final String referal) {
    try {
        int file_index = -1;
        if (_file_index == -1) {
            EnhancedDownloadManager edm = DownloadManagerEnhancer.getSingleton().getEnhancedDownload(dm);
            if (edm != null) {
                file_index = edm.getPrimaryFileIndex();
            }
        } else {
            file_index = _file_index;
        }
        if (file_index == -1) {
            return (1);
        }
        final int f_file_index = file_index;
        com.biglybt.pif.disk.DiskManagerFileInfo file = PluginCoreUtils.wrap(dm).getDiskManagerFileInfo()[file_index];
        final URL url;
        if ((!complete_only) && file.getDownloaded() != file.getLength()) {
            url = PlayUtils.getMediaServerContentURL(file);
        } else {
            url = null;
        }
        if (url != null) {
            if (PlayUtils.isStreamPermitted()) {
                final boolean show_debug_window = false;
                new AEThread2("stream:async") {

                    @Override
                    public void run() {
                        StreamManager sm = StreamManager.getSingleton();
                        synchronized (TorrentListViewsUtils.class) {
                            if (current_stream != null && !current_stream.isCancelled()) {
                                if (current_stream.getURL().equals(url)) {
                                    current_stream.setPreviewMode(!current_stream.getPreviewMode());
                                    return;
                                }
                                current_stream.cancel();
                                current_stream = null;
                            }
                            if (show_debug_window && (stream_viewer == null || stream_viewer.isDisposed())) {
                                Utils.execSWTThread(new Runnable() {

                                    @Override
                                    public void run() {
                                        if (stream_viewer != null) {
                                            stream_viewer.close();
                                        }
                                        stream_viewer = new TextViewerWindow("Stream Status", "Debug information for stream process", "", false);
                                        stream_viewer.addListener(new TextViewerWindow.TextViewerWindowListener() {

                                            @Override
                                            public void closed() {
                                                synchronized (TorrentListViewsUtils.class) {
                                                    if (current_stream != null) {
                                                        current_stream.cancel();
                                                        current_stream = null;
                                                    }
                                                }
                                            }
                                        });
                                    }
                                });
                            }
                            current_stream = sm.stream(dm, f_file_index, url, false, new StreamManagerDownloadListener() {

                                private long last_log = 0;

                                @Override
                                public void updateActivity(String str) {
                                    append("Activity: " + str);
                                }

                                @Override
                                public void updateStats(int secs_until_playable, int buffer_secs, long buffer_bytes, int target_secs) {
                                    long now = SystemTime.getMonotonousTime();
                                    if (now - last_log >= 1000) {
                                        last_log = now;
                                        append("stats: play in " + secs_until_playable + " sec, buffer=" + DisplayFormatters.formatByteCountToKiBEtc(buffer_bytes) + "/" + buffer_secs + " sec - target=" + target_secs + " sec");
                                    }
                                }

                                @Override
                                public void ready() {
                                    append("ready");
                                }

                                @Override
                                public void failed(Throwable error) {
                                    append("failed: " + Debug.getNestedExceptionMessage(error));
                                    Debug.out(error);
                                }

                                private void append(final String str) {
                                    if (stream_viewer != null) {
                                        Utils.execSWTThread(new Runnable() {

                                            @Override
                                            public void run() {
                                                if (stream_viewer != null && !stream_viewer.isDisposed()) {
                                                    stream_viewer.append(str + "\r\n");
                                                }
                                            }
                                        });
                                    }
                                }
                            });
                        }
                    }
                }.start();
            } else {
            // FeatureManagerUI.openStreamPlusWindow(referal);
            }
            return (0);
        }
        synchronized (TorrentListViewsUtils.class) {
            if (current_stream != null && !current_stream.isCancelled()) {
                current_stream.cancel();
                current_stream = null;
            }
        }
        Class epwClass = null;
        try {
            // Assumed we have a core, since we are passed a
            // DownloadManager
            PluginInterface pi = CoreFactory.getSingleton().getPluginManager().getPluginInterfaceByID("azemp", false);
            if (pi == null) {
                return (installEMP(dm.getDisplayName(), new Runnable() {

                    @Override
                    public void run() {
                        openInEMP(dm, f_file_index, complete_only, referal);
                    }
                }));
            } else if (!pi.getPluginState().isOperational()) {
                return (1);
            }
            epwClass = pi.getPlugin().getClass().getClassLoader().loadClass("com.azureus.plugins.azemp.ui.swt.emp.EmbeddedPlayerWindowSWT");
        } catch (ClassNotFoundException e1) {
            return 1;
        }
        try {
            Method method = epwClass.getMethod("openWindow", new Class[] { File.class, String.class });
            File f = file.getFile(true);
            method.invoke(null, new Object[] { f, f.getName() });
            return (0);
        } catch (Throwable e) {
            debug("file/name open method missing");
        }
        // fall through here if old emp
        Method method = epwClass.getMethod("openWindow", new Class[] { DownloadManager.class });
        method.invoke(null, new Object[] { dm });
        return 0;
    } catch (Throwable e) {
        e.printStackTrace();
        if (e.getMessage() == null || !e.getMessage().toLowerCase().endsWith("only")) {
            Debug.out(e);
        }
    }
    return 1;
}
Also used : PluginInterface(com.biglybt.pif.PluginInterface) Method(java.lang.reflect.Method) URL(java.net.URL) TextViewerWindow(com.biglybt.ui.swt.TextViewerWindow) VuzeFile(com.biglybt.core.vuzefile.VuzeFile) File(java.io.File)

Example 2 with TextViewerWindow

use of com.biglybt.ui.swt.TextViewerWindow in project BiglyBT by BiglySoftware.

the class ManagerUtils method locateFiles.

public static void locateFiles(final DownloadManager[] dms, final DiskManagerFileInfo[][] dm_files, Shell shell) {
    DirectoryDialog dd = new DirectoryDialog(shell);
    dd.setFilterPath(TorrentOpener.getFilterPathData());
    dd.setText(MessageText.getString("MyTorrentsView.menu.locatefiles.dialog"));
    String path = dd.open();
    if (path != null) {
        TorrentOpener.setFilterPathData(path);
        final File dir = new File(path);
        final TextViewerWindow viewer = new TextViewerWindow(MessageText.getString("locatefiles.view.title"), null, "", true, true);
        viewer.setEditable(false);
        viewer.setOKEnabled(true);
        new AEThread2("FileLocator") {

            @Override
            public void run() {
                final int MAX_LINKS = DownloadManagerStateFactory.MAX_FILES_FOR_INCOMPLETE_AND_DND_LINKAGE;
                final String LINK_LIMIT_MSG = "Link limit of " + MAX_LINKS + " exceeded. See Tools->Options->Files to increase this";
                try {
                    Map<Long, Set<File>> file_map = new HashMap<>();
                    final boolean[] quit = { false };
                    viewer.addListener(new TextViewerWindow.TextViewerWindowListener() {

                        @Override
                        public void closed() {
                            synchronized (quit) {
                                quit[0] = true;
                            }
                        }
                    });
                    logLine(viewer, new SimpleDateFormat().format(new Date()) + ": Enumerating files in " + dir);
                    long bfm_start = SystemTime.getMonotonousTime();
                    long[] last_log = { bfm_start };
                    int file_count = buildFileMap(viewer, dir, file_map, last_log, quit);
                    logLine(viewer, (bfm_start == last_log[0] ? "" : "\r\n") + "Found " + file_count + " files with " + file_map.size() + " distinct sizes");
                    Set<String> all_dm_incomplete_files = null;
                    ConcurrentHasher hasher = ConcurrentHasher.getSingleton();
                    int downloads_modified = 0;
                    for (int i = 0; i < dms.length; i++) {
                        DownloadManager dm = dms[i];
                        synchronized (quit) {
                            if (quit[0]) {
                                break;
                            }
                        }
                        if (!dm.isPersistent()) {
                            continue;
                        }
                        TOTorrent torrent = dm.getTorrent();
                        if (torrent == null) {
                            continue;
                        }
                        DiskManagerFileInfo[] selected_files = dm_files == null ? null : dm_files[i];
                        Set<Integer> selected_file_indexes;
                        if (selected_files == null) {
                            selected_file_indexes = null;
                        } else {
                            selected_file_indexes = new HashSet<>();
                            for (DiskManagerFileInfo f : selected_files) {
                                selected_file_indexes.add(f.getIndex());
                            }
                        }
                        TOTorrentFile[] to_files = torrent.getFiles();
                        long piece_size = torrent.getPieceLength();
                        byte[][] pieces = torrent.getPieces();
                        logLine(viewer, "Processing '" + dm.getDisplayName() + "', piece size=" + DisplayFormatters.formatByteCountToKiBEtc(piece_size));
                        int dm_state = dm.getState();
                        if (!(dm_state == DownloadManager.STATE_STOPPED || dm_state == DownloadManager.STATE_ERROR)) {
                            logLine(viewer, "    Download must be stopped");
                            continue;
                        }
                        DiskManagerFileInfo[] files = dm.getDiskManagerFileInfoSet().getFiles();
                        Set<String> dm_files = null;
                        Map<DiskManagerFileInfo, File> links_established = new HashMap<>();
                        Map<DiskManagerFileInfo, Set<String>> unmatched_files = new TreeMap<>(new Comparator<DiskManagerFileInfo>() {

                            @Override
                            public int compare(DiskManagerFileInfo o1, DiskManagerFileInfo o2) {
                                long diff = o2.getLength() - o1.getLength();
                                if (diff < 0) {
                                    return (-1);
                                } else if (diff > 0) {
                                    return (1);
                                } else {
                                    return (0);
                                }
                            }
                        });
                        int no_candidates = 0;
                        int already_complete = 0;
                        int link_count = 0;
                        try {
                            download_loop: for (final DiskManagerFileInfo file : files) {
                                synchronized (quit) {
                                    if (quit[0]) {
                                        break;
                                    }
                                }
                                if (selected_file_indexes != null) {
                                    if (!selected_file_indexes.contains(file.getIndex())) {
                                        continue;
                                    }
                                }
                                long file_length = file.getLength();
                                if (file.getDownloaded() == file_length) {
                                    already_complete++;
                                    continue;
                                }
                                Set<File> candidates = file_map.get(file_length);
                                if (candidates != null) {
                                    if (candidates.size() > 0) {
                                        if (all_dm_incomplete_files == null) {
                                            all_dm_incomplete_files = new HashSet<>();
                                            List<DownloadManager> all_dms = CoreFactory.getSingleton().getGlobalManager().getDownloadManagers();
                                            for (DownloadManager x : all_dms) {
                                                if (!x.isDownloadComplete(false)) {
                                                    DiskManagerFileInfo[] fs = x.getDiskManagerFileInfoSet().getFiles();
                                                    for (DiskManagerFileInfo f : fs) {
                                                        if (f.isSkipped() || f.getDownloaded() != f.getLength()) {
                                                            all_dm_incomplete_files.add(f.getFile(true).getAbsolutePath());
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        Iterator<File> it = candidates.iterator();
                                        while (it.hasNext()) {
                                            File f = it.next();
                                            if (all_dm_incomplete_files.contains(f.getAbsolutePath())) {
                                                it.remove();
                                            }
                                        }
                                    }
                                    if (candidates.size() > 0) {
                                        // duplicate now as this is download-specific
                                        candidates = new HashSet<>(candidates);
                                        if (dm_files == null) {
                                            dm_files = new HashSet<>();
                                            for (DiskManagerFileInfo f : files) {
                                                dm_files.add(f.getFile(true).getAbsolutePath());
                                            }
                                        }
                                        Iterator<File> it = candidates.iterator();
                                        while (it.hasNext()) {
                                            File f = it.next();
                                            if (dm_files.contains(f.getAbsolutePath())) {
                                                it.remove();
                                            }
                                        }
                                    }
                                    if (candidates.size() > 0) {
                                        boolean matched = false;
                                        Set<String> failed_candidates = new HashSet<>();
                                        TOTorrentFile to_file = file.getTorrentFile();
                                        long offset = 0;
                                        for (TOTorrentFile tf : to_files) {
                                            if (tf == to_file) {
                                                break;
                                            }
                                            offset += tf.getLength();
                                        }
                                        int to_piece_number = to_file.getFirstPieceNumber();
                                        long to_file_offset = offset % piece_size;
                                        if (to_file_offset != 0) {
                                            to_file_offset = piece_size - to_file_offset;
                                            to_piece_number++;
                                        }
                                        long to_stop_at = file_length - piece_size;
                                        if (to_file_offset < to_stop_at) {
                                            logLine(viewer, "    " + candidates.size() + " candidate(s) for " + to_file.getRelativePath() + " (size=" + DisplayFormatters.formatByteCountToKiBEtc(to_file.getLength()) + ")");
                                            byte[] buffer = new byte[(int) piece_size];
                                            for (File candidate : candidates) {
                                                synchronized (quit) {
                                                    if (quit[0]) {
                                                        break;
                                                    }
                                                }
                                                log(viewer, "        Testing " + candidate);
                                                RandomAccessFile raf = null;
                                                boolean error = false;
                                                boolean hash_failed = false;
                                                long last_ok_log = SystemTime.getMonotonousTime();
                                                try {
                                                    raf = new RandomAccessFile(candidate, "r");
                                                    long file_offset = to_file_offset;
                                                    int piece_number = to_piece_number;
                                                    while (file_offset < to_stop_at) {
                                                        synchronized (quit) {
                                                            if (quit[0]) {
                                                                break;
                                                            }
                                                        }
                                                        raf.seek(file_offset);
                                                        raf.read(buffer);
                                                        ConcurrentHasherRequest req = hasher.addRequest(ByteBuffer.wrap(buffer));
                                                        byte[] hash = req.getResult();
                                                        boolean match = Arrays.equals(pieces[piece_number], hash);
                                                        if (match) {
                                                            long now = SystemTime.getMonotonousTime();
                                                            if (now - last_ok_log >= 250) {
                                                                last_ok_log = now;
                                                                log(viewer, ".");
                                                            }
                                                            file_offset += piece_size;
                                                            piece_number++;
                                                        } else {
                                                            hash_failed = true;
                                                            failed_candidates.add(candidate.getAbsolutePath());
                                                            logLine(viewer, "X");
                                                            break;
                                                        }
                                                    }
                                                } catch (Throwable e) {
                                                    logLine(viewer, "X");
                                                    error = true;
                                                } finally {
                                                    if (raf != null) {
                                                        try {
                                                            raf.close();
                                                        } catch (Throwable e) {
                                                        }
                                                    }
                                                }
                                                if (!(error || hash_failed)) {
                                                    logLine(viewer, " Matched");
                                                    try {
                                                        dm.setUserData("set_link_dont_delete_existing", true);
                                                        if (file.setLink(candidate)) {
                                                            logLine(viewer, "        Link successful");
                                                            links_established.put(file, candidate);
                                                            link_count++;
                                                            matched = true;
                                                            if (link_count > MAX_LINKS) {
                                                                logLine(viewer, "    " + LINK_LIMIT_MSG);
                                                                break download_loop;
                                                            }
                                                        } else {
                                                            logLine(viewer, "        Link failed");
                                                        }
                                                    } finally {
                                                        dm.setUserData("set_link_dont_delete_existing", null);
                                                    }
                                                    break;
                                                }
                                            }
                                        }
                                        if (!matched) {
                                            unmatched_files.put(file, failed_candidates);
                                        }
                                    } else {
                                        no_candidates++;
                                    }
                                } else {
                                    no_candidates++;
                                }
                            }
                            logLine(viewer, "    Matched=" + links_established.size() + ", complete=" + already_complete + ", no candidates=" + no_candidates + ", remaining=" + unmatched_files.size() + " (total=" + files.length + ")");
                            if (links_established.size() > 0 && unmatched_files.size() > 0) {
                                logLine(viewer, "    Looking for other potential name-based matches");
                                File overall_root = null;
                                for (Map.Entry<DiskManagerFileInfo, File> entry : links_established.entrySet()) {
                                    DiskManagerFileInfo dm_file = entry.getKey();
                                    File root = entry.getValue();
                                    String rel = dm_file.getTorrentFile().getRelativePath();
                                    int pos = 0;
                                    while (root != null) {
                                        root = root.getParentFile();
                                        pos = rel.indexOf(File.separatorChar, pos);
                                        if (pos >= 0) {
                                            pos = pos + 1;
                                        } else {
                                            break;
                                        }
                                    }
                                    if (root == null) {
                                        logLine(viewer, "        No usable root folder found");
                                        break;
                                    }
                                    if (overall_root == null) {
                                        overall_root = root;
                                    } else {
                                        if (!overall_root.equals(root)) {
                                            overall_root = null;
                                            logLine(viewer, "        Inconsistent root folder found");
                                            break;
                                        }
                                    }
                                }
                                if (overall_root != null) {
                                    logLine(viewer, "        Root folder is " + overall_root.getAbsolutePath());
                                    int links_ok = 0;
                                    for (Map.Entry<DiskManagerFileInfo, Set<String>> entry : unmatched_files.entrySet()) {
                                        synchronized (quit) {
                                            if (quit[0]) {
                                                break;
                                            }
                                        }
                                        DiskManagerFileInfo file = entry.getKey();
                                        if (selected_file_indexes != null) {
                                            if (!selected_file_indexes.contains(file.getIndex())) {
                                                continue;
                                            }
                                        }
                                        File expected_file = new File(overall_root, file.getTorrentFile().getRelativePath());
                                        if (expected_file.exists() && expected_file.length() == file.getLength()) {
                                            if (!entry.getValue().contains(expected_file.getAbsolutePath())) {
                                                try {
                                                    dm.setUserData("set_link_dont_delete_existing", true);
                                                    if (file.setLink(expected_file)) {
                                                        links_ok++;
                                                        link_count++;
                                                        if (link_count > MAX_LINKS) {
                                                            logLine(viewer, "        " + LINK_LIMIT_MSG);
                                                            break;
                                                        }
                                                    }
                                                } finally {
                                                    dm.setUserData("set_link_dont_delete_existing", null);
                                                }
                                            }
                                        }
                                    }
                                    logLine(viewer, "        Linked " + links_ok + " of " + unmatched_files.size());
                                }
                            }
                        } finally {
                            if (link_count > 0) {
                                dm.forceRecheck();
                                downloads_modified++;
                            }
                        }
                    }
                    logLine(viewer, new SimpleDateFormat().format(new Date()) + ": Complete, downloads updated=" + downloads_modified);
                } catch (Throwable e) {
                    log(viewer, "\r\n" + new SimpleDateFormat().format(new Date()) + ": Failed: " + Debug.getNestedExceptionMessage(e) + "\r\n");
                }
            }
        }.start();
        viewer.goModal();
    }
}
Also used : DiskManagerFileInfoSet(com.biglybt.core.disk.DiskManagerFileInfoSet) DownloadManager(com.biglybt.core.download.DownloadManager) TextViewerWindow(com.biglybt.ui.swt.TextViewerWindow) DirectoryDialog(org.eclipse.swt.widgets.DirectoryDialog) DiskManagerFileInfo(com.biglybt.core.disk.DiskManagerFileInfo) TOTorrentFile(com.biglybt.core.torrent.TOTorrentFile) TOTorrent(com.biglybt.core.torrent.TOTorrent) TOTorrentFile(com.biglybt.core.torrent.TOTorrentFile) SimpleDateFormat(java.text.SimpleDateFormat)

Example 3 with TextViewerWindow

use of com.biglybt.ui.swt.TextViewerWindow in project BiglyBT by BiglySoftware.

the class FilesViewMenuUtil method rename.

public static void rename(final TableView tv, final Object[] datasources, boolean rename_it, boolean retarget_it, boolean batch) {
    if (datasources.length == 0) {
        return;
    }
    final List<DownloadManager> pausedDownloads = new ArrayList<>(0);
    final AESemaphore task_sem = new AESemaphore("tasksem");
    final List<DiskManagerFileInfo> affected_files = new ArrayList<>();
    try {
        if (batch) {
            StringBuilder details = new StringBuilder(32 * 1024);
            Map<DownloadManager, Integer> dm_map = new IdentityHashMap<>();
            Map<String, DownloadManager> dm_name_map = new HashMap<>();
            for (int i = 0; i < datasources.length; i++) {
                DiskManagerFileInfo fileInfo = (DiskManagerFileInfo) datasources[i];
                DownloadManager dm = fileInfo.getDownloadManager();
                if (!dm_map.containsKey(dm)) {
                    dm_map.put(dm, i);
                    dm_name_map.put(dm.getInternalName(), dm);
                }
            }
            Arrays.sort(datasources, new Comparator<Object>() {

                @Override
                public int compare(Object o1, Object o2) {
                    DiskManagerFileInfo f1 = (DiskManagerFileInfo) o1;
                    DiskManagerFileInfo f2 = (DiskManagerFileInfo) o2;
                    DownloadManager d1 = f1.getDownloadManager();
                    DownloadManager d2 = f2.getDownloadManager();
                    if (d1 == d2) {
                        return (0);
                    } else {
                        return (dm_map.get(d1) - dm_map.get(d2));
                    }
                }
            });
            DownloadManager current_dm = null;
            for (int i = 0; i < datasources.length; i++) {
                DiskManagerFileInfo fileInfo = (DiskManagerFileInfo) datasources[i];
                DownloadManager dm = fileInfo.getDownloadManager();
                if (dm != current_dm) {
                    if (dm_map.size() > 1) {
                        if (current_dm != null) {
                            details.append("\n");
                        }
                        details.append("# " + dm.getInternalName() + " - ");
                        details.append(dm.getDisplayName());
                        details.append("\n\n");
                    }
                    current_dm = dm;
                }
                String index_str = String.valueOf(fileInfo.getIndex() + 1);
                while (index_str.length() < 5) {
                    index_str += " ";
                }
                details.append(index_str);
                details.append(fileInfo.getFile(true).getAbsolutePath());
                details.append("\n");
            }
            TextViewerWindow viewer = new TextViewerWindow(Utils.findAnyShell(), "batch.retarget.title", "batch.retarget.text", details.toString(), true, true);
            viewer.setEditable(true);
            viewer.setNonProportionalFont();
            DownloadManager f_dm = current_dm;
            viewer.addListener(new TextViewerWindow.TextViewerWindowListener() {

                @Override
                public void closed() {
                    if (!viewer.getOKPressed()) {
                        return;
                    }
                    String text = viewer.getText();
                    if (text.equals(details.toString())) {
                        return;
                    }
                    String[] lines = text.split("\n");
                    StringBuilder result = new StringBuilder(23 * 1024);
                    List<Object[]> actions = new ArrayList<>();
                    DiskManagerFileInfo[] current_files = f_dm.getDiskManagerFileInfoSet().getFiles();
                    for (String line : lines) {
                        line = line.trim();
                        if (line.isEmpty()) {
                            continue;
                        }
                        if (line.startsWith("#")) {
                            try {
                                String[] bits = line.split("\\s+", 3);
                                DownloadManager dm = dm_name_map.get(bits[1].trim());
                                current_files = dm.getDiskManagerFileInfoSet().getFiles();
                            } catch (Throwable e) {
                                result.append("Invalid line: " + line + "\n");
                            }
                        } else {
                            try {
                                String[] bits = line.split("\\s+", 2);
                                int index = Integer.parseInt(bits[0].trim());
                                DiskManagerFileInfo file = current_files[index - 1];
                                String path = bits[1].trim();
                                File existing_file = file.getFile(true);
                                if (!existing_file.getAbsolutePath().equals(path)) {
                                    File target_file = new File(path);
                                    actions.add(new Object[] { file, existing_file, target_file });
                                }
                            } catch (Throwable e) {
                                result.append("Invalid line: " + line + "\n");
                            }
                        }
                    }
                    if (result.length() > 0) {
                        Utils.execSWTThreadLater(1, new Runnable() {

                            public void run() {
                                TextViewerWindow viewer = new TextViewerWindow(Utils.findAnyShell(), "batch.retarget.title", "batch.retarget.error.text", result.toString(), true, true);
                                viewer.setNonProportionalFont();
                                viewer.goModal();
                            }
                        });
                    } else if (!actions.isEmpty()) {
                        for (Object[] action : actions) {
                            DiskManagerFileInfo file = (DiskManagerFileInfo) action[0];
                            File existing_file = (File) action[1];
                            File target_file = (File) action[2];
                            DownloadManager manager = file.getDownloadManager();
                            if (!pausedDownloads.contains(manager)) {
                                if (manager.pause()) {
                                    pausedDownloads.add(manager);
                                }
                            }
                            boolean dont_delete_existing = false;
                            if (target_file.exists()) {
                                if (target_file.equals(existing_file)) {
                                    continue;
                                } else {
                                    if (checkRetargetOK(file, target_file)) {
                                        dont_delete_existing = true;
                                    } else {
                                        continue;
                                    }
                                }
                            }
                            affected_files.add(file);
                            result.append(existing_file + " -> " + target_file + "\n");
                            moveFile(manager, file, target_file, dont_delete_existing, new Runnable() {

                                @Override
                                public void run() {
                                    task_sem.release();
                                }
                            });
                        }
                        if (result.length() > 0) {
                            Utils.execSWTThreadLater(1, new Runnable() {

                                public void run() {
                                    TextViewerWindow viewer = new TextViewerWindow(Utils.findAnyShell(), "batch.retarget.title", "batch.retarget.result.text", result.toString(), true, true);
                                    viewer.setNonProportionalFont();
                                    viewer.goModal();
                                }
                            });
                        }
                    }
                }
            });
            viewer.goModal();
        } else {
            String save_dir = null;
            if (!rename_it && retarget_it) {
                // better count (text based on rename/retarget)
                String s = MessageText.getString("label.num_selected", new String[] { Integer.toString(datasources.length) });
                save_dir = askForSaveDirectory((DiskManagerFileInfo) datasources[0], s);
                if (save_dir == null) {
                    return;
                }
            }
            for (int i = 0; i < datasources.length; i++) {
                if (datasources[i] instanceof DownloadManager) {
                    AdvRenameWindow window = new AdvRenameWindow();
                    window.open((DownloadManager) datasources[i]);
                    continue;
                }
                if (!(datasources[i] instanceof DiskManagerFileInfo)) {
                    continue;
                }
                final DiskManagerFileInfo fileInfo = (DiskManagerFileInfo) datasources[i];
                File existing_file = fileInfo.getFile(true);
                File f_target = null;
                if (rename_it && retarget_it) {
                    String s_target = askForRetargetedFilename(fileInfo);
                    if (s_target != null)
                        f_target = new File(s_target);
                } else if (rename_it) {
                    askForRenameFilenameAndExec(fileInfo, tv);
                    continue;
                } else {
                    // Parent directory has changed.
                    f_target = new File(save_dir, existing_file.getName());
                }
                // If the user has decided against it - abort the op.
                if (f_target == null) {
                    return;
                }
                DownloadManager manager = fileInfo.getDownloadManager();
                if (!pausedDownloads.contains(manager)) {
                    if (manager.pause()) {
                        pausedDownloads.add(manager);
                    }
                }
                boolean dont_delete_existing = false;
                if (f_target.exists()) {
                    if (f_target.equals(existing_file)) {
                        continue;
                    } else if (retarget_it) {
                        if (checkRetargetOK(fileInfo, f_target)) {
                            dont_delete_existing = true;
                        } else {
                            continue;
                        }
                    } else if (existing_file.exists() && !askCanOverwrite(existing_file)) {
                        continue;
                    }
                // If we reach here, then it means we are doing a real move, but there is
                // no existing file.
                }
                final File ff_target = f_target;
                final boolean f_dont_delete_existing = dont_delete_existing;
                affected_files.add(fileInfo);
                moveFile(fileInfo.getDownloadManager(), fileInfo, ff_target, f_dont_delete_existing, new Runnable() {

                    @Override
                    public void run() {
                        task_sem.release();
                    }
                });
            }
        }
    } finally {
        if (affected_files.size() > 0) {
            Utils.getOffOfSWTThread(new AERunnable() {

                @Override
                public void runSupport() {
                    for (int i = 0; i < affected_files.size(); i++) {
                        task_sem.reserve();
                    }
                    for (DownloadManager manager : pausedDownloads) {
                        manager.resume();
                    }
                    invalidateRows(tv, affected_files);
                }
            });
        }
    }
}
Also used : AdvRenameWindow(com.biglybt.ui.swt.shells.AdvRenameWindow) DownloadManager(com.biglybt.core.download.DownloadManager) TextViewerWindow(com.biglybt.ui.swt.TextViewerWindow) List(java.util.List) DiskManagerFileInfo(com.biglybt.core.disk.DiskManagerFileInfo) File(java.io.File)

Example 4 with TextViewerWindow

use of com.biglybt.ui.swt.TextViewerWindow in project BiglyBT by BiglySoftware.

the class MultiTrackerEditor method createWindow.

private void createWindow(Shell parent_shell) {
    if (parent_shell == null) {
        this.shell = ShellFactory.createMainShell(SWT.DIALOG_TRIM | SWT.RESIZE);
    } else {
        this.shell = ShellFactory.createShell(parent_shell, SWT.DIALOG_TRIM | SWT.RESIZE);
    }
    Messages.setLanguageText(this.shell, anonymous ? "wizard.multitracker.edit.title" : "wizard.multitracker.template.title");
    Utils.setShellIcon(shell);
    GridLayout layout = new GridLayout();
    layout.numColumns = 3;
    shell.setLayout(layout);
    GridData gridData;
    if (!anonymous) {
        Label labelName = new Label(shell, SWT.NULL);
        Messages.setLanguageText(labelName, "wizard.multitracker.edit.name");
        textName = new Text(shell, SWT.BORDER);
        textName.setText(currentName);
        gridData = new GridData(GridData.FILL_HORIZONTAL);
        gridData.horizontalSpan = 2;
        textName.setLayoutData(gridData);
        textName.addModifyListener(new ModifyListener() {

            @Override
            public void modifyText(ModifyEvent arg0) {
                currentName = textName.getText();
                computeSaveEnable();
            }
        });
    }
    treeGroups = new Tree(shell, SWT.BORDER);
    gridData = new GridData(GridData.FILL_BOTH);
    gridData.horizontalSpan = 3;
    gridData.heightHint = 150;
    treeGroups.setLayoutData(gridData);
    treeGroups.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseDoubleClick(MouseEvent arg0) {
            if (treeGroups.getSelectionCount() == 1) {
                TreeItem treeItem = treeGroups.getSelection()[0];
                String type = (String) treeItem.getData("type");
                if (type.equals("tracker")) {
                    editTreeItem(treeItem);
                }
            }
        }
    });
    if (showTemplates) {
        // template operations
        Composite cTemplate = new Composite(shell, SWT.NONE);
        gridData = new GridData(GridData.FILL_HORIZONTAL);
        gridData.horizontalSpan = 3;
        cTemplate.setLayoutData(gridData);
        GridLayout layoutTemplate = new GridLayout();
        layoutTemplate.numColumns = 5;
        cTemplate.setLayout(layoutTemplate);
        final Label labelTitle = new Label(cTemplate, SWT.NULL);
        Messages.setLanguageText(labelTitle, "Search.menu.engines");
        final Combo configList = new Combo(cTemplate, SWT.READ_ONLY);
        gridData = new GridData(GridData.FILL_HORIZONTAL);
        configList.setLayoutData(gridData);
        final List<Button> buttons = new ArrayList<>();
        String sel_str = COConfigurationManager.getStringParameter("multitrackereditor.last.selection", null);
        final String[] currentTemplate = { sel_str == null || sel_str.length() == 0 ? null : sel_str };
        final Runnable updateSelection = new Runnable() {

            @Override
            public void run() {
                int selection = configList.getSelectionIndex();
                boolean enabled = selection != -1;
                String sel_str = currentTemplate[0] = enabled ? configList.getItem(selection) : null;
                COConfigurationManager.setParameter("multitrackereditor.last.selection", sel_str == null ? "" : sel_str);
                Iterator<Button> it = buttons.iterator();
                // skip the new button
                it.next();
                while (it.hasNext()) {
                    it.next().setEnabled(enabled);
                }
            }
        };
        final Runnable updateTemplates = new Runnable() {

            @Override
            public void run() {
                Map<String, List<List<String>>> multiTrackers = TrackersUtil.getInstance().getMultiTrackers();
                configList.removeAll();
                List<String> names = new ArrayList<String>(multiTrackers.keySet());
                Collections.sort(names, new FormattersImpl().getAlphanumericComparator(true));
                for (String str : names) {
                    configList.add(str);
                }
                String toBeSelected = currentTemplate[0];
                if (toBeSelected != null) {
                    int selection = configList.indexOf(toBeSelected);
                    if (selection != -1) {
                        configList.select(selection);
                    } else if (configList.getItemCount() > 0) {
                        currentTemplate[0] = configList.getItem(0);
                        configList.select(0);
                    }
                }
                updateSelection.run();
            }
        };
        final TrackerEditorListener templateTEL = new TrackerEditorListener() {

            @Override
            public void trackersChanged(String oldName, String newName, List<List<String>> trackers) {
                TrackersUtil util = TrackersUtil.getInstance();
                if (oldName != null && !oldName.equals(newName)) {
                    util.removeMultiTracker(oldName);
                }
                util.addMultiTracker(newName, trackers);
                currentTemplate[0] = newName;
                updateTemplates.run();
            }
        };
        final Button btnNew = new Button(cTemplate, SWT.PUSH);
        buttons.add(btnNew);
        Messages.setLanguageText(btnNew, "wizard.multitracker.new");
        btnNew.addListener(SWT.Selection, new Listener() {

            @Override
            public void handleEvent(Event e) {
                List group = new ArrayList();
                List tracker = new ArrayList();
                group.add(tracker);
                new MultiTrackerEditor(btnNew.getShell(), null, group, templateTEL);
            }
        });
        configList.addListener(SWT.Selection, new Listener() {

            @Override
            public void handleEvent(Event e) {
                updateSelection.run();
            }
        });
        final Button btnEdit = new Button(cTemplate, SWT.PUSH);
        buttons.add(btnEdit);
        Messages.setLanguageText(btnEdit, "wizard.multitracker.edit");
        btnEdit.addListener(SWT.Selection, new Listener() {

            @Override
            public void handleEvent(Event e) {
                Map multiTrackers = TrackersUtil.getInstance().getMultiTrackers();
                String selected = currentTemplate[0];
                new MultiTrackerEditor(btnEdit.getShell(), selected, (List) multiTrackers.get(selected), templateTEL);
            }
        });
        final Button btnDelete = new Button(cTemplate, SWT.PUSH);
        buttons.add(btnDelete);
        Messages.setLanguageText(btnDelete, "wizard.multitracker.delete");
        btnDelete.addListener(SWT.Selection, new Listener() {

            @Override
            public void handleEvent(Event e) {
                final String selected = currentTemplate[0];
                MessageBoxShell mb = new MessageBoxShell(MessageText.getString("message.confirm.delete.title"), MessageText.getString("message.confirm.delete.text", new String[] { selected }), new String[] { MessageText.getString("Button.yes"), MessageText.getString("Button.no") }, 1);
                mb.open(new UserPrompterResultListener() {

                    @Override
                    public void prompterClosed(int result) {
                        if (result == 0) {
                            TrackersUtil.getInstance().removeMultiTracker(selected);
                            updateTemplates.run();
                        }
                    }
                });
            }
        });
        Label labelApply = new Label(cTemplate, SWT.NULL);
        gridData = new GridData(GridData.FILL_HORIZONTAL);
        gridData.horizontalSpan = 2;
        labelApply.setLayoutData(gridData);
        Messages.setLanguageText(labelApply, "apply.selected.template");
        final Button btnReplace = new Button(cTemplate, SWT.PUSH);
        buttons.add(btnReplace);
        Messages.setLanguageText(btnReplace, "label.replace");
        btnReplace.addListener(SWT.Selection, new Listener() {

            @Override
            public void handleEvent(Event e) {
                Map<String, List<List<String>>> multiTrackers = TrackersUtil.getInstance().getMultiTrackers();
                String selected = currentTemplate[0];
                trackers = TorrentUtils.getClone(multiTrackers.get(selected));
                refresh();
                computeSaveEnable();
            }
        });
        final Button btnMerge = new Button(cTemplate, SWT.PUSH);
        buttons.add(btnMerge);
        Messages.setLanguageText(btnMerge, "label.merge");
        btnMerge.addListener(SWT.Selection, new Listener() {

            @Override
            public void handleEvent(Event e) {
                Map<String, List<List<String>>> multiTrackers = TrackersUtil.getInstance().getMultiTrackers();
                String selected = currentTemplate[0];
                trackers = TorrentUtils.mergeAnnounceURLs(trackers, multiTrackers.get(selected));
                refresh();
                computeSaveEnable();
            }
        });
        final Button btnRemove = new Button(cTemplate, SWT.PUSH);
        buttons.add(btnRemove);
        Messages.setLanguageText(btnRemove, "Button.remove");
        btnRemove.addListener(SWT.Selection, new Listener() {

            @Override
            public void handleEvent(Event e) {
                Map<String, List<List<String>>> multiTrackers = TrackersUtil.getInstance().getMultiTrackers();
                String selected = currentTemplate[0];
                trackers = TorrentUtils.removeAnnounceURLs(trackers, multiTrackers.get(selected), false);
                refresh();
                computeSaveEnable();
            }
        });
        updateTemplates.run();
        Utils.makeButtonsEqualWidth(buttons);
    }
    Label labelSeparator = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL);
    gridData = new GridData(GridData.FILL_HORIZONTAL);
    gridData.horizontalSpan = 3;
    labelSeparator.setLayoutData(gridData);
    // button row
    Composite cButtons = new Composite(shell, SWT.NONE);
    gridData = new GridData(GridData.FILL_HORIZONTAL);
    gridData.horizontalSpan = 3;
    cButtons.setLayoutData(gridData);
    GridLayout layoutButtons = new GridLayout();
    layoutButtons.numColumns = 5;
    cButtons.setLayout(layoutButtons);
    List<Button> buttons = new ArrayList<>();
    final Button btnedittext = new Button(cButtons, SWT.PUSH);
    buttons.add(btnedittext);
    gridData = new GridData();
    gridData.horizontalAlignment = GridData.END;
    btnedittext.setLayoutData(gridData);
    Messages.setLanguageText(btnedittext, "wizard.multitracker.edit.text");
    btnedittext.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event e) {
            btnSave.setEnabled(false);
            btnedittext.setEnabled(false);
            trackers = new ArrayList();
            TreeItem[] groupItems = treeGroups.getItems();
            for (int i = 0; i < groupItems.length; i++) {
                TreeItem group = groupItems[i];
                TreeItem[] trackerItems = group.getItems();
                List groupList = new ArrayList(group.getItemCount());
                for (int j = 0; j < trackerItems.length; j++) {
                    groupList.add(trackerItems[j].getText());
                }
                trackers.add(groupList);
            }
            final String old_text = TorrentUtils.announceGroupsToText(trackers);
            final TextViewerWindow viewer = new TextViewerWindow(shell, "wizard.multitracker.edit.text.title", "wizard.multitracker.edit.text.msg", old_text, false, false);
            viewer.setEditable(true);
            viewer.addListener(new TextViewerWindow.TextViewerWindowListener() {

                @Override
                public void closed() {
                    try {
                        if (viewer.getOKPressed()) {
                            String new_text = viewer.getText();
                            if (!old_text.equals(new_text)) {
                                String[] lines = new_text.split("\n");
                                StringBuilder valid_text = new StringBuilder(new_text.length() + 1);
                                for (String line : lines) {
                                    line = line.trim();
                                    if (line.length() > 0) {
                                        if (!validURL(line)) {
                                            continue;
                                        }
                                    }
                                    valid_text.append(line);
                                    valid_text.append("\n");
                                }
                                trackers = TorrentUtils.announceTextToGroups(valid_text.toString());
                                refresh();
                            }
                        }
                    } finally {
                        computeSaveEnable();
                        btnedittext.setEnabled(true);
                    }
                }
            });
        }
    });
    final Button btnAddTrackerList = new Button(cButtons, SWT.PUSH);
    buttons.add(btnAddTrackerList);
    gridData = new GridData();
    gridData.horizontalAlignment = GridData.END;
    btnAddTrackerList.setLayoutData(gridData);
    Messages.setLanguageText(btnAddTrackerList, "wizard.multitracker.add.trackerlist");
    btnAddTrackerList.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event e) {
            SimpleTextEntryWindow entryWindow = new SimpleTextEntryWindow("enter.url", "enter.trackerlist.url");
            entryWindow.prompt(new UIInputReceiverListener() {

                @Override
                public void UIInputReceiverClosed(UIInputReceiver receiver) {
                    if (!receiver.hasSubmittedInput()) {
                        return;
                    }
                    String url = receiver.getSubmittedInput().trim();
                    if (!url.isEmpty()) {
                        TreeItem group = newGroup();
                        TreeItem itemTracker = newTracker(group, "trackerlist:" + url.trim());
                    }
                }
            });
        }
    });
    Label label = new Label(cButtons, SWT.NULL);
    gridData = new GridData(GridData.FILL_HORIZONTAL);
    label.setLayoutData(gridData);
    btnSave = new Button(cButtons, SWT.PUSH);
    buttons.add(btnSave);
    gridData = new GridData();
    gridData.horizontalAlignment = GridData.END;
    btnSave.setLayoutData(gridData);
    Messages.setLanguageText(btnSave, "wizard.multitracker.edit.save");
    btnSave.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event e) {
            update();
            shell.dispose();
        }
    });
    btnCancel = new Button(cButtons, SWT.PUSH);
    buttons.add(btnCancel);
    gridData = new GridData();
    gridData.horizontalAlignment = GridData.END;
    btnCancel.setLayoutData(gridData);
    Messages.setLanguageText(btnCancel, "Button.cancel");
    btnCancel.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event e) {
            shell.dispose();
        }
    });
    Utils.makeButtonsEqualWidth(buttons);
    shell.setDefaultButton(btnSave);
    shell.addListener(SWT.Traverse, new Listener() {

        @Override
        public void handleEvent(Event e) {
            if (e.character == SWT.ESC) {
                shell.dispose();
            }
        }
    });
    computeSaveEnable();
    refresh();
    constructMenu();
    editor = new TreeEditor(treeGroups);
    treeGroups.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent arg0) {
            if (itemEdited != null && !itemEdited.isDisposed() && !editor.getEditor().isDisposed()) {
                itemEdited.setText(((Text) editor.getEditor()).getText());
            }
            removeEditor();
        }
    });
    Point size = shell.computeSize(500, SWT.DEFAULT);
    shell.setSize(size);
    Utils.centreWindow(shell);
    shell.open();
}
Also used : UserPrompterResultListener(com.biglybt.ui.UserPrompterResultListener) UIInputReceiverListener(com.biglybt.pif.ui.UIInputReceiverListener) ArrayList(java.util.ArrayList) GridLayout(org.eclipse.swt.layout.GridLayout) SimpleTextEntryWindow(com.biglybt.ui.swt.SimpleTextEntryWindow) TrackersUtil(com.biglybt.core.util.TrackersUtil) ArrayList(java.util.ArrayList) List(java.util.List) TextViewerWindow(com.biglybt.ui.swt.TextViewerWindow) TreeEditor(org.eclipse.swt.custom.TreeEditor) MessageBoxShell(com.biglybt.ui.swt.shells.MessageBoxShell) MessageText(com.biglybt.core.internat.MessageText) Point(org.eclipse.swt.graphics.Point) FormattersImpl(com.biglybt.pifimpl.local.utils.FormattersImpl) Point(org.eclipse.swt.graphics.Point) UserPrompterResultListener(com.biglybt.ui.UserPrompterResultListener) UIInputReceiver(com.biglybt.pif.ui.UIInputReceiver) GridData(org.eclipse.swt.layout.GridData) UIInputReceiverListener(com.biglybt.pif.ui.UIInputReceiverListener) Map(java.util.Map)

Example 5 with TextViewerWindow

use of com.biglybt.ui.swt.TextViewerWindow in project BiglyBT by BiglySoftware.

the class PrivacyView method showSOCKSInfo.

private void showSOCKSInfo() {
    AEProxySelector proxy_selector = AEProxySelectorFactory.getSelector();
    String info = proxy_selector.getInfo();
    TextViewerWindow viewer = new TextViewerWindow(MessageText.getString("proxy.info.title"), null, info, false);
}
Also used : AEProxySelector(com.biglybt.core.proxy.AEProxySelector) TextViewerWindow(com.biglybt.ui.swt.TextViewerWindow)

Aggregations

TextViewerWindow (com.biglybt.ui.swt.TextViewerWindow)9 File (java.io.File)4 GridData (org.eclipse.swt.layout.GridData)3 GridLayout (org.eclipse.swt.layout.GridLayout)3 BackupManager (com.biglybt.core.backup.BackupManager)2 DiskManagerFileInfo (com.biglybt.core.disk.DiskManagerFileInfo)2 DownloadManager (com.biglybt.core.download.DownloadManager)2 AEProxySelector (com.biglybt.core.proxy.AEProxySelector)2 AERunnable (com.biglybt.core.util.AERunnable)2 UserPrompterResultListener (com.biglybt.ui.UserPrompterResultListener)2 MessageBoxShell (com.biglybt.ui.swt.shells.MessageBoxShell)2 List (java.util.List)2 DiskManagerFileInfoSet (com.biglybt.core.disk.DiskManagerFileInfoSet)1 MessageText (com.biglybt.core.internat.MessageText)1 NetworkAdminSocksProxy (com.biglybt.core.networkmanager.admin.NetworkAdminSocksProxy)1 TOTorrent (com.biglybt.core.torrent.TOTorrent)1 TOTorrentFile (com.biglybt.core.torrent.TOTorrentFile)1 AESemaphore (com.biglybt.core.util.AESemaphore)1 AEThread2 (com.biglybt.core.util.AEThread2)1 TrackersUtil (com.biglybt.core.util.TrackersUtil)1