Search in sources :

Example 21 with UIInputReceiverListener

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

the class CategoryUIUtils method showCreateCategoryDialog.

public static void showCreateCategoryDialog(final UIFunctions.TagReturner tagReturner) {
    SimpleTextEntryWindow entryWindow = new SimpleTextEntryWindow("CategoryAddWindow.title", "CategoryAddWindow.message");
    entryWindow.setParentShell(Utils.findAnyShell());
    entryWindow.prompt(new UIInputReceiverListener() {

        @Override
        public void UIInputReceiverClosed(UIInputReceiver entryWindow) {
            if (entryWindow.hasSubmittedInput()) {
                TagUIUtils.checkTagSharing(false);
                Category newCategory = CategoryManager.createCategory(entryWindow.getSubmittedInput());
                if (tagReturner != null) {
                    tagReturner.returnedTags(new Tag[] { newCategory });
                }
            }
        }
    });
}
Also used : Category(com.biglybt.core.category.Category) SimpleTextEntryWindow(com.biglybt.ui.swt.SimpleTextEntryWindow) UIInputReceiver(com.biglybt.pif.ui.UIInputReceiver) UIInputReceiverListener(com.biglybt.pif.ui.UIInputReceiverListener) Tag(com.biglybt.core.tag.Tag)

Example 22 with UIInputReceiverListener

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

the class BuddyPluginViewInstance method addBuddyTable.

