Search in sources :

Example 1 with MenuItemListener

use of com.biglybt.pif.ui.menus.MenuItemListener in project BiglyBT by BiglySoftware.

the class SubscriptionManagerUI method addTagSubMenu.

private static void addTagSubMenu(MenuManager menu_manager, MenuItem menu, final Subscription subs) {
    menu.removeAllChildItems();
    TagManager tm = TagManagerFactory.getTagManager();
    List<Tag> tags = tm.getTagType(TagType.TT_DOWNLOAD_MANUAL).getTags();
    tags = TagUIUtils.sortTags(tags);
    long tag_id = subs.getTagID();
    Tag assigned_tag = tm.lookupTagByUID(tag_id);
    MenuItem m = menu_manager.addMenuItem(menu, "label.no.tag");
    m.setStyle(MenuItem.STYLE_RADIO);
    m.setData(Boolean.valueOf(assigned_tag == null));
    m.addListener(new MenuItemListener() {

        @Override
        public void selected(MenuItem menu, Object target) {
            subs.setTagID(-1);
        }
    });
    m = menu_manager.addMenuItem(menu, "sep1");
    m.setStyle(MenuItem.STYLE_SEPARATOR);
    List<String> menu_names = new ArrayList<>();
    Map<String, Tag> menu_name_map = new IdentityHashMap<>();
    for (Tag t : tags) {
        if (!t.isTagAuto()[0]) {
            String name = t.getTagName(true);
            menu_names.add(name);
            menu_name_map.put(name, t);
        }
    }
    List<Object> menu_structure = MenuBuildUtils.splitLongMenuListIntoHierarchy(menu_names, TagUIUtils.MAX_TOP_LEVEL_TAGS_IN_MENU);
    for (Object obj : menu_structure) {
        List<Tag> bucket_tags = new ArrayList<>();
        MenuItem parent_menu;
        if (obj instanceof String) {
            parent_menu = menu;
            bucket_tags.add(menu_name_map.get((String) obj));
        } else {
            Object[] entry = (Object[]) obj;
            List<String> tag_names = (List<String>) entry[1];
            boolean has_selected = false;
            for (String name : tag_names) {
                Tag tag = menu_name_map.get(name);
                bucket_tags.add(tag);
                if (assigned_tag == tag) {
                    has_selected = true;
                }
            }
            parent_menu = menu_manager.addMenuItem(menu, "!" + (String) entry[0] + (has_selected ? " (*)" : "") + "!");
            parent_menu.setStyle(MenuItem.STYLE_MENU);
        }
        for (final Tag tag : bucket_tags) {
            m = menu_manager.addMenuItem(parent_menu, tag.getTagName(false));
            m.setStyle(MenuItem.STYLE_RADIO);
            m.setData(Boolean.valueOf(assigned_tag == tag));
            m.addListener(new MenuItemListener() {

                @Override
                public void selected(MenuItem menu, Object target) {
                    subs.setTagID(tag.getTagUID());
                }
            });
        }
    }
    m = menu_manager.addMenuItem(menu, "sep2");
    m.setStyle(MenuItem.STYLE_SEPARATOR);
    m = menu_manager.addMenuItem(menu, "label.add.tag");
    m.addListener(new MenuItemListener() {

        @Override
        public void selected(MenuItem menu, Object target) {
            addTag(subs);
        }
    });
}
Also used : MenuItem(com.biglybt.pif.ui.menus.MenuItem) MenuItemListener(com.biglybt.pif.ui.menus.MenuItemListener)

Example 2 with MenuItemListener

use of com.biglybt.pif.ui.menus.MenuItemListener in project BiglyBT by BiglySoftware.

the class BuddyUIUtils method createChat.

