use of com.biglybt.pifimpl.local.utils.FormattersImpl in project BiglyBT by BiglySoftware.
the class ManagerUtils method browse.
public static String browse(final DownloadManager dm, DiskManagerFileInfo _file, final boolean anon, final boolean launch) {
Properties props = new Properties();
File save_location = dm.getSaveLocation();
final String root_dir;
if (save_location.isFile()) {
root_dir = save_location.getParentFile().getAbsolutePath();
} else {
root_dir = save_location.getAbsolutePath();
}
final String url_suffix;
boolean always_browse = COConfigurationManager.getBooleanParameter("Library.LaunchWebsiteInBrowserDirList");
if (!always_browse) {
if (_file == null) {
_file = getBrowseHomePage(dm);
}
}
final DiskManagerFileInfo file = _file;
if (file == null) {
// asked to launch a download (note that the double-click on a download that has an index.html file will by default result in
// us getting here with the file set, not null)
url_suffix = "";
} else {
String relative_path = file.getTorrentFile().getRelativePath();
String[] bits = relative_path.replace(File.separatorChar, '/').split("/");
String _url_suffix = "";
int bits_to_use = always_browse ? bits.length - 1 : bits.length;
for (int i = 0; i < bits_to_use; i++) {
String bit = bits[i];
if (bit.length() == 0) {
continue;
}
_url_suffix += (_url_suffix == "" ? "" : "/") + UrlUtils.encode(bit);
}
url_suffix = _url_suffix;
}
synchronized (browse_plugins) {
WebPlugin plugin = browse_plugins.get(dm);
if (plugin == null) {
props.put(WebPlugin.PR_PORT, 0);
props.put(WebPlugin.PR_BIND_IP, "127.0.0.1");
props.put(WebPlugin.PR_HOME_PAGE, "");
props.put(WebPlugin.PR_ROOT_DIR, root_dir);
props.put(WebPlugin.PR_ACCESS, "local");
props.put(WebPlugin.PR_HIDE_RESOURCE_CONFIG, true);
props.put(WebPlugin.PR_ENABLE_KEEP_ALIVE, true);
props.put(WebPlugin.PR_ENABLE_PAIRING, false);
props.put(WebPlugin.PR_ENABLE_UPNP, false);
props.put(WebPlugin.PR_ENABLE_I2P, false);
props.put(WebPlugin.PR_ENABLE_TOR, false);
final String plugin_id = "webserver:" + dm.getInternalName();
final String plugin_name = "Web Server for " + dm.getDisplayName();
Properties messages = new Properties();
messages.put("plugins." + plugin_id, plugin_name);
PluginInitializer.getDefaultInterface().getUtilities().getLocaleUtilities().integrateLocalisedMessageBundle(messages);
final AESemaphore waiter = new AESemaphore("waiter");
final String[] url_holder = { null };
plugin = new UnloadableWebPlugin(props) {
private Map<String, Object> file_map = new HashMap<>();
private String protocol;
private String host;
private int port;
@Override
public void initialize(PluginInterface plugin_interface) throws PluginException {
DiskManagerFileInfoSet file_set = dm.getDiskManagerFileInfoSet();
DiskManagerFileInfo[] files = file_set.getFiles();
Set<Object> root_dir = new HashSet<>();
file_map.put("", root_dir);
for (DiskManagerFileInfo dm_file : files) {
TOTorrentFile file = dm_file.getTorrentFile();
String path = file.getRelativePath();
file_map.put(path, dm_file);
if (path.startsWith(File.separator)) {
path = path.substring(1);
}
Set<Object> dir = root_dir;
int pos = 0;
while (true) {
int next_pos = path.indexOf(File.separatorChar, pos);
if (next_pos == -1) {
dir.add(dm_file);
break;
} else {
String bit = path.substring(pos, next_pos);
dir.add(bit);
String sub_path = path.substring(0, next_pos);
dir = (Set<Object>) file_map.get(sub_path);
if (dir == null) {
dir = new HashSet<>();
file_map.put(sub_path, dir);
}
pos = next_pos + 1;
}
}
}
Properties props = plugin_interface.getPluginProperties();
props.put("plugin.name", plugin_name);
super.initialize(plugin_interface);
InetAddress bind_ip = getServerBindIP();
if (bind_ip.isAnyLocalAddress()) {
host = "127.0.0.1";
} else {
host = bind_ip.getHostAddress();
}
port = getServerPort();
log("Assigned port: " + port);
protocol = getProtocol();
String url = protocol + "://" + host + ":" + port + "/" + url_suffix;
if (launch) {
Utils.launch(url, false, true, anon);
} else {
synchronized (url_holder) {
url_holder[0] = url;
}
waiter.release();
}
}
@Override
public boolean generate(TrackerWebPageRequest request, TrackerWebPageResponse response) throws IOException {
try {
boolean res = super.generate(request, response);
if (!res) {
response.setReplyStatus(404);
}
} catch (Throwable e) {
response.setReplyStatus(404);
}
return (true);
}
@Override
protected boolean useFile(TrackerWebPageRequest request, final TrackerWebPageResponse response, String root, String relative_url) throws IOException {
URL absolute_url = request.getAbsoluteURL();
String query = absolute_url.getQuery();
if (query != null) {
String[] args = query.split("&");
String vuze_source = null;
int vuze_file_index = -1;
String vuze_file_name = null;
List<String> networks = new ArrayList<>();
for (String arg : args) {
String[] bits = arg.split("=");
String lhs = bits[0];
String rhs = UrlUtils.decode(bits[1]);
if (lhs.equals("vuze_source")) {
if (rhs.endsWith(".torrent") || rhs.startsWith("magnet")) {
vuze_source = rhs;
}
} else if (lhs.equals("vuze_file_index")) {
vuze_file_index = Integer.parseInt(rhs);
} else if (lhs.equals("vuze_file_name")) {
vuze_file_name = rhs;
} else if (lhs.equals("vuze_network")) {
String net = AENetworkClassifier.internalise(rhs);
if (net != null) {
networks.add(net);
}
}
}
if (vuze_source != null) {
String referrer = (String) request.getHeaders().get("referer");
if (referrer == null || !referrer.contains("://" + host + ":" + port)) {
response.setReplyStatus(403);
return (true);
}
if (vuze_source.endsWith(".torrent")) {
Object file_node = file_map.get(vuze_source);
if (file_node instanceof DiskManagerFileInfo) {
DiskManagerFileInfo dm_file = (DiskManagerFileInfo) file_node;
long file_size = dm_file.getLength();
File target_file = dm_file.getFile(true);
boolean done = dm_file.getDownloaded() == file_size && target_file.length() == file_size;
if (done) {
return (handleRedirect(dm, target_file, vuze_file_index, vuze_file_name, networks, request, response));
} else {
try {
File torrent_file = AETemporaryFileHandler.createTempFile();
final FileOutputStream fos = new FileOutputStream(torrent_file);
try {
DiskManagerChannel chan = PluginCoreUtils.wrap(dm_file).createChannel();
try {
final DiskManagerRequest req = chan.createRequest();
req.setOffset(0);
req.setLength(file_size);
req.addListener(new DiskManagerListener() {
@Override
public void eventOccurred(DiskManagerEvent event) {
int type = event.getType();
if (type == DiskManagerEvent.EVENT_TYPE_BLOCKED) {
return;
} else if (type == DiskManagerEvent.EVENT_TYPE_FAILED) {
throw (new RuntimeException(event.getFailure()));
}
PooledByteBuffer buffer = event.getBuffer();
if (buffer == null) {
throw (new RuntimeException("eh?"));
}
try {
byte[] data = buffer.toByteArray();
fos.write(data);
} catch (IOException e) {
throw (new RuntimeException("Failed to write to " + file, e));
} finally {
buffer.returnToPool();
}
}
});
req.run();
} finally {
chan.destroy();
}
} finally {
fos.close();
}
return (handleRedirect(dm, torrent_file, vuze_file_index, vuze_file_name, networks, request, response));
} catch (Throwable e) {
Debug.out(e);
return (false);
}
}
} else {
return (false);
}
} else {
URL magnet = new URL(vuze_source);
File torrent_file = AETemporaryFileHandler.createTempFile();
try {
URLConnection connection = magnet.openConnection();
connection.connect();
FileUtil.copyFile(connection.getInputStream(), torrent_file.getAbsoluteFile());
return (handleRedirect(dm, torrent_file, vuze_file_index, vuze_file_name, networks, request, response));
} catch (Throwable e) {
Debug.out(e);
}
}
}
}
String path = absolute_url.getPath();
if (path.equals("/")) {
if (COConfigurationManager.getBooleanParameter("Library.LaunchWebsiteInBrowserDirList")) {
relative_url = "/";
}
}
String download_name = XUXmlWriter.escapeXML(dm.getDisplayName());
String relative_file = relative_url.replace('/', File.separatorChar);
String node_key = relative_file.substring(1);
Object file_node = file_map.get(node_key);
boolean file_node_is_parent = false;
if (file_node == null) {
int pos = node_key.lastIndexOf(File.separator);
if (pos == -1) {
node_key = "";
} else {
node_key = node_key.substring(0, pos);
}
file_node = file_map.get(node_key);
file_node_is_parent = true;
}
if (file_node == null) {
return (false);
}
if (file_node instanceof Set) {
if (relative_url.equals("/favicon.ico")) {
try {
InputStream stream = getClass().getClassLoader().getResourceAsStream("com/biglybt/ui/icons/favicon.ico");
response.useStream("image/x-icon", stream);
return (true);
} catch (Throwable e) {
}
}
Set<Object> kids = (Set<Object>) file_node;
String request_url = request.getURL();
if (file_node_is_parent) {
int pos = request_url.lastIndexOf("/");
if (pos == -1) {
request_url = "";
} else {
request_url = request_url.substring(0, pos);
}
}
response.setContentType("text/html");
OutputStream os = response.getOutputStream();
String title = XUXmlWriter.escapeXML(UrlUtils.decode(request_url));
if (title.length() == 0) {
title = "/";
}
os.write(("<html>" + NL + " <head>" + NL + " <meta charset=\"UTF-8\">" + NL + " <title>" + download_name + ": Index of " + title + "</title>" + NL + " </head>" + NL + " <body>" + NL + " <p>" + download_name + "</p>" + NL + " <h1>Index of " + title + "</h1>" + NL + " <pre><hr>" + NL).getBytes("UTF-8"));
String root_url = request_url;
if (!root_url.endsWith("/")) {
root_url += "/";
}
if (request_url.length() > 1) {
int pos = request_url.lastIndexOf('/');
if (pos == 0) {
pos++;
}
String parent = request_url.substring(0, pos);
os.write(("<a href=\"" + parent + "\">..</a>" + NL).getBytes("UTF-8"));
}
List<String[]> filenames = new ArrayList<>(kids.size());
int max_filename = 0;
int MAX_LEN = 120;
for (Object entry : kids) {
DiskManagerFileInfo file;
String file_name;
if (entry instanceof String) {
file = null;
file_name = (String) entry;
} else {
file = (DiskManagerFileInfo) entry;
if (file.isSkipped()) {
continue;
}
file_name = file.getTorrentFile().getRelativePath();
int pos = file_name.lastIndexOf(File.separatorChar);
if (pos != -1) {
file_name = file_name.substring(pos + 1);
}
}
String url = root_url + UrlUtils.encode(file_name);
if (file == null) {
file_name += "/";
}
int len = file_name.length();
if (len > MAX_LEN) {
file_name = file_name.substring(0, MAX_LEN - 3) + "...";
len = file_name.length();
}
if (len > max_filename) {
max_filename = len;
}
filenames.add(new String[] { url, file_name, file == null ? "" : DisplayFormatters.formatByteCountToKiBEtc(file.getLength()) });
}
max_filename = ((max_filename + 15) / 8) * 8;
char[] padding = new char[max_filename];
Arrays.fill(padding, ' ');
Collections.sort(filenames, new Comparator<String[]>() {
Comparator comp = new FormattersImpl().getAlphanumericComparator(true);
@Override
public int compare(String[] o1, String[] o2) {
return (comp.compare(o1[0], o2[0]));
}
});
for (String[] entry : filenames) {
String file_name = entry[1];
int len = file_name.length();
StringBuilder line = new StringBuilder(max_filename + 64);
line.append("<a href=\"").append(entry[0]).append("\">").append(XUXmlWriter.escapeXML(file_name)).append("</a>");
line.append(padding, 0, max_filename - len);
line.append(entry[2]);
line.append(NL);
os.write(line.toString().getBytes("UTF-8"));
}
os.write((" <hr></pre>" + NL + " <address>" + Constants.APP_NAME + " Web Server at " + host + " Port " + getServerPort() + "</address>" + NL + " </body>" + NL + "</html>").getBytes("UTF-8"));
return (true);
} else {
DiskManagerFileInfo dm_file = (DiskManagerFileInfo) file_node;
long file_size = dm_file.getLength();
File target_file = dm_file.getFile(true);
boolean done = dm_file.getDownloaded() == file_size && target_file.length() == file_size;
String file_type;
// Use the original torrent file name when deducing file type to
// avoid incomplete suffix issues etc
String relative_path = dm_file.getTorrentFile().getRelativePath();
int pos = relative_path.lastIndexOf(".");
if (pos == -1) {
file_type = "";
} else {
file_type = relative_path.substring(pos + 1);
}
if (file_size >= 512 * 1024) {
String content_type = HTTPUtils.guessContentTypeFromFileType(file_type);
if (content_type.startsWith("text/") || content_type.startsWith("image/")) {
// don't want to be redirecting here as (for example) .html needs
// to remain in the 'correct' place so that relative assets work
} else {
URL stream_url = getMediaServerContentURL(dm_file);
if (stream_url != null) {
OutputStream os = response.getRawOutputStream();
os.write(("HTTP/1.1 302 Found" + NL + "Location: " + stream_url.toExternalForm() + NL + NL).getBytes("UTF-8"));
return (true);
}
}
}
if (done) {
if (file_size < 512 * 1024) {
FileInputStream fis = null;
try {
fis = new FileInputStream(target_file);
response.useStream(file_type, fis);
return (true);
} finally {
if (fis != null) {
fis.close();
}
}
} else {
OutputStream os = null;
InputStream is = null;
try {
os = response.getRawOutputStream();
os.write(("HTTP/1.1 200 OK" + NL + "Content-Type:" + HTTPUtils.guessContentTypeFromFileType(file_type) + NL + "Content-Length: " + file_size + NL + "Connection: close" + NL + NL).getBytes("UTF-8"));
byte[] buffer = new byte[128 * 1024];
is = new FileInputStream(target_file);
while (true) {
int len = is.read(buffer);
if (len <= 0) {
break;
}
os.write(buffer, 0, len);
}
} catch (Throwable e) {
// e.printStackTrace();
} finally {
try {
os.close();
} catch (Throwable e) {
}
try {
is.close();
} catch (Throwable e) {
}
}
return (true);
}
} else {
dm_file.setPriority(10);
try {
final OutputStream os = response.getRawOutputStream();
os.write(("HTTP/1.1 200 OK" + NL + "Content-Type:" + HTTPUtils.guessContentTypeFromFileType(file_type) + NL + "Content-Length: " + file_size + NL + "Connection: close" + NL + "X-Vuze-Hack: X").getBytes("UTF-8"));
DiskManagerChannel chan = PluginCoreUtils.wrap(dm_file).createChannel();
try {
final DiskManagerRequest req = chan.createRequest();
final boolean[] header_complete = { false };
final long[] last_write = { 0 };
req.setOffset(0);
req.setLength(file_size);
req.addListener(new DiskManagerListener() {
@Override
public void eventOccurred(DiskManagerEvent event) {
int type = event.getType();
if (type == DiskManagerEvent.EVENT_TYPE_BLOCKED) {
return;
} else if (type == DiskManagerEvent.EVENT_TYPE_FAILED) {
throw (new RuntimeException(event.getFailure()));
}
PooledByteBuffer buffer = event.getBuffer();
if (buffer == null) {
throw (new RuntimeException("eh?"));
}
try {
boolean do_header = false;
synchronized (header_complete) {
if (!header_complete[0]) {
do_header = true;
header_complete[0] = true;
}
last_write[0] = SystemTime.getMonotonousTime();
}
if (do_header) {
os.write((NL + NL).getBytes("UTF-8"));
}
byte[] data = buffer.toByteArray();
os.write(data);
} catch (IOException e) {
throw (new RuntimeException("Failed to write to " + file, e));
} finally {
buffer.returnToPool();
}
}
});
final TimerEventPeriodic[] timer_event = { null };
timer_event[0] = SimpleTimer.addPeriodicEvent("KeepAlive", 10 * 1000, new TimerEventPerformer() {
boolean cancel_outstanding = false;
@Override
public void perform(TimerEvent event) {
if (cancel_outstanding) {
req.cancel();
} else {
synchronized (header_complete) {
if (header_complete[0]) {
if (SystemTime.getMonotonousTime() - last_write[0] >= 5 * 60 * 1000) {
req.cancel();
}
} else {
try {
os.write("X".getBytes("UTF-8"));
os.flush();
} catch (Throwable e) {
req.cancel();
}
}
}
if (!response.isActive()) {
cancel_outstanding = true;
}
}
}
});
try {
req.run();
} finally {
timer_event[0].cancel();
}
return (true);
} finally {
chan.destroy();
}
} catch (Throwable e) {
return (false);
}
}
}
}
private boolean handleRedirect(DownloadManager dm, File torrent_file, int file_index, String file_name, List<String> networks, TrackerWebPageRequest request, TrackerWebPageResponse response) {
try {
TOTorrent torrent = TOTorrentFactory.deserialiseFromBEncodedFile(torrent_file);
GlobalManager gm = CoreFactory.getSingleton().getGlobalManager();
UIFunctions uif = UIFunctionsManager.getUIFunctions();
TorrentOpenOptions torrent_options = new TorrentOpenOptions(torrent_file.getAbsolutePath(), torrent, false);
torrent_options.setTorrent(torrent);
String[] existing_nets;
if (networks.size() == 0) {
// inherit networks from parent
existing_nets = dm.getDownloadState().getNetworks();
} else {
existing_nets = networks.toArray(new String[networks.size()]);
}
for (String net : AENetworkClassifier.AT_NETWORKS) {
boolean found = false;
for (String x : existing_nets) {
if (net == x) {
found = true;
break;
}
}
torrent_options.setNetworkEnabled(net, found);
}
Map<String, Object> add_options = new HashMap<>();
add_options.put(UIFunctions.OTO_SILENT, true);
if (uif.addTorrentWithOptions(torrent_options, add_options)) {
long start = SystemTime.getMonotonousTime();
while (true) {
DownloadManager o_dm = gm.getDownloadManager(torrent);
if (o_dm != null) {
if (!o_dm.getDownloadState().getFlag(DownloadManagerState.FLAG_METADATA_DOWNLOAD)) {
DiskManagerFileInfo[] files = o_dm.getDiskManagerFileInfoSet().getFiles();
DiskManagerFileInfo o_dm_file = null;
if (file_name != null) {
for (DiskManagerFileInfo file : files) {
String path = file.getTorrentFile().getRelativePath();
if (path.equals(file_name)) {
o_dm_file = file;
break;
}
}
if (o_dm_file == null) {
o_dm_file = files[0];
}
} else {
if (file_index < 0) {
long largest = -1;
for (DiskManagerFileInfo file : files) {
if (file.getLength() > largest) {
o_dm_file = file;
largest = file.getLength();
}
}
} else {
o_dm_file = files[file_index];
}
}
String original_path = request.getAbsoluteURL().getPath();
if (original_path.endsWith(".html")) {
String url = browse(o_dm, file_index < 0 ? null : o_dm_file, anon, false);
OutputStream os = response.getRawOutputStream();
os.write(("HTTP/1.1 302 Found" + NL + "Location: " + url + NL + NL).getBytes("UTF-8"));
return (true);
} else {
URL stream_url = getMediaServerContentURL(o_dm_file);
if (stream_url != null) {
OutputStream os = response.getRawOutputStream();
os.write(("HTTP/1.1 302 Found" + NL + "Location: " + stream_url.toExternalForm() + NL + NL).getBytes("UTF-8"));
return (true);
}
}
}
}
long now = SystemTime.getMonotonousTime();
if (now - start > 3 * 60 * 1000) {
Debug.out("Timeout waiting for download to be added");
return (false);
}
Thread.sleep(1000);
}
} else {
Debug.out("Failed to add download for some reason");
return (false);
}
} catch (Throwable e) {
Debug.out(e);
return (false);
}
}
@Override
public void unload() throws PluginException {
synchronized (browse_plugins) {
browse_plugins.remove(dm);
}
super.unload();
}
};
PluginManager.registerPlugin(plugin, plugin_id, plugin_id);
browse_plugins.put(dm, plugin);
if (launch) {
return (null);
} else {
waiter.reserve(10 * 1000);
synchronized (url_holder) {
return (url_holder[0]);
}
}
} else {
String protocol = plugin.getProtocol();
InetAddress bind_ip = plugin.getServerBindIP();
String host;
if (bind_ip.isAnyLocalAddress()) {
host = "127.0.0.1";
} else {
host = bind_ip.getHostAddress();
}
String url = protocol + "://" + host + ":" + plugin.getServerPort() + "/" + url_suffix;
if (launch) {
Utils.launch(url, false, true, anon);
return (null);
} else {
return (url);
}
}
}
}
use of com.biglybt.pifimpl.local.utils.FormattersImpl in project BiglyBT by BiglySoftware.
the class SubscriptionManagerUI method createSubscriptionMdiEntry.
private MdiEntry createSubscriptionMdiEntry(final Subscription subs) {
if (!subs.isSubscribed()) {
return null;
}
MultipleDocumentInterfaceSWT mdi = UIFunctionsManagerSWT.getUIFunctionsSWT().getMDISWT();
if (mdi == null) {
return (null);
}
String parent_name = subs.getParent();
if (parent_name != null && parent_name.length() == 0) {
parent_name = null;
}
final String key = getKey(subs);
String subs_name = subs.getName();
TreeMap<String, String> name_map = new TreeMap<String, String>(new FormattersImpl().getAlphanumericComparator(true));
name_map.put(subs_name, key);
MdiEntry[] existing = mdi.getEntries();
for (MdiEntry e : existing) {
String id = e.getId();
if (id.startsWith("Subscription_")) {
Object ds = e.getDatasource();
if (ds instanceof Subscription) {
String sp = ((Subscription) ds).getParent();
if (sp != null && sp.length() == 0) {
sp = null;
}
if (sp == parent_name || (sp != null && parent_name != null && sp.equals(parent_name))) {
name_map.put(e.getTitle(), id);
}
}
}
}
String prev_id = null;
for (String this_id : name_map.values()) {
if (this_id == key) {
break;
}
prev_id = this_id;
}
if (prev_id == null && name_map.size() > 1) {
Iterator<String> it = name_map.values().iterator();
it.next();
prev_id = "~" + it.next();
}
MdiEntry entry;
if (parent_name == null || parent_name.length() == 0) {
entry = mdi.createEntryFromEventListener(MultipleDocumentInterface.SIDEBAR_SECTION_SUBSCRIPTIONS, new UISWTViewEventListenerHolder(key, SubscriptionView.class, subs, null), key, true, subs, prev_id);
} else {
MdiEntry parent_entry;
synchronized (parent_views) {
parent_entry = parent_views.get(parent_name);
if (parent_entry == null) {
SubsParentView parent = new SubsParentView(parent_name);
String parent_key = getParentKey(parent_name);
String parent_prev_id = null;
parent_views.put(parent_name, parent_entry);
String parent_prev = null;
for (String pn : parent_views.keySet()) {
if (pn == parent_name) {
break;
}
parent_prev = pn;
}
boolean is_before;
if (parent_prev == null && parent_views.size() > 1) {
Iterator<String> it = parent_views.keySet().iterator();
it.next();
parent_prev = it.next();
is_before = true;
} else {
is_before = false;
}
if (parent_prev != null) {
parent_prev_id = getParentKey(parent_prev);
if (is_before) {
parent_prev_id = "~" + parent_prev_id;
}
}
parent_entry = mdi.createEntryFromSkinRef(MultipleDocumentInterface.SIDEBAR_SECTION_SUBSCRIPTIONS, parent_key, null, parent_name, parent, null, false, parent_prev_id);
}
}
entry = mdi.createEntryFromEventListener(parent_entry.getId(), new UISWTViewEventListenerHolder(key, SubscriptionView.class, subs, null), key, true, subs, prev_id);
}
// This sets up the entry (menu, etc)
SubscriptionMDIEntry entryInfo = new SubscriptionMDIEntry(subs, entry);
subs.setUserData(SUB_ENTRYINFO_KEY, entryInfo);
entry.addListener(new MdiCloseListener() {
@Override
public void mdiEntryClosed(MdiEntry entry, boolean userClosed) {
subs.setUserData(SUB_ENTRYINFO_KEY, null);
}
});
return entry;
}
use of com.biglybt.pifimpl.local.utils.FormattersImpl 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();
}
use of com.biglybt.pifimpl.local.utils.FormattersImpl in project BiglyBT by BiglySoftware.
the class TagUIUtils method sortTagTypes.
public static List<TagType> sortTagTypes(Collection<TagType> _tag_types) {
List<TagType> tag_types = new ArrayList<>(_tag_types);
Collections.sort(tag_types, new Comparator<TagType>() {
final Comparator<String> comp = new FormattersImpl().getAlphanumericComparator(true);
@Override
public int compare(TagType o1, TagType o2) {
return (comp.compare(o1.getTagTypeName(true), o2.getTagTypeName(true)));
}
});
return (tag_types);
}
use of com.biglybt.pifimpl.local.utils.FormattersImpl in project BiglyBT by BiglySoftware.
the class MenuBuildUtils method splitLongMenuListIntoHierarchy.
/**
* @param flat_entries Overall list of menu entry names
* @param split_after Split if more than this
* @return Entries are either a String or Object[]{ submeuname, List<String> submenu entries }
*/
public static List<Object> splitLongMenuListIntoHierarchy(List<String> flat_entries, int split_after) {
List<Object> result = new ArrayList<>();
int flat_entry_count = flat_entries.size();
if (flat_entry_count == 0) {
return (result);
}
Collections.sort(flat_entries, new Comparator<String>() {
final Comparator<String> comp = new FormattersImpl().getAlphanumericComparator(true);
@Override
public int compare(String o1, String o2) {
return (comp.compare(o1, o2));
}
});
int[] buckets = new int[split_after];
for (int i = 0; i < flat_entry_count; i++) {
buckets[i % buckets.length]++;
}
List<char[]> edges = new ArrayList<>();
int pos = 0;
for (int i = 0; i < buckets.length; i++) {
int entries = buckets[i];
edges.add(flat_entries.get(pos).toCharArray());
if (entries > 1) {
edges.add(flat_entries.get(pos + entries - 1).toCharArray());
pos += entries;
} else {
break;
}
}
int[] edge_lens = new int[edges.size()];
for (int i = 0; i < edges.size() - 1; i++) {
char[] c1 = edges.get(i);
char[] c2 = edges.get(i + 1);
int j;
for (j = 0; j < Math.min(Math.min(c1.length, c2.length), 5); j++) {
if (c1[j] != c2[j]) {
break;
}
}
j++;
edge_lens[i] = Math.min(c1.length, Math.max(edge_lens[i], j));
edge_lens[i + 1] = j;
}
int bucket_pos = 0;
int edge_pos = 0;
Iterator<String> tag_it = flat_entries.iterator();
while (tag_it.hasNext()) {
int bucket_entries = buckets[bucket_pos++];
List<String> bucket_tags = new ArrayList<>();
for (int i = 0; i < bucket_entries; i++) {
bucket_tags.add(tag_it.next());
}
if (bucket_entries == 1) {
result.add(bucket_tags.get(0));
} else {
String level_name = new String(edges.get(edge_pos), 0, edge_lens[edge_pos++]) + " - " + new String(edges.get(edge_pos), 0, edge_lens[edge_pos++]);
result.add(new Object[] { level_name, bucket_tags });
}
}
return (result);
}
Aggregations