private Comparator<BuddyPluginBuddy> addBuddyTable(Composite child1) {
    buddy_table = new Table(child1, SWT.MULTI | SWT.BORDER | SWT.FULL_SELECTION | SWT.VIRTUAL);
    final String[] headers = { "azbuddy.ui.table.name", "azbuddy.ui.table.online", "azbuddy.ui.table.lastseen", "azbuddy.ui.table.last_ygm", "azbuddy.ui.table.last_msg", "azbuddy.ui.table.loc_cat", "azbuddy.ui.table.rem_cat", "azbuddy.ui.table.read_cat", "azbuddy.ui.table.con", "azbuddy.ui.table.track", "azbuddy.ui.table.msg_in", "azbuddy.ui.table.msg_out", "azbuddy.ui.table.msg_queued", "label.bytesIn", "label.bytesOut", "azbuddy.ui.table.ss" };
    int[] sizes = { 250, 100, 100, 100, 200, 100, 100, 100, 75, 75, 75, 75, 75, 75, 75, 40 };
    int[] aligns = { SWT.LEFT, SWT.CENTER, SWT.CENTER, SWT.CENTER, SWT.CENTER, SWT.LEFT, SWT.LEFT, SWT.LEFT, SWT.LEFT, SWT.CENTER, SWT.CENTER, SWT.CENTER, SWT.CENTER, SWT.CENTER, SWT.CENTER, SWT.CENTER };
    for (int i = 0; i < headers.length; i++) {
        TableColumn tc = new TableColumn(buddy_table, aligns[i]);
        tc.setWidth(Utils.adjustPXForDPI(sizes[i]));
        Messages.setLanguageText(tc, headers[i]);
    }
    buddy_table.setHeaderVisible(true);
    TableColumn[] columns = buddy_table.getColumns();
    columns[0].setData(new Integer(FilterComparator.FIELD_NAME));
    columns[1].setData(new Integer(FilterComparator.FIELD_ONLINE));
    columns[2].setData(new Integer(FilterComparator.FIELD_LAST_SEEN));
    columns[3].setData(new Integer(FilterComparator.FIELD_YGM));
    columns[4].setData(new Integer(FilterComparator.FIELD_LAST_MSG));
    columns[5].setData(new Integer(FilterComparator.FIELD_LOC_CAT));
    columns[6].setData(new Integer(FilterComparator.FIELD_REM_CAT));
    columns[7].setData(new Integer(FilterComparator.FIELD_READ_CAT));
    columns[8].setData(new Integer(FilterComparator.FIELD_CON));
    columns[9].setData(new Integer(FilterComparator.FIELD_TRACK));
    columns[10].setData(new Integer(FilterComparator.FIELD_MSG_IN));
    columns[11].setData(new Integer(FilterComparator.FIELD_MSG_OUT));
    columns[12].setData(new Integer(FilterComparator.FIELD_QUEUED));
    columns[13].setData(new Integer(FilterComparator.FIELD_BYTES_IN));
    columns[14].setData(new Integer(FilterComparator.FIELD_BYTES_OUT));
    columns[15].setData(new Integer(FilterComparator.FIELD_SS));
    final FilterComparator comparator = new FilterComparator();
    Listener sort_listener = new Listener() {

        @Override
        public void handleEvent(Event e) {
            TableColumn tc = (TableColumn) e.widget;
            int field = ((Integer) tc.getData()).intValue();
            comparator.setField(field);
            Collections.sort(buddies, comparator);
            updateTable();
        }
    };
    for (int i = 0; i < columns.length; i++) {
        columns[i].addListener(SWT.Selection, sort_listener);
    }
    GridData gridData = new GridData(GridData.FILL_BOTH);
    gridData.heightHint = buddy_table.getHeaderHeight() * 3;
    Utils.setLayoutData(buddy_table, gridData);
    buddy_table.addListener(SWT.SetData, new Listener() {

        @Override
        public void handleEvent(Event event) {
            TableItem item = (TableItem) event.item;
            int index = buddy_table.indexOf(item);
            if (index < 0 || index >= buddies.size()) {
                return;
            }
            BuddyPluginBuddy buddy = (BuddyPluginBuddy) buddies.get(index);
            item.setText(0, buddy.getName());
            int os;
            if (buddy.isOnline(false)) {
                os = buddy.getOnlineStatus();
            } else {
                os = BuddyPlugin.STATUS_APPEAR_OFFLINE;
            }
            if (os == BuddyPlugin.STATUS_APPEAR_OFFLINE) {
                item.setText(1, "");
            } else {
                item.setText(1, plugin.getOnlineStatus(os));
            }
            long lo = buddy.getLastTimeOnline();
            item.setText(2, lo == 0 ? "" : new SimpleDateFormat().format(new Date(lo)));
            long last_ygm = buddy.getLastMessagePending();
            item.setText(3, last_ygm == 0 ? "" : new SimpleDateFormat().format(new Date(last_ygm)));
            String lm = buddy.getLastMessageReceived();
            item.setText(4, lm == null ? "" : lm);
            String loc_cat = buddy.getLocalAuthorisedRSSTagsOrCategoriesAsString();
            if (loc_cat == null) {
                loc_cat = "";
            }
            item.setText(5, "" + loc_cat);
            String rem_cat = buddy.getRemoteAuthorisedRSSTagsOrCategoriesAsString();
            if (rem_cat == null) {
                rem_cat = "";
            }
            item.setText(6, "" + rem_cat);
            String read_cat = buddy.getLocalReadTagsOrCategoriesAsString();
            if (read_cat == null) {
                read_cat = "";
            }
            item.setText(7, "" + read_cat);
            item.setText(8, "" + buddy.getConnectionsString());
            item.setText(9, "" + tracker.getTrackingStatus(buddy));
            String in_frag = buddy.getMessageInFragmentDetails();
            item.setText(10, "" + buddy.getMessageInCount() + (in_frag.length() == 0 ? "" : ("+" + in_frag)));
            item.setText(11, "" + buddy.getMessageOutCount());
            item.setText(12, "" + buddy.getMessageHandler().getMessageCount());
            item.setText(13, "" + DisplayFormatters.formatByteCountToKiBEtc(buddy.getBytesInCount()));
            item.setText(14, "" + DisplayFormatters.formatByteCountToKiBEtc(buddy.getBytesOutCount()));
            item.setText(15, "" + buddy.getSubsystem() + " v" + buddy.getVersion());
            item.setData(buddy);
        }
    });
    final Listener tt_label_listener = new Listener() {

        @Override
        public void handleEvent(Event event) {
            Label label = (Label) event.widget;
            Shell shell = label.getShell();
            switch(event.type) {
                case SWT.MouseDown:
                    Event e = new Event();
                    e.item = (TableItem) label.getData("_TABLEITEM");
                    buddy_table.setSelection(new TableItem[] { (TableItem) e.item });
                    buddy_table.notifyListeners(SWT.Selection, e);
                // fall through
                case SWT.MouseExit:
                    shell.dispose();
                    break;
            }
        }
    };
    Listener tt_table_listener = new Listener() {

        private Shell tip = null;

        private Label label = null;

        @Override
        public void handleEvent(Event event) {
            switch(event.type) {
                case SWT.Dispose:
                case SWT.KeyDown:
                case SWT.MouseMove:
                    {
                        if (tip == null)
                            break;
                        tip.dispose();
                        tip = null;
                        label = null;
                        break;
                    }
                case SWT.MouseHover:
                    {
                        Point mouse_position = new Point(event.x, event.y);
                        TableItem item = buddy_table.getItem(mouse_position);
                        if (item != null) {
                            if (tip != null && !tip.isDisposed()) {
                                tip.dispose();
                                tip = null;
                            }
                            int index = buddy_table.indexOf(item);
                            if (index < 0 || index >= buddies.size()) {
                                return;
                            }
                            BuddyPluginBuddy buddy = (BuddyPluginBuddy) buddies.get(index);
                            int item_index = 0;
                            for (int i = 0; i < headers.length; i++) {
                                Rectangle bounds = item.getBounds(i);
                                if (bounds.contains(mouse_position)) {
                                    item_index = i;
                                    break;
                                }
                            }
                            if (item_index != 0) {
                                return;
                            }
                            tip = new Shell(buddy_table.getShell(), SWT.ON_TOP | SWT.TOOL);
                            tip.setLayout(new FillLayout());
                            label = new Label(tip, SWT.NONE);
                            label.setForeground(buddy_table.getDisplay().getSystemColor(SWT.COLOR_INFO_FOREGROUND));
                            label.setBackground(buddy_table.getDisplay().getSystemColor(SWT.COLOR_INFO_BACKGROUND));
                            label.setData("_TABLEITEM", item);
                            label.setText(getToolTip(buddy));
                            label.addListener(SWT.MouseExit, tt_label_listener);
                            label.addListener(SWT.MouseDown, tt_label_listener);
                            Point size = tip.computeSize(SWT.DEFAULT, SWT.DEFAULT);
                            Rectangle rect = item.getBounds(item_index);
                            Point pt = buddy_table.toDisplay(rect.x, rect.y);
                            tip.setBounds(pt.x, pt.y, size.x, size.y);
                            tip.setVisible(true);
                        }
                    }
            }
        }

        protected String getToolTip(BuddyPluginBuddy buddy) {
            List<InetAddress> addresses = buddy.getAdjustedIPs();
            InetAddress ip = buddy.getIP();
            InetAddress adj = buddy.getAdjustedIP();
            String str = "";
            if (ip == null) {
                str = "<none>";
            } else if (ip == adj) {
                str = ip.getHostAddress();
            } else {
                str = ip.getHostAddress() + "{";
                for (int i = 0; i < addresses.size(); i++) {
                    str += (i == 0 ? "" : "/") + addresses.get(i).getHostAddress();
                }
                str += "}";
            }
            return ("ip=" + str + ",tcp=" + buddy.getTCPPort() + ",udp=" + buddy.getUDPPort());
        }
    };
    buddy_table.addListener(SWT.Dispose, tt_table_listener);
    buddy_table.addListener(SWT.KeyDown, tt_table_listener);
    buddy_table.addListener(SWT.MouseMove, tt_table_listener);
    buddy_table.addListener(SWT.MouseHover, tt_table_listener);
    buddy_table.addKeyListener(new KeyAdapter() {

        @Override
        public void keyPressed(KeyEvent event) {
            if (event.stateMask == SWT.MOD1) {
                int key = event.character;
                if (key <= 26 && key > 0) {
                    key += 'a' - 1;
                }
                if (key == 'a') {
                    buddy_table.selectAll();
                    event.doit = false;
                }
            } else if (event.stateMask == 0 && event.keyCode == SWT.DEL) {
                TableItem[] selection = buddy_table.getSelection();
                String str = "";
                for (int i = 0; i < selection.length; i++) {
                    BuddyPluginBuddy buddy = (BuddyPluginBuddy) selection[i].getData();
                    str += (str.isEmpty() ? "" : ", ") + buddy.getName();
                }
                MessageBoxShell mb = new MessageBoxShell(MessageText.getString("message.confirm.delete.title"), MessageText.getString("message.confirm.delete.text", new String[] { str }), new String[] { MessageText.getString("Button.yes"), MessageText.getString("Button.no") }, 1);
                mb.open(new UserPrompterResultListener() {

                    @Override
                    public void prompterClosed(int result) {
                        if (result == 0) {
                            for (int i = 0; i < selection.length; i++) {
                                BuddyPluginBuddy buddy = (BuddyPluginBuddy) selection[i].getData();
                                buddy.remove();
                            }
                            buddy_table.setSelection(new int[0]);
                        }
                    }
                });
                event.doit = false;
            }
        }
    });
    final Menu menu = new Menu(buddy_table);
    final MenuItem remove_item = new MenuItem(menu, SWT.PUSH);
    remove_item.setText(lu.getLocalisedMessageText("azbuddy.ui.menu.remove"));
    remove_item.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            TableItem[] selection = buddy_table.getSelection();
            for (int i = 0; i < selection.length; i++) {
                BuddyPluginBuddy buddy = (BuddyPluginBuddy) selection[i].getData();
                buddy.remove();
            }
        }
    });
    // get public key
    final MenuItem get_pk_item = new MenuItem(menu, SWT.PUSH);
    get_pk_item.setText(lu.getLocalisedMessageText("azbuddy.ui.menu.copypk"));
    get_pk_item.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent event) {
            TableItem[] selection = buddy_table.getSelection();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < selection.length; i++) {
                BuddyPluginBuddy buddy = (BuddyPluginBuddy) selection[i].getData();
                sb.append(buddy.getPublicKey()).append("\r\n");
            }
            if (sb.length() > 0) {
                writeToClipboard(sb.toString());
            }
        }
    });
    // disconnect message
    final MenuItem disconnect_msg_item;
    if (Constants.isCVSVersion()) {
        disconnect_msg_item = new MenuItem(menu, SWT.PUSH);
        disconnect_msg_item.setText(lu.getLocalisedMessageText("azbuddy.ui.menu.disconnect"));
        disconnect_msg_item.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent event) {
                TableItem[] selection = buddy_table.getSelection();
                for (int i = 0; i < selection.length; i++) {
                    BuddyPluginBuddy buddy = (BuddyPluginBuddy) selection[i].getData();
                    buddy.disconnect();
                }
            }
        });
    } else {
        disconnect_msg_item = null;
    }
    // send message
    final MenuItem send_msg_item = new MenuItem(menu, SWT.PUSH);
    send_msg_item.setText(lu.getLocalisedMessageText("azbuddy.ui.menu.send"));
    send_msg_item.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent event) {
            final TableItem[] selection = buddy_table.getSelection();
            UIInputReceiver prompter = ui_instance.getInputReceiver();
            prompter.setLocalisedTitle(lu.getLocalisedMessageText("azbuddy.ui.menu.send"));
            prompter.setLocalisedMessage(lu.getLocalisedMessageText("azbuddy.ui.menu.send_msg"));
            try {
                prompter.prompt(new UIInputReceiverListener() {

                    @Override
                    public void UIInputReceiverClosed(UIInputReceiver prompter) {
                        String text = prompter.getSubmittedInput();
                        if (text != null) {
                            for (int i = 0; i < selection.length; i++) {
                                BuddyPluginBuddy buddy = (BuddyPluginBuddy) selection[i].getData();
                                plugin.getAZ2Handler().sendAZ2Message(buddy, text);
                            }
                        }
                    }
                });
            } catch (Throwable e) {
            }
        }
    });
    // chat
    final MenuItem chat_item = new MenuItem(menu, SWT.PUSH);
    chat_item.setText(lu.getLocalisedMessageText("azbuddy.ui.menu.chat"));
    chat_item.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent event) {
            TableItem[] selection = buddy_table.getSelection();
            BuddyPluginBuddy[] buddies = new BuddyPluginBuddy[selection.length];
            for (int i = 0; i < selection.length; i++) {
                BuddyPluginBuddy buddy = (BuddyPluginBuddy) selection[i].getData();
                buddies[i] = buddy;
            }
            plugin.getAZ2Handler().createChat(buddies);
        }
    });
    // ping
    final MenuItem ping_item = new MenuItem(menu, SWT.PUSH);
    ping_item.setText(lu.getLocalisedMessageText("azbuddy.ui.menu.ping"));
    ping_item.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent event) {
            TableItem[] selection = buddy_table.getSelection();
            for (int i = 0; i < selection.length; i++) {
                BuddyPluginBuddy buddy = (BuddyPluginBuddy) selection[i].getData();
                try {
                    buddy.ping();
                } catch (Throwable e) {
                    print("Ping failed", e);
                }
            }
        }
    });
    // ygm
    final MenuItem ygm_item = new MenuItem(menu, SWT.PUSH);
    ygm_item.setText(lu.getLocalisedMessageText("azbuddy.ui.menu.ygm"));
    ygm_item.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent event) {
            TableItem[] selection = buddy_table.getSelection();
            for (int i = 0; i < selection.length; i++) {
                BuddyPluginBuddy buddy = (BuddyPluginBuddy) selection[i].getData();
                try {
                    buddy.setMessagePending();
                } catch (Throwable e) {
                    print("YGM failed", e);
                }
            }
        }
    });
    // encrypt
    final MenuItem encrypt_item = new MenuItem(menu, SWT.PUSH);
    encrypt_item.setText(lu.getLocalisedMessageText("azbuddy.ui.menu.enc"));
    encrypt_item.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent event) {
            TableItem[] selection = buddy_table.getSelection();
            String str = readFromClipboard();
            if (str != null) {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < selection.length; i++) {
                    BuddyPluginBuddy buddy = (BuddyPluginBuddy) selection[i].getData();
                    try {
                        byte[] contents = str.getBytes("UTF-8");
                        BuddyPlugin.cryptoResult result = buddy.encrypt(contents);
                        sb.append("key: ");
                        sb.append(plugin.getPublicKey());
                        sb.append("\r\n");
                        sb.append("hash: ");
                        sb.append(Base32.encode(result.getChallenge()));
                        sb.append("\r\n");
                        sb.append("payload: ");
                        sb.append(Base32.encode(result.getPayload()));
                        sb.append("\r\n\r\n");
                    } catch (Throwable e) {
                        print("YGM failed", e);
                    }
                }
                writeToClipboard(sb.toString());
            }
        }
    });
    // decrypt
    final MenuItem decrypt_item = new MenuItem(menu, SWT.PUSH);
    decrypt_item.setText(lu.getLocalisedMessageText("azbuddy.ui.menu.dec"));
    decrypt_item.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent event) {
            String str = readFromClipboard();
            if (str != null) {
                String[] bits = str.split("\n");
                StringBuilder sb = new StringBuilder();
                BuddyPluginBuddy buddy = null;
                byte[] hash = null;
                for (int i = 0; i < bits.length; i++) {
                    String bit = bits[i].trim();
                    if (bit.length() > 0) {
                        int pos = bit.indexOf(':');
                        if (pos == -1) {
                            continue;
                        }
                        String lhs = bit.substring(0, pos).trim();
                        String rhs = bit.substring(pos + 1).trim();
                        if (lhs.equals("key")) {
                            buddy = plugin.getBuddyFromPublicKey(rhs);
                        } else if (lhs.equals("hash")) {
                            hash = Base32.decode(rhs);
                        } else if (lhs.equals("payload")) {
                            byte[] payload = Base32.decode(rhs);
                            if (buddy != null) {
                                try {
                                    BuddyPlugin.cryptoResult result = buddy.decrypt(payload);
                                    byte[] sha1 = new SHA1Simple().calculateHash(result.getChallenge());
                                    sb.append("key: ");
                                    sb.append(buddy.getPublicKey());
                                    sb.append("\r\n");
                                    sb.append("hash_ok: ").append(Arrays.equals(hash, sha1));
                                    sb.append("\r\n");
                                    sb.append("payload: ");
                                    sb.append(new String(result.getPayload(), "UTF-8"));
                                    sb.append("\r\n\r\n");
                                } catch (Throwable e) {
                                    print("decrypt failed", e);
                                }
                            }
                        }
                    }
                }
                if (sb.length() > 0) {
                    writeToClipboard(sb.toString());
                }
            }
        }
    });
    // sign
    final MenuItem sign_item = new MenuItem(menu, SWT.PUSH);
    sign_item.setText(lu.getLocalisedMessageText("azbuddy.ui.menu.sign"));
    sign_item.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent event) {
            String str = readFromClipboard();
            if (str != null) {
                StringBuilder sb = new StringBuilder();
                try {
                    sb.append("key: ");
                    sb.append(plugin.getPublicKey());
                    sb.append("\r\n");
                    byte[] payload = str.getBytes("UTF-8");
                    sb.append("data: ");
                    sb.append(Base32.encode(payload));
                    sb.append("\r\n");
                    byte[] sig = plugin.sign(payload);
                    sb.append("sig: ");
                    sb.append(Base32.encode(sig));
                    sb.append("\r\n");
                } catch (Throwable e) {
                    print("sign failed", e);
                }
                if (sb.length() > 0) {
                    writeToClipboard(sb.toString());
                }
            }
        }
    });
    // verify
    final MenuItem verify_item = new MenuItem(menu, SWT.PUSH);
    verify_item.setText(lu.getLocalisedMessageText("azbuddy.ui.menu.verify"));
    verify_item.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent event) {
            String str = readFromClipboard();
            if (str != null) {
                String[] bits = str.split("\n");
                StringBuilder sb = new StringBuilder();
                String pk = null;
                byte[] data = null;
                for (int i = 0; i < bits.length; i++) {
                    String bit = bits[i].trim();
                    if (bit.length() > 0) {
                        int pos = bit.indexOf(':');
                        if (pos == -1) {
                            continue;
                        }
                        String lhs = bit.substring(0, pos).trim();
                        String rhs = bit.substring(pos + 1).trim();
                        if (lhs.equals("key")) {
                            pk = rhs;
                        } else if (lhs.equals("data")) {
                            data = Base32.decode(rhs);
                        } else if (lhs.equals("sig")) {
                            byte[] sig = Base32.decode(rhs);
                            if (pk != null && data != null) {
                                try {
                                    sb.append("key: ");
                                    sb.append(pk);
                                    sb.append("\r\n");
                                    boolean ok = plugin.verify(pk, data, sig);
                                    sb.append("sig_ok: ").append(ok);
                                    sb.append("\r\n");
                                    sb.append("data: ");
                                    sb.append(new String(data, "UTF-8"));
                                    sb.append("\r\n\r\n");
                                } catch (Throwable e) {
                                    print("decrypt failed", e);
                                }
                            }
                        }
                    }
                }
                if (sb.length() > 0) {
                    writeToClipboard(sb.toString());
                }
            }
        }
    });
    // cats
    Menu cat_menu = new Menu(menu.getShell(), SWT.DROP_DOWN);
    MenuItem cat_item = new MenuItem(menu, SWT.CASCADE);
    Messages.setLanguageText(cat_item, "azbuddy.ui.menu.cat");
    cat_item.setMenu(cat_menu);
    // cats - share
    final MenuItem cat_share_item = new MenuItem(cat_menu, SWT.PUSH);
    cat_share_item.setText(lu.getLocalisedMessageText("azbuddy.ui.menu.cat.share"));
    cat_share_item.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent event) {
            UIInputReceiver prompter = ui_instance.getInputReceiver();
            prompter.setLocalisedTitle(lu.getLocalisedMessageText("azbuddy.ui.menu.cat.set"));
            prompter.setLocalisedMessage(lu.getLocalisedMessageText("azbuddy.ui.menu.cat.set_msg"));
            prompter.prompt(new UIInputReceiverListener() {

                @Override
                public void UIInputReceiverClosed(UIInputReceiver prompter) {
                    String cats = prompter.getSubmittedInput();
                    if (cats != null) {
                        cats = cats.trim();
                        if (cats.equalsIgnoreCase("None")) {
                            cats = "";
                        }
                        TableItem[] selection = buddy_table.getSelection();
                        for (int i = 0; i < selection.length; i++) {
                            BuddyPluginBuddy buddy = (BuddyPluginBuddy) selection[i].getData();
                            buddy.setLocalAuthorisedRSSTagsOrCategories(cats);
                        }
                    }
                }
            });
        }
    });
    // cats - subscribe
    final Menu cat_subs_menu = new Menu(cat_menu.getShell(), SWT.DROP_DOWN);
    final MenuItem cat_subs_item = new MenuItem(cat_menu, SWT.CASCADE);
    Messages.setLanguageText(cat_subs_item, "azbuddy.ui.menu.cat_subs");
    cat_subs_item.setMenu(cat_subs_menu);
    cat_subs_menu.addMenuListener(new MenuListener() {

        @Override
        public void menuShown(MenuEvent arg0) {
            MenuItem[] items = cat_subs_menu.getItems();
            for (int i = 0; i < items.length; i++) {
                items[i].dispose();
            }
            final TableItem[] selection = buddy_table.getSelection();
            Set<String> avail_cats = new TreeSet<>();
            for (int i = 0; i < selection.length; i++) {
                BuddyPluginBuddy buddy = (BuddyPluginBuddy) selection[i].getData();
                Set<String> cats = buddy.getRemoteAuthorisedRSSTagsOrCategories();
                if (cats != null) {
                    avail_cats.addAll(cats);
                }
            }
            for (final String cat : avail_cats) {
                final MenuItem subs_item = new MenuItem(cat_subs_menu, SWT.PUSH);
                subs_item.setText(cat);
                subs_item.addSelectionListener(new SelectionAdapter() {

                    @Override
                    public void widgetSelected(SelectionEvent event) {
                        for (int i = 0; i < selection.length; i++) {
                            BuddyPluginBuddy buddy = (BuddyPluginBuddy) selection[i].getData();
                            if (buddy.isRemoteRSSTagOrCategoryAuthorised(cat)) {
                                try {
                                    buddy.subscribeToCategory(cat);
                                } catch (Throwable e) {
                                    print("Failed", e);
                                }
                            }
                        }
                    }
                });
            }
        }

        @Override
        public void menuHidden(MenuEvent arg0) {
        }
    });
    // done with menus
    buddy_table.setMenu(menu);
    menu.addMenuListener(new MenuListener() {

        @Override
        public void menuShown(MenuEvent arg0) {
            boolean available = plugin.isAvailable();
            TableItem[] selection = buddy_table.getSelection();
            remove_item.setEnabled(selection.length > 0);
            get_pk_item.setEnabled(available && selection.length > 0);
            if (disconnect_msg_item != null) {
                disconnect_msg_item.setEnabled(selection.length > 0);
            }
            send_msg_item.setEnabled(available && selection.length > 0);
            chat_item.setEnabled(available && selection.length > 0);
            ping_item.setEnabled(available && selection.length > 0);
            ygm_item.setEnabled(available && selection.length > 0);
            encrypt_item.setEnabled(selection.length > 0);
            decrypt_item.setEnabled(true);
            sign_item.setEnabled(true);
            verify_item.setEnabled(true);
            cat_item.setEnabled(selection.length > 0);
        }

        @Override
        public void menuHidden(MenuEvent arg0) {
        }
    });
    return (comparator);
}
Also used : UserPrompterResultListener(com.biglybt.ui.UserPrompterResultListener) UIInputReceiverListener(com.biglybt.pif.ui.UIInputReceiverListener) LinkLabel(com.biglybt.ui.swt.components.LinkLabel) Rectangle(org.eclipse.swt.graphics.Rectangle) MessageBoxShell(com.biglybt.ui.swt.shells.MessageBoxShell) MessageBoxShell(com.biglybt.ui.swt.shells.MessageBoxShell) Point(org.eclipse.swt.graphics.Point) Point(org.eclipse.swt.graphics.Point) UserPrompterResultListener(com.biglybt.ui.UserPrompterResultListener) UIInputReceiver(com.biglybt.pif.ui.UIInputReceiver) UIManagerEvent(com.biglybt.pif.ui.UIManagerEvent) UIInputReceiverListener(com.biglybt.pif.ui.UIInputReceiverListener) SimpleDateFormat(java.text.SimpleDateFormat) InetAddress(java.net.InetAddress)