public static void createChat(MenuManager menu_manager, MenuItem menu, boolean immediate, ChatCreationListener _listener) {
    ChatCreationListener listener = new ChatCreationListener() {

        Object lock = new Object();

        TimerEventPeriodic timer;

        public void chatCreated(Object target, String name) {
            _listener.chatCreated(target, name);
        }

        public void chatAvailable(Object target, ChatInstance chat) {
            synchronized (lock) {
                if (timer != null) {
                    return;
                }
                long start = SystemTime.getMonotonousTime();
                timer = SimpleTimer.addPeriodicEvent("availcheck", 1000, (ev) -> {
                    if (chat.isAvailable()) {
                        if (!chat.isDestroyed()) {
                            _listener.chatAvailable(target, chat);
                        }
                        synchronized (lock) {
                            timer.cancel();
                        }
                    }
                    if (SystemTime.getMonotonousTime() - start > 3 * 60 * 1000) {
                        Debug.out("Gave up waiting for " + chat.getNetAndKey() + " to become available");
                        synchronized (lock) {
                            timer.cancel();
                        }
                    }
                });
            }
        }
    };
    Runnable build = () -> {
        MenuItem mi = menu_manager.addMenuItem(menu, "!" + MessageText.getString("label.public") + "...!");
        mi.addMultiListener(new MenuItemListener() {

            @Override
            public void selected(MenuItem menu, Object target) {
                SimpleTextEntryWindow entryWindow = new SimpleTextEntryWindow("chat.view.enter.key.title", "chat.view.enter.key.msg");
                // if we don't do this then the fancy-menu will stay open...
                entryWindow.setParentShell(Utils.findAnyShell(true));
                entryWindow.prompt(new UIInputReceiverListener() {

                    @Override
                    public void UIInputReceiverClosed(UIInputReceiver receiver) {
                        if (!receiver.hasSubmittedInput()) {
                            return;
                        }
                        String key = receiver.getSubmittedInput().trim();
                        listener.chatCreated(target, AENetworkClassifier.AT_PUBLIC + ": " + key);
                        BuddyPluginUtils.createBetaChat(AENetworkClassifier.AT_PUBLIC, key, (chat) -> {
                            listener.chatAvailable(target, chat);
                        });
                    }
                });
            }
        });
        mi = menu_manager.addMenuItem(menu, "!" + MessageText.getString("label.anon") + "...!");
        mi.addMultiListener(new MenuItemListener() {

            @Override
            public void selected(MenuItem menu, Object target) {
                if (BuddyPluginUtils.getBetaPlugin().isI2PAvailable()) {
                    SimpleTextEntryWindow entryWindow = new SimpleTextEntryWindow("chat.view.enter.key.title", "chat.view.enter.key.msg");
                    // if we don't do this then the fancy-menu will stay open...
                    entryWindow.setParentShell(Utils.findAnyShell(true));
                    entryWindow.prompt(new UIInputReceiverListener() {

                        @Override
                        public void UIInputReceiverClosed(UIInputReceiver receiver) {
                            if (!receiver.hasSubmittedInput()) {
                                return;
                            }
                            String key = receiver.getSubmittedInput().trim();
                            listener.chatCreated(target, AENetworkClassifier.AT_I2P + ": " + key);
                            BuddyPluginUtils.createBetaChat(AENetworkClassifier.AT_I2P, key, (chat) -> {
                                if (chat != null) {
                                    listener.chatAvailable(target, chat);
                                }
                            });
                        }
                    });
                } else {
                    I2PHelpers.installI2PHelper(null, null, null);
                }
            }
        });
        if (I2PHelpers.isInstallingI2PHelper()) {
            mi.setEnabled(false);
            mi.setText(mi.getText() + " (" + MessageText.getString("PeersView.state.pending") + ")");
        }
    };
    if (immediate) {
        build.run();
    } else {
        menu.addFillListener(new com.biglybt.pif.ui.menus.MenuItemFillListener() {

            @Override
            public void menuWillBeShown(MenuItem menu, Object data) {
                menu.removeAllChildItems();
                build.run();
            }
        });
    }
}
Also used : TimerEventPeriodic(com.biglybt.core.util.TimerEventPeriodic) SystemTime(com.biglybt.core.util.SystemTime) UIInputReceiver(com.biglybt.pif.ui.UIInputReceiver) TimerEventPeriodic(com.biglybt.core.util.TimerEventPeriodic) Messages(com.biglybt.ui.swt.Messages) UIInputReceiverListener(com.biglybt.pif.ui.UIInputReceiverListener) MenuManager(com.biglybt.pif.ui.menus.MenuManager) I2PHelpers(com.biglybt.plugin.I2PHelpers) MessageText(com.biglybt.core.internat.MessageText) ChatInstance(com.biglybt.plugin.net.buddy.BuddyPluginBeta.ChatInstance) Debug(com.biglybt.core.util.Debug) Utils(com.biglybt.ui.swt.Utils) SimpleTimer(com.biglybt.core.util.SimpleTimer) MenuItemListener(com.biglybt.pif.ui.menus.MenuItemListener) SimpleTextEntryWindow(com.biglybt.ui.swt.SimpleTextEntryWindow) SWT(org.eclipse.swt.SWT) MenuItem(com.biglybt.pif.ui.menus.MenuItem) Menu(org.eclipse.swt.widgets.Menu) AENetworkClassifier(com.biglybt.core.util.AENetworkClassifier) BuddyPluginUtils(com.biglybt.plugin.net.buddy.BuddyPluginUtils) ChatInstance(com.biglybt.plugin.net.buddy.BuddyPluginBeta.ChatInstance) MenuItem(com.biglybt.pif.ui.menus.MenuItem) SimpleTextEntryWindow(com.biglybt.ui.swt.SimpleTextEntryWindow) UIInputReceiver(com.biglybt.pif.ui.UIInputReceiver) MenuItemListener(com.biglybt.pif.ui.menus.MenuItemListener) UIInputReceiverListener(com.biglybt.pif.ui.UIInputReceiverListener)

Example 3 with MenuItemListener

use of com.biglybt.pif.ui.menus.MenuItemListener in project BiglyBT by BiglySoftware.

the class StartStopRulesDefaultPlugin method reloadConfigParams.

