Search in sources :

Example 56 with LogAlert

use of com.biglybt.core.logging.LogAlert in project BiglyBT by BiglySoftware.

the class SystemWarningWindow method openWindow.

protected void openWindow() {
    Display display = parent.getDisplay();
    // shell = new Shell(parent, SWT.TOOL | SWT.TITLE | SWT.CLOSE);
    // shell.setText("Warning (X of X)");
    shell = new Shell(parent, SWT.TOOL);
    shell.setLayout(new FormLayout());
    shell.setBackground(Colors.getSystemColor(display, SWT.COLOR_INFO_BACKGROUND));
    shell.setForeground(Colors.getSystemColor(display, SWT.COLOR_INFO_FOREGROUND));
    Menu menu = new Menu(shell);
    MenuItem menuItem = new MenuItem(menu, SWT.PUSH);
    Messages.setLanguageText(menuItem, "MyTorrentsView.menu.thisColumn.toClipboard");
    menuItem.addSelectionListener(new SelectionListener() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            ClipboardCopy.copyToClipBoard(logAlert.text + (logAlert.details == null ? "" : "\n" + logAlert.details));
        }

        @Override
        public void widgetDefaultSelected(SelectionEvent e) {
        }
    });
    shell.setMenu(menu);
    ImageLoader imageLoader = ImageLoader.getInstance();
    imgClose = imageLoader.getImage("image.systemwarning.closeitem");
    boundsClose = imgClose.getBounds();
    GC gc = new GC(shell);
    FontData[] fontdata = gc.getFont().getFontData();
    fontdata[0].setHeight(fontdata[0].getHeight() + 1);
    fontdata[0].setStyle(SWT.BOLD);
    fontTitle = new Font(display, fontdata);
    fontdata = gc.getFont().getFontData();
    fontdata[0].setHeight(fontdata[0].getHeight() - 1);
    fontCount = new Font(display, fontdata);
    shell.addDisposeListener(new DisposeListener() {

        @Override
        public void widgetDisposed(DisposeEvent e) {
            Utils.disposeSWTObjects(new Object[] { fontTitle, fontCount });
            numWarningWindowsOpen--;
        }
    });
    Rectangle printArea = new Rectangle(BORDER_X, 0, WIDTH - (BORDER_X * 2), 5000);
    spText = new GCStringPrinter(gc, text, printArea, true, false, SWT.WRAP);
    spText.setUrlColor(Colors.blues[Colors.FADED_DARKEST]);
    spText.calculateMetrics();
    gc.setFont(fontCount);
    String sCount = MessageText.getString("label.xOfTotal", new String[] { "" + historyPosition + 1, "" + getWarningCount() });
    spCount = new GCStringPrinter(gc, sCount, printArea, true, false, SWT.WRAP);
    spCount.calculateMetrics();
    gc.setFont(fontTitle);
    spTitle = new GCStringPrinter(gc, title, printArea, true, false, SWT.WRAP);
    spTitle.calculateMetrics();
    gc.dispose();
    sizeText = spText.getCalculatedSize();
    sizeTitle = spTitle.getCalculatedSize();
    sizeCount = spCount.getCalculatedSize();
    FormData fd;
    Button btnDismiss = new Button(shell, SWT.PUSH);
    Messages.setLanguageText(btnDismiss, "Button.dismiss");
    final int btnHeight = btnDismiss.computeSize(SWT.DEFAULT, SWT.DEFAULT).y;
    Button btnPrev = new Button(shell, SWT.PUSH);
    btnPrev.setText("<");
    Button btnNext = new Button(shell, SWT.PUSH);
    btnNext.setText(">");
    fd = new FormData();
    fd.bottom = new FormAttachment(100, -BORDER_Y1);
    fd.right = new FormAttachment(100, -BORDER_X);
    btnNext.setLayoutData(fd);
    fd = new FormData();
    fd.bottom = new FormAttachment(100, -BORDER_Y1);
    fd.right = new FormAttachment(btnNext, -BORDER_X);
    btnPrev.setLayoutData(fd);
    fd = new FormData();
    fd.bottom = new FormAttachment(100, -BORDER_Y1);
    fd.right = new FormAttachment(btnPrev, -BORDER_X);
    btnDismiss.setLayoutData(fd);
    height = BORDER_Y0 + sizeTitle.y + GAP_Y + sizeText.y + GAP_Y_TITLE_COUNT + sizeCount.y + GAP_BUTTON_Y + btnHeight + BORDER_Y1;
    Rectangle area = shell.computeTrim(ptBottomRight.x - WIDTH, ptBottomRight.y - height, WIDTH, height);
    shell.setBounds(area);
    shell.setLocation(ptBottomRight.x - area.width, ptBottomRight.y - area.height - 2);
    rectX = new Rectangle(area.width - BORDER_X - boundsClose.width, BORDER_Y0, boundsClose.width, boundsClose.height);
    shell.addMouseMoveListener(new MouseMoveListener() {

        int lastCursor = SWT.CURSOR_ARROW;

        @Override
        public void mouseMove(MouseEvent e) {
            if (shell == null || shell.isDisposed()) {
                return;
            }
            URLInfo hitUrl = spText.getHitUrl(e.x, e.y);
            int cursor = (rectX.contains(e.x, e.y)) || hitUrl != null ? SWT.CURSOR_HAND : SWT.CURSOR_ARROW;
            if (cursor != lastCursor) {
                lastCursor = cursor;
                shell.setCursor(e.display.getSystemCursor(cursor));
            }
        }
    });
    shell.addMouseListener(new MouseListener() {

        @Override
        public void mouseUp(MouseEvent e) {
            if (shell == null || shell.isDisposed()) {
                return;
            }
            if (rectX.contains(e.x, e.y)) {
                shell.dispose();
            }
            URLInfo hitUrl = spText.getHitUrl(e.x, e.y);
            if (hitUrl != null) {
                if (hitUrl.url.equals("details")) {
                    MessageBoxShell mb = new MessageBoxShell(Constants.APP_NAME, logAlert.details, new String[] { MessageText.getString("Button.ok") }, 0);
                    mb.setUseTextBox(true);
                    mb.setParent(Utils.findAnyShell());
                    mb.open(null);
                } else {
                    Utils.launch(hitUrl.url);
                }
            }
        }

        @Override
        public void mouseDown(MouseEvent e) {
        }

        @Override
        public void mouseDoubleClick(MouseEvent e) {
        }
    });
    shell.addPaintListener(new PaintListener() {

        @Override
        public void paintControl(PaintEvent e) {
            e.gc.drawImage(imgClose, WIDTH - BORDER_X - boundsClose.width, BORDER_Y0);
            Rectangle printArea;
            printArea = new Rectangle(BORDER_X, BORDER_Y0 + sizeTitle.y + GAP_Y_TITLE_COUNT, WIDTH, 100);
            String sCount = MessageText.getString("label.xOfTotal", new String[] { "" + (historyPosition + 1), "" + getWarningCount() });
            e.gc.setAlpha(180);
            Font lastFont = e.gc.getFont();
            e.gc.setFont(fontCount);
            spCount = new GCStringPrinter(e.gc, sCount, printArea, true, false, SWT.WRAP | SWT.TOP);
            spCount.printString();
            e.gc.setAlpha(255);
            sizeCount = spCount.getCalculatedSize();
            e.gc.setFont(lastFont);
            spText.printString(e.gc, new Rectangle(BORDER_X, BORDER_Y0 + sizeTitle.y + GAP_Y_TITLE_COUNT + sizeCount.y + GAP_Y, WIDTH - BORDER_X - BORDER_X, 5000), SWT.WRAP | SWT.TOP);
            e.gc.setFont(fontTitle);
            e.gc.setForeground(ColorCache.getColor(e.gc.getDevice(), "#54728c"));
            spTitle.printString(e.gc, new Rectangle(BORDER_X, BORDER_Y0, WIDTH - BORDER_X - BORDER_X, 5000), SWT.WRAP | SWT.TOP);
            e.gc.setLineStyle(SWT.LINE_DOT);
            e.gc.setLineWidth(1);
            e.gc.setAlpha(180);
            e.gc.drawLine(BORDER_X, height - btnHeight - (GAP_BUTTON_Y / 2) - BORDER_Y1, WIDTH - BORDER_X, height - btnHeight - (GAP_BUTTON_Y / 2) - BORDER_Y1);
        }
    });
    shell.addTraverseListener(new TraverseListener() {

        @Override
        public void keyTraversed(TraverseEvent e) {
            if (e.detail == SWT.TRAVERSE_ESCAPE) {
                shell.dispose();
                return;
            }
        }
    });
    btnPrev.addSelectionListener(new SelectionListener() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            ArrayList<LogAlert> alerts = Alerts.getUnviewedLogAlerts();
            int pos = historyPosition - 1;
            if (pos < 0 || pos >= alerts.size()) {
                return;
            }
            new SystemWarningWindow(alerts.get(pos), ptBottomRight, parent, pos);
            shell.dispose();
        }

        @Override
        public void widgetDefaultSelected(SelectionEvent e) {
        }
    });
    btnPrev.setEnabled(historyPosition > 0);
    btnNext.addSelectionListener(new SelectionListener() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            ArrayList<LogAlert> alerts = Alerts.getUnviewedLogAlerts();
            int pos = historyPosition + 1;
            if (pos >= alerts.size()) {
                return;
            }
            new SystemWarningWindow(alerts.get(pos), ptBottomRight, parent, pos);
            shell.dispose();
        }

        @Override
        public void widgetDefaultSelected(SelectionEvent e) {
        }
    });
    ArrayList<LogAlert> alerts = Alerts.getUnviewedLogAlerts();
    btnNext.setEnabled(alerts.size() != historyPosition + 1);
    btnDismiss.addSelectionListener(new SelectionListener() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            ArrayList<LogAlert> alerts = Alerts.getUnviewedLogAlerts();
            for (int i = 0; i < alerts.size() && i <= historyPosition; i++) {
                Alerts.markAlertAsViewed(alerts.get(i));
            }
            shell.dispose();
        }

        @Override
        public void widgetDefaultSelected(SelectionEvent e) {
        }
    });
    shell.open();
    numWarningWindowsOpen++;
}
Also used : GCStringPrinter(com.biglybt.ui.swt.shells.GCStringPrinter) ArrayList(java.util.ArrayList) MessageBoxShell(com.biglybt.ui.swt.shells.MessageBoxShell) MessageBoxShell(com.biglybt.ui.swt.shells.MessageBoxShell) URLInfo(com.biglybt.ui.swt.shells.GCStringPrinter.URLInfo) LogAlert(com.biglybt.core.logging.LogAlert) ImageLoader(com.biglybt.ui.swt.imageloader.ImageLoader)