Example 23 with UIInputReceiverListener

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

the class BuddyPluginView method buildMenu.

private void buildMenu(final Set<ChatInstance> current_instances) {
    if (menu_items.size() == 0 || !menu_latest_instances.equals(current_instances)) {
        for (MenuItem mi : menu_items) {
            mi.remove();
        }
        menu_items.clear();
        final MenuManager menu_manager = plugin.getPluginInterface().getUIManager().getMenuManager();
        MenuContext mc = beta_status.getMenuContext();
        for (final ChatInstance chat : sortChats(current_instances)) {
            String short_name = chat.getShortName();
            MenuItem mi = menu_manager.addMenuItem(mc, "!" + short_name + "!");
            mi.addListener(new MenuItemListener() {

                @Override
                public void selected(MenuItem menu, Object target) {
                    try {
                        openChat(chat.getClone());
                    } catch (Throwable e) {
                        Debug.out(e);
                    }
                }
            });
            menu_items.add(mi);
        }
        boolean need_sep = true;
        if (current_instances.size() > 1) {
            MenuItem mi = menu_manager.addMenuItem(mc, "sep1");
            need_sep = false;
            mi.setStyle(MenuItem.STYLE_SEPARATOR);
            menu_items.add(mi);
            mi = menu_manager.addMenuItem(mc, "label.open.all");
            mi.addListener(new MenuItemListener() {

                @Override
                public void selected(MenuItem menu, Object target) {
                    for (ChatInstance chat : current_instances) {
                        try {
                            openChat(chat.getClone());
                        } catch (Throwable e) {
                            Debug.out(e);
                        }
                    }
                }
            });
            menu_items.add(mi);
        }
        if (need_sep) {
            MenuItem mi = menu_manager.addMenuItem(mc, "sep2");
            mi.setStyle(MenuItem.STYLE_SEPARATOR);
            menu_items.add(mi);
        }
        // create channel
        MenuItem mi = menu_manager.addMenuItem(mc, "chat.view.create.chat");
        mi.setStyle(MenuItem.STYLE_MENU);
        menu_items.add(mi);
        mi.addFillListener(new com.biglybt.pif.ui.menus.MenuItemFillListener() {

            @Override
            public void menuWillBeShown(MenuItem menu, Object data) {
                menu.removeAllChildItems();
                MenuItem mi = menu_manager.addMenuItem(menu, "!" + MessageText.getString("label.public") + "...!");
                mi.addListener(new MenuItemListener() {

                    @Override
                    public void selected(MenuItem menu, Object target) {
                        SimpleTextEntryWindow entryWindow = new SimpleTextEntryWindow("chat.view.enter.key.title", "chat.view.enter.key.msg");
                        entryWindow.prompt(new UIInputReceiverListener() {

                            @Override
                            public void UIInputReceiverClosed(UIInputReceiver receiver) {
                                if (!receiver.hasSubmittedInput()) {
                                    return;
                                }
                                String key = receiver.getSubmittedInput().trim();
                                BuddyPluginUtils.createBetaChat(AENetworkClassifier.AT_PUBLIC, key, null);
                            }
                        });
                    }
                });
                mi = menu_manager.addMenuItem(menu, "!" + MessageText.getString("label.anon") + "...!");
                mi.addListener(new MenuItemListener() {

                    @Override
                    public void selected(MenuItem menu, Object target) {
                        if (plugin.getBeta().isI2PAvailable()) {
                            SimpleTextEntryWindow entryWindow = new SimpleTextEntryWindow("chat.view.enter.key.title", "chat.view.enter.key.msg");
                            entryWindow.prompt(new UIInputReceiverListener() {

                                @Override
                                public void UIInputReceiverClosed(UIInputReceiver receiver) {
                                    if (!receiver.hasSubmittedInput()) {
                                        return;
                                    }
                                    String key = receiver.getSubmittedInput().trim();
                                    BuddyPluginUtils.createBetaChat(AENetworkClassifier.AT_I2P, key, null);
                                }
                            });
                        } else {
                            I2PHelpers.installI2PHelper(null, null, null);
                        }
                    }
                });
                if (I2PHelpers.isInstallingI2PHelper()) {
                    mi.setEnabled(false);
                    mi.setText(mi.getText() + " (" + MessageText.getString("PeersView.state.pending") + ")");
                }
            }
        });
        // chat overview
        mi = menu_manager.addMenuItem(mc, "!" + MessageText.getString("chats.view.heading") + "...!");
        mi.addListener(new MenuItemListener() {

            @Override
            public void selected(MenuItem menu, Object target) {
                UIFunctions uif = UIFunctionsManager.getUIFunctions();
                if (uif != null) {
                    uif.getMDI().showEntryByID(MultipleDocumentInterface.SIDEBAR_SECTION_CHAT);
                }
            }
        });
        menu_items.add(mi);
        mi = menu_manager.addMenuItem(mc, "sep3");
        mi.setStyle(MenuItem.STYLE_SEPARATOR);
        menu_items.add(mi);
        // options
        mi = menu_manager.addMenuItem(mc, "MainWindow.menu.view.configuration");
        mi.addListener(new MenuItemListener() {

            @Override
            public void selected(MenuItem menu, Object target) {
                ui_instance.openView(UISWTInstance.VIEW_MAIN, VIEW_ID, null);
            }
        });
        menu_items.add(mi);
        menu_latest_instances = current_instances;
    }
}
Also used : ChatInstance(com.biglybt.plugin.net.buddy.BuddyPluginBeta.ChatInstance) MenuItem(com.biglybt.pif.ui.menus.MenuItem) MenuContext(com.biglybt.pif.ui.menus.MenuContext) UIFunctions(com.biglybt.ui.UIFunctions) SimpleTextEntryWindow(com.biglybt.ui.swt.SimpleTextEntryWindow) UIInputReceiver(com.biglybt.pif.ui.UIInputReceiver) MenuManager(com.biglybt.pif.ui.menus.MenuManager) MenuItemListener(com.biglybt.pif.ui.menus.MenuItemListener) UIInputReceiverListener(com.biglybt.pif.ui.UIInputReceiverListener)

