Search in sources :

Example 71 with ImageLoader

use of com.biglybt.ui.swt.imageloader.ImageLoader 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);
    statusText.setLayoutData(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;
    progressBar.setLayoutData(progressGridData);
    // addRIP();
    /*
		 * Progress reporting window image label
		 */
    progressViewerImageLabel = new CLabelPadding(statusBar, SWT.NONE);
    // image set below after adding listener
    Utils.setTT(progressViewerImageLabel, 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("");
    Utils.setTT(dhtStatus, 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(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 72 with ImageLoader

use of com.biglybt.ui.swt.imageloader.ImageLoader 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 sCountAndTime = MessageText.getString("label.xOfTotal", new String[] { "" + historyPosition + 1, "" + getWarningCount() });
    sCountAndTime += " " + new SimpleDateFormat().format(new Date(logAlert.when));
    spCount = new GCStringPrinter(gc, sCountAndTime, 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 sCountAndTime = MessageText.getString("label.xOfTotal", new String[] { "" + (historyPosition + 1), "" + getWarningCount() });
            sCountAndTime += " " + new SimpleDateFormat().format(new Date(logAlert.when));
            e.gc.setAlpha(180);
            Font lastFont = e.gc.getFont();
            e.gc.setFont(fontCount);
            spCount = new GCStringPrinter(e.gc, sCountAndTime, 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) Date(java.util.Date) LogAlert(com.biglybt.core.logging.LogAlert) ImageLoader(com.biglybt.ui.swt.imageloader.ImageLoader) SimpleDateFormat(java.text.SimpleDateFormat)

Example 73 with ImageLoader

use of com.biglybt.ui.swt.imageloader.ImageLoader in project BiglyBT by BiglySoftware.

the class TabbedMDI_Ren method draw.

@Override
protected void draw(int part, int state, Rectangle bounds, GC gc) {
    if (part < 0 || part >= tabFolder.getItemCount()) {
        try {
            // super.draw(part, state & ~(SWT.FOREGROUND), bounds, gc);
            super.draw(part, state, bounds, gc);
        } catch (Throwable t) {
            Debug.out(t);
        }
        return;
    }
    try {
        super.draw(part, state & ~(SWT.FOREGROUND), bounds, gc);
    // super.draw(part, state, bounds, gc);
    } catch (Throwable t) {
        Debug.out(t);
    }
    if (bounds.width == 0 || bounds.height == 0) {
        return;
    }
    try {
        CTabItem item = mdi.getTabFolder().getItem(part);
        if (item == null) {
            return;
        }
        TabbedEntry entry = mdi.getEntryFromTabItem(item);
        if (entry == null) {
            return;
        }
        int x2 = bounds.x + bounds.width;
        boolean showUnselectedClose = tabFolder.getUnselectedCloseVisible();
        boolean selected = (state & SWT.SELECTED) != 0;
        boolean parentHasClose = (tabFolder.getStyle() & SWT.CLOSE) != 0;
        boolean showingClose = (parentHasClose || item.getShowClose()) && (showUnselectedClose || selected);
        Rectangle closeRect = null;
        int closeImageState = 0;
        if (showingClose) {
            try {
                Field fldCloseRect = CTabItem.class.getDeclaredField("closeRect");
                fldCloseRect.setAccessible(true);
                closeRect = (Rectangle) fldCloseRect.get(item);
                if (item.getShowClose() && closeRect != null && closeRect.x > 0) {
                    x2 = closeRect.x;
                }
                Field fldCloseImageState = CTabItem.class.getDeclaredField("closeImageState");
                fldCloseImageState.setAccessible(true);
                closeImageState = (int) fldCloseImageState.get(item);
            } catch (Throwable t) {
                x2 -= 20;
            }
        } else {
            x2 -= PADDING_INDICATOR_AND_CLOSE;
        }
        int oldAntiAlias = gc.getAntialias();
        boolean oldAdvanced = gc.getAdvanced();
        try {
            gc.setAdvanced(true);
            gc.setAntialias(SWT.ON);
            List<MdiEntryVitalityImageSWT> vitalityImages = entry.getVitalityImages();
            Collections.reverse(vitalityImages);
            boolean first = true;
            for (MdiEntryVitalityImageSWT vitalityImage : vitalityImages) {
                if (vitalityImage == null || !vitalityImage.isVisible() || vitalityImage.getAlignment() != SWT.RIGHT || vitalityImage.getShowOutsideOfEntry()) {
                    continue;
                }
                if (!selected && vitalityImage.getShowOnlyOnSelection()) {
                    vitalityImage.setHitArea(null);
                    continue;
                }
                vitalityImage.switchSuffix(entry.isActive() ? "-selected" : "");
                Image image = vitalityImage.getImage();
                if (image == null || image.isDisposed()) {
                    continue;
                }
                Rectangle imageBounds = image.getBounds();
                int startX = x2 - imageBounds.width;
                int startY = bounds.y + ((bounds.height - imageBounds.height) / 2) + 1;
                if (first && !vitalityImage.getAlwaysLast()) {
                    // startX -= PADDING_INDICATOR_AND_CLOSE;
                    first = false;
                }
                gc.drawImage(image, startX, startY);
                vitalityImage.setHitArea(new Rectangle(startX, startY, imageBounds.width, imageBounds.height));
                x2 = startX;
                x2 -= PADDING_INDICATOR_X1;
            }
            ViewTitleInfo viewTitleInfo = entry.getViewTitleInfo();
            if (viewTitleInfo != null) {
                String textIndicator = (String) item.getData("textIndicator");
                if (textIndicator != null) {
                    Point textSize = gc.textExtent("" + textIndicator, 0);
                    // Point minTextSize = gc.textExtent("99");
                    // if (textSize.x < minTextSize.x + 2) {
                    // textSize.x = minTextSize.x + 2;
                    // }
                    int width = textSize.x + (PADDING_BUBBLE_X * 2) + PADDING_INDICATOR_X1;
                    int startX = x2 - width;
                    if (first) {
                        startX -= PADDING_INDICATOR_AND_CLOSE;
                        first = false;
                    }
                    int textOffsetY = 0;
                    int height = textSize.y + 1;
                    int startY = bounds.y + ((bounds.height - height) / 2) + 1;
                    Color default_color = ColorCache.getSchemedColor(gc.getDevice(), "#5b6e87");
                    Object color = viewTitleInfo.getTitleInfoProperty(ViewTitleInfo.TITLE_INDICATOR_COLOR);
                    if (color instanceof int[]) {
                        gc.setBackground(ColorCache.getColor(gc.getDevice(), (int[]) color));
                    } else {
                        gc.setBackground(default_color);
                    }
                    Color text_color = Colors.white;
                    int bubbleStartX = startX + PADDING_INDICATOR_X1;
                    int bubbleStartY = startY;
                    int bubbleWidth = width - PADDING_INDICATOR_X1;
                    gc.fillRoundRectangle(bubbleStartX, bubbleStartY, bubbleWidth, height, textSize.y * 2 / 3, height * 2 / 3);
                    if (color != null) {
                        text_color = Colors.getInstance().getReadableColor(gc.getBackground());
                        gc.setBackground(default_color);
                        gc.drawRoundRectangle(bubbleStartX, bubbleStartY, bubbleWidth, height, textSize.y * 2 / 3, height * 2 / 3);
                    }
                    gc.setForeground(text_color);
                    GCStringPrinter.printString(gc, textIndicator, new Rectangle(bubbleStartX, bubbleStartY + textOffsetY, bubbleWidth, height), true, false, SWT.CENTER);
                    x2 = startX;
                }
            }
            // ///////////////
            if ((state & SWT.FOREGROUND) != 0) {
                // draw Image
                Rectangle trim = computeTrim(part, SWT.NONE, 0, 0, 0, 0);
                int xDraw = bounds.x - trim.x;
                Image image = item.getImage();
                if (image != null && !image.isDisposed() && tabFolder.getUnselectedImageVisible()) {
                    Rectangle imageBounds = image.getBounds();
                    // only draw image if it won't overlap with close button
                    int maxImageWidth = bounds.x + bounds.width - xDraw - (trim.width + trim.x);
                    if (showingClose && closeRect != null) {
                        // INTERNAL_SPACING;
                        maxImageWidth -= closeRect.width + 4;
                    }
                    if (imageBounds.width < maxImageWidth) {
                        int imageX = xDraw;
                        int imageHeight = imageBounds.height;
                        int imageY = bounds.y + (bounds.height - imageHeight) / 2;
                        boolean onBottom = (tabFolder.getStyle() & SWT.BOTTOM) != 0;
                        imageY += onBottom ? -1 : 1;
                        int imageWidth = imageBounds.width * imageHeight / imageBounds.height;
                        gc.drawImage(image, imageBounds.x, imageBounds.y, imageBounds.width, imageBounds.height, imageX, imageY, imageWidth, imageHeight);
                        // INTERNAL_SPACING;
                        xDraw += imageWidth + 4;
                    }
                }
                if (showingClose) {
                    if (closeImageState == 0 && Utils.isDarkAppearanceNative() && Constants.isOSX) {
                        // OSX + Linux paint an almost black cross on a black background
                        // hack to take whatever the OS paints and lighten it
                        Image img = new Image(gc.getDevice(), closeRect);
                        GC gcImg = new GC(img);
                        gcImg.setBackground(Colors.black);
                        gcImg.fillRectangle(0, 0, closeRect.width, closeRect.height);
                        try {
                            Method methDrawClose = CTabFolderRenderer.class.getDeclaredMethod("drawClose", GC.class, Rectangle.class, int.class);
                            methDrawClose.setAccessible(true);
                            methDrawClose.invoke(this, gcImg, new Rectangle(0, 0, closeRect.width, closeRect.height), closeImageState);
                        } catch (Throwable t) {
                            t.printStackTrace();
                        }
                        // linux hang here :(
                        ImageData idata = img.getImageData();
                        PaletteData pdata = idata.palette;
                        int redMask = pdata.redMask;
                        int greenMask = pdata.greenMask;
                        int blueMask = pdata.blueMask;
                        int redShift = pdata.redShift;
                        int greenShift = pdata.greenShift;
                        int blueShift = pdata.blueShift;
                        for (int i = 0; i < closeRect.width; i++) {
                            for (int j = 0; j < closeRect.height; j++) {
                                int pixel = idata.getPixel(i, j);
                                int red = pixel & redMask;
                                red = (redShift < 0) ? (red >>> -redShift) : (red << redShift);
                                int green = pixel & greenMask;
                                green = (greenShift < 0) ? (green >>> -greenShift) : (green << greenShift);
                                int blue = pixel & blueMask;
                                blue = (blueShift < 0) ? (blue >>> -blueShift) : (blue << blueShift);
                                int rgb = (red << 16) | (green << 8) | blue;
                                if (rgb != 0x000000) {
                                    Color c = new Color(gc.getDevice(), new RGB(red + 75, green + 75, blue + 75));
                                    gc.setForeground(c);
                                    gc.drawPoint(closeRect.x + i, closeRect.y + j);
                                    c.dispose();
                                }
                            }
                        }
                        gcImg.dispose();
                        img.dispose();
                    } else if (closeImageState == 0 && Utils.isDarkAppearanceNative() && Constants.isLinux) {
                        ImageLoader imageLoader = ImageLoader.getInstance();
                        Image img = imageLoader.getImage("image.tabfolder.close.up._dark");
                        Rectangle b = img.getBounds();
                        gc.drawImage(img, closeRect.x + (closeRect.width - b.width) / 2, closeRect.y + 1 + (closeRect.height - b.height) / 2);
                        imageLoader.releaseImage("image.tabfolder.close.up._dark");
                    } else {
                        try {
                            Method methDrawClose = CTabFolderRenderer.class.getDeclaredMethod("drawClose", GC.class, Rectangle.class, int.class);
                            methDrawClose.setAccessible(true);
                            methDrawClose.invoke(this, gc, closeRect, closeImageState);
                        } catch (Throwable t) {
                            t.printStackTrace();
                        }
                    }
                }
                // Draw Text
                Rectangle printArea = new Rectangle(xDraw, bounds.y + 1, x2 - xDraw + 1, bounds.height);
                gc.setForeground(selected ? tabFolder.getSelectionForeground() : tabFolder.getForeground());
                Font gcFont = gc.getFont();
                gc.setFont(item.getFont() == null ? tabFolder.getFont() : item.getFont());
                GCStringPrinter sp = new GCStringPrinter(gc, item.getText(), printArea, false, true, 0);
                sp.printString();
                gc.setFont(gcFont);
                // draw a Focus rectangle
                if (tabFolder.isFocusControl() && selected) {
                    Display display = tabFolder.getDisplay();
                    if (tabFolder.getSimple() || tabFolder.getSingle()) {
                        Rectangle drawRect = sp.getCalculatedDrawRect();
                        if (drawRect != null) {
                            gc.setBackground(Colors.getSystemColor(display, SWT.COLOR_BLACK));
                            gc.setForeground(Colors.getSystemColor(display, SWT.COLOR_WHITE));
                            gc.drawFocus(drawRect.x - 1, drawRect.y - 1, drawRect.width + 2, drawRect.height + 2);
                        }
                    } else {
                        gc.setForeground(display.getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW));
                        int lineY = tabFolder.getTabHeight();
                        int lineX2 = xDraw + sp.getCalculatedSize().x + 1;
                        gc.drawLine(xDraw, lineY, lineX2, lineY);
                    }
                }
            }
        } finally {
            gc.setAntialias(oldAntiAlias);
            gc.setAdvanced(oldAdvanced);
        }
    } catch (Throwable t) {
        Debug.out(t);
    }
}
Also used : GCStringPrinter(com.biglybt.ui.swt.shells.GCStringPrinter) CTabItem(org.eclipse.swt.custom.CTabItem) Field(java.lang.reflect.Field) Method(java.lang.reflect.Method) CTabFolderRenderer(org.eclipse.swt.custom.CTabFolderRenderer) ImageLoader(com.biglybt.ui.swt.imageloader.ImageLoader) ViewTitleInfo(com.biglybt.ui.common.viewtitleinfo.ViewTitleInfo) Display(org.eclipse.swt.widgets.Display)

Example 74 with ImageLoader

use of com.biglybt.ui.swt.imageloader.ImageLoader in project BiglyBT by BiglySoftware.

the class SubscriptionWizard method initColumns.

private static void initColumns() {
    if (columnsAdded) {
        return;
    }
    columnsAdded = true;
    UIManager uiManager = PluginInitializer.getDefaultInterface().getUIManager();
    TableManager tableManager = uiManager.getTableManager();
    tableManager.registerColumn(Subscription.class, "SubWizName", new TableColumnCreationListener() {

        private Image rssIcon;

        @Override
        public void tableColumnCreated(com.biglybt.pif.ui.tables.TableColumn column) {
            // this'll get triggered for the Subscriptions Overview table too - easiest fix is to default to hidden there
            column.setVisible(column.getTableID().equals("SubscriptionWizard"));
            ImageLoader imageLoader = ImageLoader.getInstance();
            rssIcon = imageLoader.getImage("icon_rss");
            column.addCellAddedListener(new TableCellAddedListener() {

                @Override
                public void cellAdded(TableCell cell) {
                    Subscription sub = (Subscription) cell.getDataSource();
                    if (sub.isSubscribed()) {
                        cell.setForeground(0xa0, 0xa0, 0xa0);
                    }
                    cell.setText(sub.getName());
                    ((TableCellSWT) cell).setIcon(rssIcon);
                    cell.setToolTip(sub.getNameEx());
                }
            });
        }
    });
    tableManager.registerColumn(Subscription.class, "SubWizRank", new TableColumnCreationListener() {

        @Override
        public void tableColumnCreated(com.biglybt.pif.ui.tables.TableColumn column) {
            column.setWidthLimits(RANK_COLUMN_WIDTH, RANK_COLUMN_WIDTH);
            // as above
            column.setVisible(column.getTableID().equals("SubscriptionWizard"));
            column.addCellRefreshListener(new TableCellRefreshListener() {

                @Override
                public void refresh(TableCell cell) {
                    Subscription sub = (Subscription) cell.getDataSource();
                    cell.setSortValue(sub.getCachedPopularity());
                }
            });
            if (column instanceof TableColumnCore) {
                TableColumnCore columnCore = (TableColumnCore) column;
                columnCore.setSortAscending(false);
                columnCore.addCellOtherListener("SWTPaint", new TableCellSWTPaintListener() {

                    @Override
                    public void cellPaint(GC gc, TableCellSWT cell) {
                        Subscription sub = (Subscription) cell.getDataSource();
                        Rectangle bounds = cell.getBounds();
                        bounds.width -= 5;
                        bounds.height -= 7;
                        bounds.x += 2;
                        bounds.y += 3;
                        gc.setBackground(ColorCache.getColor(gc.getDevice(), 255, 255, 255));
                        gc.fillRectangle(bounds);
                        gc.setForeground(ColorCache.getColor(gc.getDevice(), 200, 200, 200));
                        gc.drawRectangle(bounds);
                        bounds.width -= 2;
                        bounds.height -= 2;
                        bounds.x += 1;
                        bounds.y += 1;
                        long popularity = sub.getCachedPopularity();
                        // Rank in pixels between 0 and 80
                        // 0 -> no subscriber
                        // 80 -> 1000 subscribers
                        int rank = 80 * (int) popularity / 1000;
                        if (rank > 80)
                            rank = 80;
                        if (rank < 5)
                            rank = 5;
                        Rectangle clipping = gc.getClipping();
                        bounds.width = rank;
                        bounds.height -= 1;
                        bounds.x += 1;
                        bounds.y += 1;
                        Utils.setClipping(gc, bounds);
                        ImageLoader imageLoader = ImageLoader.getInstance();
                        Image rankingBars = imageLoader.getImage("ranking_bars");
                        gc.drawImage(rankingBars, bounds.x, bounds.y);
                        imageLoader.releaseImage("ranking_bars");
                        Utils.setClipping(gc, clipping);
                    }
                });
            }
        }
    });
    TableColumnManager tcm = TableColumnManager.getInstance();
    tcm.setDefaultColumnNames(TABLE_SUB_WIZ, new String[] { "SubWizName", "SubWizRank" });
}
Also used : TableCellSWTPaintListener(com.biglybt.ui.swt.views.table.TableCellSWTPaintListener) TableCellSWT(com.biglybt.ui.swt.views.table.TableCellSWT) Rectangle(org.eclipse.swt.graphics.Rectangle) UIManager(com.biglybt.pif.ui.UIManager) TableColumnCore(com.biglybt.ui.common.table.TableColumnCore) Image(org.eclipse.swt.graphics.Image) TableCellAddedListener(com.biglybt.pif.ui.tables.TableCellAddedListener) TableColumnManager(com.biglybt.ui.common.table.impl.TableColumnManager) TableCellRefreshListener(com.biglybt.pif.ui.tables.TableCellRefreshListener) TableColumnCreationListener(com.biglybt.pif.ui.tables.TableColumnCreationListener) TableCell(com.biglybt.pif.ui.tables.TableCell) TableManager(com.biglybt.pif.ui.tables.TableManager) ImageLoader(com.biglybt.ui.swt.imageloader.ImageLoader) Subscription(com.biglybt.core.subs.Subscription) GC(org.eclipse.swt.graphics.GC)

Example 75 with ImageLoader

use of com.biglybt.ui.swt.imageloader.ImageLoader in project BiglyBT by BiglySoftware.

the class SBC_SubscriptionResultsView method skinObjectInitialShow.

@Override
public Object skinObjectInitialShow(SWTSkinObject skinObject, Object params) {
    CoreFactory.addCoreRunningListener(new CoreRunningListener() {

        @Override
        public void coreRunning(Core core) {
            initColumns(core);
        }
    });
    MultipleDocumentInterfaceSWT mdi = UIFunctionsManagerSWT.getUIFunctionsSWT().getMDISWT();
    if (mdi != null && ds != null) {
        String mdi_key = "Subscription_" + ByteFormatter.encodeString(ds.getPublicKey());
        mdi_entry = mdi.getEntry(mdi_key);
        if (mdi_entry != null) {
            mdi_entry.addToolbarEnabler(this);
            MdiEntrySWT to_deactivate = null;
            synchronized (activated_views) {
                activated_views.add(mdi_entry);
                if (activated_views.size() > 8) {
                    for (MdiEntrySWT m : activated_views) {
                        if (m != mdi_entry) {
                            // stand-alone views can cause confusion - don't deactive the one
                            // currently being built to avoid borkage...
                            to_deactivate = m;
                            break;
                        }
                    }
                }
            }
            if (to_deactivate != null) {
                to_deactivate.triggerEvent(UISWTViewEvent.TYPE_DESTROY, null);
            }
        }
    }
    if (ds != null) {
        if ((ds.getViewOptions() & Subscription.VO_HIDE_HEADER) != 0) {
            SWTSkinObject top_area = getSkinObject("toparea");
            top_area.setVisible(false);
        }
        SWTSkinObjectText title = (SWTSkinObjectText) getSkinObject("title");
        if (title != null) {
            title.setText(MessageText.getString("subs.results.view.title", new String[] { ds.getName() }));
            Control control = title.getControl();
            final Menu menu = new Menu(control);
            control.setMenu(menu);
            final String menu_key = SubscriptionMDIEntry.setupMenus(ds, null);
            menu.addMenuListener(new MenuListener() {

                @Override
                public void menuShown(MenuEvent e) {
                    for (MenuItem mi : menu.getItems()) {
                        mi.dispose();
                    }
                    com.biglybt.pif.ui.menus.MenuItem[] menu_items = MenuItemManager.getInstance().getAllAsArray(menu_key);
                    MenuBuildUtils.addPluginMenuItems(menu_items, menu, true, true, new MenuBuildUtils.MenuItemPluginMenuControllerImpl(new Object[] { ds }));
                }

                @Override
                public void menuHidden(MenuEvent e) {
                }
            });
        }
    }
    final SWTSkinObject soFilterArea = getSkinObject("filterarea");
    if (soFilterArea != null) {
        SWTSkinObjectToggle soFilterButton = (SWTSkinObjectToggle) getSkinObject("filter-button");
        if (soFilterButton != null) {
            boolean toggled = COConfigurationManager.getBooleanParameter("Subscription View Filter Options Expanded", false);
            if (toggled) {
                soFilterButton.setToggled(true);
                soFilterArea.setVisible(true);
            }
            soFilterButton.addSelectionListener(new SWTSkinToggleListener() {

                @Override
                public void toggleChanged(SWTSkinObjectToggle so, boolean toggled) {
                    COConfigurationManager.setParameter("Subscription View Filter Options Expanded", toggled);
                    soFilterArea.setVisible(toggled);
                    Utils.relayout(soFilterArea.getControl().getParent());
                }
            });
        }
        Composite parent = (Composite) soFilterArea.getControl();
        Label label;
        FormData fd;
        GridLayout layout;
        int sepHeight = 20;
        Composite cFilters = new Composite(parent, SWT.NONE);
        fd = Utils.getFilledFormData();
        cFilters.setLayoutData(fd);
        layout = new GridLayout(1, true);
        layout.marginBottom = layout.marginTop = layout.marginLeft = layout.marginRight = 0;
        layout.marginWidth = layout.marginHeight = 0;
        cFilters.setLayout(layout);
        Runnable pFilterUpdater = null;
        if (ds != null && ds.isUpdateable()) {
            try {
                Composite pFilters = new Composite(cFilters, SWT.NONE);
                pFilters.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
                layout = new GridLayout(1, false);
                layout.marginBottom = layout.marginTop = layout.marginLeft = layout.marginRight = 0;
                layout.marginWidth = layout.marginHeight = 0;
                pFilters.setLayout(layout);
                final Label pflabel = new Label(pFilters, SWT.NONE);
                pflabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
                pFilterUpdater = new Runnable() {

                    @Override
                    public void run() {
                        long kInB = DisplayFormatters.getKinB();
                        long mInB = kInB * kInB;
                        long min_size = Math.max(0, ds_filter.getMinSize() / mInB);
                        long max_size = Math.max(0, ds_filter.getMaxSize() / mInB);
                        long min_seeds = Math.max(0, ds_filter.getMinSeeds());
                        long max_age = Math.max(0, ds_filter.getMaxAgeSecs());
                        pflabel.setText(MessageText.getString("subs.persistent.filters", new String[] { getString(ds_filter.getWithWords()), getString(ds_filter.getWithoutWords()), String.valueOf(min_size), String.valueOf(max_size) }) + ", " + MessageText.getString("label.min.seeds") + " = " + (min_seeds) + ", " + MessageText.getString("label.max.age") + " = " + (TimeFormatter.format3(max_age, null, true)));
                    }
                };
                pFilterUpdater.run();
            } catch (Throwable e) {
                Debug.out(e);
            }
        }
        Composite vFilters = new Composite(cFilters, SWT.NONE);
        vFilters.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
        RowLayout rowLayout = new RowLayout(SWT.HORIZONTAL);
        rowLayout.spacing = 5;
        rowLayout.marginBottom = rowLayout.marginTop = rowLayout.marginLeft = rowLayout.marginRight = 0;
        rowLayout.center = true;
        vFilters.setLayout(rowLayout);
        // with/without keywords
        ImageLoader imageLoader = ImageLoader.getInstance();
        Function<String[], String> flattener = (words) -> {
            String str = "";
            for (String word : words) {
                str += (str.isEmpty() ? "" : " ") + word;
            }
            return (str);
        };
        for (int i = 0; i < 2; i++) {
            final boolean with = i == 0;
            if (!with) {
                label = new Label(vFilters, SWT.VERTICAL | SWT.SEPARATOR);
                label.setLayoutData(new RowData(-1, sepHeight));
            }
            Composite cWithKW = new Composite(vFilters, SWT.NONE);
            layout = new GridLayout(2, false);
            layout.marginWidth = 0;
            layout.marginBottom = layout.marginTop = layout.marginLeft = layout.marginRight = 0;
            cWithKW.setLayout(layout);
            // Label lblWithKW = new Label(cWithKW, SWT.NONE);
            // lblWithKW.setText(MessageText.getString(with?"SubscriptionResults.filter.with.words":"SubscriptionResults.filter.without.words"));
            Label lblWithKWImg = new Label(cWithKW, SWT.NONE);
            lblWithKWImg.setImage(imageLoader.getImage(with ? "icon_filter_plus" : "icon_filter_minus"));
            final Text textWithKW = new Text(cWithKW, SWT.BORDER);
            textWithKW.setMessage(MessageText.getString(with ? "SubscriptionResults.filter.with.words" : "SubscriptionResults.filter.without.words"));
            GridData gd = new GridData();
            gd.widthHint = 100;
            textWithKW.setText(flattener.apply(with ? ds_filter.getWithWords() : ds_filter.getWithoutWords()));
            textWithKW.setLayoutData(gd);
            textWithKW.addModifyListener(new ModifyListener() {

                @Override
                public void modifyText(ModifyEvent e) {
                    String text = textWithKW.getText().toLowerCase(Locale.US);
                    String[] bits = text.split("\\s+");
                    Set<String> temp = new HashSet<>();
                    for (String bit : bits) {
                        bit = bit.trim();
                        if (bit.length() > 0) {
                            temp.add(bit);
                        }
                    }
                    String[] words = temp.toArray(new String[temp.size()]);
                    synchronized (filter_lock) {
                        if (with) {
                            ds_filter.setWithWords(words);
                        } else {
                            ds_filter.setWithoutWords(words);
                        }
                    }
                    refilter_dispatcher.dispatch();
                }
            });
        }
        int kInB = DisplayFormatters.getKinB();
        long mInB = kInB * kInB;
        // min size
        label = new Label(vFilters, SWT.VERTICAL | SWT.SEPARATOR);
        label.setLayoutData(new RowData(-1, sepHeight));
        Composite cMinSize = new Composite(vFilters, SWT.NONE);
        layout = new GridLayout(2, false);
        layout.marginWidth = 0;
        layout.marginBottom = layout.marginTop = layout.marginLeft = layout.marginRight = 0;
        cMinSize.setLayout(layout);
        Label lblMinSize = new Label(cMinSize, SWT.NONE);
        lblMinSize.setText(MessageText.getString("SubscriptionResults.filter.min_size"));
        Spinner spinMinSize = new Spinner(cMinSize, SWT.BORDER);
        spinMinSize.setMinimum(0);
        // 100 TB should do...
        spinMinSize.setMaximum(100 * kInB * kInB);
        spinMinSize.setSelection(Math.max(0, (int) (ds_filter.getMinSize() / mInB)));
        spinMinSize.addListener(SWT.Selection, new Listener() {

            @Override
            public void handleEvent(Event event) {
                ds_filter.setMinSize(((Spinner) event.widget).getSelection() * mInB);
                refilter_dispatcher.dispatch();
            }
        });
        // max size
        label = new Label(vFilters, SWT.VERTICAL | SWT.SEPARATOR);
        label.setLayoutData(new RowData(-1, sepHeight));
        Composite cMaxSize = new Composite(vFilters, SWT.NONE);
        layout = new GridLayout(2, false);
        layout.marginWidth = 0;
        layout.marginBottom = layout.marginTop = layout.marginLeft = layout.marginRight = 0;
        cMaxSize.setLayout(layout);
        Label lblMaxSize = new Label(cMaxSize, SWT.NONE);
        lblMaxSize.setText(MessageText.getString("SubscriptionResults.filter.max_size"));
        Spinner spinMaxSize = new Spinner(cMaxSize, SWT.BORDER);
        spinMaxSize.setMinimum(0);
        // 100 TB should do...
        spinMaxSize.setMaximum(100 * kInB * kInB);
        spinMaxSize.setSelection(Math.max(0, (int) (ds_filter.getMaxSize() / mInB)));
        spinMaxSize.addListener(SWT.Selection, new Listener() {

            @Override
            public void handleEvent(Event event) {
                ds_filter.setMaxSize(((Spinner) event.widget).getSelection() * mInB);
                refilter_dispatcher.dispatch();
            }
        });
        // min seeds
        label = new Label(vFilters, SWT.VERTICAL | SWT.SEPARATOR);
        label.setLayoutData(new RowData(-1, sepHeight));
        Composite cMinSeeds = new Composite(vFilters, SWT.NONE);
        layout = new GridLayout(2, false);
        layout.marginWidth = 0;
        layout.marginBottom = layout.marginTop = layout.marginLeft = layout.marginRight = 0;
        cMinSeeds.setLayout(layout);
        Label lblMinSeeds = new Label(cMinSeeds, SWT.NONE);
        lblMinSeeds.setText(MessageText.getString("label.min.seeds"));
        Spinner spinMinSeeds = new Spinner(cMinSeeds, SWT.BORDER);
        spinMinSeeds.setMinimum(0);
        spinMinSeeds.setMaximum(Integer.MAX_VALUE);
        spinMinSeeds.setSelection((int) ds_filter.getMinSeeds());
        spinMinSeeds.addListener(SWT.Selection, new Listener() {

            @Override
            public void handleEvent(Event event) {
                ds_filter.setMinSeeds(((Spinner) event.widget).getSelection());
                refilter_dispatcher.dispatch();
            }
        });
        // max age
        label = new Label(vFilters, SWT.VERTICAL | SWT.SEPARATOR);
        label.setLayoutData(new RowData(-1, sepHeight));
        Composite cMaxAge = new Composite(vFilters, SWT.NONE);
        layout = new GridLayout(3, false);
        layout.marginWidth = 0;
        layout.marginBottom = layout.marginTop = layout.marginLeft = layout.marginRight = 0;
        cMaxAge.setLayout(layout);
        Label lblMaxAge = new Label(cMaxAge, SWT.NONE);
        lblMaxAge.setText(MessageText.getString("label.max.age"));
        Spinner spinMaxAge = new Spinner(cMaxAge, SWT.BORDER);
        spinMaxAge.setMinimum(0);
        spinMaxAge.setMaximum(Integer.MAX_VALUE);
        Combo combMaxAge = new Combo(cMaxAge, SWT.SINGLE | SWT.READ_ONLY);
        for (String unit : TimeFormatter.TIME_SUFFIXES_2) {
            combMaxAge.add(unit);
        }
        Listener maxAgeListener = (e) -> {
            int val = spinMaxAge.getSelection();
            int unit = combMaxAge.getSelectionIndex();
            long secs = TimeFormatter.TIME_SUFFIXES_2_MULT[unit] * (long) (val + 1) - 1;
            ds_filter.setMaxAgeSecs(secs);
            refilter_dispatcher.dispatch();
        };
        int[] temp = TimeFormatter.format3Support(ds_filter.getMaxAgeSecs(), null, true);
        int val = temp[0];
        spinMaxAge.setSelection(val < 0 ? 0 : val);
        combMaxAge.select(temp[1]);
        spinMaxAge.addListener(SWT.Selection, maxAgeListener);
        combMaxAge.addListener(SWT.Selection, maxAgeListener);
        if (ds != null && ds.isUpdateable()) {
            label = new Label(vFilters, SWT.VERTICAL | SWT.SEPARATOR);
            label.setLayoutData(new RowData(-1, sepHeight));
            final Runnable f_pFilterUpdater = pFilterUpdater;
            Button save = new Button(vFilters, SWT.PUSH);
            save.setText(MessageText.getString("ConfigView.button.save"));
            save.addListener(SWT.Selection, new Listener() {

                @Override
                public void handleEvent(Event event) {
                    try {
                        ds_filter.save();
                        f_pFilterUpdater.run();
                    } catch (Throwable e) {
                        Debug.out(e);
                    }
                }
            });
            label = new Label(vFilters, SWT.VERTICAL | SWT.SEPARATOR);
            label.setLayoutData(new RowData(-1, sepHeight));
            Button more = new Button(vFilters, SWT.PUSH);
            more.setText(MessageText.getString("Subscription.menu.forcecheck"));
            more.addListener(SWT.Selection, new Listener() {

                @Override
                public void handleEvent(Event event) {
                    try {
                        more.setEnabled(false);
                        ds.getManager().getScheduler().download(ds, true, new SubscriptionDownloadListener() {

                            public void complete(Subscription subs) {
                                done();
                            }

                            public void failed(Subscription subs, SubscriptionException error) {
                                done();
                            }

                            private void done() {
                                Utils.execSWTThread(new Runnable() {

                                    @Override
                                    public void run() {
                                        if (!more.isDisposed()) {
                                            more.setEnabled(true);
                                        }
                                    }
                                });
                            }
                        });
                    } catch (Throwable e) {
                        Debug.out(e);
                    }
                }
            });
        }
        parent.layout(true);
    }
    return null;
}
Also used : COConfigurationManager(com.biglybt.core.config.COConfigurationManager) MultipleDocumentInterfaceSWT(com.biglybt.ui.swt.mdi.MultipleDocumentInterfaceSWT) SubscriptionException(com.biglybt.core.subs.SubscriptionException) SelectedContentManager(com.biglybt.ui.selectedcontent.SelectedContentManager) Colors(com.biglybt.ui.swt.mainwindow.Colors) DownloadUrlInfo(com.biglybt.ui.selectedcontent.DownloadUrlInfo) UIFunctionsManagerSWT(com.biglybt.ui.swt.UIFunctionsManagerSWT) SBC_SearchResultsView(com.biglybt.ui.swt.search.SBC_SearchResultsView) UIFunctionsManager(com.biglybt.ui.UIFunctionsManager) ToolBarItem(com.biglybt.ui.common.ToolBarItem) Utils(com.biglybt.ui.swt.Utils) UIUpdatable(com.biglybt.ui.common.updater.UIUpdatable) TableColumnCreator(com.biglybt.ui.swt.views.table.utils.TableColumnCreator) UIPluginViewToolBarListener(com.biglybt.pif.ui.UIPluginViewToolBarListener) TableColumnManager(com.biglybt.ui.common.table.impl.TableColumnManager) TableViewFactory(com.biglybt.ui.swt.views.table.impl.TableViewFactory) TableRowSWT(com.biglybt.ui.swt.views.table.TableRowSWT) ColumnSubResultNew(com.biglybt.ui.swt.columns.subscriptions.ColumnSubResultNew) org.eclipse.swt.layout(org.eclipse.swt.layout) SearchSubsUtils(com.biglybt.ui.swt.utils.SearchSubsUtils) SkinView(com.biglybt.ui.swt.views.skin.SkinView) ImageLoader(com.biglybt.ui.swt.imageloader.ImageLoader) SelectedContent(com.biglybt.ui.selectedcontent.SelectedContent) MessageText(com.biglybt.core.internat.MessageText) SubscriptionResultFilter(com.biglybt.core.subs.SubscriptionResultFilter) com.biglybt.ui.swt.columns.searchsubs(com.biglybt.ui.swt.columns.searchsubs) List(java.util.List) SubscriptionListener(com.biglybt.core.subs.SubscriptionListener) SWT(org.eclipse.swt.SWT) com.biglybt.ui.common.table(com.biglybt.ui.common.table) ColumnDateSizer(com.biglybt.ui.swt.views.tableitems.ColumnDateSizer) UIFunctions(com.biglybt.ui.UIFunctions) TableColumn(com.biglybt.pif.ui.tables.TableColumn) TableViewSWTMenuFillListener(com.biglybt.ui.swt.views.table.TableViewSWTMenuFillListener) java.util(java.util) UIToolBarItem(com.biglybt.pif.ui.toolbar.UIToolBarItem) MdiEntrySWT(com.biglybt.ui.swt.mdi.MdiEntrySWT) Subscription(com.biglybt.core.subs.Subscription) Function(java.util.function.Function) UISWTViewEvent(com.biglybt.ui.swt.pif.UISWTViewEvent) MenuBuildUtils(com.biglybt.ui.swt.MenuBuildUtils) SubscriptionDownloadListener(com.biglybt.core.subs.SubscriptionDownloadListener) TableColumnCreationListener(com.biglybt.pif.ui.tables.TableColumnCreationListener) SubscriptionResult(com.biglybt.core.subs.SubscriptionResult) MenuItemManager(com.biglybt.ui.common.util.MenuItemManager) CoreFactory(com.biglybt.core.CoreFactory) Core(com.biglybt.core.Core) org.eclipse.swt.events(org.eclipse.swt.events) SubscriptionResultFilterable(com.biglybt.core.subs.util.SubscriptionResultFilterable) org.eclipse.swt.widgets(org.eclipse.swt.widgets) com.biglybt.core.util(com.biglybt.core.util) ISelectedContent(com.biglybt.ui.selectedcontent.ISelectedContent) Color(org.eclipse.swt.graphics.Color) CoreRunningListener(com.biglybt.core.CoreRunningListener) ClipboardCopy(com.biglybt.ui.swt.mainwindow.ClipboardCopy) com.biglybt.ui.swt.skin(com.biglybt.ui.swt.skin) TableViewSWT(com.biglybt.ui.swt.views.table.TableViewSWT) UIPluginViewToolBarListener(com.biglybt.pif.ui.UIPluginViewToolBarListener) SubscriptionListener(com.biglybt.core.subs.SubscriptionListener) TableViewSWTMenuFillListener(com.biglybt.ui.swt.views.table.TableViewSWTMenuFillListener) SubscriptionDownloadListener(com.biglybt.core.subs.SubscriptionDownloadListener) TableColumnCreationListener(com.biglybt.pif.ui.tables.TableColumnCreationListener) CoreRunningListener(com.biglybt.core.CoreRunningListener) SubscriptionDownloadListener(com.biglybt.core.subs.SubscriptionDownloadListener) CoreRunningListener(com.biglybt.core.CoreRunningListener) MultipleDocumentInterfaceSWT(com.biglybt.ui.swt.mdi.MultipleDocumentInterfaceSWT) Subscription(com.biglybt.core.subs.Subscription) Core(com.biglybt.core.Core) SubscriptionException(com.biglybt.core.subs.SubscriptionException) MdiEntrySWT(com.biglybt.ui.swt.mdi.MdiEntrySWT) MessageText(com.biglybt.core.internat.MessageText) UISWTViewEvent(com.biglybt.ui.swt.pif.UISWTViewEvent) ImageLoader(com.biglybt.ui.swt.imageloader.ImageLoader)

Aggregations

ImageLoader (com.biglybt.ui.swt.imageloader.ImageLoader)78 Image (org.eclipse.swt.graphics.Image)20 GridData (org.eclipse.swt.layout.GridData)16 GridLayout (org.eclipse.swt.layout.GridLayout)16 Rectangle (org.eclipse.swt.graphics.Rectangle)6 MessageText (com.biglybt.core.internat.MessageText)5 AERunnable (com.biglybt.core.util.AERunnable)5 UIFunctions (com.biglybt.ui.UIFunctions)5 UserPrompterResultListener (com.biglybt.ui.UserPrompterResultListener)5 File (java.io.File)5 ArrayList (java.util.ArrayList)5 Core (com.biglybt.core.Core)4 CoreRunningListener (com.biglybt.core.CoreRunningListener)4 MessageBoxShell (com.biglybt.ui.swt.shells.MessageBoxShell)4 MouseAdapter (org.eclipse.swt.events.MouseAdapter)4 MouseEvent (org.eclipse.swt.events.MouseEvent)4 Point (org.eclipse.swt.graphics.Point)4 Subscription (com.biglybt.core.subs.Subscription)3 MenuItem (com.biglybt.pif.ui.menus.MenuItem)3 TableColumnCreationListener (com.biglybt.pif.ui.tables.TableColumnCreationListener)3