Example 57 with LogAlert

use of com.biglybt.core.logging.LogAlert in project BiglyBT by BiglySoftware.

the class MainStatusBar method initStatusBar.

/**
 * @return composite holding the statusbar
 */
public Composite initStatusBar(final Composite _parent) {
    this.parent = _parent;
    this.display = parent.getDisplay();
    this.uiFunctions = UIFunctionsManager.getUIFunctions();
    ImageLoader imageLoader = ImageLoader.getInstance();
    FormData formData;
    Color fgColor = parent.getForeground();
    statusBar = new Composite(parent, SWT.NONE);
    statusBar.setForeground(fgColor);
    isAZ3 = "az3".equalsIgnoreCase(COConfigurationManager.getStringParameter("ui"));
    statusBar.getShell().addListener(SWT.Deiconify, new Listener() {

        @Override
        public void handleEvent(Event event) {
            Utils.execSWTThreadLater(0, new AERunnable() {

                @Override
                public void runSupport() {
                    if (!statusBar.isDisposed()) {
                        statusBar.layout();
                    }
                }
            });
        }
    });
    statusBar.addDisposeListener(new DisposeListener() {

        @Override
        public void widgetDisposed(DisposeEvent e) {
            if (uiFunctions != null) {
                UIUpdater uiUpdater = uiFunctions.getUIUpdater();
                if (uiUpdater != null) {
                    uiUpdater.removeUpdater(MainStatusBar.this);
                }
            }
            PRManager.removeListener(progressListener);
            Utils.disposeSWTObjects(imgRec, imgSent);
            Utils.removeParameterListeners(mapConfigListeners);
            if (alert_flasher_event != null) {
                alert_flasher_event.cancel();
                alert_flasher_event = null;
            }
            if (alertHistoryListener != null) {
                Alerts.removeMessageHistoryListener(alertHistoryListener);
                alertHistoryListener = null;
            }
        }
    });
    GridLayout layout_status = new GridLayout();
    layout_status.numColumns = 20;
    layout_status.horizontalSpacing = 0;
    layout_status.verticalSpacing = 0;
    layout_status.marginHeight = 0;
    if (Constants.isOSX) {
        // OSX has a resize widget on the bottom right.  It's about 15px wide.
        try {
            layout_status.marginRight = 15;
        } catch (NoSuchFieldError e) {
            // Pre SWT 3.1
            layout_status.marginWidth = 15;
        }
    } else {
        layout_status.marginWidth = 0;
    }
    statusBar.setLayout(layout_status);
    // Either the Status Text
    statusText = new CLabel(statusBar, borderFlag);
    statusText.setForeground(fgColor);
    Utils.setLayoutData(statusText, new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));
    addStatusBarMenu(statusText);
    GC gc = new GC(statusText);
    // add 6, because CLabel forces a 3 pixel indent
    int height = Math.max(16, gc.getFontMetrics().getHeight()) + 6;
    gc.dispose();
    formData = new FormData();
    formData.height = height;
    // 2 params for Pre SWT 3.0
    formData.bottom = new FormAttachment(100, 0);
    // 2 params for Pre SWT 3.0
    formData.left = new FormAttachment(0, 0);
    // 2 params for Pre SWT 3.0
    formData.right = new FormAttachment(100, 0);
    statusBar.setLayoutData(formData);
    Listener listener = new Listener() {

        @Override
        public void handleEvent(Event e) {
            if (clickListener == null) {
                if (updateWindow != null) {
                    updateWindow.show();
                }
            } else {
                clickListener.UIStatusTextClicked();
            }
        }
    };
    statusText.addListener(SWT.MouseUp, listener);
    statusText.addListener(SWT.MouseDoubleClick, listener);
    // KN: Don't know why OSX is treated differently but this check was already here from the previous code
    if (Constants.isOSX) {
        progressBar = new AZProgressBar(statusBar, true);
    } else {
        progressBar = new AZProgressBar(statusBar, false);
    }
    progressBar.setVisible(false);
    progressGridData = new GridData(SWT.CENTER, SWT.CENTER, false, false);
    progressGridData.widthHint = 5;
    Utils.setLayoutData(progressBar, progressGridData);
    // addRIP();
    /*
		 * Progress reporting window image label
		 */
    progressViewerImageLabel = new CLabelPadding(statusBar, SWT.NONE);
    // image set below after adding listener
    progressViewerImageLabel.setToolTipText(MessageText.getString("Progress.reporting.statusbar.button.tooltip"));
    progressViewerImageLabel.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseDown(MouseEvent e) {
            /*
				 * Opens the progress viewer if any of the reporters in the array is NOT already opened
				 * KN: TODO -- This is only a partial solution to minimize the occurrence of the main progress window
				 * opening more than once.  The one remaining case where multiple windows will still open is
				 * when you have one opened already... then run another process such as a torrent file download...
				 * at this point this new process is not in the already opened window so the check would
				 * allow the second window to open.
				 */
            IProgressReporter[] reporters = PRManager.getReportersArray(false);
            if (reporters.length == 0) {
                /*
					 * If there's nothing to see then open the window; the default widow will say there's nothing to see
					 * KN: calling isShowingEmpty return true is there is already a window opened showing the empty panel
					 */
                if (!ProgressReporterWindow.isShowingEmpty()) {
                    ProgressReporterWindow.open(reporters, ProgressReporterWindow.SHOW_TOOLBAR);
                }
            } else {
                for (int i = 0; i < reporters.length; i++) {
                    if (!ProgressReporterWindow.isOpened(reporters[i])) {
                        ProgressReporterWindow.open(reporters, ProgressReporterWindow.SHOW_TOOLBAR);
                        break;
                    }
                }
            }
        }
    });
    progressViewerImageLabel.addDisposeListener(new DisposeListener() {

        @Override
        public void widgetDisposed(DisposeEvent e) {
            ImageLoader imageLoader = ImageLoader.getInstance();
            imageLoader.releaseImage("progress_error");
            imageLoader.releaseImage("progress_info");
            imageLoader.releaseImage("progress_viewer");
        }
    });
    this.plugin_label_composite = new Composite(statusBar, SWT.NONE);
    this.plugin_label_composite.setForeground(fgColor);
    GridLayout gridLayout = new GridLayout();
    gridLayout.horizontalSpacing = 0;
    gridLayout.verticalSpacing = 0;
    gridLayout.marginHeight = 0;
    gridLayout.marginBottom = 0;
    gridLayout.marginTop = 0;
    gridLayout.marginLeft = 0;
    gridLayout.marginRight = 0;
    // Something nice and big. :)
    gridLayout.numColumns = 20;
    GridData gridData = new GridData(GridData.FILL_VERTICAL);
    gridData.heightHint = height;
    gridData.minimumHeight = height;
    plugin_label_composite.setLayout(gridLayout);
    plugin_label_composite.setLayoutData(gridData);
    srStatus = new CLabelPadding(statusBar, borderFlag);
    srStatus.setText(MessageText.getString("SpeedView.stats.ratio"));
    Utils.addAndFireParameterListener(mapConfigListeners, true, "Status Area Show SR", new ParameterListener() {

        @Override
        public void parameterChanged(String parameterName) {
            srStatus.setVisible(COConfigurationManager.getBooleanParameter(parameterName));
            statusBar.layout();
        }
    });
    natStatus = new CLabelPadding(statusBar, borderFlag);
    natStatus.setText("");
    final Menu natStatusMenu = new Menu(statusBar.getShell(), SWT.POP_UP);
    natStatus.setMenu(natStatusMenu);
    MenuItem nat_test = new MenuItem(natStatusMenu, SWT.PUSH);
    Messages.setLanguageText(nat_test, "MainWindow.menu.tools.nattest");
    nat_test.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent arg0) {
            new NatTestWindow();
        }
    });
    Utils.addAndFireParameterListener(mapConfigListeners, true, "Status Area Show NAT", new ParameterListener() {

        @Override
        public void parameterChanged(String parameterName) {
            natStatus.setVisible(COConfigurationManager.getBooleanParameter(parameterName));
            statusBar.layout();
        }
    });
    dhtStatus = new CLabelPadding(statusBar, borderFlag);
    dhtStatus.setText("");
    dhtStatus.setToolTipText(MessageText.getString("MainWindow.dht.status.tooltip"));
    Utils.addAndFireParameterListener(mapConfigListeners, true, "Status Area Show DDB", new ParameterListener() {

        @Override
        public void parameterChanged(String parameterName) {
            dhtStatus.setVisible(COConfigurationManager.getBooleanParameter(parameterName));
            statusBar.layout();
        }
    });
    // ip filters
    ipBlocked = new CLabelPadding(statusBar, borderFlag);
    // $NON-NLS-1$
    ipBlocked.setText("{} IPs:");
    Messages.setLanguageText(ipBlocked, "MainWindow.IPs.tooltip");
    ipBlocked.addListener(SWT.MouseDoubleClick, new ListenerNeedingCoreRunning() {

        @Override
        public void handleEvent(Core core, Event event) {
            BlockedIpsWindow.showBlockedIps(core, parent.getShell());
        }
    });
    final Menu menuIPFilter = new Menu(statusBar.getShell(), SWT.POP_UP);
    ipBlocked.setMenu(menuIPFilter);
    menuIPFilter.addListener(SWT.Show, new Listener() {

        @Override
        public void handleEvent(Event e) {
            MenuItem[] oldItems = menuIPFilter.getItems();
            for (int i = 0; i < oldItems.length; i++) {
                oldItems[i].dispose();
            }
            if (!CoreFactory.isCoreRunning()) {
                return;
            }
            Core core = CoreFactory.getSingleton();
            final IpFilter ip_filter = core.getIpFilterManager().getIPFilter();
            final MenuItem ipfEnable = new MenuItem(menuIPFilter, SWT.CHECK);
            ipfEnable.setSelection(ip_filter.isEnabled());
            Messages.setLanguageText(ipfEnable, "MyTorrentsView.menu.ipf_enable");
            ipfEnable.addSelectionListener(new SelectionAdapter() {

                @Override
                public void widgetSelected(SelectionEvent e) {
                    ip_filter.setEnabled(ipfEnable.getSelection());
                }
            });
            final MenuItem ipfOptions = new MenuItem(menuIPFilter, SWT.PUSH);
            Messages.setLanguageText(ipfOptions, "ipfilter.options");
            ipfOptions.addSelectionListener(new SelectionAdapter() {

                @Override
                public void widgetSelected(SelectionEvent e) {
                    UIFunctions uif = UIFunctionsManager.getUIFunctions();
                    if (uif != null) {
                        uif.getMDI().showEntryByID(MultipleDocumentInterface.SIDEBAR_SECTION_CONFIG, "ipfilter");
                    }
                }
            });
        }
    });
    Utils.addAndFireParameterListener(mapConfigListeners, true, "Status Area Show IPF", new ParameterListener() {

        @Override
        public void parameterChanged(String parameterName) {
            ipBlocked.setVisible(COConfigurationManager.getBooleanParameter(parameterName));
            statusBar.layout();
        }
    });
    // down speed
    statusDown = new CLabelPadding(statusBar, borderFlag);
    statusDown.setImage(imageLoader.getImage("down"));
    // statusDown.setText(/*MessageText.getString("ConfigView.download.abbreviated") +*/"n/a");
    Messages.setLanguageText(statusDown, "MainWindow.status.updowndetails.tooltip");
    Listener lStats = new Listener() {

        @Override
        public void handleEvent(Event e) {
            uiFunctions.getMDI().loadEntryByID(StatsView.VIEW_ID, true, false, "TransferStatsView");
        }
    };
    statusUp = new CLabelPadding(statusBar, borderFlag);
    statusUp.setImage(imageLoader.getImage("up"));
    // statusUp.setText(/*MessageText.getString("ConfigView.upload.abbreviated") +*/"n/a");
    Messages.setLanguageText(statusUp, "MainWindow.status.updowndetails.tooltip");
    statusDown.addListener(SWT.MouseDoubleClick, lStats);
    statusUp.addListener(SWT.MouseDoubleClick, lStats);
    Listener lDHT = new Listener() {

        @Override
        public void handleEvent(Event e) {
            uiFunctions.getMDI().loadEntryByID(StatsView.VIEW_ID, true, false, "DHTView");
        }
    };
    dhtStatus.addListener(SWT.MouseDoubleClick, lDHT);
    Listener lSR = new Listener() {

        @Override
        public void handleEvent(Event e) {
            uiFunctions.getMDI().loadEntryByID(StatsView.VIEW_ID, true, false, "SpeedView");
            OverallStats stats = StatsFactory.getStats();
            if (stats == null) {
                return;
            }
            long ratio = (1000 * stats.getUploadedBytes() / (stats.getDownloadedBytes() + 1));
            if (ratio < 900) {
            // Utils.launch(Constants.AZUREUS_WIKI + "Share_Ratio");
            }
        }
    };
    srStatus.addListener(SWT.MouseDoubleClick, lSR);
    Listener lNAT = new ListenerNeedingCoreRunning() {

        @Override
        public void handleEvent(Core core, Event e) {
            uiFunctions.getMDI().loadEntryByID(MultipleDocumentInterface.SIDEBAR_SECTION_CONFIG, true, false, ConfigSection.SECTION_CONNECTION);
            if (PluginInitializer.getDefaultInterface().getConnectionManager().getNATStatus() != ConnectionManager.NAT_OK) {
                Utils.launch(Constants.AZUREUS_WIKI + "NAT_problem");
            }
        }
    };
    natStatus.addListener(SWT.MouseDoubleClick, lNAT);
    boolean bSpeedMenu = COConfigurationManager.getBooleanParameter("GUI_SWT_bOldSpeedMenu");
    if (bSpeedMenu) {
        // Status Bar Menu construction
        final Menu menuUpSpeed = new Menu(statusBar.getShell(), SWT.POP_UP);
        menuUpSpeed.addListener(SWT.Show, new Listener() {

            @Override
            public void handleEvent(Event e) {
                if (!CoreFactory.isCoreRunning()) {
                    return;
                }
                Core core = CoreFactory.getSingleton();
                GlobalManager globalManager = core.getGlobalManager();
                SelectableSpeedMenu.generateMenuItems(menuUpSpeed, core, globalManager, true);
            }
        });
        statusUp.setMenu(menuUpSpeed);
    } else {
        statusUp.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseDown(MouseEvent e) {
                if (!(e.button == 3 || (e.button == 1 && e.stateMask == SWT.CONTROL))) {
                    return;
                }
                Event event = new Event();
                event.type = SWT.MouseUp;
                event.widget = e.widget;
                event.stateMask = e.stateMask;
                event.button = e.button;
                e.widget.getDisplay().post(event);
                CoreWaiterSWT.waitForCoreRunning(new CoreRunningListener() {

                    @Override
                    public void coreRunning(Core core) {
                        SelectableSpeedMenu.invokeSlider(statusUp, core, true);
                    }
                });
            }
        });
    }
    if (bSpeedMenu) {
        final Menu menuDownSpeed = new Menu(statusBar.getShell(), SWT.POP_UP);
        menuDownSpeed.addListener(SWT.Show, new Listener() {

            @Override
            public void handleEvent(Event e) {
                if (!CoreFactory.isCoreRunning()) {
                    return;
                }
                Core core = CoreFactory.getSingleton();
                GlobalManager globalManager = core.getGlobalManager();
                SelectableSpeedMenu.generateMenuItems(menuDownSpeed, core, globalManager, false);
            }
        });
        statusDown.setMenu(menuDownSpeed);
    } else {
        statusDown.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseDown(MouseEvent e) {
                if (!(e.button == 3 || (e.button == 1 && e.stateMask == SWT.CONTROL))) {
                    return;
                }
                Event event = new Event();
                event.type = SWT.MouseUp;
                event.widget = e.widget;
                event.stateMask = e.stateMask;
                event.button = e.button;
                e.widget.getDisplay().post(event);
                CoreWaiterSWT.waitForCoreRunning(new CoreRunningListener() {

                    @Override
                    public void coreRunning(Core core) {
                        SelectableSpeedMenu.invokeSlider(statusDown, core, false);
                    }
                });
            }
        });
    }
    statusWarnings = new CLabelPadding(statusBar, borderFlag);
    warningIcon = imageLoader.getImage("image.sidebar.vitality.alert");
    warningGreyIcon = imageLoader.getImage("image.sidebar.vitality.alert-gray");
    infoIcon = imageLoader.getImage("image.sidebar.vitality.info");
    updateStatusWarnings(null, false);
    Messages.setLanguageText(statusWarnings, "MainWindow.status.warning.tooltip");
    alertHistoryListener = new AlertHistoryListener() {

        @Override
        public void alertHistoryAdded(LogAlert alert) {
            updateStatusWarnings(alert, true);
        }

        @Override
        public void alertHistoryRemoved(LogAlert alert) {
            updateStatusWarnings(alert, false);
        }
    };
    Alerts.addMessageHistoryListener(alertHistoryListener);
    statusWarnings.addMouseListener(new MouseListener() {

        @Override
        public void mouseUp(MouseEvent e) {
            if (e.button != 1) {
                return;
            }
            if (SystemWarningWindow.numWarningWindowsOpen > 0) {
                return;
            }
            ArrayList<LogAlert> alerts = Alerts.getUnviewedLogAlerts();
            if (alerts.size() == 0) {
                return;
            }
            Shell shell = statusWarnings.getShell();
            Rectangle bounds = statusWarnings.getClientArea();
            Point ptBottomRight = statusWarnings.toDisplay(bounds.x + bounds.width, bounds.y);
            new SystemWarningWindow(alerts.get(0), ptBottomRight, shell, 0);
        }

        @Override
        public void mouseDown(MouseEvent e) {
        }

        @Override
        public void mouseDoubleClick(MouseEvent e) {
        }
    });
    Menu menuStatusWarnings = new Menu(statusBar.getShell(), SWT.POP_UP);
    statusWarnings.setMenu(menuStatusWarnings);
    final MenuItem dismissAllItem = new MenuItem(menuStatusWarnings, SWT.PUSH);
    menuStatusWarnings.addListener(SWT.Show, new Listener() {

        @Override
        public void handleEvent(Event e) {
            dismissAllItem.setEnabled(Alerts.getUnviewedLogAlerts().size() > 0);
        }
    });
    Messages.setLanguageText(dismissAllItem, "label.dismiss.all");
    dismissAllItem.addListener(SWT.Selection, new Listener() {

        @Override
        public void handleEvent(Event event) {
            ArrayList<LogAlert> alerts = Alerts.getUnviewedLogAlerts();
            for (LogAlert a : alerts) {
                Alerts.markAlertAsViewed(a);
            }
        }
    });
    Utils.addAndFireParameterListener(mapConfigListeners, true, "status.rategraphs", new ParameterListener() {

        @Override
        public void parameterChanged(String parameterName) {
            boolean doRateGraphs = COConfigurationManager.getBooleanParameter("status.rategraphs");
            if (doRateGraphs) {
                if (imgRec == null || imgRec.isDisposed()) {
                    imgRec = new Image(display, 100, 20);
                    GC gc = new GC(imgRec);
                    gc.setBackground(statusDown.getBackground());
                    gc.fillRectangle(0, 0, 100, 20);
                    gc.dispose();
                    statusDown.setBackgroundImage(imgRec);
                }
                if (imgSent == null || imgSent.isDisposed()) {
                    imgSent = new Image(display, 100, 20);
                    GC gc = new GC(imgSent);
                    gc.setBackground(statusUp.getBackground());
                    gc.fillRectangle(0, 0, 100, 20);
                    gc.dispose();
                    statusUp.setBackgroundImage(imgSent);
                }
            } else {
                statusUp.setBackgroundImage(null);
                statusDown.setBackgroundImage(null);
                Utils.disposeSWTObjects(imgRec, imgSent);
                imgRec = imgSent = null;
            }
        }
    });
    // ///////
    progressListener = new ProgressListener();
    PRManager.addListener(progressListener);
    uiFunctions.getUIUpdater().addUpdater(this);
    ArrayList<Runnable> list;
    this_mon.enter();
    try {
        list = listRunAfterInit;
        listRunAfterInit = null;
    } finally {
        this_mon.exit();
    }
    for (Runnable runnable : list) {
        try {
            runnable.run();
        } catch (Exception e) {
            Debug.out(e);
        }
    }
    statusBar.layout(true);
    return statusBar;
}
Also used : GlobalManager(com.biglybt.core.global.GlobalManager) UIFunctions(com.biglybt.ui.UIFunctions) AlertHistoryListener(com.biglybt.ui.swt.Alerts.AlertHistoryListener) CoreRunningListener(com.biglybt.core.CoreRunningListener) FormAttachment(org.eclipse.swt.layout.FormAttachment) Core(com.biglybt.core.Core) FormData(org.eclipse.swt.layout.FormData) LogAlert(com.biglybt.core.logging.LogAlert) UIUpdater(com.biglybt.ui.common.updater.UIUpdater) CLabel(org.eclipse.swt.custom.CLabel) IpFilter(com.biglybt.core.ipfilter.IpFilter) ParameterListener(com.biglybt.core.config.ParameterListener) UIStatusTextClickListener(com.biglybt.ui.UIStatusTextClickListener) AlertHistoryListener(com.biglybt.ui.swt.Alerts.AlertHistoryListener) CoreRunningListener(com.biglybt.core.CoreRunningListener) OverallStats(com.biglybt.core.stats.transfer.OverallStats) GridLayout(org.eclipse.swt.layout.GridLayout) NatTestWindow(com.biglybt.ui.swt.nat.NatTestWindow) GridData(org.eclipse.swt.layout.GridData) ParameterListener(com.biglybt.core.config.ParameterListener) ImageLoader(com.biglybt.ui.swt.imageloader.ImageLoader)

