Search in sources :

Example 16 with UserPrompterResultListener

use of com.biglybt.ui.UserPrompterResultListener in project BiglyBT by BiglySoftware.

the class BuddyPluginViewBetaChat method buildSupport2.

private void buildSupport2(Composite parent) {
    boolean public_chat = !chat.isPrivateChat();
    if (chat.getViewType() == BuddyPluginBeta.VIEW_TYPE_DEFAULT || chat.isReadOnly()) {
        GridLayout layout = new GridLayout();
        layout.numColumns = 2;
        layout.marginHeight = 0;
        layout.marginWidth = 0;
        parent.setLayout(layout);
        GridData grid_data = new GridData(GridData.FILL_BOTH);
        Utils.setLayoutData(parent, grid_data);
        Composite sash_area = new Composite(parent, SWT.NONE);
        layout = new GridLayout();
        layout.numColumns = 1;
        layout.marginHeight = 0;
        layout.marginWidth = 0;
        sash_area.setLayout(layout);
        grid_data = new GridData(GridData.FILL_BOTH);
        grid_data.horizontalSpan = 2;
        Utils.setLayoutData(sash_area, grid_data);
        final SashForm sash = new SashForm(sash_area, SWT.HORIZONTAL);
        grid_data = new GridData(GridData.FILL_BOTH);
        Utils.setLayoutData(sash, grid_data);
        final Composite lhs = new Composite(sash, SWT.NONE);
        layout = new GridLayout();
        layout.numColumns = 2;
        layout.marginHeight = 0;
        layout.marginWidth = 0;
        layout.marginTop = 4;
        layout.marginLeft = 4;
        lhs.setLayout(layout);
        grid_data = new GridData(GridData.FILL_BOTH);
        grid_data.widthHint = 300;
        Utils.setLayoutData(lhs, grid_data);
        buildStatus(parent, lhs);
        Composite log_holder = buildFTUX(lhs, SWT.BORDER);
        // LOG panel
        layout = new GridLayout();
        layout.numColumns = 1;
        layout.marginHeight = 0;
        layout.marginWidth = 0;
        layout.marginLeft = 4;
        log_holder.setLayout(layout);
        // grid_data = new GridData(GridData.FILL_BOTH );
        // grid_data.horizontalSpan = 2;
        // Utils.setLayoutData(log_holder, grid_data);
        log = new StyledText(log_holder, SWT.READ_ONLY | SWT.V_SCROLL | SWT.WRAP | SWT.NO_FOCUS);
        grid_data = new GridData(GridData.FILL_BOTH);
        grid_data.horizontalSpan = 1;
        // grid_data.horizontalIndent = 4;
        Utils.setLayoutData(log, grid_data);
        // log.setIndent( 4 );
        log.setEditable(false);
        log_holder.setBackground(log.getBackground());
        final Menu log_menu = new Menu(log);
        log.setMenu(log_menu);
        log.addMenuDetectListener(new MenuDetectListener() {

            @Override
            public void menuDetected(MenuDetectEvent e) {
                e.doit = false;
                boolean handled = false;
                for (MenuItem mi : log_menu.getItems()) {
                    mi.dispose();
                }
                try {
                    Point mapped = log.getDisplay().map(null, log, new Point(e.x, e.y));
                    int offset = log.getOffsetAtLocation(mapped);
                    final StyleRange sr = log.getStyleRangeAtOffset(offset);
                    if (sr != null) {
                        Object data = sr.data;
                        if (data instanceof ChatParticipant) {
                            ChatParticipant cp = (ChatParticipant) data;
                            List<ChatParticipant> cps = new ArrayList<>();
                            cps.add(cp);
                            buildParticipantMenu(log_menu, cps);
                            handled = true;
                        } else if (data instanceof String) {
                            String url_str = (String) sr.data;
                            String str = url_str;
                            if (str.length() > 50) {
                                str = str.substring(0, 50) + "...";
                            }
                            if (chat.isAnonymous() && url_str.toLowerCase(Locale.US).startsWith("magnet:")) {
                                String[] magnet_uri = { url_str };
                                Set<String> networks = UrlUtils.extractNetworks(magnet_uri);
                                String i2p_only_uri = magnet_uri[0] + "&net=" + UrlUtils.encode(AENetworkClassifier.AT_I2P);
                                String i2p_only_str = i2p_only_uri;
                                if (i2p_only_str.length() > 50) {
                                    i2p_only_str = i2p_only_str.substring(0, 50) + "...";
                                }
                                i2p_only_str = lu.getLocalisedMessageText("azbuddy.dchat.open.i2p.magnet") + ": " + i2p_only_str;
                                final MenuItem mi_open_i2p_vuze = new MenuItem(log_menu, SWT.PUSH);
                                mi_open_i2p_vuze.setText(i2p_only_str);
                                mi_open_i2p_vuze.setData(i2p_only_uri);
                                mi_open_i2p_vuze.addSelectionListener(new SelectionAdapter() {

                                    @Override
                                    public void widgetSelected(SelectionEvent e) {
                                        String url_str = (String) mi_open_i2p_vuze.getData();
                                        if (url_str != null) {
                                            TorrentOpener.openTorrent(url_str);
                                        }
                                    }
                                });
                                if (networks.size() == 1 && networks.iterator().next() == AENetworkClassifier.AT_I2P) {
                                // already done above
                                } else {
                                    str = lu.getLocalisedMessageText("azbuddy.dchat.open.magnet") + ": " + str;
                                    final MenuItem mi_open_vuze = new MenuItem(log_menu, SWT.PUSH);
                                    mi_open_vuze.setText(str);
                                    mi_open_vuze.setData(url_str);
                                    mi_open_vuze.addSelectionListener(new SelectionAdapter() {

                                        @Override
                                        public void widgetSelected(SelectionEvent e) {
                                            String url_str = (String) mi_open_vuze.getData();
                                            if (url_str != null) {
                                                TorrentOpener.openTorrent(url_str);
                                            }
                                        }
                                    });
                                }
                            } else {
                                str = lu.getLocalisedMessageText("azbuddy.dchat.open.in.vuze") + ": " + str;
                                final MenuItem mi_open_vuze = new MenuItem(log_menu, SWT.PUSH);
                                mi_open_vuze.setText(str);
                                mi_open_vuze.setData(url_str);
                                mi_open_vuze.addSelectionListener(new SelectionAdapter() {

                                    @Override
                                    public void widgetSelected(SelectionEvent e) {
                                        String url_str = (String) mi_open_vuze.getData();
                                        if (url_str != null) {
                                            String lc_url_str = url_str.toLowerCase(Locale.US);
                                            if (lc_url_str.startsWith("chat:")) {
                                                try {
                                                    beta.handleURI(url_str, true);
                                                } catch (Throwable f) {
                                                    Debug.out(f);
                                                }
                                            } else {
                                                TorrentOpener.openTorrent(url_str);
                                            }
                                        }
                                    }
                                });
                            }
                            final MenuItem mi_open_ext = new MenuItem(log_menu, SWT.PUSH);
                            mi_open_ext.setText(lu.getLocalisedMessageText("azbuddy.dchat.open.in.browser"));
                            mi_open_ext.addSelectionListener(new SelectionAdapter() {

                                @Override
                                public void widgetSelected(SelectionEvent e) {
                                    String url_str = (String) mi_open_ext.getData();
                                    Utils.launch(url_str);
                                }
                            });
                            new MenuItem(log_menu, SWT.SEPARATOR);
                            if (chat.isAnonymous() && url_str.toLowerCase(Locale.US).startsWith("magnet:")) {
                                String[] magnet_uri = { url_str };
                                Set<String> networks = UrlUtils.extractNetworks(magnet_uri);
                                String i2p_only_uri = magnet_uri[0] + "&net=" + UrlUtils.encode(AENetworkClassifier.AT_I2P);
                                final MenuItem mi_copy_i2p_clip = new MenuItem(log_menu, SWT.PUSH);
                                mi_copy_i2p_clip.setText(lu.getLocalisedMessageText("azbuddy.dchat.copy.i2p.magnet"));
                                mi_copy_i2p_clip.setData(i2p_only_uri);
                                mi_copy_i2p_clip.addSelectionListener(new SelectionAdapter() {

                                    @Override
                                    public void widgetSelected(SelectionEvent e) {
                                        String url_str = (String) mi_copy_i2p_clip.getData();
                                        if (url_str != null) {
                                            ClipboardCopy.copyToClipBoard(url_str);
                                        }
                                    }
                                });
                                if (networks.size() == 1 && networks.iterator().next() == AENetworkClassifier.AT_I2P) {
                                // already done above
                                } else {
                                    final MenuItem mi_copy_clip = new MenuItem(log_menu, SWT.PUSH);
                                    mi_copy_clip.setText(lu.getLocalisedMessageText("azbuddy.dchat.copy.magnet"));
                                    mi_copy_clip.setData(url_str);
                                    mi_copy_clip.addSelectionListener(new SelectionAdapter() {

                                        @Override
                                        public void widgetSelected(SelectionEvent e) {
                                            String url_str = (String) mi_copy_clip.getData();
                                            if (url_str != null) {
                                                ClipboardCopy.copyToClipBoard(url_str);
                                            }
                                        }
                                    });
                                }
                            } else {
                                final MenuItem mi_copy_clip = new MenuItem(log_menu, SWT.PUSH);
                                mi_copy_clip.setText(lu.getLocalisedMessageText("label.copy.to.clipboard"));
                                mi_copy_clip.setData(url_str);
                                mi_copy_clip.addSelectionListener(new SelectionAdapter() {

                                    @Override
                                    public void widgetSelected(SelectionEvent e) {
                                        String url_str = (String) mi_copy_clip.getData();
                                        if (url_str != null) {
                                            ClipboardCopy.copyToClipBoard(url_str);
                                        }
                                    }
                                });
                            }
                            if (url_str.toLowerCase().startsWith("http")) {
                                mi_open_ext.setData(url_str);
                                mi_open_ext.setEnabled(true);
                            } else {
                                mi_open_ext.setEnabled(false);
                            }
                            handled = true;
                        } else {
                            if (Constants.isCVSVersion()) {
                                if (sr instanceof MyStyleRange) {
                                    final MyStyleRange msr = (MyStyleRange) sr;
                                    MenuItem item = new MenuItem(log_menu, SWT.NONE);
                                    item.setText(MessageText.getString("label.copy.to.clipboard"));
                                    item.addSelectionListener(new SelectionAdapter() {

                                        @Override
                                        public void widgetSelected(SelectionEvent e) {
                                            ClipboardCopy.copyToClipBoard(msr.message.getMessage());
                                        }
                                    });
                                    handled = true;
                                }
                            }
                        }
                    }
                } catch (Throwable f) {
                }
                if (!handled) {
                    final String text = log.getSelectionText();
                    if (text != null && text.length() > 0) {
                        MenuItem item = new MenuItem(log_menu, SWT.NONE);
                        item.setText(MessageText.getString("label.copy.to.clipboard"));
                        item.addSelectionListener(new SelectionAdapter() {

                            @Override
                            public void widgetSelected(SelectionEvent e) {
                                ClipboardCopy.copyToClipBoard(text);
                            }
                        });
                        handled = true;
                    }
                }
                if (handled) {
                    e.doit = true;
                }
            }
        });
        log.addListener(SWT.MouseDoubleClick, new Listener() {

            @Override
            public void handleEvent(Event e) {
                try {
                    final int offset = log.getOffsetAtLocation(new Point(e.x, e.y));
                    for (int i = 0; i < log_styles.length; i++) {
                        StyleRange sr = log_styles[i];
                        Object data = sr.data;
                        if (data != null && offset >= sr.start && offset < sr.start + sr.length) {
                            boolean anon_chat = chat.isAnonymous();
                            if (data instanceof String) {
                                final String url_str = (String) data;
                                String lc_url_str = url_str.toLowerCase(Locale.US);
                                if (lc_url_str.startsWith("chat:")) {
                                    if (anon_chat && !lc_url_str.startsWith("chat:anon:")) {
                                        return;
                                    }
                                    try {
                                        beta.handleURI(url_str, true);
                                    } catch (Throwable f) {
                                        Debug.out(f);
                                    }
                                } else {
                                    if (anon_chat) {
                                        try {
                                            String host = new URL(lc_url_str).getHost();
                                            if (AENetworkClassifier.categoriseAddress(host) == AENetworkClassifier.AT_PUBLIC) {
                                                return;
                                            }
                                        } catch (Throwable f) {
                                            return;
                                        }
                                    }
                                    if (lc_url_str.contains(".torrent") || UrlUtils.parseTextForMagnets(url_str) != null) {
                                        TorrentOpener.openTorrent(url_str);
                                    } else {
                                        if (url_str.toLowerCase(Locale.US).startsWith("http")) {
                                            // without this backoff we end up with the text widget
                                            // being left in a 'mouse down' state when returning to it :(
                                            Utils.execSWTThreadLater(100, new Runnable() {

                                                @Override
                                                public void run() {
                                                    Utils.launch(url_str);
                                                }
                                            });
                                        } else {
                                            TorrentOpener.openTorrent(url_str);
                                        }
                                    }
                                }
                                log.setSelection(offset);
                                e.doit = false;
                            } else if (data instanceof ChatParticipant) {
                                ChatParticipant participant = (ChatParticipant) data;
                                addNickString(participant);
                            }
                        }
                    }
                } catch (Throwable f) {
                }
            }
        });
        log.addMouseTrackListener(new MouseTrackListener() {

            private StyleRange old_range;

            private StyleRange temp_range;

            private int temp_index;

            @Override
            public void mouseHover(MouseEvent e) {
                boolean active = false;
                try {
                    int offset = log.getOffsetAtLocation(new Point(e.x, e.y));
                    for (int i = 0; i < log_styles.length; i++) {
                        StyleRange sr = log_styles[i];
                        Object data = sr.data;
                        if (data != null && offset >= sr.start && offset < sr.start + sr.length) {
                            if (old_range != null) {
                                if (temp_index < log_styles.length && log_styles[temp_index] == temp_range) {
                                    log_styles[temp_index] = old_range;
                                    old_range = null;
                                }
                            }
                            sr = log_styles[i];
                            String tt_extra = "";
                            if (data instanceof String) {
                                try {
                                    URL url = new URL((String) data);
                                    String query = url.getQuery();
                                    if (query != null) {
                                        String[] bits = query.split("&");
                                        int seeds = -1;
                                        int leechers = -1;
                                        for (String bit : bits) {
                                            String[] temp = bit.split("=");
                                            String lhs = temp[0];
                                            if (lhs.equals("_s")) {
                                                seeds = Integer.parseInt(temp[1]);
                                            } else if (lhs.equals("_l")) {
                                                leechers = Integer.parseInt(temp[1]);
                                            }
                                        }
                                        if (seeds != -1 && leechers != -1) {
                                            tt_extra = ": seeds=" + seeds + ", leechers=" + leechers;
                                        }
                                    }
                                } catch (Throwable f) {
                                }
                            }
                            log.setToolTipText(MessageText.getString("label.right.click.for.options") + tt_extra);
                            StyleRange derp;
                            if (sr instanceof MyStyleRange) {
                                derp = new MyStyleRange((MyStyleRange) sr);
                            } else {
                                derp = new StyleRange(sr);
                            }
                            derp.start = sr.start;
                            derp.length = sr.length;
                            derp.borderStyle = SWT.BORDER_DASH;
                            old_range = sr;
                            temp_range = derp;
                            temp_index = i;
                            log_styles[i] = derp;
                            log.setStyleRanges(log_styles);
                            active = true;
                            break;
                        }
                    }
                } catch (Throwable f) {
                }
                if (!active) {
                    log.setToolTipText("");
                    if (old_range != null) {
                        if (temp_index < log_styles.length && log_styles[temp_index] == temp_range) {
                            log_styles[temp_index] = old_range;
                            old_range = null;
                            log.setStyleRanges(log_styles);
                        }
                    }
                }
            }

            @Override
            public void mouseExit(MouseEvent e) {
            // TODO Auto-generated method stub
            }

            @Override
            public void mouseEnter(MouseEvent e) {
            // TODO Auto-generated method stub
            }
        });
        log.addKeyListener(new KeyAdapter() {

            @Override
            public void keyPressed(KeyEvent event) {
                int key = event.character;
                if (key <= 26 && key > 0) {
                    key += 'a' - 1;
                }
                if (key == 'a' && event.stateMask == SWT.MOD1) {
                    event.doit = false;
                    log.selectAll();
                }
            }
        });
        Composite rhs = new Composite(sash, SWT.NONE);
        layout = new GridLayout();
        layout.numColumns = 1;
        layout.marginHeight = 0;
        layout.marginWidth = 0;
        layout.marginTop = 4;
        layout.marginRight = 4;
        rhs.setLayout(layout);
        grid_data = new GridData(GridData.FILL_VERTICAL);
        int rhs_width = Constants.isWindows ? 150 : 160;
        grid_data.widthHint = rhs_width;
        Utils.setLayoutData(rhs, grid_data);
        // options
        Composite top_right = buildHelp(rhs);
        // nick name
        Composite nick_area = new Composite(top_right, SWT.NONE);
        layout = new GridLayout();
        layout.numColumns = 4;
        layout.marginHeight = 0;
        layout.marginWidth = 0;
        if (!Constants.isWindows) {
            layout.horizontalSpacing = 2;
            layout.verticalSpacing = 2;
        }
        nick_area.setLayout(layout);
        grid_data = new GridData(GridData.FILL_HORIZONTAL);
        grid_data.horizontalSpan = 3;
        Utils.setLayoutData(nick_area, grid_data);
        Label label = new Label(nick_area, SWT.NULL);
        label.setText(lu.getLocalisedMessageText("azbuddy.dchat.nick"));
        grid_data = new GridData();
        // grid_data.horizontalIndent=4;
        Utils.setLayoutData(label, grid_data);
        nickname = new Text(nick_area, SWT.BORDER);
        grid_data = new GridData(GridData.FILL_HORIZONTAL);
        grid_data.horizontalSpan = 1;
        Utils.setLayoutData(nickname, grid_data);
        nickname.setText(chat.getNickname(false));
        nickname.setMessage(chat.getDefaultNickname());
        label = new Label(nick_area, SWT.NULL);
        label.setText(lu.getLocalisedMessageText("label.shared"));
        label.setToolTipText(lu.getLocalisedMessageText("azbuddy.dchat.shared.tooltip"));
        shared_nick_button = new Button(nick_area, SWT.CHECK);
        shared_nick_button.setSelection(chat.isSharedNickname());
        shared_nick_button.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent arg0) {
                boolean shared = shared_nick_button.getSelection();
                chat.setSharedNickname(shared);
            }
        });
        nickname.addListener(SWT.FocusOut, new Listener() {

            @Override
            public void handleEvent(Event event) {
                String nick = nickname.getText().trim();
                if (chat.isSharedNickname()) {
                    if (chat.getNetwork() == AENetworkClassifier.AT_PUBLIC) {
                        beta.setSharedPublicNickname(nick);
                    } else {
                        beta.setSharedAnonNickname(nick);
                    }
                } else {
                    chat.setInstanceNickname(nick);
                }
            }
        });
        table_header_left = new BufferedLabel(top_right, SWT.DOUBLE_BUFFERED);
        grid_data = new GridData(GridData.FILL_HORIZONTAL);
        grid_data.horizontalSpan = 2;
        if (!Constants.isWindows) {
            grid_data.horizontalIndent = 2;
        }
        Utils.setLayoutData(table_header_left, grid_data);
        table_header_left.setText(MessageText.getString("PeersView.state.pending"));
        LinkLabel link = new LinkLabel(top_right, "Views.plugins.azbuddy.title", new Runnable() {

            @Override
            public void run() {
                if (!plugin.isClassicEnabled()) {
                    plugin.setClassicEnabled(true);
                }
                beta.selectClassicTab();
            }
        });
        // table
        buddy_table = new Table(rhs, SWT.MULTI | SWT.BORDER | SWT.FULL_SELECTION | SWT.VIRTUAL);
        String[] headers = { "azbuddy.ui.table.name" };
        int[] sizes = { rhs_width - 10 };
        int[] aligns = { SWT.LEFT };
        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);
        grid_data = new GridData(GridData.FILL_BOTH);
        // grid_data.heightHint = buddy_table.getHeaderHeight() * 3;
        Utils.setLayoutData(buddy_table, grid_data);
        buddy_table.addListener(SWT.SetData, new Listener() {

            @Override
            public void handleEvent(Event event) {
                TableItem item = (TableItem) event.item;
                setItemData(item);
            }
        });
        final Menu menu = new Menu(buddy_table);
        buddy_table.setMenu(menu);
        menu.addMenuListener(new MenuListener() {

            @Override
            public void menuShown(MenuEvent e) {
                MenuItem[] items = menu.getItems();
                for (int i = 0; i < items.length; i++) {
                    items[i].dispose();
                }
                final TableItem[] selection = buddy_table.getSelection();
                List<ChatParticipant> participants = new ArrayList<>(selection.length);
                for (int i = 0; i < selection.length; i++) {
                    TableItem item = selection[i];
                    ChatParticipant participant = (ChatParticipant) item.getData();
                    if (participant == null) {
                        // item data won't be set yet for items that haven't been
                        // visible...
                        participant = setItemData(item);
                    }
                    if (participant != null) {
                        participants.add(participant);
                    }
                }
                buildParticipantMenu(menu, participants);
            }

            @Override
            public void menuHidden(MenuEvent e) {
            }
        });
        buddy_table.addKeyListener(new KeyAdapter() {

            @Override
            public void keyPressed(KeyEvent event) {
                int key = event.character;
                if (key <= 26 && key > 0) {
                    key += 'a' - 1;
                }
                if (key == 'a' && event.stateMask == SWT.MOD1) {
                    event.doit = false;
                    buddy_table.selectAll();
                }
            }
        });
        buddy_table.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseDoubleClick(MouseEvent e) {
                TableItem[] selection = buddy_table.getSelection();
                if (selection.length != 1) {
                    return;
                }
                TableItem item = selection[0];
                ChatParticipant participant = (ChatParticipant) item.getData();
                addNickString(participant);
            }
        });
        Utils.maintainSashPanelWidth(sash, rhs, new int[] { 700, 300 }, "azbuddy.dchat.ui.sash.pos");
        /*
		    Listener sash_listener=
		    	new Listener()
		    	{
		    		private int	lhs_weight;
		    		private int	lhs_width;
	
			    	public void
					handleEvent(
						Event ev )
					{
			    		if ( ev.widget == lhs ){
	
			    			int[] weights = sash.getWeights();
	
	
			    			if ( lhs_weight != weights[0] ){
	
			    					// sash has moved
	
			    				lhs_weight = weights[0];
	
			    					// keep track of the width
	
			    				lhs_width = lhs.getBounds().width;
			    			}
			    		}else{
	
			    				// resize
	
			    			if ( lhs_width > 0 ){
	
					            int width = sash.getClientArea().width;
	
					            double ratio = (double)lhs_width/width;
	
					            lhs_weight = (int)(ratio*1000 );
	
					            sash.setWeights( new int[]{ lhs_weight, 1000 - lhs_weight });
			    			}
			    		}
				    }
			    };
	
		    lhs.addListener(SWT.Resize, sash_listener );
		    sash.addListener(SWT.Resize, sash_listener );
		    */
        // bottom area
        Composite bottom_area = new Composite(parent, SWT.NULL);
        layout = new GridLayout();
        layout.numColumns = 2;
        layout.marginHeight = 0;
        layout.marginWidth = 0;
        bottom_area.setLayout(layout);
        grid_data = new GridData(GridData.FILL_HORIZONTAL);
        grid_data.horizontalSpan = 2;
        bottom_area.setLayoutData(grid_data);
        // Text
        input_area = new Text(bottom_area, SWT.MULTI | SWT.V_SCROLL | SWT.WRAP | SWT.BORDER);
        grid_data = new GridData(GridData.FILL_HORIZONTAL);
        grid_data.horizontalSpan = 1;
        grid_data.heightHint = 30;
        grid_data.horizontalIndent = 4;
        Utils.setLayoutData(input_area, grid_data);
        // input_area.setIndent( 4 );
        input_area.setTextLimit(MAX_MSG_OVERALL_LENGTH);
        input_area.addVerifyListener(new VerifyListener() {

            @Override
            public void verifyText(VerifyEvent ev) {
                if (ev.text.equals("\t")) {
                    ev.doit = false;
                }
            }
        });
        input_area.addKeyListener(new KeyListener() {

            private LinkedList<String> history = new LinkedList<>();

            private int history_pos = -1;

            private String buffered_message = "";

            @Override
            public void keyPressed(KeyEvent e) {
                if (e.keyCode == SWT.CR || e.keyCode == SWT.KEYPAD_CR) {
                    e.doit = false;
                    if ((e.stateMask & SWT.ALT) != 0) {
                        input_area.insert("\n");
                        return;
                    }
                    String message = input_area.getText().trim();
                    if (message.length() > 0) {
                        sendMessage(message, true);
                        history.addFirst(message);
                        if (history.size() > 32) {
                            history.removeLast();
                        }
                        history_pos = -1;
                        buffered_message = "";
                        input_area.setText("");
                        text_cache.put(chat.getNetAndKey(), "");
                    }
                } else if (e.keyCode == SWT.ARROW_UP) {
                    history_pos++;
                    if (history_pos < history.size()) {
                        if (history_pos == 0) {
                            buffered_message = input_area.getText().trim();
                        }
                        String msg = history.get(history_pos);
                        input_area.setText(msg);
                        input_area.setSelection(msg.length());
                    } else {
                        history_pos = history.size() - 1;
                    }
                    e.doit = false;
                } else if (e.keyCode == SWT.ARROW_DOWN) {
                    history_pos--;
                    if (history_pos >= 0) {
                        String msg = history.get(history_pos);
                        input_area.setText(msg);
                        input_area.setSelection(msg.length());
                    } else {
                        if (history_pos == -1) {
                            input_area.setText(buffered_message);
                            if (buffered_message.length() > 0) {
                                input_area.setSelection(buffered_message.length());
                                buffered_message = "";
                            }
                        } else {
                            history_pos = -1;
                        }
                    }
                    e.doit = false;
                } else {
                    if (e.stateMask == SWT.MOD1) {
                        int key = e.character;
                        if (key <= 26 && key > 0) {
                            key += 'a' - 1;
                        }
                        if (key == 'a') {
                            input_area.selectAll();
                        } else if (key == 'b' || key == 'i') {
                            String emp = key == 'b' ? "**" : "*";
                            String sel = input_area.getSelectionText();
                            Point p = input_area.getSelection();
                            while (sel.endsWith(" ")) {
                                sel = sel.substring(0, sel.length() - 1);
                                p.y--;
                            }
                            if (!sel.isEmpty()) {
                                /*
										int[] range = input_area.getSelectionRanges();
										
										int emp_len = emp.length();
										
										if ( sel.startsWith( emp ) && sel.endsWith( emp ) && sel.length() >= emp_len * 2 ){
											
											input_area.replaceTextRange( range[0], range[1], sel.substring(emp_len, sel.length() - emp_len ));
											
											input_area.setSelection( range[0], range[0] + range[1] - emp_len*2 );
											
										}else{
											
											input_area.replaceTextRange( range[0], range[1], emp + sel + emp );
											
											input_area.setSelection( range[0], range[0] + range[1] + emp_len*2 );
										}
										*/
                                int emp_len = emp.length();
                                String text = input_area.getText();
                                if (sel.startsWith(emp) && sel.endsWith(emp) && sel.length() >= emp_len * 2) {
                                    input_area.setText(text.substring(0, p.x) + sel.substring(emp_len, sel.length() - emp_len) + text.substring(p.y));
                                    p.y -= emp_len * 2;
                                } else {
                                    input_area.setText(text.substring(0, p.x) + emp + sel + emp + text.substring(p.y));
                                    p.y += emp_len * 2;
                                }
                                input_area.setSelection(p);
                            }
                        }
                    }
                }
            }

            @Override
            public void keyReleased(KeyEvent e) {
            }
        });
        input_area.addDisposeListener(new DisposeListener() {

            @Override
            public void widgetDisposed(DisposeEvent arg0) {
                if (input_area != null) {
                    String text = input_area.getText();
                    text_cache.put(chat.getNetAndKey(), text);
                }
            }
        });
        String cached_text = text_cache.get(chat.getNetAndKey());
        if (cached_text != null && !cached_text.isEmpty()) {
            input_area.setText(cached_text);
            input_area.setSelection(cached_text.length());
        }
        Composite button_area = new Composite(bottom_area, SWT.NULL);
        layout = new GridLayout();
        layout.numColumns = 1;
        layout.marginHeight = 0;
        layout.marginWidth = 0;
        layout.marginRight = 4;
        button_area.setLayout(layout);
        buildRSSButton(button_area);
        hookFTUXListener();
        if (chat.isReadOnly()) {
            input_area.setText(MessageText.getString("azbuddy.dchat.ro"));
        }
        setInputAvailability(true);
        if (!chat.isReadOnly()) {
            drop_targets = new DropTarget[] { new DropTarget(log, DND.DROP_COPY), new DropTarget(input_area, DND.DROP_COPY) };
            for (DropTarget drop_target : drop_targets) {
                drop_target.setTransfer(new Transfer[] { FixedURLTransfer.getInstance(), FileTransfer.getInstance(), TextTransfer.getInstance() });
                drop_target.addDropListener(new DropTargetAdapter() {

                    @Override
                    public void dropAccept(DropTargetEvent event) {
                        event.currentDataType = FixedURLTransfer.pickBestType(event.dataTypes, event.currentDataType);
                    }

                    @Override
                    public void dragEnter(DropTargetEvent event) {
                    }

                    @Override
                    public void dragOperationChanged(DropTargetEvent event) {
                    }

                    @Override
                    public void dragOver(DropTargetEvent event) {
                        if ((event.operations & DND.DROP_LINK) > 0)
                            event.detail = DND.DROP_LINK;
                        else if ((event.operations & DND.DROP_COPY) > 0)
                            event.detail = DND.DROP_COPY;
                        else if ((event.operations & DND.DROP_DEFAULT) > 0)
                            event.detail = DND.DROP_COPY;
                        event.feedback = DND.FEEDBACK_SELECT | DND.FEEDBACK_SCROLL | DND.FEEDBACK_EXPAND;
                    }

                    @Override
                    public void dragLeave(DropTargetEvent event) {
                    }

                    @Override
                    public void drop(DropTargetEvent event) {
                        handleDrop(event.data, new DropAccepter() {

                            @Override
                            public void accept(String link) {
                                input_area.setText(input_area.getText() + link);
                            }
                        });
                    }
                });
            }
        }
        Control[] focus_controls = { log, input_area, buddy_table, nickname, shared_nick_button };
        Listener focus_listener = new Listener() {

            @Override
            public void handleEvent(Event event) {
                activate();
            }
        };
        for (Control c : focus_controls) {
            c.addListener(SWT.FocusIn, focus_listener);
        }
        BuddyPluginBeta.ChatParticipant[] existing_participants = chat.getParticipants();
        synchronized (participants) {
            participants.addAll(Arrays.asList(existing_participants));
        }
        table_resort_required = true;
        updateTable(false);
        BuddyPluginBeta.ChatMessage[] history = chat.getHistory();
        logChatMessages(history);
        boolean can_popout = shell == null && public_chat;
        if (can_popout && !ftux_ok && !auto_ftux_popout_done) {
            auto_ftux_popout_done = true;
            try {
                createChatWindow(view, plugin, chat.getClone(), true);
            } catch (Throwable e) {
            }
        }
    } else {
        GridLayout layout = new GridLayout();
        layout.numColumns = 2;
        layout.marginHeight = 0;
        layout.marginWidth = 0;
        parent.setLayout(layout);
        GridData grid_data = new GridData(GridData.FILL_BOTH);
        Utils.setLayoutData(parent, grid_data);
        Composite status_area = new Composite(parent, SWT.NULL);
        grid_data = new GridData(GridData.FILL_HORIZONTAL);
        status_area.setLayoutData(grid_data);
        layout = new GridLayout();
        layout.numColumns = 3;
        layout.marginHeight = 0;
        layout.marginWidth = 0;
        layout.marginTop = 4;
        layout.marginLeft = 4;
        status_area.setLayout(layout);
        buildStatus(parent, status_area);
        buildHelp(status_area);
        Composite ftux_parent = new Composite(parent, SWT.NULL);
        layout = new GridLayout();
        layout.numColumns = 2;
        layout.marginHeight = 0;
        layout.marginWidth = 0;
        ftux_parent.setLayout(layout);
        grid_data = new GridData(GridData.FILL_BOTH);
        grid_data.horizontalSpan = 2;
        ftux_parent.setLayoutData(grid_data);
        Composite share_area_holder = buildFTUX(ftux_parent, SWT.NULL);
        layout = new GridLayout();
        layout.numColumns = 1;
        layout.marginHeight = 0;
        layout.marginWidth = 0;
        share_area_holder.setLayout(layout);
        Canvas share_area = new Canvas(share_area_holder, SWT.NO_BACKGROUND);
        grid_data = new GridData(GridData.FILL_BOTH);
        share_area.setLayoutData(grid_data);
        share_area.setBackground(Colors.white);
        share_area.addPaintListener(new PaintListener() {

            @Override
            public void paintControl(PaintEvent e) {
                GC gc = e.gc;
                gc.setAdvanced(true);
                gc.setAntialias(SWT.ON);
                Rectangle bounds = share_area.getBounds();
                int width = bounds.width;
                int height = bounds.height;
                gc.setBackground(Colors.white);
                gc.fillRectangle(0, 0, width, height);
                Rectangle text_area = new Rectangle(50, 50, width - 100, height - 100);
                gc.setLineWidth(8);
                gc.setLineStyle(SWT.LINE_DOT);
                gc.setForeground(Colors.light_grey);
                gc.drawRoundRectangle(40, 40, width - 80, height - 80, 25, 25);
                gc.setForeground(Colors.dark_grey);
                gc.setFont(big_font);
                String msg = MessageText.getString("dchat.share.dnd.info", new String[] { MessageText.getString(chat.getNetwork() == AENetworkClassifier.AT_PUBLIC ? "label.publicly" : "label.anonymously"), chat.getName() });
                GCStringPrinter p = new GCStringPrinter(gc, msg, text_area, 0, SWT.CENTER | SWT.WRAP);
                p.printString();
            }
        });
        input_area = new Text(share_area, SWT.MULTI | SWT.V_SCROLL | SWT.WRAP | SWT.BORDER);
        input_area.setVisible(false);
        hookFTUXListener();
        drop_targets = new DropTarget[] { new DropTarget(share_area, DND.DROP_COPY) };
        for (DropTarget drop_target : drop_targets) {
            drop_target.setTransfer(new Transfer[] { FixedURLTransfer.getInstance(), FileTransfer.getInstance(), TextTransfer.getInstance() });
            drop_target.addDropListener(new DropTargetAdapter() {

                @Override
                public void dropAccept(DropTargetEvent event) {
                    event.currentDataType = FixedURLTransfer.pickBestType(event.dataTypes, event.currentDataType);
                }

                @Override
                public void dragEnter(DropTargetEvent event) {
                }

                @Override
                public void dragOperationChanged(DropTargetEvent event) {
                }

                @Override
                public void dragOver(DropTargetEvent event) {
                    if ((event.operations & DND.DROP_LINK) > 0)
                        event.detail = DND.DROP_LINK;
                    else if ((event.operations & DND.DROP_COPY) > 0)
                        event.detail = DND.DROP_COPY;
                    else if ((event.operations & DND.DROP_DEFAULT) > 0)
                        event.detail = DND.DROP_COPY;
                    event.feedback = DND.FEEDBACK_SELECT | DND.FEEDBACK_SCROLL | DND.FEEDBACK_EXPAND;
                }

                @Override
                public void dragLeave(DropTargetEvent event) {
                }

                @Override
                public void drop(DropTargetEvent event) {
                    if (!chat_available) {
                        MessageBoxShell mb = new MessageBoxShell(MessageText.getString("dchat.share.dnd.wait.title"), MessageText.getString("dchat.share.dnd.wait.text"));
                        mb.setButtons(0, new String[] { MessageText.getString("Button.ok") }, new Integer[] { 0 });
                        mb.open(null);
                        return;
                    }
                    MessageBoxShell mb = new MessageBoxShell(MessageText.getString("dchat.share.dnd.prompt.title"), MessageText.getString("dchat.share.dnd.prompt.text", new String[] { MessageText.getString(chat.getNetwork() == AENetworkClassifier.AT_PUBLIC ? "label.publicly" : "label.anonymously"), chat.getName() }));
                    mb.setRemember("chat.dnd." + chat.getKey(), false, MessageText.getString("MessageBoxWindow.nomoreprompting"));
                    mb.setButtons(0, new String[] { MessageText.getString("Button.yes"), MessageText.getString("Button.no") }, new Integer[] { 0, 1 });
                    mb.setRememberOnlyIfButton(0);
                    mb.open(new UserPrompterResultListener() {

                        @Override
                        public void prompterClosed(int result) {
                            if (result == 0) {
                                handleDrop(event.data, new DropAccepter() {

                                    @Override
                                    public void accept(String link) {
                                        link = link.trim();
                                        sendMessage(link, false);
                                        String rendered = renderMessage(link);
                                        MessageBoxShell mb = new MessageBoxShell(MessageText.getString("dchat.share.dnd.shared.title"), MessageText.getString("dchat.share.dnd.shared.text", new String[] { rendered }));
                                        mb.setButtons(0, new String[] { MessageText.getString("Button.ok") }, new Integer[] { 0 });
                                        mb.open(null);
                                        checkSubscriptions(false);
                                    }
                                });
                            }
                        }
                    });
                }
            });
        }
    }
}
Also used : GCStringPrinter(com.biglybt.ui.swt.shells.GCStringPrinter) MouseTrackListener(org.eclipse.swt.events.MouseTrackListener) KeyAdapter(org.eclipse.swt.events.KeyAdapter) TableItem(org.eclipse.swt.widgets.TableItem) BufferedLabel(com.biglybt.ui.swt.components.BufferedLabel) Label(org.eclipse.swt.widgets.Label) LinkLabel(com.biglybt.ui.swt.components.LinkLabel) Rectangle(org.eclipse.swt.graphics.Rectangle) DisposeEvent(org.eclipse.swt.events.DisposeEvent) Button(org.eclipse.swt.widgets.Button) SelectionEvent(org.eclipse.swt.events.SelectionEvent) StyledText(org.eclipse.swt.custom.StyledText) VerifyListener(org.eclipse.swt.events.VerifyListener) PaintListener(org.eclipse.swt.events.PaintListener) Canvas(org.eclipse.swt.widgets.Canvas) DropTargetEvent(org.eclipse.swt.dnd.DropTargetEvent) TableColumn(org.eclipse.swt.widgets.TableColumn) DropTargetAdapter(org.eclipse.swt.dnd.DropTargetAdapter) MenuDetectEvent(org.eclipse.swt.events.MenuDetectEvent) DropTarget(org.eclipse.swt.dnd.DropTarget) DisposeListener(org.eclipse.swt.events.DisposeListener) UserPrompterResultListener(com.biglybt.ui.UserPrompterResultListener) PaintListener(org.eclipse.swt.events.PaintListener) ControlListener(org.eclipse.swt.events.ControlListener) Listener(org.eclipse.swt.widgets.Listener) UIInputReceiverListener(com.biglybt.pif.ui.UIInputReceiverListener) DisposeListener(org.eclipse.swt.events.DisposeListener) VerifyListener(org.eclipse.swt.events.VerifyListener) MouseTrackListener(org.eclipse.swt.events.MouseTrackListener) MenuListener(org.eclipse.swt.events.MenuListener) MenuDetectListener(org.eclipse.swt.events.MenuDetectListener) KeyListener(org.eclipse.swt.events.KeyListener) BufferedLabel(com.biglybt.ui.swt.components.BufferedLabel) MenuListener(org.eclipse.swt.events.MenuListener) StyleRange(org.eclipse.swt.custom.StyleRange) URL(java.net.URL) KeyEvent(org.eclipse.swt.events.KeyEvent) GridLayout(org.eclipse.swt.layout.GridLayout) Control(org.eclipse.swt.widgets.Control) Menu(org.eclipse.swt.widgets.Menu) GC(org.eclipse.swt.graphics.GC) VerifyEvent(org.eclipse.swt.events.VerifyEvent) MenuEvent(org.eclipse.swt.events.MenuEvent) MouseEvent(org.eclipse.swt.events.MouseEvent) Table(org.eclipse.swt.widgets.Table) PaintEvent(org.eclipse.swt.events.PaintEvent) Composite(org.eclipse.swt.widgets.Composite) SelectionAdapter(org.eclipse.swt.events.SelectionAdapter) MouseAdapter(org.eclipse.swt.events.MouseAdapter) MessageBoxShell(com.biglybt.ui.swt.shells.MessageBoxShell) MenuItem(org.eclipse.swt.widgets.MenuItem) StyledText(org.eclipse.swt.custom.StyledText) Text(org.eclipse.swt.widgets.Text) MessageText(com.biglybt.core.internat.MessageText) Point(org.eclipse.swt.graphics.Point) Point(org.eclipse.swt.graphics.Point) SashForm(org.eclipse.swt.custom.SashForm) UserPrompterResultListener(com.biglybt.ui.UserPrompterResultListener) LinkLabel(com.biglybt.ui.swt.components.LinkLabel) AERunnable(com.biglybt.core.util.AERunnable) GridData(org.eclipse.swt.layout.GridData) MenuDetectListener(org.eclipse.swt.events.MenuDetectListener) DropTargetEvent(org.eclipse.swt.dnd.DropTargetEvent) MenuEvent(org.eclipse.swt.events.MenuEvent) KeyEvent(org.eclipse.swt.events.KeyEvent) MouseEvent(org.eclipse.swt.events.MouseEvent) MenuDetectEvent(org.eclipse.swt.events.MenuDetectEvent) ControlEvent(org.eclipse.swt.events.ControlEvent) DisposeEvent(org.eclipse.swt.events.DisposeEvent) PaintEvent(org.eclipse.swt.events.PaintEvent) UIManagerEvent(com.biglybt.pif.ui.UIManagerEvent) Event(org.eclipse.swt.widgets.Event) VerifyEvent(org.eclipse.swt.events.VerifyEvent) SelectionEvent(org.eclipse.swt.events.SelectionEvent) KeyListener(org.eclipse.swt.events.KeyListener)

