Search in sources :

Example 16 with AEThread2

use of com.biglybt.core.util.AEThread2 in project BiglyBT by BiglySoftware.

the class ConfigSectionLogging method configSectionCreate.

@Override
public Composite configSectionCreate(final Composite parent) {
    ImageLoader imageLoader = ImageLoader.getInstance();
    Image imgOpenFolder = imageLoader.getImage("openFolderButton");
    GridData gridData;
    GridLayout layout;
    Composite gLogging = new Composite(parent, SWT.NULL);
    gridData = new GridData(GridData.VERTICAL_ALIGN_FILL | GridData.HORIZONTAL_ALIGN_FILL);
    Utils.setLayoutData(gLogging, gridData);
    layout = new GridLayout();
    layout.numColumns = 2;
    gLogging.setLayout(layout);
    int userMode = COConfigurationManager.getIntParameter("User Mode");
    BooleanParameter enable_logger = new BooleanParameter(gLogging, "Logger.Enabled", "ConfigView.section.logging.loggerenable");
    gridData = new GridData();
    gridData.horizontalSpan = 2;
    enable_logger.setLayoutData(gridData);
    // row
    final BooleanParameter enableLogging = new BooleanParameter(gLogging, "Logging Enable", "ConfigView.section.logging.enable");
    gridData = new GridData();
    gridData.horizontalSpan = 2;
    enableLogging.setLayoutData(gridData);
    Composite cArea = new Composite(gLogging, SWT.NULL);
    layout = new GridLayout();
    layout.marginHeight = 0;
    layout.marginWidth = 0;
    layout.numColumns = 3;
    cArea.setLayout(layout);
    gridData = new GridData(GridData.FILL_HORIZONTAL);
    gridData.horizontalSpan = 2;
    cArea.setLayoutData(gridData);
    // row
    Label lStatsPath = new Label(cArea, SWT.NULL);
    // $NON-NLS-1$
    Messages.setLanguageText(lStatsPath, "ConfigView.section.logging.logdir");
    gridData = new GridData();
    gridData.widthHint = 150;
    // $NON-NLS-1$ //$NON-NLS-2$
    final StringParameter pathParameter = new StringParameter(cArea, "Logging Dir");
    pathParameter.setLayoutData(gridData);
    Button browse = new Button(cArea, 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());
            // $NON-NLS-1$
            dialog.setText(MessageText.getString("ConfigView.section.logging.choosedefaultsavepath"));
            String path = dialog.open();
            if (path != null) {
                pathParameter.setValue(path);
            }
        }
    });
    Label lMaxLog = new Label(cArea, SWT.NULL);
    Messages.setLanguageText(lMaxLog, "ConfigView.section.logging.maxsize");
    final String[] lmLabels = new String[logFileSizes.length];
    final int[] lmValues = new int[logFileSizes.length];
    for (int i = 0; i < logFileSizes.length; i++) {
        int num = logFileSizes[i];
        lmLabels[i] = " " + num + " MB";
        lmValues[i] = num;
    }
    IntListParameter paramMaxSize = new IntListParameter(cArea, "Logging Max Size", lmLabels, lmValues);
    gridData = new GridData();
    gridData.horizontalSpan = 2;
    paramMaxSize.setLayoutData(gridData);
    if (userMode > 1) {
        Label timeStampLbl = new Label(cArea, SWT.NULL);
        Messages.setLanguageText(timeStampLbl, "ConfigView.section.logging.timestamp");
        Utils.setLayoutData(timeStampLbl, new GridData());
        StringParameter timeStamp = new StringParameter(cArea, "Logging Timestamp");
        gridData = new GridData();
        gridData.horizontalSpan = 2;
        gridData.widthHint = 150;
        timeStamp.setLayoutData(gridData);
    }
    /**
     * FileLogging filter, consisting of a List of types (info, warning, error)
     * and a checkbox Table of component IDs.
     */
    final String sFilterPrefix = "ConfigView.section.logging.filter";
    Group gLogIDs = new Group(gLogging, SWT.NULL);
    Messages.setLanguageText(gLogIDs, sFilterPrefix);
    layout = new GridLayout();
    layout.numColumns = 2;
    gLogIDs.setLayout(layout);
    gridData = new GridData(SWT.BEGINNING, SWT.BEGINNING, true, true);
    gridData.horizontalSpan = 2;
    Utils.setLayoutData(gLogIDs, gridData);
    final List listLogTypes = new List(gLogIDs, SWT.BORDER | SWT.SINGLE | SWT.V_SCROLL);
    gridData = new GridData(SWT.NULL, SWT.BEGINNING, false, false);
    listLogTypes.setLayoutData(gridData);
    final int[] logTypes = { LogEvent.LT_INFORMATION, LogEvent.LT_WARNING, LogEvent.LT_ERROR };
    for (int i = 0; i < logTypes.length; i++) listLogTypes.add(MessageText.getString("ConfigView.section.logging.log" + i + "type"));
    listLogTypes.select(0);
    final LogIDs[] logIDs = FileLogging.configurableLOGIDs;
    // Arrays.sort(logIDs);
    final Table tableLogIDs = new Table(gLogIDs, SWT.CHECK | SWT.BORDER | SWT.SINGLE | SWT.FULL_SELECTION);
    gridData = new GridData(GridData.FILL_BOTH);
    tableLogIDs.setLayoutData(gridData);
    tableLogIDs.setLinesVisible(false);
    tableLogIDs.setHeaderVisible(false);
    TableColumn column = new TableColumn(tableLogIDs, SWT.NONE);
    for (int i = 0; i < logIDs.length; i++) {
        TableItem item = new TableItem(tableLogIDs, SWT.NULL);
        item.setText(0, MessageText.getString(sFilterPrefix + "." + logIDs[i], logIDs[i].toString()));
        item.setData(logIDs[i]);
        boolean checked = COConfigurationManager.getBooleanParameter("bLog." + logTypes[0] + "." + logIDs[i], true);
        item.setChecked(checked);
    }
    column.pack();
    // Update table when list selection changes
    listLogTypes.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            int index = listLogTypes.getSelectionIndex();
            if (index < 0 || index >= logTypes.length)
                return;
            TableItem[] items = tableLogIDs.getItems();
            for (int i = 0; i < items.length; i++) {
                boolean checked = COConfigurationManager.getBooleanParameter("bLog." + logTypes[index] + "." + items[i].getData(), true);
                items[i].setChecked(checked);
            }
        }
    });
    // Save config when checkbox is clicked
    tableLogIDs.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            if (e.detail != SWT.CHECK)
                return;
            int index = listLogTypes.getSelectionIndex();
            if (index < 0 || index >= logTypes.length)
                return;
            TableItem item = (TableItem) e.item;
            COConfigurationManager.setParameter("bLog." + logTypes[index] + "." + item.getData(), item.getChecked());
        }
    });
    final Control[] controls_main = { cArea, gLogIDs };
    final ChangeSelectionActionPerformer perf2 = new ChangeSelectionActionPerformer(controls_main);
    enableLogging.setAdditionalActionPerformer(perf2);
    enable_logger.setAdditionalActionPerformer(new IAdditionalActionPerformer() {

        ChangeSelectionActionPerformer p1 = new ChangeSelectionActionPerformer(new Control[] { enableLogging.getControl() });

        @Override
        public void performAction() {
            p1.performAction();
        }

        @Override
        public void setSelected(boolean selected) {
            p1.setSelected(selected);
            if (!selected && enableLogging.isSelected())
                enableLogging.setSelected(false);
        }

        @Override
        public void setIntValue(int value) {
        /*nothing*/
        }

        @Override
        public void setStringValue(String value) {
        /*nothing*/
        }
    });
    if (userMode > 0) {
        Composite cDebugFiles = new Composite(gLogging, SWT.NULL);
        layout = new GridLayout();
        layout.marginHeight = 0;
        layout.marginWidth = 0;
        layout.numColumns = 3;
        cDebugFiles.setLayout(layout);
        gridData = new GridData(GridData.FILL_HORIZONTAL);
        gridData.horizontalSpan = 2;
        cDebugFiles.setLayoutData(gridData);
        Label l_debug_file_size = new Label(cDebugFiles, SWT.NULL);
        Messages.setLanguageText(l_debug_file_size, "ConfigView.section.logging.debugfilesize");
        l_debug_file_size.setLayoutData(new GridData());
        new IntParameter(cDebugFiles, "Logger.DebugFiles.SizeKB", 10, Integer.MAX_VALUE);
        new Label(cDebugFiles, SWT.NULL).setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    }
    if (userMode > 1) {
        // advanced option
        Group cAO = new Group(gLogging, SWT.NULL);
        cAO.setText(MessageText.getString("dht.advanced.group"));
        layout = new GridLayout();
        layout.marginHeight = 0;
        layout.marginWidth = 0;
        layout.numColumns = 5;
        cAO.setLayout(layout);
        gridData = new GridData(GridData.FILL_HORIZONTAL);
        gridData.horizontalSpan = 2;
        cAO.setLayoutData(gridData);
        // name
        Label aoName = new Label(cAO, SWT.NULL);
        Messages.setLanguageText(aoName, "label.name");
        aoName.setLayoutData(new GridData());
        final StringParameter name = new StringParameter(cAO, "Advanced Option Name");
        gridData = new GridData();
        gridData.widthHint = 150;
        name.setLayoutData(gridData);
        // value
        Label aoValue = new Label(cAO, SWT.NULL);
        Messages.setLanguageText(aoValue, "label.value");
        aoName.setLayoutData(new GridData());
        final StringParameter value = new StringParameter(cAO, "Advanced Option Value");
        gridData = new GridData();
        gridData.widthHint = 150;
        value.setLayoutData(gridData);
        // set
        Button set_option = new Button(cAO, SWT.PUSH);
        Messages.setLanguageText(set_option, "Button.set");
        set_option.addListener(SWT.Selection, new Listener() {

            @Override
            public void handleEvent(Event event) {
                String key = name.getValue().trim();
                if ((key.startsWith("'") && key.endsWith("'")) || (key.startsWith("\"") && key.endsWith("\""))) {
                    key = key.substring(1, key.length() - 1);
                }
                if (key.length() > 0) {
                    if (key.startsWith("!")) {
                        key = key.substring(1);
                    } else {
                        key = "adv.setting." + key;
                    }
                    String val = value.getValue().trim();
                    boolean is_string = false;
                    if ((val.startsWith("'") && val.endsWith("'")) || (val.startsWith("\"") && val.endsWith("\""))) {
                        val = val.substring(1, val.length() - 1);
                        is_string = true;
                    }
                    if (val.length() == 0) {
                        COConfigurationManager.removeParameter(key);
                    } else {
                        if (is_string) {
                            COConfigurationManager.setParameter(key, val);
                        } else {
                            String lc_val = val.toLowerCase(Locale.US);
                            if (lc_val.equals("false") || lc_val.equals("true")) {
                                COConfigurationManager.setParameter(key, lc_val.startsWith("t"));
                            } else {
                                try {
                                    long l = Long.parseLong(val);
                                    COConfigurationManager.setParameter(key, l);
                                } catch (Throwable e) {
                                    COConfigurationManager.setParameter(key, val);
                                }
                            }
                        }
                    }
                    COConfigurationManager.save();
                }
            }
        });
    }
    // network diagnostics
    Label generate_net_info = new Label(gLogging, SWT.NULL);
    Messages.setLanguageText(generate_net_info, "ConfigView.section.logging.netinfo");
    Button generate_net_button = new Button(gLogging, SWT.PUSH);
    Messages.setLanguageText(generate_net_button, "ConfigView.section.logging.generatediagnostics");
    generate_net_button.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            new AEThread2("GenerateNetDiag", true) {

                @Override
                public void run() {
                    StringWriter sw = new StringWriter();
                    PrintWriter pw = new PrintWriter(sw);
                    IndentWriter iw = new IndentWriter(pw);
                    NetworkAdmin admin = NetworkAdmin.getSingleton();
                    admin.generateDiagnostics(iw);
                    pw.close();
                    final String info = sw.toString();
                    Logger.log(new LogEvent(LOGID, "Network Info:\n" + info));
                    Utils.execSWTThread(new Runnable() {

                        @Override
                        public void run() {
                            ClipboardCopy.copyToClipBoard(info);
                        }
                    });
                }
            }.start();
        }
    });
    // stats
    Label generate_stats_info = new Label(gLogging, SWT.NULL);
    Messages.setLanguageText(generate_stats_info, "ConfigView.section.logging.statsinfo");
    Button generate_stats_button = new Button(gLogging, SWT.PUSH);
    Messages.setLanguageText(generate_stats_button, "ConfigView.section.logging.generatediagnostics");
    generate_stats_button.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            java.util.Set types = new HashSet();
            types.add(CoreStats.ST_ALL);
            Map reply = CoreStats.getStats(types);
            Iterator it = reply.entrySet().iterator();
            StringBuilder buffer = new StringBuilder(16000);
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                buffer.append(entry.getKey()).append(" -> ").append(entry.getValue()).append("\r\n");
            }
            String str = buffer.toString();
            ClipboardCopy.copyToClipBoard(str);
            Logger.log(new LogEvent(LOGID, "Stats Info:\n" + str));
        }
    });
    // diagnostics
    Label generate_info = new Label(gLogging, SWT.NULL);
    Messages.setLanguageText(generate_info, "ConfigView.section.logging.generatediagnostics.info");
    Button generate_button = new Button(gLogging, SWT.PUSH);
    Messages.setLanguageText(generate_button, "ConfigView.section.logging.generatediagnostics");
    generate_button.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            AEDiagnostics.generateEvidence(pw);
            pw.close();
            String evidence = sw.toString();
            ClipboardCopy.copyToClipBoard(evidence);
            Logger.log(new LogEvent(LOGID, "Evidence Generation:\n" + evidence));
        }
    });
    if (false) {
        Button test_button = new Button(gLogging, SWT.PUSH);
        test_button.setText("Test");
        test_button.addListener(SWT.Selection, new Listener() {

            @Override
            public void handleEvent(Event event) {
                try {
                    PluginInterface pi = CoreFactory.getSingleton().getPluginManager().getDefaultPluginInterface();
                    UpdateInstaller installer = pi.getUpdateManager().createInstaller();
                    installer.addMoveAction("C:\\temp\\file1", "C:\\temp\\file2");
                    installer.installNow(new UpdateInstallerListener() {

                        @Override
                        public void reportProgress(String str) {
                            System.out.println(str);
                        }

                        @Override
                        public void complete() {
                            System.out.println("complete");
                        }

                        @Override
                        public void failed(UpdateException e) {
                            System.out.println("failed");
                            e.printStackTrace();
                        }
                    });
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
        });
    }
    return gLogging;
}
Also used : Image(org.eclipse.swt.graphics.Image) NetworkAdmin(com.biglybt.core.networkmanager.admin.NetworkAdmin) SelectionEvent(org.eclipse.swt.events.SelectionEvent) HashSet(java.util.HashSet) LogEvent(com.biglybt.core.logging.LogEvent) AEThread2(com.biglybt.core.util.AEThread2) UpdateInstaller(com.biglybt.pif.update.UpdateInstaller) Map(java.util.Map) IndentWriter(com.biglybt.core.util.IndentWriter) UpdateInstallerListener(com.biglybt.pif.update.UpdateInstallerListener) HashSet(java.util.HashSet) GridLayout(org.eclipse.swt.layout.GridLayout) StringWriter(java.io.StringWriter) Iterator(java.util.Iterator) UpdateException(com.biglybt.pif.update.UpdateException) PrintWriter(java.io.PrintWriter) SelectionAdapter(org.eclipse.swt.events.SelectionAdapter) PluginInterface(com.biglybt.pif.PluginInterface) LogIDs(com.biglybt.core.logging.LogIDs) UpdateInstallerListener(com.biglybt.pif.update.UpdateInstallerListener) GridData(org.eclipse.swt.layout.GridData) LogEvent(com.biglybt.core.logging.LogEvent) SelectionEvent(org.eclipse.swt.events.SelectionEvent) ImageLoader(com.biglybt.ui.swt.imageloader.ImageLoader)

Example 17 with AEThread2

use of com.biglybt.core.util.AEThread2 in project BiglyBT by BiglySoftware.

the class ConfigSectionConnectionProxy method configSectionCreate.

@Override
public Composite configSectionCreate(final Composite parent) {
    GridData gridData;
    GridLayout layout;
    Composite cSection = new Composite(parent, SWT.NULL);
    gridData = new GridData(GridData.VERTICAL_ALIGN_FILL | GridData.HORIZONTAL_ALIGN_FILL);
    Utils.setLayoutData(cSection, gridData);
    layout = new GridLayout();
    layout.numColumns = 2;
    cSection.setLayout(layout);
    int userMode = COConfigurationManager.getIntParameter("User Mode");
    if (userMode < REQUIRED_MODE) {
        Label label = new Label(cSection, SWT.WRAP);
        gridData = new GridData();
        gridData.horizontalSpan = 2;
        Utils.setLayoutData(label, gridData);
        final String[] modeKeys = { "ConfigView.section.mode.beginner", "ConfigView.section.mode.intermediate", "ConfigView.section.mode.advanced" };
        String param1, param2;
        if (REQUIRED_MODE < modeKeys.length)
            param1 = MessageText.getString(modeKeys[REQUIRED_MODE]);
        else
            param1 = String.valueOf(REQUIRED_MODE);
        if (userMode < modeKeys.length)
            param2 = MessageText.getString(modeKeys[userMode]);
        else
            param2 = String.valueOf(userMode);
        label.setText(MessageText.getString("ConfigView.notAvailableForMode", new String[] { param1, param2 }));
        return cSection;
    }
    // ////////////////////  PROXY GROUP /////////////////
    Group gProxyTracker = new Group(cSection, SWT.NULL);
    Messages.setLanguageText(gProxyTracker, "ConfigView.section.proxy.group.tracker");
    gridData = new GridData(GridData.FILL_HORIZONTAL);
    gridData.horizontalSpan = 2;
    Utils.setLayoutData(gProxyTracker, gridData);
    layout = new GridLayout();
    layout.numColumns = 2;
    gProxyTracker.setLayout(layout);
    final BooleanParameter enableProxy = new BooleanParameter(gProxyTracker, "Enable.Proxy", "ConfigView.section.proxy.enable_proxy");
    gridData = new GridData();
    gridData.horizontalSpan = 2;
    enableProxy.setLayoutData(gridData);
    final BooleanParameter enableSocks = new BooleanParameter(gProxyTracker, "Enable.SOCKS", "ConfigView.section.proxy.enable_socks");
    gridData = new GridData();
    gridData.horizontalSpan = 2;
    enableSocks.setLayoutData(gridData);
    Label lHost = new Label(gProxyTracker, SWT.NULL);
    Messages.setLanguageText(lHost, "ConfigView.section.proxy.host");
    final StringParameter pHost = new StringParameter(gProxyTracker, "Proxy.Host", "", false);
    gridData = new GridData();
    gridData.widthHint = 105;
    pHost.setLayoutData(gridData);
    Label lPort = new Label(gProxyTracker, SWT.NULL);
    Messages.setLanguageText(lPort, "ConfigView.section.proxy.port");
    final StringParameter pPort = new StringParameter(gProxyTracker, "Proxy.Port", "", false);
    gridData = new GridData();
    gridData.widthHint = 40;
    pPort.setLayoutData(gridData);
    Label lUser = new Label(gProxyTracker, SWT.NULL);
    Messages.setLanguageText(lUser, "ConfigView.section.proxy.username");
    final StringParameter pUser = new StringParameter(gProxyTracker, "Proxy.Username", false);
    gridData = new GridData();
    gridData.widthHint = 105;
    pUser.setLayoutData(gridData);
    Label lPass = new Label(gProxyTracker, SWT.NULL);
    Messages.setLanguageText(lPass, "ConfigView.section.proxy.password");
    final StringParameter pPass = new StringParameter(gProxyTracker, "Proxy.Password", "", false);
    gridData = new GridData();
    gridData.widthHint = 105;
    pPass.setLayoutData(gridData);
    final BooleanParameter trackerDNSKill = new BooleanParameter(gProxyTracker, "Proxy.SOCKS.Tracker.DNS.Disable", "ConfigView.section.proxy.no.local.dns");
    gridData = new GridData();
    gridData.horizontalSpan = 2;
    trackerDNSKill.setLayoutData(gridData);
    final NetworkAdminSocksProxy[] test_proxy = { null };
    final Button test_socks = new Button(gProxyTracker, SWT.PUSH);
    Messages.setLanguageText(test_socks, "ConfigView.section.proxy.testsocks");
    test_socks.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            final NetworkAdminSocksProxy target;
            synchronized (test_proxy) {
                target = test_proxy[0];
            }
            if (target != null) {
                final TextViewerWindow viewer = new TextViewerWindow(MessageText.getString("ConfigView.section.proxy.testsocks.title"), null, "Testing SOCKS connection to " + target.getHost() + ":" + target.getPort(), false);
                final AESemaphore test_done = new AESemaphore("");
                new AEThread2("SOCKS test") {

                    @Override
                    public void run() {
                        try {
                            String[] vers = target.getVersionsSupported();
                            String ver = "";
                            for (String v : vers) {
                                ver += (ver.length() == 0 ? "" : ", ") + v;
                            }
                            appendText(viewer, "\r\nConnection OK - supported version(s): " + ver);
                        } catch (Throwable e) {
                            appendText(viewer, "\r\n" + Debug.getNestedExceptionMessage(e));
                        } finally {
                            test_done.release();
                        }
                    }
                }.start();
                new AEThread2("SOCKS test dotter") {

                    @Override
                    public void run() {
                        while (!test_done.reserveIfAvailable()) {
                            appendText(viewer, ".");
                            try {
                                Thread.sleep(500);
                            } catch (Throwable e) {
                                break;
                            }
                        }
                    }
                }.start();
            }
        }

        private void appendText(final TextViewerWindow viewer, final String line) {
            Utils.execSWTThread(new Runnable() {

                @Override
                public void run() {
                    if (!viewer.isDisposed()) {
                        viewer.append2(line);
                    }
                }
            });
        }
    });
    Parameter[] socks_params = { enableProxy, enableSocks, pHost, pPort, pUser, pPass, trackerDNSKill };
    ParameterChangeAdapter socks_adapter = new ParameterChangeAdapter() {

        @Override
        public void parameterChanged(Parameter p, boolean caused_internally) {
            if (test_socks.isDisposed()) {
                p.removeChangeListener(this);
            } else {
                if (!caused_internally) {
                    boolean enabled = enableProxy.isSelected() && enableSocks.isSelected() && pHost.getValue().trim().length() > 0 && pPort.getValue().trim().length() > 0;
                    boolean socks_enabled = enableProxy.isSelected() && enableSocks.isSelected();
                    trackerDNSKill.setEnabled(socks_enabled);
                    if (enabled) {
                        try {
                            int port = Integer.parseInt(pPort.getValue());
                            NetworkAdminSocksProxy nasp = NetworkAdmin.getSingleton().createSocksProxy(pHost.getValue(), port, pUser.getValue(), pPass.getValue());
                            synchronized (test_proxy) {
                                test_proxy[0] = nasp;
                            }
                        } catch (Throwable e) {
                            enabled = false;
                        }
                    }
                    if (!enabled) {
                        synchronized (test_proxy) {
                            test_proxy[0] = null;
                        }
                    }
                    final boolean f_enabled = enabled;
                    Utils.execSWTThread(new Runnable() {

                        @Override
                        public void run() {
                            if (!test_socks.isDisposed()) {
                                test_socks.setEnabled(f_enabled);
                            }
                        }
                    });
                }
            }
        }
    };
    for (Parameter p : socks_params) {
        p.addChangeListener(socks_adapter);
    }
    // init settings
    socks_adapter.parameterChanged(null, false);
    // //////////////////////////////////////////////
    Group gProxyPeer = new Group(cSection, SWT.NULL);
    Messages.setLanguageText(gProxyPeer, "ConfigView.section.proxy.group.peer");
    gridData = new GridData(GridData.FILL_HORIZONTAL);
    gridData.horizontalSpan = 2;
    Utils.setLayoutData(gProxyPeer, gridData);
    layout = new GridLayout();
    layout.numColumns = 2;
    gProxyPeer.setLayout(layout);
    final BooleanParameter enableSocksPeer = new BooleanParameter(gProxyPeer, "Proxy.Data.Enable", "ConfigView.section.proxy.enable_socks.peer");
    gridData = new GridData();
    gridData.horizontalSpan = 2;
    enableSocksPeer.setLayoutData(gridData);
    final BooleanParameter socksPeerInform = new BooleanParameter(gProxyPeer, "Proxy.Data.SOCKS.inform", "ConfigView.section.proxy.peer.informtracker");
    gridData = new GridData();
    gridData.horizontalSpan = 2;
    socksPeerInform.setLayoutData(gridData);
    Label lSocksVersion = new Label(gProxyPeer, SWT.NULL);
    Messages.setLanguageText(lSocksVersion, "ConfigView.section.proxy.socks.version");
    String[] socks_types = { "V4", "V4a", "V5" };
    String[] dropLabels = new String[socks_types.length];
    String[] dropValues = new String[socks_types.length];
    for (int i = 0; i < socks_types.length; i++) {
        dropLabels[i] = socks_types[i];
        dropValues[i] = socks_types[i];
    }
    final StringListParameter socksType = new StringListParameter(gProxyPeer, "Proxy.Data.SOCKS.version", "V4", dropLabels, dropValues);
    final BooleanParameter sameConfig = new BooleanParameter(gProxyPeer, "Proxy.Data.Same", "ConfigView.section.proxy.peer.same");
    gridData = new GridData();
    gridData.horizontalSpan = 2;
    sameConfig.setLayoutData(gridData);
    Label lDataHost = new Label(gProxyPeer, SWT.NULL);
    Messages.setLanguageText(lDataHost, "ConfigView.section.proxy.host");
    StringParameter pDataHost = new StringParameter(gProxyPeer, "Proxy.Data.Host", "");
    gridData = new GridData();
    gridData.widthHint = 105;
    pDataHost.setLayoutData(gridData);
    Label lDataPort = new Label(gProxyPeer, SWT.NULL);
    Messages.setLanguageText(lDataPort, "ConfigView.section.proxy.port");
    StringParameter pDataPort = new StringParameter(gProxyPeer, "Proxy.Data.Port", "");
    gridData = new GridData();
    gridData.widthHint = 40;
    pDataPort.setLayoutData(gridData);
    Label lDataUser = new Label(gProxyPeer, SWT.NULL);
    Messages.setLanguageText(lDataUser, "ConfigView.section.proxy.username");
    StringParameter pDataUser = new StringParameter(gProxyPeer, "Proxy.Data.Username");
    gridData = new GridData();
    gridData.widthHint = 105;
    pDataUser.setLayoutData(gridData);
    Label lDataPass = new Label(gProxyPeer, SWT.NULL);
    Messages.setLanguageText(lDataPass, "ConfigView.section.proxy.password");
    StringParameter pDataPass = new StringParameter(gProxyPeer, "Proxy.Data.Password", "");
    gridData = new GridData();
    gridData.widthHint = 105;
    pDataPass.setLayoutData(gridData);
    final Control[] proxy_controls = new Control[] { enableSocks.getControl(), lHost, pHost.getControl(), lPort, pPort.getControl(), lUser, pUser.getControl(), lPass, pPass.getControl() };
    IAdditionalActionPerformer proxy_enabler = new GenericActionPerformer(new Control[] {}) {

        @Override
        public void performAction() {
            for (int i = 0; i < proxy_controls.length; i++) {
                proxy_controls[i].setEnabled(enableProxy.isSelected());
            }
        }
    };
    final Control[] proxy_peer_controls = new Control[] { lDataHost, pDataHost.getControl(), lDataPort, pDataPort.getControl(), lDataUser, pDataUser.getControl(), lDataPass, pDataPass.getControl() };
    final Control[] proxy_peer_details = new Control[] { sameConfig.getControl(), socksPeerInform.getControl(), socksType.getControl(), lSocksVersion };
    IAdditionalActionPerformer proxy_peer_enabler = new GenericActionPerformer(new Control[] {}) {

        @Override
        public void performAction() {
            for (int i = 0; i < proxy_peer_controls.length; i++) {
                proxy_peer_controls[i].setEnabled(enableSocksPeer.isSelected() && !sameConfig.isSelected());
            }
            for (int i = 0; i < proxy_peer_details.length; i++) {
                proxy_peer_details[i].setEnabled(enableSocksPeer.isSelected());
            }
        }
    };
    enableSocks.setAdditionalActionPerformer(proxy_enabler);
    enableProxy.setAdditionalActionPerformer(proxy_enabler);
    enableSocksPeer.setAdditionalActionPerformer(proxy_peer_enabler);
    sameConfig.setAdditionalActionPerformer(proxy_peer_enabler);
    // dns info
    Label label = new Label(cSection, SWT.WRAP);
    Messages.setLanguageText(label, "ConfigView.section.proxy.dns.info");
    gridData = new GridData(GridData.FILL_HORIZONTAL);
    gridData.horizontalSpan = 2;
    // needed for wrap
    gridData.widthHint = 200;
    Utils.setLayoutData(label, gridData);
    // disable plugin proxies
    final BooleanParameter disablepps = new BooleanParameter(cSection, "Proxy.SOCKS.disable.plugin.proxies", "ConfigView.section.proxy.disable.plugin.proxies");
    gridData = new GridData();
    gridData.horizontalSpan = 2;
    disablepps.setLayoutData(gridData);
    // check on start
    final BooleanParameter checkOnStart = new BooleanParameter(cSection, "Proxy.Check.On.Start", "ConfigView.section.proxy.check.on.start");
    gridData = new GridData();
    gridData.horizontalSpan = 2;
    checkOnStart.setLayoutData(gridData);
    // icon
    final BooleanParameter showIcon = new BooleanParameter(cSection, "Proxy.SOCKS.ShowIcon", "ConfigView.section.proxy.show_icon");
    gridData = new GridData();
    gridData.horizontalSpan = 2;
    showIcon.setLayoutData(gridData);
    final BooleanParameter flagIncoming = new BooleanParameter(cSection, "Proxy.SOCKS.ShowIcon.FlagIncoming", "ConfigView.section.proxy.show_icon.flag.incoming");
    gridData = new GridData();
    gridData.horizontalIndent = 50;
    gridData.horizontalSpan = 2;
    flagIncoming.setLayoutData(gridData);
    showIcon.setAdditionalActionPerformer(new ChangeSelectionActionPerformer(flagIncoming));
    // username info
    label = new Label(cSection, SWT.WRAP);
    gridData = new GridData();
    gridData.horizontalSpan = 2;
    Utils.setLayoutData(label, gridData);
    label.setText(MessageText.getString("ConfigView.section.proxy.username.info"));
    return cSection;
}
Also used : Group(org.eclipse.swt.widgets.Group) Listener(org.eclipse.swt.widgets.Listener) Label(org.eclipse.swt.widgets.Label) AESemaphore(com.biglybt.core.util.AESemaphore) GridLayout(org.eclipse.swt.layout.GridLayout) Control(org.eclipse.swt.widgets.Control) Button(org.eclipse.swt.widgets.Button) TextViewerWindow(com.biglybt.ui.swt.TextViewerWindow) Composite(org.eclipse.swt.widgets.Composite) NetworkAdminSocksProxy(com.biglybt.core.networkmanager.admin.NetworkAdminSocksProxy) AEThread2(com.biglybt.core.util.AEThread2) GridData(org.eclipse.swt.layout.GridData) Event(org.eclipse.swt.widgets.Event)