Example 58 with LogAlert

use of com.biglybt.core.logging.LogAlert in project BiglyBT by BiglySoftware.

the class TRBlockingServer method acceptLoop.

protected void acceptLoop(ServerSocket ss) {
    long successfull_accepts = 0;
    long failed_accepts = 0;
    while (!closed) {
        try {
            Socket socket = ss.accept();
            successfull_accepts++;
            String ip = socket.getInetAddress().getHostAddress();
            if ((!isIPFilterEnabled()) || (!ip_filter.isInRange(ip, "Tracker", null))) {
                runProcessor(new TRBlockingServerProcessor(this, socket));
            } else {
                socket.close();
            }
        } catch (Throwable e) {
            if (!closed) {
                failed_accepts++;
                Logger.log(new LogEvent(LOGID, "TRTrackerServer: listener failed on port " + getPort(), e));
                if (failed_accepts > 100 && successfull_accepts == 0) {
                    // looks like its not going to work...
                    // some kind of socket problem
                    Logger.logTextResource(new LogAlert(LogAlert.UNREPEATABLE, LogAlert.AT_ERROR, "Network.alert.acceptfail"), new String[] { "" + getPort(), "TCP" });
                    break;
                }
            }
        }
    }
}
Also used : LogEvent(com.biglybt.core.logging.LogEvent) Socket(java.net.Socket) ServerSocket(java.net.ServerSocket) SSLServerSocket(javax.net.ssl.SSLServerSocket) LogAlert(com.biglybt.core.logging.LogAlert)