private void reloadConfigParams() {
    try {
        this_mon.enter();
        int iNewRankType = plugin_config.getUnsafeIntParameter("StartStopManager_iRankType");
        minSpeedForActiveSeeding = plugin_config.getUnsafeIntParameter("StartStopManager_iMinSpeedForActiveSeeding");
        if (minSpeedForActiveSeeding == 0) {
            maxStalledSeeding = 0;
            stalledSeedingIgnoreZP = false;
        } else {
            maxStalledSeeding = plugin_config.getUnsafeIntParameter("StartStopManager_iMaxStalledSeeding");
            if (maxStalledSeeding <= 0) {
                // insanity :)
                maxStalledSeeding = 999;
            }
            stalledSeedingIgnoreZP = plugin_config.getUnsafeBooleanParameter("StartStopManager_bMaxStalledSeedingIgnoreZP");
        }
        _maxActive = plugin_config.getUnsafeIntParameter("max active torrents");
        _maxActiveWhenSeedingEnabled = plugin_config.getUnsafeBooleanParameter("StartStopManager_bMaxActiveTorrentsWhenSeedingEnabled");
        _maxActiveWhenSeeding = plugin_config.getUnsafeIntParameter("StartStopManager_iMaxActiveTorrentsWhenSeeding");
        maxConfiguredDownloads = plugin_config.getUnsafeIntParameter("max downloads");
        boolean min_eq_max = plugin_config.getUnsafeBooleanParameter("StartStopManager_bMaxMinDLLinked");
        if (min_eq_max) {
            minDownloads = maxConfiguredDownloads;
        } else {
            minDownloads = plugin_config.getUnsafeIntParameter("min downloads");
        }
        bMaxDownloadIgnoreChecking = plugin_config.getUnsafeBooleanParameter("StartStopManager_bMaxDownloadIgnoreChecking");
        bAutoReposition = plugin_config.getUnsafeBooleanParameter("StartStopManager_bAutoReposition");
        minTimeAlive = plugin_config.getUnsafeIntParameter("StartStopManager_iMinSeedingTime") * 1000;
        bDebugLog = plugin_config.getUnsafeBooleanParameter("StartStopManager_bDebugLog");
        bAutoStart0Peers = plugin_config.getUnsafeBooleanParameter("StartStopManager_bAutoStart0Peers");
        globalDownloadLimit = plugin_config.getUnsafeIntParameter("Max Download Speed KBs", 0);
        globalUploadLimit = plugin_config.getUnsafeIntParameter("Max Upload Speed KBs", 0);
        globalUploadWhenSeedingLimit = plugin_config.getUnsafeBooleanParameter("enable.seedingonly.upload.rate") ? plugin_config.getUnsafeIntParameter("Max Upload Speed Seeding KBs", 0) : globalUploadLimit;
        bStopOnceBandwidthMet = plugin_config.getUnsafeBooleanParameter("StartStopManager_bStopOnceBandwidthMet");
        bStartNoMoreSeedsWhenUpLimitMet = plugin_config.getUnsafeBooleanParameter("StartStopManager_bStartNoMoreSeedsWhenUpLimitMet");
        bStartNoMoreSeedsWhenUpLimitMetPercent = plugin_config.getUnsafeBooleanParameter("StartStopManager_bStartNoMoreSeedsWhenUpLimitMetPercent");
        bStartNoMoreSeedsWhenUpLimitMetSlack = plugin_config.getUnsafeIntParameter("StartStopManager_bStartNoMoreSeedsWhenUpLimitMetSlack");
        boolean move_top = plugin_config.getUnsafeBooleanParameter("StartStopManager_bNewSeedsMoveTop");
        plugin_config.setCoreBooleanParameter(PluginConfig.CORE_PARAM_BOOLEAN_NEW_SEEDS_START_AT_TOP, move_top);
        if (iNewRankType != iRankType) {
            iRankType = iNewRankType;
            // shorten recalc for timed rank type, since the calculation is fast and we want to stop on the second
            if (iRankType == RANK_TIMED) {
                if (recalcSeedingRanksTask == null) {
                    recalcAllSeedingRanks();
                    recalcSeedingRanksTask = new RecalcSeedingRanksTask();
                    SimpleTimer.addPeriodicEvent("StartStop:recalcSR", 1000, recalcSeedingRanksTask);
                }
            } else if (recalcSeedingRanksTask != null) {
                recalcSeedingRanksTask.cancel();
                recalcSeedingRanksTask = null;
            }
        }
        iDownloadSortType = plugin_config.getUnsafeIntParameter("StartStopManager_Downloading_iSortType", -1);
        // migrate from old boolean setting
        if (iDownloadSortType == -1) {
            boolean bDownloadAutoReposition = plugin_config.getUnsafeBooleanParameter("StartStopManager_Downloading_bAutoReposition");
            iDownloadSortType = bDownloadAutoReposition ? DefaultRankCalculator.DOWNLOAD_ORDER_SPEED : DefaultRankCalculator.DOWNLOAD_ORDER_INDEX;
            plugin_config.setCoreIntParameter("StartStopManager_Downloading_iSortType", iDownloadSortType);
        }
        iDownloadTestTimeMillis = plugin_config.getUnsafeIntParameter("StartStopManager_Downloading_iTestTimeSecs") * 1000;
        iDownloadReTestMillis = plugin_config.getUnsafeIntParameter("StartStopManager_Downloading_iRetestTimeMins") * 60 * 1000;
        bDownloadTestActive = plugin_config.getUnsafeBooleanParameter("StartStopManager_Downloading_bTestActive");
        bTagFirstPriority = plugin_config.getUnsafeBooleanParameter("StartStopManager_bTagFirstPriority");
        if (bTagFirstPriority) {
            TagManager tag_manager = TagManagerFactory.getTagManager();
            if (tag_manager != null && tag_manager.isEnabled()) {
                TagType tt = tag_manager.getTagType(TagType.TT_DOWNLOAD_MANUAL);
                if (fp_tag == null) {
                    fp_tag = tt.getTag("First Priority", true);
                    if (fp_tag == null) {
                        try {
                            fp_tag = tt.createTag("First Priority", true);
                            fp_tag.setPublic(false);
                        } catch (Throwable e) {
                            Debug.out(e);
                        }
                    }
                }
                Tag not_fp_tag = tt.getTag("Not First Priority", true);
                if (not_fp_tag == null) {
                    try {
                        not_fp_tag = tt.createTag("Not First Priority", true);
                        not_fp_tag.setPublic(false);
                    } catch (Throwable e) {
                        Debug.out(e);
                    }
                }
                if (not_fp_tag != null) {
                    TagProperty constraint = ((TagFeatureProperties) not_fp_tag).getProperty(TagFeatureProperties.PR_CONSTRAINT);
                    constraint.setStringList(new String[] { "isComplete() && !hasTag( \"First Priority\" )" });
                }
            }
        }
        maxOverLimitSeeding = plugin_config.getUnsafeIntParameter("Flexible Seed Slots");
        int numslots = plugin_config.getUnsafeIntParameter("Light Seed Slots Reserved");
        int diff = numslots - numReservedSeedingSlots;
        numReservedSeedingSlots = numslots;
        if (diff > 0) {
            for (int i = 0; i < diff; i++) {
                RankCalculatorSlotReserver slot = new RankCalculatorSlotReserver();
                reservedSlots.add(slot);
                synchronized (rankCalculatorMap) {
                    rankCalculatorMap.put(slot, slot);
                    sortedArrayCache = null;
                }
            }
        } else if (diff < 0) {
            for (int i = -diff; i > 0 && !reservedSlots.isEmpty(); i--) {
                RankCalculatorSlotReserver slot = reservedSlots.removeFirst();
                synchronized (rankCalculatorMap) {
                    rankCalculatorMap.remove(slot);
                    sortedArrayCache = null;
                }
            }
        }
        /*
			 // limit _maxActive and maxDownloads based on TheColonel's specs

			 // maxActive = max_upload_speed / (slots_per_torrent * min_speed_per_peer)
			 if (_maxActive > 0) {
			 int iSlotsPerTorrent = plugin_config.getUnsafeIntParameter("Max Uploads");
			 // TODO: Track upload speed, storing the max upload speed over a minute
			 //        and use that for "unlimited" setting, or huge settings (like 200)
			 if (iSlotsPerTorrent > 0) {
			 int iMinSpeedPerPeer = 3; // for now.  TODO: config value
			 int _maxActiveLimit = iMaxUploadSpeed / (iSlotsPerTorrent * iMinSpeedPerPeer);
			 if (_maxActive > _maxActiveLimit) {
			 _maxActive = _maxActiveLimit;
			 plugin_config.setCoreIntParameter(PluginConfig.CORE_PARAM_INT_MAX_ACTIVE, _maxActive);
			 }
			 }

			 if (maxDownloads > _maxActive) {
			 maxDownloads = _maxActive;
			 plugin_config.setCoreIntParameter(PluginConfig.CORE_PARAM_INT_MAX_DOWNLOADS, maxDownloads);
			 }
			 }
			 */
        // force a recalc on all downloads by setting SR to 0, scheduling
        // a recalc on next process, and requsting a process cycle
        Collection<DefaultRankCalculator> allDownloads = rankCalculatorMap.values();
        try {
            ranksToRecalc_mon.enter();
            synchronized (rankCalculatorMap) {
                ranksToRecalc.addAll(allDownloads);
            }
        } finally {
            ranksToRecalc_mon.exit();
        }
        requestProcessCycle(null);
        if (bDebugLog) {
            log.log(LoggerChannel.LT_INFORMATION, "somethingChanged: config reload");
            try {
                if (debugMenuItem == null) {
                    final String DEBUG_MENU_ID = "StartStopRules.menu.viewDebug";
                    MenuItemListener menuListener = new MenuItemListener() {

                        @Override
                        public void selected(MenuItem menu, Object target) {
                            if (!(target instanceof TableRow))
                                return;
                            TableRow tr = (TableRow) target;
                            Object ds = tr.getDataSource();
                            if (!(ds instanceof Download))
                                return;
                            DefaultRankCalculator dlData = rankCalculatorMap.get(ds);
                            if (dlData != null) {
                                if (swt_ui != null)
                                    swt_ui.openDebugWindow(dlData);
                                else
                                    pi.getUIManager().showTextMessage(null, null, "FP:\n" + dlData.getExplainFP() + "\n" + "SR:" + dlData.getExplainSR() + "\n" + "TRACE:\n" + dlData.getTrace());
                            }
                        }
                    };
                    TableManager tm = pi.getUIManager().getTableManager();
                    debugMenuItem = tm.addContextMenuItem(TableManager.TABLE_MYTORRENTS_COMPLETE, DEBUG_MENU_ID);
                    debugMenuItem.setHeaderCategory(MenuItem.HEADER_CONTROL);
                    debugMenuItem.addListener(menuListener);
                    debugMenuItem = tm.addContextMenuItem(TableManager.TABLE_MYTORRENTS_INCOMPLETE, DEBUG_MENU_ID);
                    debugMenuItem.setHeaderCategory(MenuItem.HEADER_CONTROL);
                    debugMenuItem.addListener(menuListener);
                }
            } catch (Throwable t) {
                Debug.printStackTrace(t);
            }
        }
    } finally {
        this_mon.exit();
    }
}
Also used : TagProperty(com.biglybt.core.tag.TagFeatureProperties.TagProperty) MenuItem(com.biglybt.pif.ui.menus.MenuItem) TagType(com.biglybt.core.tag.TagType) TagManager(com.biglybt.core.tag.TagManager) MenuItemListener(com.biglybt.pif.ui.menus.MenuItemListener) Tag(com.biglybt.core.tag.Tag) TagFeatureProperties(com.biglybt.core.tag.TagFeatureProperties)