Example 24 with UIInputReceiverListener

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

the class PeersViewBase method addPeersMenu.

protected static boolean addPeersMenu(final DownloadManager man, String column_name, Menu menu) {
    new MenuItem(menu, SWT.SEPARATOR);
    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();
            if (str.isEmpty()) {
                str = "<no usable peers>";
            }
            ClipboardCopy.copyToClipBoard(str);
        }
    });
    if (man == null) {
        return (true);
    }
    PEPeerManager pm = man.getPeerManager();
    if (pm == null) {
        return (true);
    }
    if (TorrentUtils.isReallyPrivate(man.getTorrent())) {
        return (true);
    }
    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();
            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.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;
                    }
                    String[] bits = sReturn.split(",");
                    for (String bit : bits) {
                        bit = bit.trim();
                        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);
                        }
                    }
                }
            });
        }
    });
    return (true);
}
Also used : PEPeer(com.biglybt.core.peer.PEPeer) SelectionListener(org.eclipse.swt.events.SelectionListener) TableViewSWTMenuFillListener(com.biglybt.ui.swt.views.table.TableViewSWTMenuFillListener) Listener(org.eclipse.swt.widgets.Listener) UIInputReceiverListener(com.biglybt.pif.ui.UIInputReceiverListener) TableSelectionListener(com.biglybt.ui.common.table.TableSelectionListener) UIManagerListener(com.biglybt.pif.ui.UIManagerListener) TableLifeCycleListener(com.biglybt.ui.common.table.TableLifeCycleListener) MenuItem(org.eclipse.swt.widgets.MenuItem) SimpleTextEntryWindow(com.biglybt.ui.swt.SimpleTextEntryWindow) UIInputReceiver(com.biglybt.pif.ui.UIInputReceiver) UISWTViewEvent(com.biglybt.ui.swt.pif.UISWTViewEvent) Event(org.eclipse.swt.widgets.Event) SelectionEvent(org.eclipse.swt.events.SelectionEvent) PEPeerManager(com.biglybt.core.peer.PEPeerManager) ArrayList(java.util.ArrayList) List(java.util.List) UIInputReceiverListener(com.biglybt.pif.ui.UIInputReceiverListener)