Example 59 with LogAlert

use of com.biglybt.core.logging.LogAlert in project BiglyBT by BiglySoftware.

the class PRUDPPacketHandlerImpl method receiveLoop.

protected void receiveLoop(AESemaphore init_sem) {
    long last_socket_close_time = 0;
    NetworkAdminPropertyChangeListener prop_listener = new NetworkAdminPropertyChangeListener() {

        @Override
        public void propertyChanged(String property) {
            if (property == NetworkAdmin.PR_DEFAULT_BIND_ADDRESS) {
                setDefaultBindAddress(NetworkAdmin.getSingleton().getSingleHomedServiceBindAddress());
            }
        }
    };
    NetworkAdmin.getSingleton().addPropertyChangeListener(prop_listener);
    try {
        while (!(failed || destroyed)) {
            if (socket != null) {
                try {
                    socket.close();
                } catch (Throwable e) {
                    Debug.printStackTrace(e);
                }
            }
            InetSocketAddress address = null;
            DatagramSocket new_socket = null;
            try {
                if (target_bind_ip == null) {
                    address = new InetSocketAddress("127.0.0.1", port);
                    new_socket = new DatagramSocket(port);
                } else {
                    address = new InetSocketAddress(target_bind_ip, port);
                    new_socket = new DatagramSocket(address);
                }
            } catch (BindException e) {
                // some firewalls (e.g. Comodo) seem to close sockets on us and then not release them quickly so we come through here and get
                // an 'address already in use' failure
                boolean rebind_worked = false;
                int delay = 25;
                for (int i = 0; i < 16 && !(failed || destroyed); i++) {
                    try {
                        Thread.sleep(delay);
                        delay = delay * 2;
                        if (delay > 1000) {
                            delay = 1000;
                        }
                        if (target_bind_ip == null) {
                            address = new InetSocketAddress("127.0.0.1", port);
                            new_socket = new DatagramSocket(port);
                        } else {
                            address = new InetSocketAddress(target_bind_ip, port);
                            new_socket = new DatagramSocket(address);
                        }
                        if (Logger.isEnabled())
                            Logger.log(new LogEvent(LOGID, "PRUDPPacketReceiver: rebind to " + target_bind_ip + " worked (tries=" + (i + 1) + ") after getting " + Debug.getNestedExceptionMessage(e)));
                        rebind_worked = true;
                        break;
                    } catch (Throwable f) {
                    }
                }
                if (!rebind_worked) {
                    if (Logger.isEnabled())
                        Logger.log(new LogEvent(LOGID, "PRUDPPacketReceiver: bind failed with " + Debug.getNestedExceptionMessage(e)));
                    if (target_bind_ip.isAnyLocalAddress()) {
                        InetAddress guess = NetworkAdmin.getSingleton().guessRoutableBindAddress();
                        if (guess != null) {
                            if (Logger.isEnabled())
                                Logger.log(new LogEvent(LOGID, "PRUDPPacketReceiver: retrying with bind IP guess of " + guess));
                            try {
                                InetSocketAddress guess_address = new InetSocketAddress(guess, port);
                                new_socket = new DatagramSocket(guess_address);
                                target_bind_ip = guess;
                                address = guess_address;
                                if (Logger.isEnabled())
                                    Logger.log(new LogEvent(LOGID, "PRUDPPacketReceiver: Switched to explicit bind ip " + target_bind_ip + " after initial bind failure with wildcard (" + e.getMessage() + ")"));
                            } catch (Throwable f) {
                                throw (e);
                            }
                        } else {
                            throw (e);
                        }
                    } else {
                        throw (e);
                    }
                }
            }
            new_socket.setReuseAddress(true);
            // short timeout on receive so that we can interrupt a receive fairly quickly
            new_socket.setSoTimeout(1000);
            // only make the socket public once fully configured
            socket = new_socket;
            current_bind_ip = target_bind_ip;
            init_sem.release();
            if (Logger.isEnabled())
                Logger.log(new LogEvent(LOGID, "PRUDPPacketReceiver: receiver established on port " + port + (current_bind_ip == null ? "" : (", bound to " + current_bind_ip))));
            byte[] buffer = null;
            long successful_accepts = 0;
            long failed_accepts = 0;
            while (!(failed || destroyed)) {
                if (current_bind_ip != target_bind_ip) {
                    break;
                }
                try {
                    if (buffer == null) {
                        buffer = new byte[MAX_PACKET_SIZE];
                    }
                    DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address);
                    receiveFromSocket(packet);
                    if (packet.getLength() > MAX_PACKET_SIZE) {
                        if (MAX_PACKET_SIZE < PRUDPPacket.MAX_PACKET_SIZE) {
                            Debug.out("UDP Packet truncated: received length=" + packet.getLength() + ", current max=" + MAX_PACKET_SIZE);
                            MAX_PACKET_SIZE = Math.min(packet.getLength() + 256, PRUDPPacket.MAX_PACKET_SIZE);
                            buffer = null;
                            continue;
                        }
                    }
                    long receive_time = SystemTime.getCurrentTime();
                    successful_accepts++;
                    failed_accepts = 0;
                    for (PRUDPPrimordialHandler prim_hand : primordial_handlers) {
                        if (prim_hand.packetReceived(packet)) {
                            // primordial handlers get their own buffer as we can't guarantee
                            // that they don't need to hang onto the data
                            buffer = null;
                            stats.primordialPacketReceived(packet.getLength());
                            break;
                        }
                    }
                    if (buffer != null) {
                        process(packet, receive_time);
                    }
                } catch (SocketTimeoutException e) {
                } catch (Throwable e) {
                    // on vista we get periodic socket closures
                    String message = e.getMessage();
                    if (socket.isClosed() || (message != null && message.toLowerCase().contains("socket closed"))) {
                        long now = SystemTime.getCurrentTime();
                        if (now - last_socket_close_time < 500) {
                            Thread.sleep(250);
                        }
                        last_socket_close_time = now;
                        if (Logger.isEnabled())
                            Logger.log(new LogEvent(LOGID, "PRUDPPacketReceiver: recycled UDP port " + port + " after close: ok=" + successful_accepts));
                        break;
                    }
                    failed_accepts++;
                    if (Logger.isEnabled())
                        Logger.log(new LogEvent(LOGID, "PRUDPPacketReceiver: receive failed on port " + port + ": ok=" + successful_accepts + ", fails=" + failed_accepts, e));
                    if ((failed_accepts > 100 && successful_accepts == 0) || failed_accepts > 1000) {
                        Logger.logTextResource(new LogAlert(LogAlert.UNREPEATABLE, LogAlert.AT_ERROR, "Network.alert.acceptfail"), new String[] { "" + port, "UDP" });
                        // break, sometimes get a screaming loop. e.g.
                        /*
							[2:01:55]  DEBUG::Tue Dec 07 02:01:55 EST 2004
							[2:01:55]    java.net.SocketException: Socket operation on nonsocket: timeout in datagram socket peek
							[2:01:55]  	at java.net.PlainDatagramSocketImpl.peekData(Native Method)
							[2:01:55]  	at java.net.DatagramSocket.receive(Unknown Source)
							[2:01:55]  	at com.biglybt.core.tracker.server.impl.udp.TRTrackerServerUDP.recvLoop(TRTrackerServerUDP.java:118)
							[2:01:55]  	at com.biglybt.core.tracker.server.impl.udp.TRTrackerServerUDP$1.runSupport(TRTrackerServerUDP.java:90)
							[2:01:55]  	at com.biglybt.core.util.AEThread.run(AEThread.java:45)
							*/
                        init_error = e;
                        failed = true;
                    }
                }
            }
        }
    } catch (Throwable e) {
        init_error = e;
        if (!(e instanceof BindException && Constants.isWindowsVistaOrHigher)) {
            Logger.logTextResource(new LogAlert(LogAlert.UNREPEATABLE, LogAlert.AT_ERROR, "Tracker.alert.listenfail"), new String[] { "UDP:" + port });
        }
        Logger.log(new LogEvent(LOGID, "PRUDPPacketReceiver: " + "DatagramSocket bind failed on port " + port, e));
    } finally {
        init_sem.release();
        destroy_sem.releaseForever();
        if (socket != null) {
            try {
                socket.close();
            } catch (Throwable e) {
                Debug.printStackTrace(e);
            }
        }
        // make sure we destroy the delegate too if something happend
        PRUDPPacketHandlerImpl delegate = altProtocolDelegate;
        if (delegate != null) {
            delegate.destroy();
        }
        NetworkAdmin.getSingleton().removePropertyChangeListener(prop_listener);
    }
}
Also used : LogEvent(com.biglybt.core.logging.LogEvent) LogAlert(com.biglybt.core.logging.LogAlert) NetworkAdminPropertyChangeListener(com.biglybt.core.networkmanager.admin.NetworkAdminPropertyChangeListener)