Example 17 with UserPrompterResultListener

use of com.biglybt.ui.UserPrompterResultListener 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 18 with UserPrompterResultListener

use of com.biglybt.ui.UserPrompterResultListener in project BiglyBT by BiglySoftware.

the class SBC_ChatOverview method initTable.

private void initTable(Composite control) {
    if (tv == null) {
        tv = TableViewFactory.createTableViewSWT(ChatInstance.class, TABLE_CHAT, TABLE_CHAT, new TableColumnCore[0], ColumnChatName.COLUMN_ID, SWT.MULTI | SWT.FULL_SELECTION | SWT.VIRTUAL);
        if (txtFilter != null) {
            tv.enableFilterCheck(txtFilter, this);
        }
        tv.setRowDefaultHeightEM(1);
        table_parent = new Composite(control, SWT.BORDER);
        table_parent.setLayoutData(Utils.getFilledFormData());
        GridLayout layout = new GridLayout();
        layout.marginHeight = layout.marginWidth = layout.verticalSpacing = layout.horizontalSpacing = 0;
        table_parent.setLayout(layout);
        tv.addMenuFillListener(this);
        tv.addSelectionListener(this, false);
        tv.addKeyListener(new KeyAdapter() {

            @Override
            public void keyPressed(KeyEvent e) {
                if (e.stateMask == 0 && e.keyCode == SWT.DEL) {
                    Object[] datasources = tv.getSelectedDataSources().toArray();
                    if (datasources.length > 0) {
                        List<ChatInstance> chats = new ArrayList<>();
                        String str = "";
                        for (Object object : datasources) {
                            if (object instanceof ChatInstance) {
                                ChatInstance chat = (ChatInstance) object;
                                chats.add(chat);
                                if (chats.size() == 1) {
                                    str = chat.getDisplayName();
                                    if (str == null) {
                                        str = chat.getName();
                                    }
                                } else if (chats.size() == 2) {
                                    str += ", ...";
                                }
                            }
                        }
                        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 (ChatInstance chat : chats) {
                                        chat.remove();
                                    }
                                }
                            }
                        });
                    }
                    e.doit = false;
                }
            }
        });
        tv.initialize(table_parent);
    }
    control.layout(true);
}
Also used : Composite(org.eclipse.swt.widgets.Composite) KeyAdapter(org.eclipse.swt.events.KeyAdapter) MessageBoxShell(com.biglybt.ui.swt.shells.MessageBoxShell) TableColumnCore(com.biglybt.ui.common.table.TableColumnCore) KeyEvent(org.eclipse.swt.events.KeyEvent) GridLayout(org.eclipse.swt.layout.GridLayout) UserPrompterResultListener(com.biglybt.ui.UserPrompterResultListener) List(java.util.List) ArrayList(java.util.ArrayList) SWTSkinObject(com.biglybt.ui.swt.skin.SWTSkinObject)