Example 25 with UIInputReceiverListener

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

the class ConfigView method _initialize.

private void _initialize(final Composite composite) {
    GridData gridData;
    /*
    /--cConfig-----------------------------------------------------------\
    | ###SashForm#form################################################## |
    | # /--cLeftSide-\ /--cRightSide---------------------------------\ # |
    | # | ##tree#### | | ***cHeader********************************* | # |
    | # | #        # | | * lHeader                    usermodeHint * | # |
    | # | #        # | | ******************************************* | # |
    | # | #        # | | ###Composite cConfigSection################ | # |
    | # | #        # | | #                                         # | # |
    | # | #        # | | #                                         # | # |
    | # | #        # | | #                                         # | # |
    | # | ########## | | #                                         # | # |
    | # |txtFilter X | | ########################################### | # |
    | # \------------/ \---------------------------------------------/ # |
    | ################################################################## |
    |                                                          [Buttons] |
    \--------------------------------------------------------------------/
    */
    try {
        Display d = composite.getDisplay();
        GridLayout configLayout;
        SashForm form = new SashForm(cConfig, SWT.HORIZONTAL);
        gridData = new GridData(GridData.FILL_BOTH);
        Utils.setLayoutData(form, gridData);
        Composite cLeftSide = new Composite(form, SWT.BORDER);
        gridData = new GridData(GridData.FILL_BOTH);
        Utils.setLayoutData(cLeftSide, gridData);
        FormLayout layout = new FormLayout();
        cLeftSide.setLayout(layout);
        Composite cFilterArea = new Composite(cLeftSide, SWT.NONE);
        cFilterArea.setLayout(new FormLayout());
        final Text txtFilter = new Text(cFilterArea, SWT.BORDER);
        txtFilter.setMessage(MessageText.getString("ConfigView.filter"));
        txtFilter.selectAll();
        txtFilter.addModifyListener(new ModifyListener() {

            @Override
            public void modifyText(ModifyEvent e) {
                filterTree(txtFilter.getText());
            }
        });
        ImageLoader imageLoader = ImageLoader.getInstance();
        imgSmallXGray = imageLoader.getImage("smallx-gray");
        imgSmallX = imageLoader.getImage("smallx");
        lblX = new Label(cFilterArea, SWT.WRAP);
        Messages.setLanguageTooltip(lblX, "MyTorrentsView.clearFilter.tooltip");
        lblX.setImage(imgSmallXGray);
        lblX.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseUp(MouseEvent e) {
                txtFilter.setText("");
            }
        });
        lblX.addDisposeListener(new DisposeListener() {

            @Override
            public void widgetDisposed(DisposeEvent arg0) {
                ImageLoader imageLoader = ImageLoader.getInstance();
                imageLoader.releaseImage("smallx-gray");
                imageLoader.releaseImage("smallx");
            }
        });
        Label lblSearch = new Label(cFilterArea, SWT.NONE);
        imageLoader.setLabelImage(lblSearch, "search");
        tree = new Tree(cLeftSide, SWT.NONE);
        FontData[] fontData = tree.getFont().getFontData();
        fontData[0].setStyle(SWT.BOLD);
        filterFoundFont = new Font(d, fontData);
        FormData formData;
        formData = new FormData();
        formData.bottom = new FormAttachment(100, -5);
        formData.left = new FormAttachment(0, 0);
        formData.right = new FormAttachment(100, 0);
        Utils.setLayoutData(cFilterArea, formData);
        formData = new FormData();
        formData.top = new FormAttachment(txtFilter, 0, SWT.CENTER);
        formData.left = new FormAttachment(0, 5);
        Utils.setLayoutData(lblSearch, formData);
        formData = new FormData();
        formData.top = new FormAttachment(0, 5);
        formData.left = new FormAttachment(lblSearch, 5);
        formData.right = new FormAttachment(lblX, -3);
        Utils.setLayoutData(txtFilter, formData);
        formData = new FormData();
        formData.top = new FormAttachment(0, 5);
        formData.right = new FormAttachment(100, -5);
        Utils.setLayoutData(lblX, formData);
        formData = new FormData();
        formData.top = new FormAttachment(0, 0);
        formData.left = new FormAttachment(0, 0);
        formData.right = new FormAttachment(100, 0);
        formData.bottom = new FormAttachment(cFilterArea, -1);
        Utils.setLayoutData(tree, formData);
        Composite cRightSide = new Composite(form, SWT.NULL);
        configLayout = new GridLayout();
        configLayout.marginHeight = 3;
        configLayout.marginWidth = 0;
        cRightSide.setLayout(configLayout);
        // Header
        Composite cHeader = new Composite(cRightSide, SWT.BORDER);
        configLayout = new GridLayout();
        configLayout.marginHeight = 3;
        configLayout.marginWidth = 0;
        configLayout.numColumns = 2;
        configLayout.marginRight = 5;
        cHeader.setLayout(configLayout);
        gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_CENTER);
        Utils.setLayoutData(cHeader, gridData);
        cHeader.setBackground(Colors.getSystemColor(d, SWT.COLOR_LIST_SELECTION));
        cHeader.setForeground(Colors.getSystemColor(d, SWT.COLOR_LIST_SELECTION_TEXT));
        lHeader = new Label(cHeader, SWT.NULL);
        lHeader.setBackground(Colors.getSystemColor(d, SWT.COLOR_LIST_SELECTION));
        lHeader.setForeground(Colors.getSystemColor(d, SWT.COLOR_LIST_SELECTION_TEXT));
        fontData = lHeader.getFont().getFontData();
        fontData[0].setStyle(SWT.BOLD);
        int fontHeight = (int) (fontData[0].getHeight() * 1.2);
        fontData[0].setHeight(fontHeight);
        headerFont = new Font(d, fontData);
        lHeader.setFont(headerFont);
        gridData = new GridData(GridData.VERTICAL_ALIGN_CENTER | GridData.HORIZONTAL_ALIGN_BEGINNING);
        Utils.setLayoutData(lHeader, gridData);
        usermodeHint = new Label(cHeader, SWT.NULL);
        usermodeHint.setBackground(Colors.getSystemColor(d, SWT.COLOR_LIST_SELECTION));
        usermodeHint.setForeground(Colors.getSystemColor(d, SWT.COLOR_LIST_SELECTION_TEXT));
        gridData = new GridData(GridData.VERTICAL_ALIGN_CENTER | GridData.HORIZONTAL_ALIGN_END | GridData.GRAB_HORIZONTAL);
        Utils.setLayoutData(usermodeHint, gridData);
        Menu headerMenu = new Menu(cHeader.getShell(), SWT.POP_UP);
        final MenuItem menuShortCut = new MenuItem(headerMenu, SWT.PUSH);
        Messages.setLanguageText(menuShortCut, "label.set.shortcut");
        menuShortCut.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {
                final TreeItem tree_item = (TreeItem) lHeader.getData("TreeItem");
                if (tree_item != null) {
                    final String id = (String) tree_item.getData("ID");
                    if (id != null) {
                        SimpleTextEntryWindow entryWindow = new SimpleTextEntryWindow("config.dialog.shortcut.title", "config.dialog.shortcut.text");
                        entryWindow.setPreenteredText(COConfigurationManager.getStringParameter("config.section.shortcut.key." + id, ""), false);
                        entryWindow.setTextLimit(1);
                        entryWindow.prompt(new UIInputReceiverListener() {

                            @Override
                            public void UIInputReceiverClosed(UIInputReceiver entryWindow) {
                                if (!entryWindow.hasSubmittedInput()) {
                                    return;
                                }
                                String sReturn = entryWindow.getSubmittedInput();
                                if (sReturn != null) {
                                    sReturn = sReturn.trim();
                                    if (sReturn.length() > 1) {
                                        sReturn = sReturn.substring(0, 1);
                                    }
                                    COConfigurationManager.setParameter("config.section.shortcut.key." + id, sReturn);
                                    updateHeader(tree_item);
                                }
                            }
                        });
                    }
                }
            }
        });
        cHeader.setMenu(headerMenu);
        lHeader.setMenu(headerMenu);
        usermodeHint.setMenu(headerMenu);
        // Config Section
        cConfigSection = new Composite(cRightSide, SWT.NULL);
        layoutConfigSection = new StackLayout();
        cConfigSection.setLayout(layoutConfigSection);
        gridData = new GridData(GridData.FILL_BOTH);
        gridData.horizontalIndent = 2;
        Utils.setLayoutData(cConfigSection, gridData);
        form.setWeights(new int[] { 20, 80 });
        tree.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {
                Tree tree = (Tree) e.getSource();
                // and you close its parent.
                if (tree.getSelection().length > 0)
                    showSection(tree.getSelection()[0], false);
            }
        });
        // Double click = expand/contract branch
        tree.addListener(SWT.DefaultSelection, new Listener() {

            @Override
            public void handleEvent(Event e) {
                TreeItem item = (TreeItem) e.item;
                if (item != null)
                    item.setExpanded(!item.getExpanded());
            }
        });
    } catch (Exception e) {
        Logger.log(new LogEvent(LOGID, "Error initializing ConfigView", e));
    }
    scResizeListener = new Listener() {

        @Override
        public void handleEvent(Event event) {
            setupSC((ScrolledComposite) event.widget);
        }
    };
    // Add sections
    /**
     * How to add a new section
     * 1) Create a new implementation of ConfigSectionSWT in a new file
     *    (Use the ConfigSectionTMP.java as a template if it's still around)
     * 2) import it into here
     * 3) add it to the internal sections list
     */
    pluginSections = ConfigSectionRepository.getInstance().getList();
    ConfigSection[] internalSections = { new ConfigSectionMode(), new ConfigSectionStartShutdown(), new ConfigSectionBackupRestore(), new ConfigSectionConnection(), new ConfigSectionConnectionProxy(), new ConfigSectionConnectionAdvanced(), new ConfigSectionConnectionEncryption(), new ConfigSectionConnectionDNS(), new ConfigSectionTransfer(), new ConfigSectionTransferAutoSpeedSelect(), new ConfigSectionTransferAutoSpeed(), new ConfigSectionTransferAutoSpeedBeta(), new ConfigSectionTransferLAN(), new ConfigSectionFile(), new ConfigSectionFileMove(), new ConfigSectionFileTorrents(), new ConfigSectionFileTorrentsDecoding(), new ConfigSectionFilePerformance(), new ConfigSectionInterface(), new ConfigSectionInterfaceLanguage(), new ConfigSectionInterfaceStart(), new ConfigSectionInterfaceDisplay(), new ConfigSectionInterfaceTables(), new ConfigSectionInterfaceColor(), new ConfigSectionInterfaceAlerts(), new ConfigSectionInterfacePassword(), new ConfigSectionInterfaceLegacy(), new ConfigSectionIPFilter(), new ConfigSectionPlugins(this), new ConfigSectionStats(), new ConfigSectionTracker(), new ConfigSectionTrackerClient(), new ConfigSectionTrackerServer(), new ConfigSectionSecurity(), new ConfigSectionSharing(), new ConfigSectionLogging() };
    pluginSections.addAll(0, Arrays.asList(internalSections));
    for (int i = 0; i < pluginSections.size(); i++) {
        // slip the non-standard "plugins" initialisation inbetween the internal ones
        // and the plugin ones so plugin ones can be children of it
        boolean plugin_section = i >= internalSections.length;
        ConfigSection section = pluginSections.get(i);
        if (section instanceof UISWTConfigSection) {
            String name;
            try {
                name = section.configSectionGetName();
            } catch (Exception e) {
                Logger.log(new LogEvent(LOGID, "A ConfigSection plugin caused an " + "error while trying to call its " + "configSectionGetName function", e));
                name = "Bad Plugin";
            }
            String section_key = name;
            if (plugin_section) {
                if (!MessageText.keyExists(section_key)) {
                    section_key = sSectionPrefix + name;
                }
            } else {
                section_key = sSectionPrefix + name;
            }
            String section_name = MessageText.getString(section_key);
            try {
                TreeItem treeItem;
                String location = section.configSectionGetParentSection();
                if (location.length() == 0 || location.equalsIgnoreCase(ConfigSection.SECTION_ROOT)) {
                    // int position = findInsertPointFor(section_name, tree);
                    // if ( position == -1 ){
                    treeItem = new TreeItem(tree, SWT.NULL);
                // }else{
                // treeItem = new TreeItem(tree, SWT.NULL, position);
                // }
                } else {
                    TreeItem treeItemFound = findTreeItem(tree, location);
                    if (treeItemFound != null) {
                        if (location.equalsIgnoreCase(ConfigSection.SECTION_PLUGINS)) {
                            // Force ordering by name here.
                            int position = findInsertPointFor(section_name, treeItemFound);
                            if (position == -1) {
                                treeItem = new TreeItem(treeItemFound, SWT.NULL);
                            } else {
                                treeItem = new TreeItem(treeItemFound, SWT.NULL, position);
                            }
                        } else {
                            treeItem = new TreeItem(treeItemFound, SWT.NULL);
                        }
                    } else {
                        treeItem = new TreeItem(tree, SWT.NULL);
                    }
                }
                ScrolledComposite sc = new ScrolledComposite(cConfigSection, SWT.H_SCROLL | SWT.V_SCROLL);
                sc.setExpandHorizontal(true);
                sc.setExpandVertical(true);
                Utils.setLayoutData(sc, new GridData(GridData.FILL_BOTH));
                sc.getVerticalBar().setIncrement(16);
                sc.addListener(SWT.Resize, scResizeListener);
                if (i == 0) {
                    Composite c = ((UISWTConfigSection) section).configSectionCreate(sc);
                    sectionsCreated.add(section);
                    sc.setContent(c);
                }
                Messages.setLanguageText(treeItem, section_key);
                treeItem.setData("Panel", sc);
                treeItem.setData("ID", name);
                treeItem.setData("ConfigSectionSWT", section);
                sections.put(treeItem, section);
                // PluginConfigModel config pages
                if (section instanceof ConfigSectionPlugins)
                    ((ConfigSectionPlugins) section).initPluginSubSections();
            } catch (Exception e) {
                Logger.log(new LogEvent(LOGID, "ConfigSection plugin '" + name + "' caused an error", e));
            }
        }
    }
    final Display d = composite.getDisplay();
    final Listener shortcut_listener = new Listener() {

        @Override
        public void handleEvent(Event e) {
            if ((e.stateMask & (SWT.MOD1 | SWT.CONTROL)) != 0 || e.keyCode == SWT.COMMAND) {
                char key = e.character;
                if (key <= 26 && key > 0) {
                    key += 'a' - 1;
                }
                if ((e.stateMask & SWT.SHIFT) != 0) {
                    key = Character.toUpperCase(key);
                }
                if (!Character.isISOControl(key)) {
                    for (TreeItem ti : sections.keySet()) {
                        if (ti.isDisposed()) {
                            continue;
                        }
                        String id = (String) ti.getData("ID");
                        if (id != null) {
                            String shortcut = COConfigurationManager.getStringParameter("config.section.shortcut.key." + id, "");
                            if (shortcut.equals(String.valueOf(key))) {
                                // findFocus( cConfig );
                                selectSection(id, true);
                                e.doit = false;
                                break;
                            }
                        }
                    }
                }
            }
        }
    };
    d.addFilter(SWT.KeyDown, shortcut_listener);
    cConfigSection.addDisposeListener(new DisposeListener() {

        @Override
        public void widgetDisposed(DisposeEvent e) {
            d.removeFilter(SWT.KeyDown, shortcut_listener);
        }
    });
    if (composite instanceof Shell) {
        initApplyCloseButton();
    } else {
        initSaveButton();
    }
    if (startSection != null) {
        if (selectSection(startSection, false)) {
            return;
        }
    }
    TreeItem selection = getLatestSelection();
    TreeItem[] items = { selection };
    tree.setSelection(items);
    // setSelection doesn't trigger a SelectionListener, so..
    showSection(selection, false);
}
Also used : LinkLabel(com.biglybt.ui.swt.components.LinkLabel) ConfigSection(com.biglybt.pif.ui.config.ConfigSection) ScrolledComposite(org.eclipse.swt.custom.ScrolledComposite) LogEvent(com.biglybt.core.logging.LogEvent) UIInputReceiver(com.biglybt.pif.ui.UIInputReceiver) UIInputReceiverListener(com.biglybt.pif.ui.UIInputReceiverListener) CoreRunningListener(com.biglybt.core.CoreRunningListener) SimpleTextEntryWindow(com.biglybt.ui.swt.SimpleTextEntryWindow) StackLayout(org.eclipse.swt.custom.StackLayout) ScrolledComposite(org.eclipse.swt.custom.ScrolledComposite) MessageText(com.biglybt.core.internat.MessageText) SashForm(org.eclipse.swt.custom.SashForm) LogEvent(com.biglybt.core.logging.LogEvent) UIInputReceiverListener(com.biglybt.pif.ui.UIInputReceiverListener) ImageLoader(com.biglybt.ui.swt.imageloader.ImageLoader)