Example 60 with LogAlert

use of com.biglybt.core.logging.LogAlert in project BiglyBT by BiglySoftware.

the class PlatformManagerImpl method getApplicationEXELocation.

protected File getApplicationEXELocation() throws PlatformManagerException {
    if (az_exe == null) {
        try {
            String az_home;
            // Try the app dir first, because we may not be using the one in the registry
            az_home = SystemProperties.getApplicationPath();
            az_exe = new File(az_home + File.separator + app_exe_name).getAbsoluteFile();
            if (!az_exe.exists()) {
                try {
                    az_home = access.getApplicationInstallDir(app_name);
                    az_exe = new File(az_home + File.separator + app_exe_name).getAbsoluteFile();
                    if (!az_exe.exists()) {
                        throw (new PlatformManagerException(app_exe_name + " not found in " + az_home + ", please re-install"));
                    }
                } catch (Throwable e) {
                }
            }
            if (!az_exe.exists()) {
                String msg = app_exe_name + " not found in " + az_home + " - can't check file associations. Please re-install " + app_name;
                az_exe = null;
                if (!az_exe_checked) {
                    Logger.log(new LogAlert(LogAlert.UNREPEATABLE, LogAlert.AT_WARNING, msg));
                }
                throw (new PlatformManagerException(msg));
            }
        } finally {
            az_exe_checked = true;
        }
    }
    return (az_exe);
}
Also used : PlatformManagerException(com.biglybt.pif.platform.PlatformManagerException) LogAlert(com.biglybt.core.logging.LogAlert)

Aggregations

LogAlert (com.biglybt.core.logging.LogAlert)72 File (java.io.File)21 LogEvent (com.biglybt.core.logging.LogEvent)20 URL (java.net.URL)7 Core (com.biglybt.core.Core)5 ParameterListener (com.biglybt.core.config.ParameterListener)5 DownloadManager (com.biglybt.core.download.DownloadManager)5 TOTorrent (com.biglybt.core.torrent.TOTorrent)5 UIFunctions (com.biglybt.ui.UIFunctions)5 IOException (java.io.IOException)5 ArrayList (java.util.ArrayList)5 VuzeFile (com.biglybt.core.vuzefile.VuzeFile)4 PlatformManagerException (com.biglybt.pif.platform.PlatformManagerException)4 Method (java.lang.reflect.Method)4 CoreRunningListener (com.biglybt.core.CoreRunningListener)3 TOTorrentException (com.biglybt.core.torrent.TOTorrentException)3 URLClassLoader (java.net.URLClassLoader)3 CoreException (com.biglybt.core.CoreException)2 CacheFile (com.biglybt.core.diskmanager.cache.CacheFile)2 DownloadManagerInitialisationAdapter (com.biglybt.core.download.DownloadManagerInitialisationAdapter)2