Search in sources :

Example 56 with Core

use of com.biglybt.core.Core in project BiglyBT by BiglySoftware.

the class MainWindowImpl method showMainWindow.

private void showMainWindow() {
    configShowDLBasketListener = new ParameterListener() {

        @Override
        public void parameterChanged(String parameterName) {
            configureDownloadBasket();
        }
    };
    COConfigurationManager.addAndFireParameterListener("Show Download Basket", configShowDLBasketListener);
    boolean isOSX = com.biglybt.core.util.Constants.isOSX;
    boolean bEnableTray = COConfigurationManager.getBooleanParameter("Enable System Tray");
    boolean bPassworded = COConfigurationManager.getBooleanParameter("Password enabled");
    boolean bStartMinimize = bEnableTray && (bPassworded || COConfigurationManager.getBooleanParameter("Start Minimized"));
    SWTSkinObject soMain = skin.getSkinObject("main");
    if (soMain != null) {
        soMain.getControl().setVisible(true);
    }
    shell.addListener(SWT.Show, new Listener() {

        @Override
        public void handleEvent(Event event) {
            System.out.println("---------SHOWN AT " + SystemTime.getCurrentTime() + ";" + (SystemTime.getCurrentTime() - Initializer.startTime) + "ms");
            if (statusBar != null) {
                Utils.execSWTThreadLater(10, new Runnable() {

                    @Override
                    public void run() {
                        statusBar.relayout();
                    }
                });
            }
            // bring back and stand-alone shells
            ShellManager.sharedManager().performForShells(new Listener() {

                @Override
                public void handleEvent(Event event) {
                    Shell this_shell = (Shell) event.widget;
                    if (this_shell.getParent() == null && !this_shell.isVisible()) {
                        boolean minimize;
                        synchronized (minimized_on_hide) {
                            minimize = minimized_on_hide.remove(this_shell);
                        }
                        this_shell.setVisible(true);
                        if (minimize) {
                            this_shell.setMinimized(true);
                        } else {
                            this_shell.moveAbove(shell);
                        }
                    }
                }
            });
        }
    });
    if (!bStartMinimize) {
        shell.open();
        if (!isOSX) {
            shell.forceActive();
        }
    }
    if (delayedCore) {
        // max 5 seconds of dispatching.  We don't display.sleep here because
        // we only want to clear the backlog of SWT events, and sleep would
        // add new ones
        Display display = Utils.getDisplay();
        if (display == null) {
            return;
        }
        try {
            long endSWTDispatchOn = SystemTime.getOffsetTime(5000);
            while (SystemTime.getCurrentTime() < endSWTDispatchOn && !display.isDisposed() && display.readAndDispatch()) ;
        } catch (Exception e) {
            Debug.out(e);
        }
        System.out.println("---------DONE DISPATCH AT " + SystemTime.getCurrentTime() + ";" + (SystemTime.getCurrentTime() - Initializer.startTime) + "ms");
        if (display.isDisposed()) {
            return;
        }
    }
    if (bEnableTray) {
        try {
            systemTraySWT = SystemTraySWT.getTray();
        } catch (Throwable e) {
            e.printStackTrace();
            Logger.log(new LogEvent(LOGID, LogEvent.LT_ERROR, "Upgrade to SWT3.0M8 or later for system tray support."));
        }
        if (bStartMinimize) {
            minimizeToTray(null);
        } else // Only show the password if not started minimized
        // Correct bug #878227
        {
            if (bPassworded) {
                minimizeToTray(null);
                // invokes password
                setVisible(true);
            }
        }
    }
    if (uiInitializer != null) {
        uiInitializer.initializationComplete();
    }
    boolean run_speed_test = false;
    if (!Utils.isAZ2UI() && !COConfigurationManager.getBooleanParameter("SpeedTest Completed")) {
        if (ConfigurationChecker.isNewInstall()) {
            run_speed_test = true;
        } else if (FeatureAvailability.triggerSpeedTestV1()) {
            long upload_limit = COConfigurationManager.getLongParameter("Max Upload Speed KBs");
            boolean auto_up = COConfigurationManager.getBooleanParameter(TransferSpeedValidator.AUTO_UPLOAD_ENABLED_CONFIGKEY);
            if (auto_up) {
                if (upload_limit <= 18) {
                    run_speed_test = true;
                }
            } else {
                boolean up_seed_limit = COConfigurationManager.getBooleanParameter("enable.seedingonly.upload.rate");
                if (upload_limit == 0 && !up_seed_limit) {
                    run_speed_test = true;
                }
            }
        }
    }
    if (run_speed_test) {
        SpeedTestSelector.runMLABTest(new AERunnable() {

            @Override
            public void runSupport() {
                WelcomeView.setWaitLoadingURL(false);
            }
        });
    } else {
        WelcomeView.setWaitLoadingURL(false);
    }
    if (Utils.isAZ2UI()) {
        if (!COConfigurationManager.getBooleanParameter("Wizard Completed")) {
            CoreWaiterSWT.waitForCoreRunning(new CoreRunningListener() {

                @Override
                public void coreRunning(Core core) {
                    new ConfigureWizard(false, ConfigureWizard.WIZARD_MODE_FULL);
                }
            });
        }
        checkForWhatsNewWindow();
    }
    AssociationChecker.checkAssociations();
    // Donation stuff
    Map<?, ?> map = VersionCheckClient.getSingleton().getMostRecentVersionCheckData();
    DonationWindow.setInitialAskHours(MapUtils.getMapInt(map, "donations.askhrs", DonationWindow.getInitialAskHours()));
    CoreFactory.addCoreRunningListener(new CoreRunningListener() {

        @Override
        public void coreRunning(Core core) {
            core.triggerLifeCycleComponentCreated(uiFunctions);
        }
    });
    System.out.println("---------READY AT " + SystemTime.getCurrentTime() + ";" + (SystemTime.getCurrentTime() - Initializer.startTime) + "ms");
    isReady = true;
// SESecurityManagerImpl.getSingleton().exitVM(0);
}
Also used : MdiEntryLogIdListener(com.biglybt.ui.mdi.MdiEntryLogIdListener) ParameterListener(com.biglybt.core.config.ParameterListener) MdiListener(com.biglybt.ui.mdi.MdiListener) NavigationHelper.navigationListener(com.biglybt.util.NavigationHelper.navigationListener) GlobalManagerListener(com.biglybt.core.global.GlobalManagerListener) CoreRunningListener(com.biglybt.core.CoreRunningListener) ConfigureWizard(com.biglybt.ui.swt.config.wizard.ConfigureWizard) MessageBoxShell(com.biglybt.ui.swt.shells.MessageBoxShell) ObfuscateShell(com.biglybt.ui.swt.debug.ObfuscateShell) SWTRunnable(com.biglybt.ui.swt.utils.SWTRunnable) CoreRunningListener(com.biglybt.core.CoreRunningListener) ParameterListener(com.biglybt.core.config.ParameterListener) Core(com.biglybt.core.Core)