Example 4 with MenuItemListener

use of com.biglybt.pif.ui.menus.MenuItemListener in project BiglyBT by BiglySoftware.

the class MagnetPlugin method initialize.

@Override
public void initialize(PluginInterface _plugin_interface) {
    plugin_interface = _plugin_interface;
    MagnetURIHandler uri_handler = MagnetURIHandler.getSingleton();
    final LocaleUtilities lu = plugin_interface.getUtilities().getLocaleUtilities();
    lu.addListener(new LocaleListener() {

        @Override
        public void localeChanged(Locale l) {
            updateLocale(lu);
        }
    });
    updateLocale(lu);
    BasicPluginConfigModel config = plugin_interface.getUIManager().createBasicPluginConfigModel(ConfigSection.SECTION_PLUGINS, PLUGIN_CONFIGSECTION_ID);
    config.addInfoParameter2("MagnetPlugin.current.port", String.valueOf(uri_handler.getPort()));
    md_lookup = config.addBooleanParameter2("MagnetPlugin.use.md.download", "MagnetPlugin.use.md.download", true);
    md_lookup_delay = config.addIntParameter2("MagnetPlugin.use.md.download.delay", "MagnetPlugin.use.md.download.delay", MD_LOOKUP_DELAY_SECS_DEFAULT);
    String et_default = "";
    for (String etd : MD_EXTRA_TRACKERS) {
        et_default += (et_default.isEmpty() ? "" : "\n") + etd;
    }
    md_extra_trackers = config.addStringParameter2("MagnetPlugin.md.extra.trackers", "MagnetPlugin.md.extra.trackers", et_default);
    md_extra_trackers.setMultiLine(3);
    md_lookup.addEnabledOnSelection(md_lookup_delay);
    md_lookup.addEnabledOnSelection(md_extra_trackers);
    timeout_param = config.addIntParameter2("MagnetPlugin.timeout.secs", "MagnetPlugin.timeout.secs", PLUGIN_DOWNLOAD_TIMEOUT_SECS_DEFAULT);
    sources_param = config.addStringListParameter2("MagnetPlugin.add.sources", "MagnetPlugin.add.sources", SOURCE_VALUES, SOURCE_STRINGS, SOURCE_VALUES[1]);
    sources_extra_param = config.addIntParameter2("MagnetPlugin.add.sources.extra", "MagnetPlugin.add.sources.extra", 0);
    magnet_recovery = config.addBooleanParameter2("MagnetPlugin.recover.magnets", "MagnetPlugin.recover.magnets", true);
    magnet_recovery_concurrency = config.addIntParameter2("MagnetPlugin.recover.magnets.conc", "MagnetPlugin.recover.magnets.conc", 32, 8, 512);
    magnet_recovery_concurrency.setIndent(1, true);
    magnet_recovery.addEnabledOnSelection(magnet_recovery_concurrency);
    BooleanParameter rename = config.addBooleanParameter2("MagnetPlugin.rename.using.dn", "MagnetPlugin.rename.using.dn", false);
    BooleanParameter rename_ext = config.addBooleanParameter2("MagnetPlugin.rename.using.dn.only.with.ext", "MagnetPlugin.rename.using.dn.only.with.ext", false);
    rename_ext.setIndent(1, true);
    rename.addEnabledOnSelection(rename_ext);
    Parameter[] nps = new Parameter[AENetworkClassifier.AT_NETWORKS.length];
    for (int i = 0; i < nps.length; i++) {
        String nn = AENetworkClassifier.AT_NETWORKS[i];
        String config_name = "Network Selection Default." + nn;
        String msg_text = "ConfigView.section.connection.networks." + nn;
        final BooleanParameter param = config.addBooleanParameter2(config_name, msg_text, COConfigurationManager.getBooleanParameter(config_name));
        COConfigurationManager.addParameterListener(config_name, new com.biglybt.core.config.ParameterListener() {

            @Override
            public void parameterChanged(String name) {
                param.setDefaultValue(COConfigurationManager.getBooleanParameter(name));
            }
        });
        nps[i] = param;
        net_params.put(nn, param);
    }
    config.createGroup("label.default.nets", nps);
    MenuItemListener listener = new MenuItemListener() {

        @Override
        public void selected(MenuItem _menu, Object _target) {
            TableRow[] rows = (TableRow[]) _target;
            String cb_all_data = "";
            for (TableRow row : rows) {
                Torrent torrent;
                String name;
                Object ds = row.getDataSource();
                Download download = null;
                ShareResource share = null;
                if (ds instanceof ShareResourceFile) {
                    ShareResourceFile sf = (ShareResourceFile) ds;
                    try {
                        torrent = sf.getItem().getTorrent();
                    } catch (ShareException e) {
                        continue;
                    }
                    name = sf.getName();
                    share = sf;
                } else if (ds instanceof ShareResourceDir) {
                    ShareResourceDir sd = (ShareResourceDir) ds;
                    try {
                        torrent = sd.getItem().getTorrent();
                    } catch (ShareException e) {
                        continue;
                    }
                    name = sd.getName();
                    share = sd;
                } else if (ds instanceof Download) {
                    download = (Download) ds;
                    torrent = download.getTorrent();
                    name = download.getName();
                } else {
                    continue;
                }
                boolean is_share = false;
                Set<String> networks = new HashSet<>();
                if (share != null) {
                    is_share = true;
                    Map<String, String> properties = share.getProperties();
                    if (properties != null) {
                        String nets = properties.get(ShareManager.PR_NETWORKS);
                        if (nets != null) {
                            String[] bits = nets.split(",");
                            for (String bit : bits) {
                                bit = AENetworkClassifier.internalise(bit.trim());
                                if (bit != null) {
                                    networks.add(bit);
                                }
                            }
                        }
                    }
                }
                if (download != null) {
                    TorrentAttribute ta = plugin_interface.getTorrentManager().getAttribute(TorrentAttribute.TA_NETWORKS);
                    String[] nets = download.getListAttribute(ta);
                    networks.addAll(Arrays.asList(nets));
                    try {
                        byte[] hash = download.getTorrentHash();
                        if (plugin_interface.getShareManager().lookupShare(hash) != null) {
                            is_share = true;
                        }
                    } catch (Throwable e) {
                    }
                }
                String cb_data = download == null ? UrlUtils.getMagnetURI(name, torrent) : UrlUtils.getMagnetURI(download);
                if (download != null) {
                    List<Tag> tags = TagManagerFactory.getTagManager().getTagsForTaggable(TagType.TT_DOWNLOAD_MANUAL, PluginCoreUtils.unwrap(download));
                    for (Tag tag : tags) {
                        if (tag.isPublic()) {
                            if (!tag.isTagAuto()[0]) {
                                cb_data += "&tag=" + UrlUtils.encode(tag.getTagName(true));
                            }
                        }
                    }
                }
                String sources = sources_param.getValue();
                boolean add_sources = sources.equals("2") || (sources.equals("1") && is_share);
                if (add_sources) {
                    if (networks.isEmpty()) {
                        for (String net : AENetworkClassifier.AT_NETWORKS) {
                            if (isNetworkEnabled(net)) {
                                networks.add(net);
                            }
                        }
                    }
                    if (networks.contains(AENetworkClassifier.AT_PUBLIC) && !cb_data.contains("xsource=")) {
                        DownloadManager dm = download == null ? null : PluginCoreUtils.unwrap(download);
                        InetAddress ip = NetworkAdmin.getSingleton().getDefaultPublicAddress();
                        InetAddress ip_v6 = NetworkAdmin.getSingleton().getDefaultPublicAddressV6();
                        int port = dm == null ? TCPNetworkManager.getSingleton().getDefaultTCPListeningPortNumber() : dm.getTCPListeningPortNumber();
                        if (ip != null && port > 0) {
                            cb_data += "&xsource=" + UrlUtils.encode(UrlUtils.getURLForm(ip, port));
                        }
                        if (ip_v6 != null && port > 0) {
                            cb_data += "&xsource=" + UrlUtils.encode(UrlUtils.getURLForm(ip_v6, port));
                        }
                        int extra = sources_extra_param.getValue();
                        if (extra > 0) {
                            if (download == null) {
                                if (torrent != null) {
                                    download = plugin_interface.getDownloadManager().getDownload(torrent);
                                }
                            }
                            if (download != null) {
                                Set<String> added = new HashSet<>();
                                PEPeerManager pm = dm.getPeerManager();
                                if (pm != null) {
                                    List<PEPeer> peers = pm.getPeers();
                                    for (PEPeer peer : peers) {
                                        String peer_ip = peer.getIp();
                                        if (AENetworkClassifier.categoriseAddress(peer_ip) == AENetworkClassifier.AT_PUBLIC) {
                                            int peer_port = peer.getTCPListenPort();
                                            if (peer_port > 0) {
                                                cb_data += "&xsource=" + UrlUtils.encode(UrlUtils.getURLForm(peer_ip, peer_port));
                                                added.add(peer_ip);
                                                extra--;
                                                if (extra == 0) {
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                                if (extra > 0) {
                                    Map response_cache = dm.getDownloadState().getTrackerResponseCache();
                                    if (response_cache != null) {
                                        List<TRTrackerAnnouncerResponsePeer> peers = TRTrackerAnnouncerFactory.getCachedPeers(response_cache);
                                        for (TRTrackerAnnouncerResponsePeer peer : peers) {
                                            String peer_ip = peer.getAddress();
                                            if (AENetworkClassifier.categoriseAddress(peer_ip) == AENetworkClassifier.AT_PUBLIC) {
                                                if (!added.contains(peer_ip)) {
                                                    int peer_port = peer.getPort();
                                                    if (peer_port > 0) {
                                                        cb_data += "&xsource=" + UrlUtils.encode(UrlUtils.getURLForm(peer_ip, peer_port));
                                                        added.add(peer_ip);
                                                        extra--;
                                                        if (extra == 0) {
                                                            break;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                // removed this as well - nothing wrong with allowing magnet copy
                // for private torrents - they still can't be tracked if you don't
                // have permission
                /*if ( torrent.isPrivate()){

							cb_data = getMessageText( "private_torrent" );

						}else if ( torrent.isDecentralised()){
						*/
                // ok
                /* relaxed this as we allow such torrents to be downloaded via magnet links
							 * (as opposed to tracked in the DHT)

						}else if ( torrent.isDecentralisedBackupEnabled()){

							TorrentAttribute ta_peer_sources 	= plugin_interface.getTorrentManager().getAttribute( TorrentAttribute.TA_PEER_SOURCES );

							String[]	sources = download.getListAttribute( ta_peer_sources );

							boolean	ok = false;

							for (int i=0;i<sources.length;i++){

								if ( sources[i].equalsIgnoreCase( "DHT")){

									ok	= true;

									break;
								}
							}

							if ( !ok ){

								cb_data = getMessageText( "decentral_disabled" );
							}
						}else{

							cb_data = getMessageText( "decentral_backup_disabled" );
							*/
                // }
                // System.out.println( "MagnetPlugin: export = " + url );
                cb_all_data += (cb_all_data.length() == 0 ? "" : "\n") + cb_data;
            }
            try {
                plugin_interface.getUIManager().copyToClipBoard(cb_all_data);
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    };
    List<TableContextMenuItem> menus = new ArrayList<>();
    for (String table : TableManager.TABLE_MYTORRENTS_ALL) {
        TableContextMenuItem menu = plugin_interface.getUIManager().getTableManager().addContextMenuItem(table, "MagnetPlugin.contextmenu.exporturi");
        menu.addMultiListener(listener);
        menu.setHeaderCategory(MenuItem.HEADER_SOCIAL);
        menus.add(menu);
    }
    uri_handler.addListener(new MagnetURIHandlerListener() {

        @Override
        public byte[] badge() {
            InputStream is = getClass().getClassLoader().getResourceAsStream("com/biglybt/plugin/magnet/Magnet.gif");
            if (is == null) {
                return (null);
            }
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                try {
                    byte[] buffer = new byte[8192];
                    while (true) {
                        int len = is.read(buffer);
                        if (len <= 0) {
                            break;
                        }
                        baos.write(buffer, 0, len);
                    }
                } finally {
                    is.close();
                }
                return (baos.toByteArray());
            } catch (Throwable e) {
                Debug.printStackTrace(e);
                return (null);
            }
        }

        @Override
        public byte[] download(MagnetURIHandlerProgressListener muh_listener, byte[] hash, String args, InetSocketAddress[] sources, long timeout) throws MagnetURIHandlerException {
            try {
                Download dl = plugin_interface.getDownloadManager().getDownload(hash);
                if (dl != null) {
                    // might just be an existing metadata download
                    com.biglybt.core.download.DownloadManager core_dm = PluginCoreUtils.unwrap(dl);
                    if (!core_dm.getDownloadState().getFlag(DownloadManagerState.FLAG_METADATA_DOWNLOAD)) {
                        Torrent torrent = dl.getTorrent();
                        if (torrent != null) {
                            byte[] torrent_data = torrent.writeToBEncodedData();
                            torrent_data = addTrackersAndWebSeedsEtc(torrent_data, args, new HashSet<String>(), Collections.emptyList(), Collections.emptyMap());
                            return (torrent_data);
                        }
                    }
                }
            } catch (Throwable e) {
                Debug.printStackTrace(e);
            }
            Object[] result = { null };
            AESemaphore sem = new AESemaphore("dlwait");
            DownloadAsyncListener dl_listener = new DownloadAsyncListener() {

                @Override
                public void failed(MagnetURIHandlerException error) {
                    synchronized (result) {
                        result[0] = error;
                    }
                    sem.release();
                }

                @Override
                public void complete(byte[] torrent_data) {
                    synchronized (result) {
                        result[0] = torrent_data;
                    }
                    sem.release();
                }
            };
            recoverableDownload(muh_listener, hash, args, sources, Collections.emptyList(), Collections.emptyMap(), timeout, SystemTime.getCurrentTime(), false, dl_listener);
            sem.reserve();
            synchronized (result) {
                Object r = result[0];
                if (r instanceof MagnetURIHandlerException) {
                    throw ((MagnetURIHandlerException) r);
                } else {
                    return ((byte[]) r);
                }
            }
        }

        @Override
        public boolean download(URL url) throws MagnetURIHandlerException {
            try {
                plugin_interface.getDownloadManager().addDownload(url, false);
                return (true);
            } catch (DownloadException e) {
                throw (new MagnetURIHandlerException("Operation failed", e));
            }
        }

        @Override
        public boolean set(String name, Map values) {
            List l = listeners.getList();
            for (int i = 0; i < l.size(); i++) {
                if (((MagnetPluginListener) l.get(i)).set(name, values)) {
                    return (true);
                }
            }
            return (false);
        }

        @Override
        public int get(String name, Map values) {
            List l = listeners.getList();
            for (int i = 0; i < l.size(); i++) {
                int res = ((MagnetPluginListener) l.get(i)).get(name, values);
                if (res != Integer.MIN_VALUE) {
                    return (res);
                }
            }
            return (Integer.MIN_VALUE);
        }
    });
    plugin_interface.getUIManager().addUIListener(new UIManagerListener() {

        @Override
        public void UIAttached(UIInstance instance) {
            if (instance.getUIType().equals(UIInstance.UIT_SWT)) {
                try {
                    Class.forName("com.biglybt.plugin.magnet.swt.MagnetPluginUISWT").getConstructor(new Class[] { UIInstance.class, TableContextMenuItem[].class }).newInstance(new Object[] { instance, menus.toArray(new TableContextMenuItem[menus.size()]) });
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void UIDetached(UIInstance instance) {
        }
    });
    final List<Download> to_delete = new ArrayList<>();
    Download[] downloads = plugin_interface.getDownloadManager().getDownloads();
    for (Download download : downloads) {
        if (download.getFlag(Download.FLAG_METADATA_DOWNLOAD)) {
            to_delete.add(download);
        }
    }
    final AESemaphore delete_done = new AESemaphore("delete waiter");
    if (to_delete.size() > 0) {
        AEThread2 t = new AEThread2("MagnetPlugin:delmds", true) {

            @Override
            public void run() {
                try {
                    for (Download download : to_delete) {
                        try {
                            download.stopAndRemove(true, true);
                        } catch (Throwable e) {
                            Debug.out(e);
                        }
                    }
                } finally {
                    delete_done.release();
                }
            }
        };
        t.start();
    } else {
        delete_done.release();
    }
    plugin_interface.addListener(new PluginListener() {

        @Override
        public void initializationComplete() {
            // make sure DDB is initialised as we need it to register its
            // transfer types
            AEThread2 t = new AEThread2("MagnetPlugin:init", true) {

                @Override
                public void run() {
                    delete_done.reserve();
                    recoverDownloads();
                    try {
                        DistributedDatabase db = plugin_interface.getDistributedDatabase();
                        synchronized (db_holder) {
                            db_holder[0] = db;
                        }
                    } catch (Throwable e) {
                        Debug.out(e);
                    } finally {
                        db_waiter.releaseForever();
                    }
                }
            };
            t.start();
        }

        @Override
        public void closedownInitiated() {
            updateRecoverableDownloads();
        }

        @Override
        public void closedownComplete() {
        }
    });
}
Also used : Torrent(com.biglybt.pif.torrent.Torrent) TOTorrent(com.biglybt.core.torrent.TOTorrent) PEPeer(com.biglybt.core.peer.PEPeer) ShareResourceDir(com.biglybt.pif.sharing.ShareResourceDir) InetSocketAddress(java.net.InetSocketAddress) LocaleUtilities(com.biglybt.pif.utils.LocaleUtilities) DownloadManager(com.biglybt.core.download.DownloadManager) DownloadException(com.biglybt.pif.download.DownloadException) MenuItemListener(com.biglybt.pif.ui.menus.MenuItemListener) UIInstance(com.biglybt.pif.ui.UIInstance) MagnetURIHandler(com.biglybt.net.magneturi.MagnetURIHandler) TableRow(com.biglybt.pif.ui.tables.TableRow) PEPeerManager(com.biglybt.core.peer.PEPeerManager) InetAddress(java.net.InetAddress) ShareResourceFile(com.biglybt.pif.sharing.ShareResourceFile) MagnetURIHandlerProgressListener(com.biglybt.net.magneturi.MagnetURIHandlerProgressListener) TableContextMenuItem(com.biglybt.pif.ui.tables.TableContextMenuItem) URL(java.net.URL) PluginListener(com.biglybt.pif.PluginListener) ShareException(com.biglybt.pif.sharing.ShareException) LocaleListener(com.biglybt.pif.utils.LocaleListener) Download(com.biglybt.pif.download.Download) ShareResource(com.biglybt.pif.sharing.ShareResource) InputStream(java.io.InputStream) TableContextMenuItem(com.biglybt.pif.ui.tables.TableContextMenuItem) MenuItem(com.biglybt.pif.ui.menus.MenuItem) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BooleanParameter(com.biglybt.pif.ui.config.BooleanParameter) TorrentAttribute(com.biglybt.pif.torrent.TorrentAttribute) BooleanParameter(com.biglybt.pif.ui.config.BooleanParameter) StringParameter(com.biglybt.pif.ui.config.StringParameter) Parameter(com.biglybt.pif.ui.config.Parameter) StringListParameter(com.biglybt.pif.ui.config.StringListParameter) IntParameter(com.biglybt.pif.ui.config.IntParameter) TRTrackerAnnouncerResponsePeer(com.biglybt.core.tracker.client.TRTrackerAnnouncerResponsePeer) Tag(com.biglybt.core.tag.Tag) MagnetURIHandlerListener(com.biglybt.net.magneturi.MagnetURIHandlerListener) MagnetURIHandlerException(com.biglybt.net.magneturi.MagnetURIHandlerException) UIManagerListener(com.biglybt.pif.ui.UIManagerListener) BasicPluginConfigModel(com.biglybt.pif.ui.model.BasicPluginConfigModel)

Example 5 with MenuItemListener

use of com.biglybt.pif.ui.menus.MenuItemListener in project BiglyBT by BiglySoftware.

the class MenuItemImpl method invokeListenersOnList.

protected void invokeListenersOnList(CopyOnWriteList listeners_to_notify, Object target) {
    for (Iterator iter = listeners_to_notify.iterator(); iter.hasNext(); ) {
        try {
            MenuItemListener l = (MenuItemListener) iter.next();
            l.selected(this, target);
        } catch (Throwable e) {
            Debug.printStackTrace(e);
        }
    }
}
Also used : Iterator(java.util.Iterator) MenuItemListener(com.biglybt.pif.ui.menus.MenuItemListener)

Aggregations

MenuItemListener (com.biglybt.pif.ui.menus.MenuItemListener)22 MenuItem (com.biglybt.pif.ui.menus.MenuItem)19 MenuItemFillListener (com.biglybt.pif.ui.menus.MenuItemFillListener)8 MenuManager (com.biglybt.pif.ui.menus.MenuManager)7 ChatInstance (com.biglybt.plugin.net.buddy.BuddyPluginBeta.ChatInstance)7 PluginInterface (com.biglybt.pif.PluginInterface)5 UIInstance (com.biglybt.pif.ui.UIInstance)5 TableContextMenuItem (com.biglybt.pif.ui.tables.TableContextMenuItem)5 ParameterListener (com.biglybt.core.config.ParameterListener)4 UIManager (com.biglybt.pif.ui.UIManager)4 UIFunctions (com.biglybt.ui.UIFunctions)4 InputStream (java.io.InputStream)4 InetSocketAddress (java.net.InetSocketAddress)4 URL (java.net.URL)4 ArrayList (java.util.ArrayList)4 List (java.util.List)4 DownloadHistoryEvent (com.biglybt.core.history.DownloadHistoryEvent)3 DownloadHistoryListener (com.biglybt.core.history.DownloadHistoryListener)3 DownloadHistoryManager (com.biglybt.core.history.DownloadHistoryManager)3 Tag (com.biglybt.core.tag.Tag)3