use of com.biglybt.pif.ui.UIInputReceiver in project BiglyBT by BiglySoftware.
the class TorrentUtil method addTrackerTorrentMenu.
protected static void addTrackerTorrentMenu(final Menu menuTracker, final DownloadManager[] dms, boolean changeUrl, boolean manualUpdate, boolean allStopped, final boolean use_open_containing_folder, boolean canMove) {
Shell shell = Utils.findAnyShell();
boolean hasSelection = dms.length > 0;
final MenuItem itemChangeTracker = new MenuItem(menuTracker, SWT.PUSH);
Messages.setLanguageText(itemChangeTracker, "MyTorrentsView.menu.changeTracker");
Utils.setMenuItemImage(itemChangeTracker, "add_tracker");
itemChangeTracker.addListener(SWT.Selection, new ListenerDMTask(dms) {
@Override
public void run(DownloadManager[] dms) {
if (dms.length > 0) {
new TrackerChangerWindow(dms);
}
}
});
itemChangeTracker.setEnabled(changeUrl);
// edit tracker URLs
final MenuItem itemEditTracker = new MenuItem(menuTracker, SWT.PUSH);
Messages.setLanguageText(itemEditTracker, "MyTorrentsView.menu.editTracker");
Utils.setMenuItemImage(itemEditTracker, "edit_trackers");
itemEditTracker.addListener(SWT.Selection, new ListenerDMTask(dms) {
@Override
public void run(final DownloadManager[] dms) {
Map<String, List<DownloadManager>> same_map = new HashMap<>();
for (DownloadManager dm : dms) {
TOTorrent torrent = dm.getTorrent();
if (torrent == null) {
continue;
}
List<List<String>> group = TorrentUtils.announceGroupsToList(torrent);
String str = "";
for (List<String> l : group) {
str += "[[";
for (String s : l) {
str += s + ", ";
}
}
List<DownloadManager> dl = same_map.get(str);
if (dl == null) {
dl = new ArrayList<>();
same_map.put(str, dl);
}
dl.add(dm);
}
for (final List<DownloadManager> set : same_map.values()) {
TOTorrent torrent = set.get(0).getTorrent();
List<List<String>> group = TorrentUtils.announceGroupsToList(torrent);
new MultiTrackerEditor(null, null, group, new TrackerEditorListener() {
@Override
public void trackersChanged(String str, String str2, List<List<String>> group) {
for (DownloadManager dm : set) {
TOTorrent torrent = dm.getTorrent();
TorrentUtils.listToAnnounceGroups(group, torrent);
try {
TorrentUtils.writeToFile(torrent);
} catch (Throwable e) {
Debug.printStackTrace(e);
}
if (dm.getTrackerClient() != null) {
dm.getTrackerClient().resetTrackerUrl(true);
}
}
}
}, true, true);
}
}
});
itemEditTracker.setEnabled(hasSelection);
// edit tracker URLs together
final MenuItem itemEditTrackerMerged = new MenuItem(menuTracker, SWT.PUSH);
Messages.setLanguageText(itemEditTrackerMerged, "MyTorrentsView.menu.editTrackerMerge");
itemEditTrackerMerged.addListener(SWT.Selection, new ListenerDMTask(dms) {
@Override
public void run(final DownloadManager[] dms) {
final List<List<String>> merged_trackers = new ArrayList<>();
Set<String> added = new HashSet<>();
for (DownloadManager dm : dms) {
TOTorrent torrent = dm.getTorrent();
if (torrent == null) {
continue;
}
List<List<String>> group = TorrentUtils.announceGroupsToList(torrent);
for (List<String> set : group) {
List<String> rem = new ArrayList<>();
for (String url_str : set) {
try {
URL url = new URL(url_str);
if (TorrentUtils.isDecentralised(url)) {
continue;
}
if (!added.contains(url_str)) {
added.add(url_str);
rem.add(url_str);
}
} catch (Throwable e) {
}
}
if (rem.size() > 0) {
merged_trackers.add(rem);
}
}
}
new MultiTrackerEditor(null, null, merged_trackers, new TrackerEditorListener() {
@Override
public void trackersChanged(String str, String str2, List<List<String>> group) {
for (DownloadManager dm : dms) {
TOTorrent torrent = dm.getTorrent();
TorrentUtils.listToAnnounceGroups(group, torrent);
try {
TorrentUtils.writeToFile(torrent);
} catch (Throwable e) {
Debug.printStackTrace(e);
}
if (dm.getTrackerClient() != null) {
dm.getTrackerClient().resetTrackerUrl(true);
}
}
}
}, true, true);
}
});
itemEditTrackerMerged.setEnabled(dms.length > 1);
// edit webseeds
final MenuItem itemEditWebSeeds = new MenuItem(menuTracker, SWT.PUSH);
Messages.setLanguageText(itemEditWebSeeds, "MyTorrentsView.menu.editWebSeeds");
itemEditWebSeeds.addListener(SWT.Selection, new ListenerDMTask(dms) {
@Override
public void run(final DownloadManager[] dms) {
final TOTorrent torrent = dms[0].getTorrent();
if (torrent == null) {
return;
}
List getright = getURLList(torrent, "url-list");
List webseeds = getURLList(torrent, "httpseeds");
Map ws = new HashMap();
ws.put("getright", getright);
ws.put("webseeds", webseeds);
ws = BDecoder.decodeStrings(ws);
new WebSeedsEditor(null, ws, new WebSeedsEditorListener() {
@Override
public void webSeedsChanged(String oldName, String newName, Map ws) {
try {
// String -> byte[]
ws = BDecoder.decode(BEncoder.encode(ws));
List getright = (List) ws.get("getright");
if (getright == null || getright.size() == 0) {
torrent.removeAdditionalProperty("url-list");
} else {
torrent.setAdditionalListProperty("url-list", getright);
}
List webseeds = (List) ws.get("webseeds");
if (webseeds == null || webseeds.size() == 0) {
torrent.removeAdditionalProperty("httpseeds");
} else {
torrent.setAdditionalListProperty("httpseeds", webseeds);
}
PluginInterface pi = CoreFactory.getSingleton().getPluginManager().getPluginInterfaceByClass(ExternalSeedPlugin.class);
if (pi != null) {
ExternalSeedPlugin ext_seed_plugin = (ExternalSeedPlugin) pi.getPlugin();
ext_seed_plugin.downloadChanged(PluginCoreUtils.wrap(dms[0]));
}
} catch (Throwable e) {
Debug.printStackTrace(e);
}
}
}, true);
}
protected List getURLList(TOTorrent torrent, String key) {
Object obj = torrent.getAdditionalProperty(key);
if (obj instanceof byte[]) {
List l = new ArrayList();
l.add(obj);
return (l);
} else if (obj instanceof List) {
return ((List) obj);
} else {
return (new ArrayList());
}
}
});
itemEditWebSeeds.setEnabled(dms.length == 1);
// manual update
final MenuItem itemManualUpdate = new MenuItem(menuTracker, SWT.PUSH);
Messages.setLanguageText(itemManualUpdate, // $NON-NLS-1$
"GeneralView.label.trackerurlupdate");
// itemManualUpdate.setImage(ImageRepository.getImage("edit_trackers"));
itemManualUpdate.addListener(SWT.Selection, new ListenerDMTask(dms) {
@Override
public void run(DownloadManager dm) {
dm.requestTrackerAnnounce(false);
}
});
itemManualUpdate.setEnabled(manualUpdate);
boolean scrape_enabled = COConfigurationManager.getBooleanParameter("Tracker Client Scrape Enable");
boolean scrape_stopped = COConfigurationManager.getBooleanParameter("Tracker Client Scrape Stopped Enable");
boolean manualScrape;
if (!scrape_enabled) {
manualScrape = false;
} else if (!scrape_stopped) {
manualScrape = false;
} else {
manualScrape = allStopped;
}
final MenuItem itemManualScrape = new MenuItem(menuTracker, SWT.PUSH);
Messages.setLanguageText(itemManualScrape, "GeneralView.label.trackerscrapeupdate");
itemManualScrape.addListener(SWT.Selection, new ListenerDMTask(dms, true, true) {
@Override
public void run(DownloadManager dm) {
dm.requestTrackerScrape(true);
}
});
itemManualScrape.setEnabled(manualScrape);
// enable hybrid v2 swarm, create hybrid/v2
List<DownloadManager> can_v2_from_hybrid = new ArrayList<>();
List<DownloadManager> can_create_from_v1 = new ArrayList<>();
for (DownloadManager dm : dms) {
TOTorrent torrent = dm.getTorrent();
if (torrent != null) {
int tt = torrent.getTorrentType();
if (tt == TOTorrent.TT_V1 && !torrent.getPrivate()) {
boolean all_complete = true;
for (DiskManagerFileInfo file : dm.getDiskManagerFileInfoSet().getFiles()) {
if (file.isSkipped() || file.getDownloaded() != file.getLength()) {
all_complete = false;
break;
}
if (file.getFile(false).length() != file.getTorrentFile().getLength()) {
all_complete = false;
break;
}
}
if (all_complete) {
can_create_from_v1.add(dm);
}
} else if (tt == TOTorrent.TT_V1_V2) {
try {
byte[] truncated_v2_hash = torrent.getTruncatedHash(TOTorrent.TT_V2);
if (dm.getGlobalManager().getDownloadManager(new HashWrapper(truncated_v2_hash)) == null) {
boolean compatible = true;
DiskManagerFileInfo[] files = dm.getDiskManagerFileInfoSet().getFiles();
for (DiskManagerFileInfo file : files) {
if (file.getTorrentFile().isPadFile()) {
} else if (file.getStorageType() != DiskManagerFileInfo.ST_LINEAR || file.getLink() != null) {
compatible = false;
break;
}
}
if (compatible) {
can_v2_from_hybrid.add(dm);
}
}
} catch (Throwable e) {
Debug.out(e);
}
}
}
}
final MenuItem itemHybridV2 = new MenuItem(menuTracker, SWT.PUSH);
Messages.setLanguageText(itemHybridV2, "GeneralView.label.run.hybrid.v2");
itemHybridV2.addListener(SWT.Selection, new ListenerDMTask(can_v2_from_hybrid.toArray(new DownloadManager[0]), true, true) {
@Override
public void run(DownloadManager old_manager) {
TOTorrent torrent = old_manager.getTorrent();
try {
TOTorrent other = torrent.selectHybridHashType(TOTorrent.TT_V2);
File temp_file = AETemporaryFileHandler.createTempFile();
TorrentUtils.writeToFile(other, temp_file, false);
File save_loc = old_manager.getSaveLocation();
String save_parent = save_loc.getParentFile().getAbsolutePath();
String save_file = save_loc.getName();
old_manager.getGlobalManager().addDownloadManager(temp_file.getAbsolutePath(), other.getHash(), save_parent, save_file, DownloadManager.STATE_WAITING, true, old_manager.getAssumedComplete(), new DownloadManagerInitialisationAdapter() {
@Override
public void initialised(DownloadManager new_manager, boolean for_seeding) {
DiskManagerFileInfoSet old_file_info_set = old_manager.getDiskManagerFileInfoSet();
DiskManagerFileInfoSet new_file_info_set = new_manager.getDiskManagerFileInfoSet();
DiskManagerFileInfo[] old_file_infos = old_file_info_set.getFiles();
DownloadManagerState new_dms = new_manager.getDownloadState();
new_dms.setDisplayName(old_manager.getDisplayName() + " (" + MessageText.getString("label.hybrid").toLowerCase() + ") (v2)");
try {
new_dms.suppressStateSave(true);
boolean[] to_skip = new boolean[old_file_infos.length];
for (int i = 0; i < old_file_infos.length; i++) {
if (old_file_infos[i].isSkipped()) {
to_skip[i] = true;
}
}
new_file_info_set.setSkipped(to_skip, true);
} finally {
new_dms.suppressStateSave(false);
}
}
@Override
public int getActions() {
return 0;
}
});
} catch (Throwable e) {
Debug.out(e);
}
}
});
itemHybridV2.setEnabled(!can_v2_from_hybrid.isEmpty());
final MenuItem itemV1Hybrid = new MenuItem(menuTracker, SWT.PUSH);
Messages.setLanguageText(itemV1Hybrid, "menu.create.hybrid.from.v1");
final MenuItem itemV1V2 = new MenuItem(menuTracker, SWT.PUSH);
Messages.setLanguageText(itemV1V2, "menu.create.v2.from.v1");
ListenerDMTask v1Listener = new ListenerDMTask(can_create_from_v1.toArray(new DownloadManager[0]), true, false) {
boolean create_hybrid;
@Override
public void handleEvent(Event event) {
create_hybrid = event.widget == itemV1Hybrid;
super.handleEvent(event);
}
@Override
public void run(DownloadManager old_manager) {
try {
File save_loc = old_manager.getSaveLocation();
TOTorrentCreator creator = TOTorrentFactory.createFromFileOrDirWithComputedPieceLength(create_hybrid ? TOTorrent.TT_V1_V2 : TOTorrent.TT_V2, save_loc, TorrentUtils.getDecentralisedEmptyURL(), false);
int[] progress = { 0 };
String[] task = { "" };
creator.addListener(new TOTorrentProgressListener() {
@Override
public void reportProgress(int percent_complete) {
synchronized (progress) {
progress[0] = percent_complete;
}
}
@Override
public void reportCurrentTask(String task_description) {
synchronized (task) {
task[0] = task_description;
}
}
});
Core core = CoreFactory.getSingleton();
core.executeOperation(CoreOperation.OP_PROGRESS, new CoreOperationTask() {
@Override
public String getName() {
return (MessageText.getString("wizard.maketorrent.progresstitle"));
}
@Override
public DownloadManager getDownload() {
return null;
}
@Override
public String[] getAffectedFileSystems() {
return (FileUtil.getFileStoreNames(save_loc));
}
@Override
public void run(CoreOperation operation) {
try {
TOTorrent torrent = creator.create();
File temp_file = AETemporaryFileHandler.createTempFile();
TorrentUtils.writeToFile(torrent, temp_file, false);
File save_loc = old_manager.getSaveLocation();
String save_parent = save_loc.getParentFile().getAbsolutePath();
String save_file = save_loc.getName();
old_manager.getGlobalManager().addDownloadManager(temp_file.getAbsolutePath(), torrent.getHash(), save_parent, save_file, DownloadManager.STATE_WAITING, true, true, new DownloadManagerInitialisationAdapter() {
@Override
public void initialised(DownloadManager new_manager, boolean for_seeding) {
DownloadManagerState new_dms = new_manager.getDownloadState();
String type_str = create_hybrid ? MessageText.getString("label.hybrid").toLowerCase() : "v2";
new_dms.setDisplayName(old_manager.getDisplayName() + " (" + type_str + ")");
}
@Override
public int getActions() {
return 0;
}
});
} catch (Throwable e) {
Debug.printStackTrace(e);
}
}
@Override
public ProgressCallback getProgressCallback() {
return (new ProgressCallbackAdapter() {
@Override
public int getSupportedTaskStates() {
return (ST_SUBTASKS | ST_CANCEL);
}
@Override
public void setTaskState(int state) {
if ((state & ST_CANCEL) != 0) {
creator.cancel();
}
}
@Override
public int getProgress() {
synchronized (progress) {
return (progress[0] * 10);
}
}
@Override
public String getSubTaskName() {
synchronized (task) {
return (task[0]);
}
}
});
}
});
} catch (Throwable e) {
Debug.out(e);
}
}
};
itemV1Hybrid.addListener(SWT.Selection, v1Listener);
itemV1V2.addListener(SWT.Selection, v1Listener);
itemV1Hybrid.setEnabled(!can_create_from_v1.isEmpty());
itemV1V2.setEnabled(!can_create_from_v1.isEmpty());
// download link
final MenuItem itemTorrentDL = new MenuItem(menuTracker, SWT.PUSH);
Messages.setLanguageText(itemTorrentDL, "MyTorrentsView.menu.torrent.dl");
itemTorrentDL.addListener(SWT.Selection, new ListenerDMTask(dms, false) {
@Override
public void run(DownloadManager dm) {
String content;
TOTorrent torrent = dm.getTorrent();
String link = null;
if (torrent == null) {
content = "Torrent not available";
} else {
link = TorrentUtils.getObtainedFrom(torrent);
if (link != null) {
try {
new URL(link);
} catch (Throwable e) {
link = null;
}
}
if (link != null) {
if (link.toLowerCase().startsWith("magnet:")) {
link = UrlUtils.getMagnetURI(dm);
content = "Torrent's magnet link:\r\n\r\n\t" + link;
} else {
content = "Torrent was obtained from\r\n\r\n\t" + link;
}
} else {
if (TorrentUtils.isReallyPrivate(torrent)) {
content = "Origin of torrent unknown and it is private so a magnet URI can't be used - sorry!";
} else {
link = UrlUtils.getMagnetURI(dm);
content = "Origin unavailable but magnet URI may work:\r\n\r\n\t" + link;
}
}
}
if (link != null) {
ClipboardCopy.copyToClipBoard(link);
content += "\r\n\r\nLink copied to clipboard";
}
final TextViewerWindow viewer = new TextViewerWindow(MessageText.getString("MyTorrentsView.menu.torrent.dl") + ": " + dm.getDisplayName(), null, content, false);
}
});
itemTorrentDL.setEnabled(dms.length == 1);
// move torrent
final MenuItem itemFileMoveTorrent = new MenuItem(menuTracker, SWT.PUSH);
Messages.setLanguageText(itemFileMoveTorrent, "MyTorrentsView.menu.movetorrent");
itemFileMoveTorrent.addListener(SWT.Selection, new ListenerDMTask(dms) {
@Override
public void run(DownloadManager[] dms) {
TorrentUtil.moveTorrentFile(shell, dms);
}
});
itemFileMoveTorrent.setEnabled(canMove);
// switch torrent
final MenuItem itemTorrentSwitch = new MenuItem(menuTracker, SWT.PUSH);
Messages.setLanguageText(itemTorrentSwitch, "MyTorrentsView.menu.torrent.switch");
itemTorrentSwitch.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event event) {
final TOTorrent torrent = dms[0].getTorrent();
if (torrent == null) {
return;
}
try {
byte[] existing_hash = torrent.getHash();
FileDialog dialog = new FileDialog(shell, SWT.OPEN | SWT.MULTI);
dialog.setText(MessageText.getString("dialog.select.torrent.file"));
dialog.setFilterExtensions(new String[] { "*.torrent" });
dialog.setFilterNames(new String[] { "*.torrent" });
String path = dialog.open();
if (path == null) {
return;
}
File file = new File(path);
byte[] replacement_hash = TOTorrentFactory.deserialiseFromBEncodedFile(file).getHash();
if (!Arrays.equals(existing_hash, replacement_hash)) {
throw (new Exception("Hash mismatch: old=" + ByteFormatter.encodeString(existing_hash) + ", new=" + ByteFormatter.encodeString(replacement_hash)));
}
dms[0].setTorrentFileName(file.getAbsolutePath());
} catch (Throwable e) {
MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
mb.setText(MessageText.getString("MyTorrentsView.menu.torrent.switch.fail"));
mb.setMessage(MessageText.getString("MyTorrentsView.menu.torrent.switch.fail.text", new String[] { Debug.getNestedExceptionMessage(e) }));
mb.open();
}
}
});
itemTorrentSwitch.setEnabled(dms.length == 1 && dms[0].isPersistent());
// set source
final MenuItem itemTorrentSource = new MenuItem(menuTracker, SWT.PUSH);
Messages.setLanguageText(itemTorrentSource, "MyTorrentsView.menu.torrent.set.source");
itemTorrentSource.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event event) {
final TOTorrent torrent = dms[0].getTorrent();
if (torrent == null) {
return;
}
String msg_key_prefix = "MyTorrentsView.menu.edit_source.";
SimpleTextEntryWindow text_entry = new SimpleTextEntryWindow();
text_entry.setParentShell(shell);
text_entry.setTitle(msg_key_prefix + "title");
text_entry.setMessage(msg_key_prefix + "message");
text_entry.setPreenteredText(TorrentUtils.getObtainedFrom(torrent), false);
text_entry.setWidthHint(500);
text_entry.prompt(new UIInputReceiverListener() {
@Override
public void UIInputReceiverClosed(UIInputReceiver text_entry) {
if (text_entry.hasSubmittedInput()) {
TorrentUtils.setObtainedFrom(torrent, text_entry.getSubmittedInput());
try {
TorrentUtils.writeToFile(torrent);
} catch (Throwable e) {
}
}
}
});
}
});
itemTorrentSource.setEnabled(dms.length == 1);
// set thumbnail
final MenuItem itemTorrentThumb = new MenuItem(menuTracker, SWT.PUSH);
Messages.setLanguageText(itemTorrentThumb, "MyTorrentsView.menu.torrent.set.thumb");
itemTorrentThumb.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event event) {
FileDialog fDialog = new FileDialog(shell, SWT.OPEN | SWT.MULTI);
fDialog.setText(MessageText.getString("MainWindow.dialog.choose.thumb"));
String path = fDialog.open();
if (path == null)
return;
File file = new File(path);
try {
byte[] thumbnail = FileUtil.readFileAsByteArray(file);
String name = file.getName();
int pos = name.lastIndexOf(".");
String ext;
if (pos != -1) {
ext = name.substring(pos + 1);
} else {
ext = "";
}
String type = HTTPUtils.guessContentTypeFromFileType(ext);
for (DownloadManager dm : dms) {
try {
TOTorrent torrent = dm.getTorrent();
PlatformTorrentUtils.setContentThumbnail(torrent, thumbnail, type);
} catch (Throwable e) {
}
}
} catch (Throwable e) {
Debug.out(e);
}
}
});
itemTorrentThumb.setEnabled(hasSelection);
// explore torrent file
final MenuItem itemTorrentExplore = new MenuItem(menuTracker, SWT.PUSH);
Messages.setLanguageText(itemTorrentExplore, "MyTorrentsView.menu." + (use_open_containing_folder ? "open_parent_folder" : "explore"));
itemTorrentExplore.addListener(SWT.Selection, new ListenerDMTask(dms, false) {
@Override
public void run(DownloadManager dm) {
ManagerUtils.open(new File(dm.getTorrentFileName()), use_open_containing_folder);
}
});
}
use of com.biglybt.pif.ui.UIInputReceiver in project BiglyBT by BiglySoftware.
the class UIFunctionsImpl method promptForSearch.
@Override
public void promptForSearch() {
SimpleTextEntryWindow entryWindow = new SimpleTextEntryWindow("Button.search", "search.dialog.text");
entryWindow.prompt(new UIInputReceiverListener() {
@Override
public void UIInputReceiverClosed(UIInputReceiver receiver) {
if (receiver.hasSubmittedInput()) {
doSearch(receiver.getSubmittedInput());
}
}
});
}
use of com.biglybt.pif.ui.UIInputReceiver in project BiglyBT by BiglySoftware.
the class PeersViewBase method fillMenu.
private static void fillMenu(final Menu menu, final PEPeer[] peers, final Shell shell, DownloadManager download_specific) {
boolean hasSelection = (peers.length > 0);
final IdentityHashSet<DownloadManager> download_managers = new IdentityHashSet<>();
Map<PEPeer, DownloadManager> peer_dm_map = new HashMap<>();
boolean downSpeedDisabled = false;
boolean downSpeedUnlimited = false;
long totalDownSpeed = 0;
long downSpeedSetMax = 0;
long maxDown = 0;
boolean upSpeedDisabled = false;
boolean upSpeedUnlimited = false;
long totalUpSpeed = 0;
long upSpeedSetMax = 0;
long maxUp = 0;
boolean onlyMyPeer = true;
boolean hasIPv4 = false;
boolean hasIPv6 = false;
if (hasSelection) {
GlobalManager gm = CoreFactory.getSingleton().getGlobalManager();
for (int i = 0; i < peers.length; i++) {
PEPeer peer = peers[i];
if (!peer.isMyPeer()) {
onlyMyPeer = false;
String ip = peer.getIp();
if (ip.indexOf(".") != -1) {
hasIPv4 = true;
} else {
hasIPv6 = true;
}
InetAddress alt = peer.getAlternativeIPv6();
if (alt != null) {
if (alt instanceof Inet4Address) {
hasIPv4 = true;
} else {
hasIPv6 = true;
}
}
}
PEPeerManager m = peer.getManager();
if (m != null) {
if (gm != null) {
DownloadManager dm = gm.getDownloadManager(new HashWrapper(m.getHash()));
if (dm != null) {
peer_dm_map.put(peer, dm);
download_managers.add(dm);
}
}
}
try {
int maxul = peer.getStats().getUploadRateLimitBytesPerSecond();
maxUp += maxul * 4;
if (maxul == 0) {
upSpeedUnlimited = true;
} else {
if (maxul > upSpeedSetMax) {
upSpeedSetMax = maxul;
}
}
if (maxul == -1) {
maxul = 0;
upSpeedDisabled = true;
}
totalUpSpeed += maxul;
int maxdl = peer.getStats().getDownloadRateLimitBytesPerSecond();
maxDown += maxdl * 4;
if (maxdl == 0) {
downSpeedUnlimited = true;
} else {
if (maxdl > downSpeedSetMax) {
downSpeedSetMax = maxdl;
}
}
if (maxdl == -1) {
maxdl = 0;
downSpeedDisabled = true;
}
totalDownSpeed += maxdl;
} catch (Exception ex) {
Debug.printStackTrace(ex);
}
}
}
if (download_specific != null) {
final MenuItem block_item = new MenuItem(menu, SWT.CHECK);
PEPeer peer = peers.length == 0 ? null : peers[0];
if (onlyMyPeer || peer == null || peer.getManager().getDiskManager().getRemainingExcludingDND() > 0) {
// disallow peer upload blocking when downloading
block_item.setSelection(false);
block_item.setEnabled(false);
} else {
block_item.setEnabled(true);
block_item.setSelection(peer.isSnubbed());
}
if (peer != null) {
final boolean newSnubbedValue = !peer.isSnubbed();
Messages.setLanguageText(block_item, "PeersView.menu.blockupload");
block_item.addListener(SWT.Selection, new PeersRunner(peers) {
@Override
public void run(PEPeer peer) {
peer.setSnubbed(newSnubbedValue);
}
});
}
} else {
if (download_managers.size() > 0) {
MenuItem itemDetails = new MenuItem(menu, SWT.PUSH);
Messages.setLanguageText(itemDetails, "PeersView.menu.showdownload");
Utils.setMenuItemImage(itemDetails, "details");
itemDetails.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event event) {
UIFunctions uiFunctions = UIFunctionsManager.getUIFunctions();
if (uiFunctions != null) {
for (DownloadManager dm : download_managers) {
uiFunctions.getMDI().showEntryByID(MultipleDocumentInterface.SIDEBAR_SECTION_TORRENT_DETAILS, dm);
}
}
}
});
new MenuItem(menu, SWT.SEPARATOR);
}
}
BuddyPlugin bp = BuddyPluginUtils.getPlugin();
if (bp != null) {
boolean has_pb = false;
boolean has_pb_potential = false;
for (PEPeer peer : peers) {
if (peer.isMyPeer()) {
continue;
}
DownloadManager dm = peer_dm_map.get(peer);
Peer p_peer = PluginCoreUtils.wrap(peer);
if (p_peer.getState() == Peer.TRANSFERING && !bp.isFullBuddy(p_peer)) {
has_pb_potential = true;
if (dm != null && bp.isPartialBuddy(PluginCoreUtils.wrap(dm), PluginCoreUtils.wrap(peer))) {
has_pb = true;
}
}
}
MenuItem boost_item = new MenuItem(menu, SWT.CHECK);
Messages.setLanguageText(boost_item, "PeersView.menu.boost");
boost_item.setSelection(has_pb);
boost_item.setEnabled(has_pb_potential);
boost_item.addListener(SWT.Selection, new PeersRunner(peers) {
@Override
public void run(PEPeer peer) {
Peer p_peer = PluginCoreUtils.wrap(peer);
if (!bp.isFullBuddy(p_peer)) {
boolean sel = boost_item.getSelection();
DownloadManager dm = peer_dm_map.get(peer);
if (dm != null) {
bp.setPartialBuddy(PluginCoreUtils.wrap(dm), p_peer, sel, true);
}
}
}
});
}
{
Map<String, Object> menu_properties = new HashMap<>();
menu_properties.put(ViewUtils.SM_PROP_PERMIT_UPLOAD_DISABLE, true);
menu_properties.put(ViewUtils.SM_PROP_PERMIT_DOWNLOAD_DISABLE, true);
ViewUtils.addSpeedMenu(shell, menu, true, true, false, hasSelection, downSpeedDisabled, downSpeedUnlimited, totalDownSpeed, downSpeedSetMax, maxDown, upSpeedDisabled, upSpeedUnlimited, totalUpSpeed, upSpeedSetMax, maxUp, peers.length, menu_properties, new ViewUtils.SpeedAdapter() {
@Override
public void setDownSpeed(int speed) {
if (peers.length > 0) {
for (int i = 0; i < peers.length; i++) {
try {
PEPeer peer = (PEPeer) peers[i];
peer.getStats().setDownloadRateLimitBytesPerSecond(speed);
} catch (Exception e) {
Debug.printStackTrace(e);
}
}
}
}
@Override
public void setUpSpeed(int speed) {
if (peers.length > 0) {
for (int i = 0; i < peers.length; i++) {
try {
PEPeer peer = (PEPeer) peers[i];
peer.getStats().setUploadRateLimitBytesPerSecond(speed);
} catch (Exception e) {
Debug.printStackTrace(e);
}
}
}
}
});
}
final MenuItem kick_item = new MenuItem(menu, SWT.PUSH);
Messages.setLanguageText(kick_item, "PeersView.menu.kick");
kick_item.addListener(SWT.Selection, new PeersRunner(peers) {
@Override
public void run(PEPeer peer) {
if (!peer.isMyPeer()) {
peer.getManager().removePeer(peer, "Peer kicked");
}
}
});
kick_item.setEnabled(!onlyMyPeer);
final MenuItem ban_item;
if (hasIPv4 && hasIPv6) {
final Menu ban_menu = new Menu(menu.getShell(), SWT.DROP_DOWN);
ban_item = new MenuItem(menu, SWT.CASCADE);
ban_item.setMenu(ban_menu);
Messages.setLanguageText(ban_item, "PeersView.menu.kickandban");
MenuItem ban_v4_item = new MenuItem(ban_menu, SWT.PUSH);
ban_v4_item.setText("IPv4");
MenuItem ban_v6_item = new MenuItem(ban_menu, SWT.PUSH);
ban_v6_item.setText("IPv6");
MenuItem ban_v4v6_item = new MenuItem(ban_menu, SWT.PUSH);
ban_v4v6_item.setText("IPv4 + IPv6");
Listener l = new PeersRunner(peers) {
@Override
public void run(Event e, PEPeer peer) {
if (!peer.isMyPeer()) {
String msg = MessageText.getString("PeersView.menu.kickandban.reason");
boolean v4 = e.widget == ban_v4_item || e.widget == ban_v4v6_item;
boolean v6 = e.widget == ban_v6_item || e.widget == ban_v4v6_item;
String ip = peer.getIp();
InetAddress ia = peer.getAlternativeIPv6();
boolean do_ip;
if (ip.indexOf('.') != -1) {
do_ip = v4;
} else {
do_ip = v6;
}
if (do_ip) {
IpFilterManagerFactory.getSingleton().getIPFilter().ban(ip, msg, true);
}
if (ia != null) {
boolean do_ia;
if (ia instanceof Inet4Address) {
do_ia = v4;
} else {
do_ia = v6;
}
if (do_ia) {
IpFilterManagerFactory.getSingleton().getIPFilter().ban(ia.getHostAddress(), msg, true);
}
}
peer.getManager().removePeer(peer, "Peer kicked and banned");
}
}
};
ban_v4_item.addListener(SWT.Selection, l);
ban_v6_item.addListener(SWT.Selection, l);
ban_v4v6_item.addListener(SWT.Selection, l);
} else {
ban_item = new MenuItem(menu, SWT.PUSH);
Messages.setLanguageText(ban_item, "PeersView.menu.kickandban");
ban_item.addListener(SWT.Selection, new PeersRunner(peers) {
@Override
public void run(PEPeer peer) {
if (!peer.isMyPeer()) {
String msg = MessageText.getString("PeersView.menu.kickandban.reason");
IpFilterManagerFactory.getSingleton().getIPFilter().ban(peer.getIp(), msg, true);
peer.getManager().removePeer(peer, "Peer kicked and banned");
}
}
});
}
ban_item.setEnabled(!onlyMyPeer);
final MenuItem ban_for_item = new MenuItem(menu, SWT.PUSH);
Messages.setLanguageText(ban_for_item, "PeersView.menu.kickandbanfor");
ban_for_item.addListener(SWT.Selection, new PeersRunner(peers) {
@Override
public boolean run(final PEPeer[] peers) {
String text = MessageText.getString("dialog.ban.for.period.text");
SimpleTextEntryWindow entryWindow = new SimpleTextEntryWindow("dialog.ban.for.period.title", "!" + text + "!");
int def = COConfigurationManager.getIntParameter("ban.for.period.default", 60);
entryWindow.setPreenteredText(String.valueOf(def), false);
entryWindow.prompt(new UIInputReceiverListener() {
@Override
public void UIInputReceiverClosed(UIInputReceiver entryWindow) {
if (!entryWindow.hasSubmittedInput()) {
return;
}
String sReturn = entryWindow.getSubmittedInput();
if (sReturn == null) {
return;
}
int mins = -1;
try {
mins = Integer.valueOf(sReturn).intValue();
} catch (NumberFormatException er) {
// Ignore
}
if (mins <= 0) {
MessageBox mb = new MessageBox(Utils.findAnyShell(), SWT.ICON_ERROR | SWT.OK);
mb.setText(MessageText.getString("MyTorrentsView.dialog.NumberError.title"));
mb.setMessage(MessageText.getString("MyTorrentsView.dialog.NumberError.text"));
mb.open();
return;
}
COConfigurationManager.setParameter("ban.for.period.default", mins);
IpFilter filter = IpFilterManagerFactory.getSingleton().getIPFilter();
for (PEPeer peer : peers) {
if (!peer.isMyPeer()) {
String msg = MessageText.getString("PeersView.menu.kickandbanfor.reason", new String[] { String.valueOf(mins) });
filter.ban(peer.getIp(), msg, true, mins);
peer.getManager().removePeer(peer, "Peer kicked and banned");
}
}
}
});
return (true);
}
});
ban_for_item.setEnabled(!onlyMyPeer);
addPeersMenu(download_specific, "", menu, peers);
}
use of com.biglybt.pif.ui.UIInputReceiver in project BiglyBT by BiglySoftware.
the class PeersViewBase method addPeersMenu.
protected static boolean addPeersMenu(DownloadManager man, String column_name, Menu menu, PEPeer[] peers) {
MenuBuildUtils.addSeparator(menu);
MenuItem copy_me_item = new MenuItem(menu, SWT.PUSH);
Messages.setLanguageText(copy_me_item, "menu.copy.my.peer");
copy_me_item.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event event) {
String str = getMyPeerDetails(man);
if (str.isEmpty()) {
str = "<no usable peers>";
}
ClipboardCopy.copyToClipBoard(str);
}
});
if (man != null && !TorrentUtils.isReallyPrivate(man.getTorrent())) {
PEPeerManager pm = man.getPeerManager();
if (pm != null) {
MenuItem copy_all_peers = new MenuItem(menu, SWT.PUSH);
Messages.setLanguageText(copy_all_peers, "menu.copy.all.peers");
copy_all_peers.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event event) {
List<PEPeer> peers = pm.getPeers();
String str = getMyPeerDetails(man);
for (PEPeer peer : peers) {
int port = peer.getTCPListenPort();
if (port > 0) {
String address = peer.getIp() + ":" + port;
str += (str.isEmpty() ? "" : ",") + address;
}
}
if (str.isEmpty()) {
str = "<no usable peers>";
}
ClipboardCopy.copyToClipBoard(str);
}
});
MenuItem add_peers_item = new MenuItem(menu, SWT.PUSH);
Messages.setLanguageText(add_peers_item, "menu.add.peers");
add_peers_item.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event event) {
SimpleTextEntryWindow entryWindow = new SimpleTextEntryWindow("dialog.add.peers.title", "dialog.add.peers.msg");
String def = COConfigurationManager.getStringParameter("add.peers.default", "");
entryWindow.setPreenteredText(String.valueOf(def), false);
entryWindow.addVerifyListener(new VerifyListener() {
@Override
public void verifyText(VerifyEvent e) {
String str = e.text.replaceAll("[\\r\\n]+", ",");
if (!str.equals(e.text)) {
while (str.contains(",,")) {
str = str.replace(",,", ",");
}
str = str.trim();
while (str.endsWith(",")) {
str = str.substring(0, str.length() - 1).trim();
}
while (str.startsWith(",")) {
str = str.substring(1).trim();
}
}
e.text = str;
}
});
entryWindow.prompt(new UIInputReceiverListener() {
@Override
public void UIInputReceiverClosed(UIInputReceiver entryWindow) {
if (!entryWindow.hasSubmittedInput()) {
return;
}
String sReturn = entryWindow.getSubmittedInput();
if (sReturn == null) {
return;
}
COConfigurationManager.setParameter("add.peers.default", sReturn);
PEPeerManager pm = man.getPeerManager();
if (pm == null) {
return;
}
Utils.getOffOfSWTThread(new AERunnable() {
@Override
public void runSupport() {
String[] bits = sReturn.replace(';', ',').split(",");
for (String bit : bits) {
bit = bit.trim();
if (bit.isEmpty()) {
continue;
}
int pos = bit.lastIndexOf(':');
if (pos != -1) {
String host = bit.substring(0, pos).trim();
String port = bit.substring(pos + 1).trim();
try {
int i_port = Integer.parseInt(port);
pm.addPeer(host, i_port, 0, NetworkManager.getCryptoRequired(NetworkManager.CRYPTO_OVERRIDE_NONE), null);
} catch (Throwable e) {
}
} else {
pm.addPeer(bit, 6881, 0, NetworkManager.getCryptoRequired(NetworkManager.CRYPTO_OVERRIDE_NONE), null);
}
}
}
});
}
});
}
});
}
}
addPeerSetMenu(menu, peers);
return (true);
}
use of com.biglybt.pif.ui.UIInputReceiver in project BiglyBT by BiglySoftware.
the class MyTorrentsView method addThisColumnSubMenu.
@Override
public void addThisColumnSubMenu(String sColumnName, Menu menuThisColumn) {
switch(sColumnName) {
case "trackername":
{
MenuItem item = new MenuItem(menuThisColumn, SWT.PUSH);
Messages.setLanguageText(item, "MyTorrentsView.menu.trackername.editprefs");
item.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event e) {
SimpleTextEntryWindow entryWindow = new SimpleTextEntryWindow("trackername.prefs.title", "trackername.prefs.message");
entryWindow.setPreenteredText(COConfigurationManager.getStringParameter("mtv.trackername.pref.hosts", ""), true);
entryWindow.selectPreenteredText(false);
entryWindow.prompt(new UIInputReceiverListener() {
@Override
public void UIInputReceiverClosed(UIInputReceiver receiver) {
if (!receiver.hasSubmittedInput()) {
return;
}
COConfigurationManager.setParameter("mtv.trackername.pref.hosts", receiver.getSubmittedInput().trim());
}
});
}
});
break;
}
case "eta":
case "smootheta":
{
boolean eta_absolute = COConfigurationManager.getBooleanParameter("mtv.eta.show_absolute", false);
final MenuItem item = new MenuItem(menuThisColumn, SWT.CHECK);
Messages.setLanguageText(item, "MyTorrentsView.menu.eta.abs");
item.setSelection(eta_absolute);
item.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event e) {
boolean eta_absolute = item.getSelection();
tv.columnInvalidate("eta");
tv.refreshTable(false);
COConfigurationManager.setParameter("mtv.eta.show_absolute", eta_absolute);
}
});
break;
}
case "ProgressETA":
{
boolean progress_eta_absolute = COConfigurationManager.getBooleanParameter("mtv.progress_eta.show_absolute", false);
final MenuItem item = new MenuItem(menuThisColumn, SWT.CHECK);
Messages.setLanguageText(item, "MyTorrentsView.menu.eta.abs");
item.setSelection(progress_eta_absolute);
item.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event e) {
boolean progress_eta_absolute = item.getSelection();
tv.columnInvalidate("ProgressETA");
tv.refreshTable(false);
COConfigurationManager.setParameter("mtv.progress_eta.show_absolute", progress_eta_absolute);
}
});
break;
}
case "status":
{
final Menu menuSort = new Menu(menuThisColumn.getShell(), SWT.DROP_DOWN);
final MenuItem itemSort = new MenuItem(menuThisColumn, SWT.CASCADE);
Messages.setLanguageText(itemSort, "menu.sort.order");
itemSort.setMenu(menuSort);
String tid = tv.getTableID();
int order = COConfigurationManager.getIntParameter("MyTorrents.status.sortorder." + tid);
MenuItem itemAlpha = new MenuItem(menuSort, SWT.RADIO);
Messages.setLanguageText(itemAlpha, "menu.sort.alphabetic");
MenuItem itemPriority = new MenuItem(menuSort, SWT.RADIO);
Messages.setLanguageText(itemPriority, "MyTorrentsView.menu.status.prioritysort");
MenuItem itemStatus = new MenuItem(menuSort, SWT.RADIO);
Messages.setLanguageText(itemStatus, "menu.sort.status");
if (order == 0) {
itemAlpha.setSelection(true);
} else if (order == 1) {
itemPriority.setSelection(true);
} else {
itemStatus.setSelection(true);
}
Listener listener = new Listener() {
@Override
public void handleEvent(Event e) {
int new_order;
if (itemAlpha.getSelection()) {
new_order = 0;
} else if (itemPriority.getSelection()) {
new_order = 1;
} else {
new_order = 2;
}
COConfigurationManager.setParameter("MyTorrents.status.sortorder." + tid, new_order);
tv.columnInvalidate("status");
tv.refreshTable(false);
}
};
itemAlpha.addListener(SWT.Selection, listener);
itemPriority.addListener(SWT.Selection, listener);
itemStatus.addListener(SWT.Selection, listener);
boolean change_status_fg = COConfigurationManager.getBooleanParameter("MyTorrents.status.change.fg");
final MenuItem item = new MenuItem(menuThisColumn, SWT.CHECK);
Messages.setLanguageText(item, "MyTorrents.status.change.fg");
item.setSelection(change_status_fg);
item.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event e) {
boolean change_status_fg = item.getSelection();
COConfigurationManager.setParameter("MyTorrents.status.change.fg", change_status_fg);
tv.columnInvalidate("status");
tv.refreshTable(false);
}
});
break;
}
}
}
Aggregations