Example 57 with Core

use of com.biglybt.core.Core in project BiglyBT by BiglySoftware.

the class UIFunctionsImpl method addTorrentWithOptions.

@Override
public boolean addTorrentWithOptions(final TorrentOpenOptions torrentOptions, Map<String, Object> addOptions) {
    Boolean is_silent = (Boolean) addOptions.get(UIFunctions.OTO_SILENT);
    if (is_silent == null) {
        is_silent = UIFunctions.OTO_SILENT_DEFAULT;
    }
    if (CoreFactory.isCoreRunning()) {
        Core core = CoreFactory.getSingleton();
        GlobalManager gm = core.getGlobalManager();
        // Check if torrent already exists in gm, and add if not
        TOTorrent torrent = torrentOptions.getTorrent();
        DownloadManager existingDownload = gm.getDownloadManager(torrent);
        if (existingDownload != null) {
            if (!is_silent) {
                final String fExistingName = existingDownload.getDisplayName();
                final DownloadManager fExistingDownload = existingDownload;
                fExistingDownload.fireGlobalManagerEvent(GlobalManagerEvent.ET_REQUEST_ATTENTION);
                Utils.execSWTThread(new AERunnable() {

                    @Override
                    public void runSupport() {
                        boolean can_merge = TorrentUtils.canMergeAnnounceURLs(torrentOptions.getTorrent(), fExistingDownload.getTorrent());
                        long existed_for = SystemTime.getCurrentTime() - fExistingDownload.getCreationTime();
                        Shell mainShell = UIFunctionsManagerSWT.getUIFunctionsSWT().getMainShell();
                        if ((Display.getDefault().getActiveShell() == null || !mainShell.isVisible() || mainShell.getMinimized()) && (!can_merge)) {
                            if (existed_for > 15 * 1000) {
                                new MessageSlideShell(Display.getCurrent(), SWT.ICON_INFORMATION, MSG_ALREADY_EXISTS, null, new String[] { // : prefix is deliberate to disable click on ref in message as might be an unwanted action
                                ":" + torrentOptions.sOriginatingLocation, fExistingName, MessageText.getString(MSG_ALREADY_EXISTS_NAME) }, new Object[] { fExistingDownload }, -1);
                            }
                        } else {
                            if (can_merge) {
                                String text = MessageText.getString(MSG_ALREADY_EXISTS + ".text", new String[] { ":" + torrentOptions.sOriginatingLocation, fExistingName, MessageText.getString(MSG_ALREADY_EXISTS_NAME) });
                                text += "\n\n" + MessageText.getString("openTorrentWindow.mb.alreadyExists.merge");
                                MessageBoxShell mb = new MessageBoxShell(SWT.YES | SWT.NO, MessageText.getString(MSG_ALREADY_EXISTS + ".title"), text);
                                mb.open(new UserPrompterResultListener() {

                                    @Override
                                    public void prompterClosed(int result) {
                                        if (result == SWT.YES) {
                                            TorrentUtils.mergeAnnounceURLs(torrentOptions.getTorrent(), fExistingDownload.getTorrent());
                                        }
                                    }
                                });
                            } else {
                                if (existed_for > 15 * 1000) {
                                    MessageBoxShell mb = new MessageBoxShell(SWT.OK, MSG_ALREADY_EXISTS, new String[] { ":" + torrentOptions.sOriginatingLocation, fExistingName, MessageText.getString(MSG_ALREADY_EXISTS_NAME) });
                                    mb.open(null);
                                }
                            }
                        }
                    }
                });
            }
            if (torrentOptions.getDeleteFileOnCancel()) {
                File torrentFile = new File(torrentOptions.sFileName);
                torrentFile.delete();
            }
            return (true);
        } else {
            try {
                final DownloadStub archived = core.getPluginManager().getDefaultPluginInterface().getDownloadManager().lookupDownloadStub(torrent.getHash());
                if (archived != null) {
                    if (is_silent) {
                        // restore it for them
                        archived.destubbify();
                        if (torrentOptions.getDeleteFileOnCancel()) {
                            File torrentFile = new File(torrentOptions.sFileName);
                            torrentFile.delete();
                        }
                        return (true);
                    } else {
                        Utils.execSWTThread(new AERunnable() {

                            @Override
                            public void runSupport() {
                                Shell mainShell = UIFunctionsManagerSWT.getUIFunctionsSWT().getMainShell();
                                String existingName = archived.getName();
                                if (Display.getDefault().getActiveShell() == null || !mainShell.isVisible() || mainShell.getMinimized()) {
                                    new MessageSlideShell(Display.getCurrent(), SWT.ICON_INFORMATION, "OpenTorrentWindow.mb.inArchive", null, new String[] { existingName }, new Object[0], -1);
                                } else {
                                    MessageBoxShell mb = new MessageBoxShell(SWT.OK, "OpenTorrentWindow.mb.inArchive", new String[] { existingName });
                                    mb.open(null);
                                }
                            }
                        });
                        return (true);
                    }
                }
            } catch (Throwable e) {
                Debug.out(e);
            }
            if (!is_silent) {
                try {
                    DownloadHistoryManager dlm = (DownloadHistoryManager) core.getGlobalManager().getDownloadHistoryManager();
                    final long[] existing = dlm.getDates(torrentOptions.getTorrent().getHash());
                    if (existing != null) {
                        long redownloaded = existing[3];
                        if (SystemTime.getCurrentTime() - redownloaded > 60 * 10 * 1000) {
                            Utils.execSWTThread(new AERunnable() {

                                @Override
                                public void runSupport() {
                                    Shell mainShell = UIFunctionsManagerSWT.getUIFunctionsSWT().getMainShell();
                                    if (mainShell != null && !mainShell.isDisposed()) {
                                        new MessageSlideShell(mainShell.getDisplay(), SWT.ICON_INFORMATION, "OpenTorrentWindow.mb.inHistory", null, new String[] { torrentOptions.getTorrentName(), new SimpleDateFormat().format(new Date(existing[0])) }, new Object[] {}, -1);
                                    }
                                }
                            });
                        }
                    }
                } catch (Throwable e) {
                    Debug.out(e);
                }
            }
        }
    }
    Boolean force = (Boolean) addOptions.get(UIFunctions.OTO_FORCE_OPEN);
    if (force == null) {
        force = UIFunctions.OTO_FORCE_OPEN_DEFAULT;
    }
    if (!force) {
        TOTorrent torrent = torrentOptions.getTorrent();
        boolean is_featured = torrent != null && PlatformTorrentUtils.isFeaturedContent(torrent);
        String showAgainMode = COConfigurationManager.getStringParameter(ConfigurationDefaults.CFG_TORRENTADD_OPENOPTIONS);
        if (is_featured || is_silent || (showAgainMode != null && ((showAgainMode.equals(ConfigurationDefaults.CFG_TORRENTADD_OPENOPTIONS_NEVER)) || (showAgainMode.equals(ConfigurationDefaults.CFG_TORRENTADD_OPENOPTIONS_MANY) && torrentOptions.getFiles() != null && torrentOptions.getFiles().length == 1)))) {
            // we're about to silently add the download - ensure that it is going to be saved somewhere vaguely sensible
            // as the current save location is simply taken from the 'default download' config which can be blank (for example)
            boolean looks_good = false;
            String save_loc = torrentOptions.getParentDir().trim();
            if (save_loc.length() == 0) {
            // blank :(
            } else if (save_loc.startsWith(".")) {
            // relative to who knows where
            } else {
                File f = new File(save_loc);
                if (!f.exists()) {
                    f.mkdirs();
                }
                if (f.isDirectory() && FileUtil.canWriteToDirectory(f)) {
                    if (!f.equals(AETemporaryFileHandler.getTempDirectory())) {
                        looks_good = true;
                    }
                }
            }
            if (looks_good) {
                TorrentManagerImpl t_man = TorrentManagerImpl.getSingleton();
                t_man.optionsAdded(torrentOptions);
                t_man.optionsAccepted(torrentOptions);
                boolean ok = TorrentOpener.addTorrent(torrentOptions);
                t_man.optionsRemoved(torrentOptions);
                return (ok);
            }
            torrentOptions.setParentDir("");
            if (is_silent) {
                return (false);
            } else {
                MessageBoxShell mb = new MessageBoxShell(SWT.OK | SWT.ICON_ERROR, "OpenTorrentWindow.mb.invaliddefsave", new String[] { save_loc });
                mb.open(new UserPrompterResultListener() {

                    @Override
                    public void prompterClosed(int result) {
                        OpenTorrentOptionsWindow.addTorrent(torrentOptions);
                    }
                });
            }
            return (true);
        }
    }
    if (is_silent) {
        return (false);
    } else {
        OpenTorrentOptionsWindow.addTorrent(torrentOptions);
        return (true);
    }
}
Also used : DownloadHistoryManager(com.biglybt.core.history.DownloadHistoryManager) MessageSlideShell(com.biglybt.ui.swt.shells.MessageSlideShell) MessageBoxShell(com.biglybt.ui.swt.shells.MessageBoxShell) TorrentManagerImpl(com.biglybt.pifimpl.local.torrent.TorrentManagerImpl) DownloadManager(com.biglybt.core.download.DownloadManager) Date(java.util.Date) Point(org.eclipse.swt.graphics.Point) DownloadStub(com.biglybt.pif.download.DownloadStub) MessageSlideShell(com.biglybt.ui.swt.shells.MessageSlideShell) MessageBoxShell(com.biglybt.ui.swt.shells.MessageBoxShell) GlobalManager(com.biglybt.core.global.GlobalManager) TOTorrent(com.biglybt.core.torrent.TOTorrent) File(java.io.File) SimpleDateFormat(java.text.SimpleDateFormat) UISWTViewCore(com.biglybt.ui.swt.pifimpl.UISWTViewCore) Core(com.biglybt.core.Core)