Example 19 with UserPrompterResultListener

use of com.biglybt.ui.UserPrompterResultListener in project BiglyBT by BiglySoftware.

the class ConfigSectionBackupRestore method configSectionCreate.

@Override
public Composite configSectionCreate(final Composite parent) {
    ImageLoader imageLoader = ImageLoader.getInstance();
    Image imgOpenFolder = imageLoader.getImage("openFolderButton");
    GridData gridData;
    GridLayout layout;
    final Composite cBR = new Composite(parent, SWT.NULL);
    gridData = new GridData(GridData.VERTICAL_ALIGN_FILL | GridData.HORIZONTAL_ALIGN_FILL);
    cBR.setLayoutData(gridData);
    layout = new GridLayout();
    layout.numColumns = 1;
    cBR.setLayout(layout);
    Label info_label = new Label(cBR, SWT.WRAP);
    Messages.setLanguageText(info_label, "ConfigView.section.br.overview");
    gridData = Utils.getWrappableLabelGridData(1, GridData.HORIZONTAL_ALIGN_FILL);
    info_label.setLayoutData(gridData);
    // wiki link
    final Label linkLabel = new Label(cBR, SWT.NULL);
    linkLabel.setText(MessageText.getString("ConfigView.label.please.visit.here"));
    linkLabel.setData(Constants.URL_WIKI + "w/Backup_And_Restore");
    linkLabel.setCursor(linkLabel.getDisplay().getSystemCursor(SWT.CURSOR_HAND));
    linkLabel.setForeground(Colors.blue);
    gridData = Utils.getWrappableLabelGridData(1, 0);
    linkLabel.setLayoutData(gridData);
    linkLabel.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseDoubleClick(MouseEvent arg0) {
            Utils.launch((String) ((Label) arg0.widget).getData());
        }

        @Override
        public void mouseDown(MouseEvent arg0) {
            Utils.launch((String) ((Label) arg0.widget).getData());
        }
    });
    ClipboardCopy.addCopyToClipMenu(linkLabel);
    final BackupManager backup_manager = BackupManagerFactory.getManager(CoreFactory.getSingleton());
    // backup
    Group gBackup = new Group(cBR, SWT.NULL);
    Messages.setLanguageText(gBackup, "br.backup");
    layout = new GridLayout(2, false);
    gBackup.setLayout(layout);
    gBackup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    // info
    Label last_backup_label = new Label(gBackup, SWT.NULL);
    Messages.setLanguageText(last_backup_label, "br.backup.last.time");
    final Label last_backup_time = new Label(gBackup, SWT.NULL);
    Label last_backup_error_label = new Label(gBackup, SWT.NULL);
    Messages.setLanguageText(last_backup_error_label, "br.backup.last.error");
    final Label last_backup_error = new Label(gBackup, SWT.NULL);
    final Runnable stats_updater = new Runnable() {

        @Override
        public void run() {
            long backup_time = backup_manager.getLastBackupTime();
            last_backup_time.setText(backup_time == 0 ? "" : String.valueOf(new Date(backup_time)));
            last_backup_error.setText(backup_manager.getLastBackupError());
        }
    };
    stats_updater.run();
    // manual button
    Label backup_manual_label = new Label(gBackup, SWT.NULL);
    Messages.setLanguageText(backup_manual_label, "br.backup.manual.info");
    Button backup_button = new Button(gBackup, SWT.PUSH);
    Messages.setLanguageText(backup_button, "br.backup");
    backup_button.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            String def_dir = COConfigurationManager.getStringParameter("br.backup.folder.default");
            DirectoryDialog dialog = new DirectoryDialog(parent.getShell(), SWT.APPLICATION_MODAL);
            if (def_dir != null) {
                dialog.setFilterPath(def_dir);
            }
            dialog.setMessage(MessageText.getString("br.backup.folder.info"));
            dialog.setText(MessageText.getString("br.backup.folder.title"));
            String path = dialog.open();
            if (path != null) {
                COConfigurationManager.setParameter("br.backup.folder.default", path);
                runBackup(backup_manager, path, stats_updater);
            }
        }
    });
    final BooleanParameter auto_backup_enable = new BooleanParameter(gBackup, "br.backup.auto.enable", "br.backup.auto.enable");
    gridData = new GridData();
    gridData.horizontalSpan = 2;
    auto_backup_enable.setLayoutData(gridData);
    Composite gDefaultDir = new Composite(gBackup, SWT.NONE);
    layout = new GridLayout();
    layout.numColumns = 3;
    layout.marginHeight = 2;
    gDefaultDir.setLayout(layout);
    gridData = new GridData(GridData.FILL_HORIZONTAL);
    gridData.horizontalSpan = 2;
    gDefaultDir.setLayoutData(gridData);
    Label lblDefaultDir = new Label(gDefaultDir, SWT.NONE);
    Messages.setLanguageText(lblDefaultDir, "ConfigView.section.file.defaultdir.ask");
    lblDefaultDir.setLayoutData(new GridData());
    gridData = new GridData(GridData.FILL_HORIZONTAL);
    final StringParameter pathParameter = new StringParameter(gDefaultDir, "br.backup.auto.dir", "");
    pathParameter.setLayoutData(gridData);
    if (pathParameter.getValue().length() == 0) {
        String def_dir = COConfigurationManager.getStringParameter("br.backup.folder.default");
        pathParameter.setValue(def_dir);
    }
    Button browse = new Button(gDefaultDir, SWT.PUSH);
    browse.setImage(imgOpenFolder);
    imgOpenFolder.setBackground(browse.getBackground());
    browse.setToolTipText(MessageText.getString("ConfigView.button.browse"));
    browse.addListener(SWT.Selection, new Listener() {

        /* (non-Javadoc)
			 * @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event)
			 */
        @Override
        public void handleEvent(Event event) {
            DirectoryDialog dialog = new DirectoryDialog(parent.getShell(), SWT.APPLICATION_MODAL);
            dialog.setFilterPath(pathParameter.getValue());
            dialog.setMessage(MessageText.getString("br.backup.auto.dir.select"));
            dialog.setText(MessageText.getString("ConfigView.section.file.defaultdir.ask"));
            String path = dialog.open();
            if (path != null) {
                pathParameter.setValue(path);
                COConfigurationManager.setParameter("br.backup.folder.default", path);
            }
        }
    });
    Composite gPeriod = new Composite(gDefaultDir, SWT.NONE);
    layout = new GridLayout();
    layout.numColumns = 6;
    layout.marginLeft = 0;
    layout.marginHeight = 0;
    layout.marginWidth = 0;
    layout.marginTop = 0;
    layout.marginBottom = 0;
    gPeriod.setLayout(layout);
    gridData = new GridData(GridData.FILL_HORIZONTAL);
    gridData.horizontalSpan = 3;
    gPeriod.setLayoutData(gridData);
    Label lbl_backup_days = new Label(gPeriod, SWT.NULL);
    Messages.setLanguageText(lbl_backup_days, "br.backup.auto.everydays");
    IntParameter backup_everydays = new IntParameter(gPeriod, "br.backup.auto.everydays", 0, Integer.MAX_VALUE);
    gridData = new GridData();
    gridData.horizontalSpan = 2;
    backup_everydays.setLayoutData(gridData);
    Label lbl_backup_hours = new Label(gPeriod, SWT.NULL);
    Messages.setLanguageText(lbl_backup_hours, "br.backup.auto.everyhours");
    IntParameter backup_everyhours = new IntParameter(gPeriod, "br.backup.auto.everyhours", 1, Integer.MAX_VALUE);
    gridData = new GridData();
    gridData.horizontalSpan = 2;
    backup_everyhours.setLayoutData(gridData);
    // for whatever reason if you set enable synchronously it gets reset :(
    Utils.execSWTThreadLater(1, new Runnable() {

        public void run() {
            backup_everyhours.setEnabled(backup_everydays.getValue() == 0);
        }
    });
    backup_everydays.addChangeListener(new ParameterChangeAdapter() {

        @Override
        public void parameterChanged(Parameter p, boolean caused_internally) {
            backup_everyhours.setEnabled(backup_everydays.getValue() == 0);
        }
    });
    Label lbl_backup_retain = new Label(gDefaultDir, SWT.NULL);
    Messages.setLanguageText(lbl_backup_retain, "br.backup.auto.retain");
    IntParameter backup_retain = new IntParameter(gDefaultDir, "br.backup.auto.retain", 1, Integer.MAX_VALUE);
    gridData = new GridData();
    gridData.horizontalSpan = 2;
    backup_retain.setLayoutData(gridData);
    BooleanParameter chkNotify = new BooleanParameter(gDefaultDir, "br.backup.notify", "br.backup.notify");
    gridData = new GridData(GridData.FILL_HORIZONTAL);
    gridData.horizontalSpan = 3;
    chkNotify.setLayoutData(gridData);
    Label backup_auto_label = new Label(gDefaultDir, SWT.NULL);
    Messages.setLanguageText(backup_auto_label, "br.backup.auto.now");
    Button backup_auto_button = new Button(gDefaultDir, SWT.PUSH);
    Messages.setLanguageText(backup_auto_button, "br.test");
    backup_auto_button.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            runBackup(backup_manager, null, stats_updater);
        }
    });
    auto_backup_enable.setAdditionalActionPerformer(new ChangeSelectionActionPerformer(gDefaultDir));
    // restore
    Group gRestore = new Group(cBR, SWT.NULL);
    Messages.setLanguageText(gRestore, "br.restore");
    layout = new GridLayout(2, false);
    gRestore.setLayout(layout);
    gRestore.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    Label restore_label = new Label(gRestore, SWT.NULL);
    Messages.setLanguageText(restore_label, "br.restore.info");
    Button restore_button = new Button(gRestore, SWT.PUSH);
    Messages.setLanguageText(restore_button, "br.restore");
    restore_button.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            String def_dir = COConfigurationManager.getStringParameter("br.backup.folder.default");
            DirectoryDialog dialog = new DirectoryDialog(parent.getShell(), SWT.APPLICATION_MODAL);
            if (def_dir != null) {
                dialog.setFilterPath(def_dir);
            }
            dialog.setMessage(MessageText.getString("br.restore.folder.info"));
            dialog.setText(MessageText.getString("br.restore.folder.title"));
            final String path = dialog.open();
            if (path != null) {
                MessageBoxShell mb = new MessageBoxShell(SWT.ICON_WARNING | SWT.OK | SWT.CANCEL, MessageText.getString("br.restore.warning.title"), MessageText.getString("br.restore.warning.info"));
                mb.setDefaultButtonUsingStyle(SWT.CANCEL);
                mb.setParent(parent.getShell());
                mb.open(new UserPrompterResultListener() {

                    @Override
                    public void prompterClosed(int returnVal) {
                        if (returnVal != SWT.OK) {
                            return;
                        }
                        final TextViewerWindow viewer = new TextViewerWindow(MessageText.getString("br.backup.progress"), null, "", true, true);
                        viewer.setEditable(false);
                        viewer.setOKEnabled(false);
                        backup_manager.restore(new File(path), new BackupManager.BackupListener() {

                            @Override
                            public boolean reportProgress(String str) {
                                return (append(str, false));
                            }

                            @Override
                            public void reportComplete() {
                                append("Restore Complete!", true);
                                Utils.execSWTThread(new AERunnable() {

                                    @Override
                                    public void runSupport() {
                                        MessageBoxShell mb = new MessageBoxShell(SWT.ICON_INFORMATION | SWT.OK, MessageText.getString("ConfigView.section.security.restart.title"), MessageText.getString("ConfigView.section.security.restart.msg"));
                                        mb.setParent(parent.getShell());
                                        mb.open(new UserPrompterResultListener() {

                                            @Override
                                            public void prompterClosed(int returnVal) {
                                                UIFunctionsSWT uiFunctions = UIFunctionsManagerSWT.getUIFunctionsSWT();
                                                if (uiFunctions != null) {
                                                    uiFunctions.dispose(true, false);
                                                }
                                            }
                                        });
                                    }
                                });
                            }

                            @Override
                            public void reportError(Throwable error) {
                                append("Restore Failed: " + Debug.getNestedExceptionMessage(error), true);
                            }

                            private boolean append(final String str, final boolean complete) {
                                if (viewer.isDisposed()) {
                                    return (false);
                                }
                                Utils.execSWTThread(new AERunnable() {

                                    @Override
                                    public void runSupport() {
                                        if (str.endsWith("...")) {
                                            viewer.append(str);
                                        } else {
                                            viewer.append(str + "\r\n");
                                        }
                                        if (complete) {
                                            viewer.setOKEnabled(true);
                                        }
                                    }
                                });
                                return (true);
                            }
                        });
                        viewer.goModal();
                    }
                });
            }
        }
    });
    return (cBR);
}
Also used : AERunnable(com.biglybt.core.util.AERunnable) ParameterChangeListener(com.biglybt.ui.swt.config.ParameterChangeListener) UserPrompterResultListener(com.biglybt.ui.UserPrompterResultListener) Image(org.eclipse.swt.graphics.Image) GridLayout(org.eclipse.swt.layout.GridLayout) TextViewerWindow(com.biglybt.ui.swt.TextViewerWindow) StringParameter(com.biglybt.ui.swt.config.StringParameter) MouseEvent(org.eclipse.swt.events.MouseEvent) MouseAdapter(org.eclipse.swt.events.MouseAdapter) ParameterChangeAdapter(com.biglybt.ui.swt.config.ParameterChangeAdapter) MessageBoxShell(com.biglybt.ui.swt.shells.MessageBoxShell) UIFunctionsSWT(com.biglybt.ui.swt.UIFunctionsSWT) BackupManager(com.biglybt.core.backup.BackupManager) BooleanParameter(com.biglybt.ui.swt.config.BooleanParameter) Date(java.util.Date) UserPrompterResultListener(com.biglybt.ui.UserPrompterResultListener) AERunnable(com.biglybt.core.util.AERunnable) GridData(org.eclipse.swt.layout.GridData) MouseEvent(org.eclipse.swt.events.MouseEvent) BooleanParameter(com.biglybt.ui.swt.config.BooleanParameter) StringParameter(com.biglybt.ui.swt.config.StringParameter) IntParameter(com.biglybt.ui.swt.config.IntParameter) Parameter(com.biglybt.ui.swt.config.Parameter) ChangeSelectionActionPerformer(com.biglybt.ui.swt.config.ChangeSelectionActionPerformer) ImageLoader(com.biglybt.ui.swt.imageloader.ImageLoader) File(java.io.File) IntParameter(com.biglybt.ui.swt.config.IntParameter)