Aggregations

UIInputReceiver (com.biglybt.pif.ui.UIInputReceiver)29 UIInputReceiverListener (com.biglybt.pif.ui.UIInputReceiverListener)29 SimpleTextEntryWindow (com.biglybt.ui.swt.SimpleTextEntryWindow)21 DownloadManager (com.biglybt.core.download.DownloadManager)8 UserPrompterResultListener (com.biglybt.ui.UserPrompterResultListener)8 CoreRunningListener (com.biglybt.core.CoreRunningListener)7 MenuItemListener (com.biglybt.pif.ui.menus.MenuItemListener)6 TrackerEditorListener (com.biglybt.ui.swt.maketorrent.TrackerEditorListener)6 DisposeEvent (org.eclipse.swt.events.DisposeEvent)6 DisposeListener (org.eclipse.swt.events.DisposeListener)6 MessageBoxShell (com.biglybt.ui.swt.shells.MessageBoxShell)5 List (java.util.List)5 SelectionEvent (org.eclipse.swt.events.SelectionEvent)4 UIManagerListener (com.biglybt.pif.ui.UIManagerListener)3 MenuBuildUtils (com.biglybt.ui.swt.MenuBuildUtils)3 Core (com.biglybt.core.Core)2 MessageText (com.biglybt.core.internat.MessageText)2 PEPeer (com.biglybt.core.peer.PEPeer)2 PEPeerManager (com.biglybt.core.peer.PEPeerManager)2 TagProperty (com.biglybt.core.tag.TagFeatureProperties.TagProperty)2