Example 58 with Core

use of com.biglybt.core.Core in project BiglyBT by BiglySoftware.

the class FileUtil method runAsTask.

public static void runAsTask(int op_type, CoreOperationTask task) {
    Core core = CoreFactory.getSingleton();
    core.createOperation(op_type, task);
}
Also used : Core(com.biglybt.core.Core)

Example 59 with Core

use of com.biglybt.core.Core in project BiglyBT by BiglySoftware.

the class PluginLauncherImpl method launch.

public static void launch(String[] args) {
    if (Launcher.checkAndLaunch(PluginLauncherImpl.class, args))
        return;
    // This *has* to be done first as it sets system properties that are read and cached by Java
    COConfigurationManager.preInitialise();
    final LoggerChannelListener listener = new LoggerChannelListener() {

        @Override
        public void messageLogged(int type, String content) {
            log(content, false);
        }

        @Override
        public void messageLogged(String str, Throwable error) {
            log(str, true);
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            error.printStackTrace(pw);
            pw.flush();
            log(sw.toString(), true);
        }

        protected synchronized void log(String str, boolean stdout) {
            File log_file = getApplicationFile("launch.log");
            PrintWriter pw = null;
            try {
                pw = new PrintWriter(new FileWriter(log_file, true));
                if (str.endsWith("\n")) {
                    if (stdout) {
                        System.err.print("PluginLauncher: " + str);
                    }
                    pw.print(str);
                } else {
                    if (stdout) {
                        System.err.println("PluginLauncher: " + str);
                    }
                    pw.println(str);
                }
            } catch (Throwable e) {
            } finally {
                if (pw != null) {
                    pw.close();
                }
            }
        }
    };
    LaunchablePlugin[] launchables = findLaunchablePlugins(listener);
    if (launchables.length == 0) {
        listener.messageLogged(LoggerChannel.LT_ERROR, "No launchable plugins found");
        return;
    } else if (launchables.length > 1) {
        listener.messageLogged(LoggerChannel.LT_ERROR, "Multiple launchable plugins found, running first");
    }
    try {
        // set default details for restarter
        SystemProperties.setApplicationEntryPoint("com.biglybt.pif.PluginLauncher");
        launchables[0].setDefaults(args);
        if (PluginSingleInstanceHandler.process(listener, args)) {
            return;
        }
        // we have to run the core startup on a separate thread and then effectively pass "this thread"
        // through to the launchable "process" method
        Thread core_thread = new Thread("PluginLauncher") {

            @Override
            public void run() {
                try {
                    // give 'process' call below some time to start up
                    Thread.sleep(500);
                    Core core = CoreFactory.create();
                    core.start();
                } catch (Throwable e) {
                    listener.messageLogged("PluginLauncher: launch fails", e);
                }
            }
        };
        core_thread.setDaemon(true);
        core_thread.start();
        boolean restart = false;
        boolean process_succeeded = false;
        try {
            restart = launchables[0].process();
            process_succeeded = true;
        } finally {
            try {
                if (restart) {
                    CoreFactory.getSingleton().restart();
                } else {
                    CoreFactory.getSingleton().stop();
                }
            } catch (Throwable e) {
                if (process_succeeded) {
                    throw (e);
                }
            }
        }
    } catch (Throwable e) {
        listener.messageLogged("PluginLauncher: launch fails", e);
    }
}
Also used : LoggerChannelListener(com.biglybt.pif.logging.LoggerChannelListener) LaunchablePlugin(com.biglybt.pif.LaunchablePlugin) Core(com.biglybt.core.Core)