Example 20 with UserPrompterResultListener

use of com.biglybt.ui.UserPrompterResultListener in project BiglyBT by BiglySoftware.

the class ConfigureWizard method onClose.

@Override
public void onClose() {
    try {
        if (!completed && wizard_mode != WIZARD_MODE_SPEED_TEST_AUTO && !COConfigurationManager.getBooleanParameter("Wizard Completed")) {
            MessageBoxShell mb = new MessageBoxShell(MessageText.getString("wizard.close.confirmation"), MessageText.getString("wizard.close.message"), new String[] { MessageText.getString("Button.yes"), MessageText.getString("Button.no") }, 0);
            mb.open(new UserPrompterResultListener() {

                @Override
                public void prompterClosed(int result) {
                    if (result == 1) {
                        COConfigurationManager.setParameter("Wizard Completed", true);
                        COConfigurationManager.save();
                    }
                }
            });
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    super.onClose();
}
Also used : UserPrompterResultListener(com.biglybt.ui.UserPrompterResultListener) MessageBoxShell(com.biglybt.ui.swt.shells.MessageBoxShell)

Aggregations

UserPrompterResultListener (com.biglybt.ui.UserPrompterResultListener)32 MessageBoxShell (com.biglybt.ui.swt.shells.MessageBoxShell)25 GridLayout (org.eclipse.swt.layout.GridLayout)6 UIInputReceiverListener (com.biglybt.pif.ui.UIInputReceiverListener)5 ArrayList (java.util.ArrayList)5 GridData (org.eclipse.swt.layout.GridData)5 SWTSkin (com.biglybt.ui.swt.skin.SWTSkin)4 SWTSkinObjectContainer (com.biglybt.ui.swt.skin.SWTSkinObjectContainer)4 List (java.util.List)4 MouseAdapter (org.eclipse.swt.events.MouseAdapter)4 MouseEvent (org.eclipse.swt.events.MouseEvent)4 Composite (org.eclipse.swt.widgets.Composite)4 AERunnable (com.biglybt.core.util.AERunnable)3 UIInputReceiver (com.biglybt.pif.ui.UIInputReceiver)3 UIManagerEvent (com.biglybt.pif.ui.UIManagerEvent)3 UIFunctionsSWT (com.biglybt.ui.swt.UIFunctionsSWT)3 ImageLoader (com.biglybt.ui.swt.imageloader.ImageLoader)3 VuzeMessageBox (com.biglybt.ui.swt.views.skin.VuzeMessageBox)3 VuzeMessageBoxListener (com.biglybt.ui.swt.views.skin.VuzeMessageBoxListener)3 File (java.io.File)3