Example 18 with AEThread2

use of com.biglybt.core.util.AEThread2 in project BiglyBT by BiglySoftware.

the class NetStatusPlugin method initialize.

@Override
public void initialize(final PluginInterface _plugin_interface) {
    plugin_interface = _plugin_interface;
    logger = plugin_interface.getLogger().getChannel("NetStatus");
    logger.setDiagnostic();
    BasicPluginConfigModel config = plugin_interface.getUIManager().createBasicPluginConfigModel("Views.plugins." + VIEW_ID + ".title");
    logging_detailed = config.addBooleanParameter2("plugin.aznetstatus.logfull", "plugin.aznetstatus.logfull", false);
    plugin_interface.getUIManager().addUIListener(new UIManagerListener() {

        @Override
        public void UIAttached(UIInstance instance) {
            if (instance.getUIType().equals(UIInstance.UIT_SWT)) {
                try {
                    swt_ui = (NetStatusPluginViewInterface) Class.forName("com.biglybt.plugin.net.netstatus.swt.NetStatusPluginView").getConstructor(new Class[] { NetStatusPlugin.class, UIInstance.class, String.class }).newInstance(new Object[] { NetStatusPlugin.this, instance, VIEW_ID });
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void UIDetached(UIInstance instance) {
            if (instance.getUIType().equals(UIInstance.UIT_SWT) && swt_ui != null) {
                swt_ui.detach(instance);
                swt_ui = null;
            }
        }
    });
    plugin_interface.addListener(new PluginListener() {

        @Override
        public void initializationComplete() {
            new AEThread2("NetstatusPlugin:init", true) {

                @Override
                public void run() {
                    try {
                        protocol_tester = new NetStatusProtocolTester(NetStatusPlugin.this, plugin_interface);
                        if (test_button != null) {
                            test_button.setEnabled(true);
                        }
                    } finally {
                        protocol_tester_sem.releaseForever();
                    }
                }
            }.start();
        }

        @Override
        public void closedownInitiated() {
        }

        @Override
        public void closedownComplete() {
        }
    });
}
Also used : UIManagerListener(com.biglybt.pif.ui.UIManagerListener) UIInstance(com.biglybt.pif.ui.UIInstance) AEThread2(com.biglybt.core.util.AEThread2) BasicPluginConfigModel(com.biglybt.pif.ui.model.BasicPluginConfigModel) PluginListener(com.biglybt.pif.PluginListener)

Example 19 with AEThread2

use of com.biglybt.core.util.AEThread2 in project BiglyBT by BiglySoftware.

the class Plugin method execute.

@Override
public void execute(String commandName, final ConsoleInput ci, List args) {
    if (args.isEmpty()) {
        printHelpExtra(ci.out, args);
        return;
    }
    String subcmd = (String) args.get(0);
    if (!java.util.Arrays.asList(new String[] { "location", "list", "listall", "status", "startup", "install", "uninstall", "update" }).contains(subcmd)) {
        ci.out.println("Invalid subcommand: " + subcmd);
        ci.out.println();
        return;
    }
    PluginManager plugin_manager = ci.getCore().getPluginManager();
    if (subcmd.equals("list") || subcmd.equals("listall")) {
        boolean all_plugins = subcmd.equals("listall");
        ci.out.println("> -----");
        PluginInterface[] plugins = plugin_manager.getPluginInterfaces();
        TreeSet plugin_ids = new TreeSet(String.CASE_INSENSITIVE_ORDER);
        for (int i = 0; i < plugins.length; i++) {
            if (!all_plugins && !plugins[i].getPluginState().isOperational()) {
                continue;
            }
            String plugin_id = plugins[i].getPluginID();
            plugin_ids.add(plugin_id);
        }
        TextWrap.printList(plugin_ids.iterator(), ci.out, "   ");
        ci.out.println("> -----");
        return;
    }
    if (subcmd.equals("location")) {
        // Taken from ConfigSectionPlugins.
        File fUserPluginDir = FileUtil.getUserFile("plugins");
        String sep = File.separator;
        String sUserPluginDir;
        try {
            sUserPluginDir = fUserPluginDir.getCanonicalPath();
        } catch (Throwable e) {
            sUserPluginDir = fUserPluginDir.toString();
        }
        if (!sUserPluginDir.endsWith(sep)) {
            sUserPluginDir += sep;
        }
        File fAppPluginDir = FileUtil.getApplicationFile("plugins");
        String sAppPluginDir;
        try {
            sAppPluginDir = fAppPluginDir.getCanonicalPath();
        } catch (Throwable e) {
            sAppPluginDir = fAppPluginDir.toString();
        }
        if (!sAppPluginDir.endsWith(sep)) {
            sAppPluginDir += sep;
        }
        ci.out.println("Shared plugin location:");
        ci.out.println("  " + sAppPluginDir);
        ci.out.println("User plugin location:");
        ci.out.println("  " + sUserPluginDir);
        ci.out.println();
        return;
    }
    if (subcmd.equals("update")) {
        if (args.size() != 1) {
            ci.out.println("Usage: update");
            return;
        }
        UpdateManager update_manager = plugin_manager.getDefaultPluginInterface().getUpdateManager();
        final UpdateCheckInstance checker = update_manager.createUpdateCheckInstance();
        checker.addListener(new UpdateCheckInstanceListener() {

            @Override
            public void cancelled(UpdateCheckInstance instance) {
            }

            @Override
            public void complete(UpdateCheckInstance instance) {
                Update[] updates = instance.getUpdates();
                try {
                    for (Update update : updates) {
                        ci.out.println("Updating " + update.getName());
                        for (ResourceDownloader rd : update.getDownloaders()) {
                            rd.addListener(new ResourceDownloaderAdapter() {

                                @Override
                                public void reportActivity(ResourceDownloader downloader, String activity) {
                                    ci.out.println("\t" + activity);
                                }

                                @Override
                                public void reportPercentComplete(ResourceDownloader downloader, int percentage) {
                                    ci.out.println("\t" + percentage + "%");
                                }
                            });
                            rd.download();
                        }
                    }
                    boolean restart_required = false;
                    for (int i = 0; i < updates.length; i++) {
                        if (updates[i].getRestartRequired() == Update.RESTART_REQUIRED_YES) {
                            restart_required = true;
                        }
                    }
                    if (restart_required) {
                        ci.out.println("**** Restart required to complete update ****");
                    }
                } catch (Throwable e) {
                    ci.out.println("Plugin update failed: " + Debug.getNestedExceptionMessage(e));
                }
            }
        });
        checker.start();
        return;
    }
    if (subcmd.equals("install")) {
        if (args.size() == 1) {
            ci.out.println("Contacting plugin repository for list of available plugins...");
            try {
                SFPluginDetails[] plugins = SFPluginDetailsLoaderFactory.getSingleton().getPluginDetails();
                for (SFPluginDetails p : plugins) {
                    String category = p.getCategory();
                    if (category != null) {
                        if (category.equalsIgnoreCase("hidden") || (category.equalsIgnoreCase("core"))) {
                            continue;
                        }
                    }
                    String id = p.getId();
                    if (plugin_manager.getPluginInterfaceByID(id, false) == null) {
                        String desc = p.getDescription();
                        int pos = desc.indexOf("<br");
                        if (pos > 0) {
                            desc = desc.substring(0, pos);
                        }
                        ci.out.println("\t" + id + ": \t\t" + desc);
                    }
                }
            } catch (Throwable e) {
                ci.out.println("Failed to list plugins: " + Debug.getNestedExceptionMessage(e));
            }
        } else {
            String target_id = (String) args.get(1);
            if (plugin_manager.getPluginInterfaceByID(target_id, false) != null) {
                ci.out.println("Plugin '" + target_id + "' already installed");
                return;
            }
            final PluginInstaller installer = plugin_manager.getPluginInstaller();
            try {
                final StandardPlugin sp = installer.getStandardPlugin(target_id);
                if (sp == null) {
                    ci.out.println("Plugin '" + target_id + "' is unknown");
                    return;
                }
                new AEThread2("Plugin Installer") {

                    @Override
                    public void run() {
                        try {
                            Map<Integer, Object> properties = new HashMap<>();
                            properties.put(UpdateCheckInstance.PT_UI_STYLE, UpdateCheckInstance.PT_UI_STYLE_NONE);
                            properties.put(UpdateCheckInstance.PT_UI_DISABLE_ON_SUCCESS_SLIDEY, true);
                            final AESemaphore sem = new AESemaphore("plugin-install");
                            final boolean[] restart_required = { false };
                            UpdateCheckInstance instance = installer.install(new InstallablePlugin[] { sp }, false, properties, new PluginInstallationListener() {

                                @Override
                                public void completed() {
                                    ci.out.println("Installation complete");
                                    sem.release();
                                }

                                @Override
                                public void cancelled() {
                                    ci.out.println("Installation cancelled");
                                    sem.release();
                                }

                                @Override
                                public void failed(PluginException e) {
                                    ci.out.println("Installation failed: " + Debug.getNestedExceptionMessage(e));
                                    sem.release();
                                }
                            });
                            instance.addListener(new UpdateCheckInstanceListener() {

                                @Override
                                public void cancelled(UpdateCheckInstance instance) {
                                    ci.out.println("Installation cancelled");
                                }

                                @Override
                                public void complete(UpdateCheckInstance instance) {
                                    Update[] updates = instance.getUpdates();
                                    for (final Update update : updates) {
                                        ResourceDownloader[] rds = update.getDownloaders();
                                        for (ResourceDownloader rd : rds) {
                                            rd.addListener(new ResourceDownloaderAdapter() {

                                                @Override
                                                public void reportActivity(ResourceDownloader downloader, String activity) {
                                                    ci.out.println("\t" + activity);
                                                }

                                                @Override
                                                public void reportPercentComplete(ResourceDownloader downloader, int percentage) {
                                                    ci.out.println("\t" + percentage + "%");
                                                }
                                            });
                                            try {
                                                rd.download();
                                            } catch (Throwable e) {
                                            }
                                        }
                                        if (update.getRestartRequired() != Update.RESTART_REQUIRED_NO) {
                                            restart_required[0] = true;
                                        }
                                    }
                                }
                            });
                            sem.reserve();
                            if (restart_required[0]) {
                                ci.out.println("**** Restart required to complete installation ****");
                            }
                        } catch (Throwable e) {
                            ci.out.println("Install failed: " + Debug.getNestedExceptionMessage(e));
                        }
                    }
                }.start();
            } catch (Throwable e) {
                ci.out.println("Install failed: " + Debug.getNestedExceptionMessage(e));
            }
        }
        return;
    }
    // Commands from this point require a plugin ID.
    if (args.size() == 1) {
        ci.out.println("No plugin ID given.");
        ci.out.println();
        return;
    }
    String plugin_id = (String) args.get(1);
    PluginInterface plugin = plugin_manager.getPluginInterfaceByID(plugin_id, false);
    if (plugin == null) {
        ci.out.println("Invalid plugin ID: " + plugin_id);
        ci.out.println();
        return;
    }
    if (subcmd.equals("status")) {
        ci.out.println("ID     : " + plugin.getPluginID());
        ci.out.println("Name   : " + plugin.getPluginName());
        ci.out.println("Version: " + plugin.getPluginVersion());
        ci.out.println("Running: " + plugin.getPluginState().isOperational());
        ci.out.println("Runs at startup: " + plugin.getPluginState().isLoadedAtStartup());
        if (!plugin.getPluginState().isBuiltIn()) {
            ci.out.println("Location: " + plugin.getPluginDirectoryName());
        }
        ci.out.println();
        return;
    }
    if (subcmd.equals("startup")) {
        if (args.size() == 2) {
            ci.out.println("Need to pass either \"on\" or \"off\"");
            ci.out.println();
            return;
        }
        String enabled_mode = (String) args.get(2);
        if (enabled_mode.equals("on")) {
            plugin.getPluginState().setLoadedAtStartup(true);
        } else if (enabled_mode.equals("off")) {
            plugin.getPluginState().setLoadedAtStartup(false);
        } else {
            ci.out.println("Need to pass either \"on\" or \"off\"");
            ci.out.println();
            return;
        }
        ci.out.println("Done.");
        ci.out.println();
        return;
    }
    if (subcmd.equals("uninstall")) {
        PluginInterface pi = plugin_manager.getPluginInterfaceByID(plugin_id, false);
        if (pi == null) {
            ci.out.println("Plugin '" + plugin_id + "' is not installed");
            return;
        }
        final PluginInstaller installer = plugin_manager.getPluginInstaller();
        try {
            final StandardPlugin sp = installer.getStandardPlugin(plugin_id);
            if (sp == null) {
                ci.out.println("Plugin '" + plugin_id + "' is not a standard plugin");
                return;
            }
            final PluginInstaller uninstaller = plugin_manager.getPluginInstaller();
            Map<Integer, Object> properties = new HashMap<>();
            final AESemaphore sem = new AESemaphore("plugin-uninstall");
            UpdateCheckInstance instance = uninstaller.uninstall(new PluginInterface[] { pi }, new PluginInstallationListener() {

                @Override
                public void completed() {
                    ci.out.println("Uninstallation complete");
                    sem.release();
                }

                @Override
                public void cancelled() {
                    ci.out.println("Uninstallation cancelled");
                    sem.release();
                }

                @Override
                public void failed(PluginException e) {
                    ci.out.println("Uninstallation failed: " + Debug.getNestedExceptionMessage(e));
                    sem.release();
                }
            }, properties);
            instance.addListener(new UpdateCheckInstanceListener() {

                @Override
                public void cancelled(UpdateCheckInstance instance) {
                    ci.out.println("InsUninstallationtallation cancelled");
                }

                @Override
                public void complete(UpdateCheckInstance instance) {
                    Update[] updates = instance.getUpdates();
                    for (final Update update : updates) {
                        ResourceDownloader[] rds = update.getDownloaders();
                        for (ResourceDownloader rd : rds) {
                            try {
                                rd.download();
                            } catch (Throwable e) {
                            }
                        }
                    }
                }
            });
            sem.reserve();
            Object obj = properties.get(UpdateCheckInstance.PT_UNINSTALL_RESTART_REQUIRED);
            if (obj instanceof Boolean && (Boolean) obj) {
                ci.out.println("**** Restart required to complete uninstallation ****");
            }
        } catch (Throwable e) {
            ci.out.println("Uninstall failed: " + Debug.getNestedExceptionMessage(e));
        }
    }
}
Also used : UpdateCheckInstance(com.biglybt.pif.update.UpdateCheckInstance) HashMap(java.util.HashMap) Update(com.biglybt.pif.update.Update) AESemaphore(com.biglybt.core.util.AESemaphore) PluginManager(com.biglybt.pif.PluginManager) PluginInstallationListener(com.biglybt.pif.installer.PluginInstallationListener) TreeSet(java.util.TreeSet) SFPluginDetails(com.biglybt.pifimpl.update.sf.SFPluginDetails) UpdateCheckInstanceListener(com.biglybt.pif.update.UpdateCheckInstanceListener) PluginInterface(com.biglybt.pif.PluginInterface) PluginException(com.biglybt.pif.PluginException) ResourceDownloader(com.biglybt.pif.utils.resourcedownloader.ResourceDownloader) StandardPlugin(com.biglybt.pif.installer.StandardPlugin) AEThread2(com.biglybt.core.util.AEThread2) InstallablePlugin(com.biglybt.pif.installer.InstallablePlugin) PluginInstaller(com.biglybt.pif.installer.PluginInstaller) ResourceDownloaderAdapter(com.biglybt.pif.utils.resourcedownloader.ResourceDownloaderAdapter) UpdateManager(com.biglybt.pif.update.UpdateManager) File(java.io.File) HashMap(java.util.HashMap) Map(java.util.Map)

Example 20 with AEThread2

use of com.biglybt.core.util.AEThread2 in project BiglyBT by BiglySoftware.

the class SimpleInstallUI method build.

protected void build(Composite parent) {
    parent.setLayout(new FormLayout());
    Button cancel_button = new Button(parent, SWT.NULL);
    cancel_button.setText("Cancel");
    cancel_button.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event arg0) {
            synchronized (SimpleInstallUI.this) {
                cancelled = true;
                if (current_downloader != null) {
                    current_downloader.cancel();
                }
            }
            instance.cancel();
        }
    });
    FormData data = new FormData();
    data.right = new FormAttachment(100, 0);
    data.top = new FormAttachment(0, 0);
    data.bottom = new FormAttachment(100, 0);
    cancel_button.setLayoutData(data);
    final Label label = new Label(parent, SWT.NULL);
    label.setText("blah blah ");
    data = new FormData();
    data.left = new FormAttachment(0, 0);
    data.top = new FormAttachment(cancel_button, 0, SWT.CENTER);
    label.setLayoutData(data);
    final ProgressBar progress = new ProgressBar(parent, SWT.NULL);
    progress.setMinimum(0);
    progress.setMaximum(100);
    progress.setSelection(0);
    data = new FormData();
    data.left = new FormAttachment(label, 4);
    data.top = new FormAttachment(cancel_button, 0, SWT.CENTER);
    data.right = new FormAttachment(cancel_button, -4);
    progress.setLayoutData(data);
    parent.layout(true, true);
    new AEThread2("SimpleInstallerUI", true) {

        @Override
        public void run() {
            try {
                Update[] updates = instance.getUpdates();
                for (Update update : updates) {
                    String name = update.getName();
                    int pos = name.indexOf('/');
                    if (pos >= 0) {
                        name = name.substring(pos + 1);
                    }
                    setLabel(name);
                    ResourceDownloader[] downloaders = update.getDownloaders();
                    for (ResourceDownloader downloader : downloaders) {
                        synchronized (SimpleInstallUI.this) {
                            if (cancelled) {
                                return;
                            }
                            current_downloader = downloader;
                        }
                        setProgress(0);
                        downloader.addListener(new ResourceDownloaderAdapter() {

                            @Override
                            public void reportPercentComplete(ResourceDownloader downloader, int percentage) {
                                setProgress(percentage);
                            }

                            @Override
                            public void reportAmountComplete(ResourceDownloader downloader, long amount) {
                            }
                        });
                        downloader.download();
                    }
                }
                boolean restart_required = false;
                for (int i = 0; i < updates.length; i++) {
                    if (updates[i].getRestartRequired() == Update.RESTART_REQUIRED_YES) {
                        restart_required = true;
                    }
                }
                if (restart_required) {
                    monitor.handleRestart();
                }
            } catch (Throwable e) {
                Debug.out("Install failed", e);
                instance.cancel();
            }
        }

        protected void setLabel(final String str) {
            Utils.execSWTThread(new Runnable() {

                @Override
                public void run() {
                    if (label != null && !label.isDisposed()) {
                        label.setText(str);
                        label.getParent().layout();
                    }
                }
            });
        }

        protected void setProgress(final int percent) {
            Utils.execSWTThread(new Runnable() {

                @Override
                public void run() {
                    if (progress != null && !progress.isDisposed()) {
                        progress.setSelection(percent);
                    }
                }
            });
        }
    }.start();
}
Also used : FormLayout(org.eclipse.swt.layout.FormLayout) FormData(org.eclipse.swt.layout.FormData) Listener(org.eclipse.swt.widgets.Listener) Label(org.eclipse.swt.widgets.Label) ResourceDownloader(com.biglybt.pif.utils.resourcedownloader.ResourceDownloader) Update(com.biglybt.pif.update.Update) AEThread2(com.biglybt.core.util.AEThread2) ResourceDownloaderAdapter(com.biglybt.pif.utils.resourcedownloader.ResourceDownloaderAdapter) Button(org.eclipse.swt.widgets.Button) Event(org.eclipse.swt.widgets.Event) ProgressBar(org.eclipse.swt.widgets.ProgressBar) FormAttachment(org.eclipse.swt.layout.FormAttachment)

Aggregations

AEThread2 (com.biglybt.core.util.AEThread2)20 File (java.io.File)6 PluginInterface (com.biglybt.pif.PluginInterface)5 Map (java.util.Map)5 GridData (org.eclipse.swt.layout.GridData)4 HashMap (java.util.HashMap)3 GridLayout (org.eclipse.swt.layout.GridLayout)3 DiskManagerFileInfoURL (com.biglybt.core.download.DiskManagerFileInfoURL)2 MessageText (com.biglybt.core.internat.MessageText)2 LogEvent (com.biglybt.core.logging.LogEvent)2 AESemaphore (com.biglybt.core.util.AESemaphore)2 PluginListener (com.biglybt.pif.PluginListener)2 IPCInterface (com.biglybt.pif.ipc.IPCInterface)2 Update (com.biglybt.pif.update.Update)2 ResourceDownloader (com.biglybt.pif.utils.resourcedownloader.ResourceDownloader)2 ResourceDownloaderAdapter (com.biglybt.pif.utils.resourcedownloader.ResourceDownloaderAdapter)2 PrintWriter (java.io.PrintWriter)2 StringWriter (java.io.StringWriter)2 URL (java.net.URL)2 Button (org.eclipse.swt.widgets.Button)2