Example 60 with Core

use of com.biglybt.core.Core in project BiglyBT by BiglySoftware.

the class PluginManagerImpl method startClient.

/**
 * Starts client.
 * <p>
 * With the exception of null ui, method does not return until client is closed.
 *
 * @param ui "swt", "console", "telnet", etc
 * @param properties
 */
public static void startClient(String ui, Properties properties, final StartClientListener startClientListener) throws PluginException {
    try {
        class_mon.enter();
        if (running) {
            throw (new RuntimeException(Constants.APP_NAME + " is already running"));
        }
        running = true;
    } finally {
        class_mon.exit();
    }
    String config_dir = (String) properties.get(PR_USER_DIRECTORY);
    if (config_dir != null) {
        System.setProperty(SystemProperties.SYSPROP_CONFIG_PATH, config_dir);
    }
    String user_dir = (String) properties.get(PR_APP_DIRECTORY);
    if (user_dir != null) {
        System.setProperty(SystemProperties.SYSPROP_INSTALL_PATH, user_dir);
        System.setProperty("user.dir", user_dir);
    }
    String doc_dir = (String) properties.get(PR_DOC_DIRECTORY);
    if (doc_dir != null) {
        System.setProperty(SystemProperties.SYSPROP_DOC_PATH, doc_dir);
    }
    String disable_native = (String) properties.get(PR_DISABLE_NATIVE_SUPPORT);
    if (disable_native != null && disable_native.equalsIgnoreCase("true")) {
        System.setProperty(SystemProperties.SYSPROP_PLATFORM_MANAGER_DISABLE, "true");
    }
    if (startClientListener != null) {
        CoreFactory.addCoreRunningListener(new CoreRunningListener() {

            @Override
            public void coreRunning(Core core) {
                startClientListener.clientStarted(core.getPluginManager());
            }
        });
    }
    if (ui == null) {
        try {
            core = CoreFactory.create();
            core.start();
        } catch (Throwable e) {
            Debug.printStackTrace(e);
            throw (new PluginException(Constants.APP_NAME + " failed to start", e));
        }
    } else {
        // Most likely, a plugin is calling this from their main(), which
        // will not be using our primary class loader.  Which means we already
        // have some core classes initialized on it, making it too late to
        // switch. (For example, aereg.dll will already be loaded, and the class
        // loading switch will cause an exception when trying to laod it again)
        System.setProperty("USE_OUR_PRIMARYCLASSLOADER", "0");
        String mi = (String) properties.get(PluginManager.PR_MULTI_INSTANCE);
        if (mi != null && mi.equalsIgnoreCase("true")) {
            System.setProperty(PluginManager.PR_MULTI_INSTANCE, "true");
        }
        try {
            Class.forName("com.biglybt.ui.Main").getMethod("main", new Class[] { String[].class }).invoke(null, (Object) new String[] { "--ui=" + ui });
        } catch (Throwable e) {
            throw (new PluginException("Main method invocation failed", e));
        }
    }
}
Also used : PluginException(com.biglybt.pif.PluginException) CoreRunningListener(com.biglybt.core.CoreRunningListener) Core(com.biglybt.core.Core)

Aggregations

Core (com.biglybt.core.Core)71 CoreRunningListener (com.biglybt.core.CoreRunningListener)37 DownloadManager (com.biglybt.core.download.DownloadManager)17 CoreLifecycleAdapter (com.biglybt.core.CoreLifecycleAdapter)12 GlobalManager (com.biglybt.core.global.GlobalManager)10 File (java.io.File)9 GridLayout (org.eclipse.swt.layout.GridLayout)8 UIFunctions (com.biglybt.ui.UIFunctions)6 Composite (org.eclipse.swt.widgets.Composite)6 ParameterListener (com.biglybt.core.config.ParameterListener)5 LogAlert (com.biglybt.core.logging.LogAlert)5 TOTorrent (com.biglybt.core.torrent.TOTorrent)5 AERunnable (com.biglybt.core.util.AERunnable)5 GridData (org.eclipse.swt.layout.GridData)5 DownloadManagerInitialisationAdapter (com.biglybt.core.download.DownloadManagerInitialisationAdapter)4 PluginInterface (com.biglybt.pif.PluginInterface)4 TableColumnCore (com.biglybt.ui.common.table.TableColumnCore)4 ArrayList (java.util.ArrayList)4 SelectionEvent (org.eclipse.swt.events.SelectionEvent)4 MessageText (com.biglybt.core.internat.MessageText)3