<commit_before>package acr.browser.lightning.browser;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;

import com.anthonycr.bonsai.CompletableOnSubscribe;
import com.anthonycr.bonsai.Schedulers;

import javax.inject.Inject;

import acr.browser.lightning.BuildConfig;
import acr.browser.lightning.R;
import acr.browser.lightning.activity.TabsManager;
import acr.browser.lightning.app.BrowserApp;
import acr.browser.lightning.constant.Constants;
import acr.browser.lightning.controller.UIController;
import acr.browser.lightning.preference.PreferenceManager;

import acr.browser.lightning.utils.UrlUtils;
import acr.browser.lightning.view.LightningView;

/**
 * Presenter in charge of keeping track of
 * the current tab and setting the current tab
 * of the
 */
public class BrowserPresenter {

    private static final String TAG = "BrowserPresenter";

    @NonNull private final TabsManager mTabsModel;
    @Inject PreferenceManager mPreferences;

    @NonNull private final BrowserView mView;
    @Nullable private LightningView mCurrentTab;

    private final boolean mIsIncognito;
    private boolean mShouldClose;

    public BrowserPresenter(@NonNull BrowserView view, boolean isIncognito) {
        BrowserApp.getAppComponent().inject(this);
        mTabsModel = ((UIController) view).getTabModel();
        mView = view;
        mIsIncognito = isIncognito;
        mTabsModel.setTabNumberChangedListener(new TabsManager.TabNumberChangedListener() {
            @Override
            public void tabNumberChanged(int newNumber) {
                mView.updateTabNumber(newNumber);
            }
        });
    }

    /**
     * Initializes the tab manager with the new intent
     * that is handed in by the BrowserActivity.
     *
     * @param intent the intent to handle, may be null.
     */
    public void setupTabs(@Nullable Intent intent) {
        mTabsModel.initializeTabs((Activity) mView, intent, mIsIncognito)
            .subscribeOn(Schedulers.main())
            .subscribe(new CompletableOnSubscribe() {
                @Override
                public void onComplete() {
                    // At this point we always have at least a tab in the tab manager
                    mView.notifyTabViewInitialized();
                    mView.updateTabNumber(mTabsModel.size());
                    tabChanged(mTabsModel.last());
                }
            });
    }

    /**
     * Notify the presenter that a change occurred to
     * the current tab. Currently doesn't do anything
     * other than tell the view to notify the adapter
     * about the change.
     *
     * @param tab the tab that changed, may be null.
     */
    public void tabChangeOccurred(@Nullable LightningView tab) {
        mView.notifyTabViewChanged(mTabsModel.indexOfTab(tab));
    }

    private void onTabChanged(@Nullable LightningView newTab) {
        Log.d(TAG, "On tab changed");
        if (newTab == null) {
            mView.removeTabView();
            if (mCurrentTab != null) {
                mCurrentTab.pauseTimers();
                mCurrentTab.onDestroy();
            }
        } else {
            if (newTab.getWebView() == null) {
                mView.removeTabView();
                if (mCurrentTab != null) {
                    mCurrentTab.pauseTimers();
                    mCurrentTab.onDestroy();
                }
            } else {
                if (mCurrentTab != null) {
                    // TODO: Restore this when Google fixes the bug where the WebView is
                    // blank after calling onPause followed by onResume.
                    // mCurrentTab.onPause();
                    mCurrentTab.setIsForegroundTab(false);
                }

                newTab.resumeTimers();
                newTab.onResume();
                newTab.setIsForegroundTab(true);

                mView.updateProgress(newTab.getProgress());
                mView.setBackButtonEnabled(newTab.canGoBack());
                mView.setForwardButtonEnabled(newTab.canGoForward());
                mView.updateUrl(newTab.getUrl(), true);
                mView.setTabView(newTab.getWebView());
                int index = mTabsModel.indexOfTab(newTab);
                if (index >= 0) {
                    mView.notifyTabViewChanged(mTabsModel.indexOfTab(newTab));
                }
            }
        }

        mCurrentTab = newTab;
    }

    /**
     * Closes all tabs but the current tab.
     */
    public void closeAllOtherTabs() {

        while (mTabsModel.last() != mTabsModel.indexOfCurrentTab()) {
            deleteTab(mTabsModel.last());
        }

        while (0 != mTabsModel.indexOfCurrentTab()) {
            deleteTab(0);
        }

    }

    /**
     * Deletes the tab at the specified position.
     *
     * @param position the position at which to
     *                 delete the tab.
     */
    public void deleteTab(int position) {
        Log.d(TAG, "delete Tab");
        final LightningView tabToDelete = mTabsModel.getTabAtPosition(position);

        if (tabToDelete == null) {
            return;
        }

        if (!UrlUtils.isSpecialUrl(tabToDelete.getUrl()) && !mIsIncognito) {
            mPreferences.setSavedUrl(tabToDelete.getUrl());
        }

        final boolean isShown = tabToDelete.isShown();
        boolean shouldClose = mShouldClose && isShown && tabToDelete.isNewTab();
        final LightningView currentTab = mTabsModel.getCurrentTab();
        if (mTabsModel.size() == 1 && currentTab != null &&
            (UrlUtils.isSpecialUrl(currentTab.getUrl()) ||
                currentTab.getUrl().equals(mPreferences.getHomepage()))) {
            mView.closeActivity();
            return;
        } else {
            if (isShown) {
                mView.removeTabView();
            }
            boolean currentDeleted = mTabsModel.deleteTab(position);
            if (currentDeleted) {
                tabChanged(mTabsModel.indexOfCurrentTab());
            }
        }

        final LightningView afterTab = mTabsModel.getCurrentTab();
        mView.notifyTabViewRemoved(position);

        if (afterTab == null) {
            mView.closeBrowser();
            return;
        } else if (afterTab != currentTab) {
            //TODO remove this?
//            switchTabs(currentTab, afterTab);
//            if (currentTab != null) {
//                currentTab.pauseTimers();
//            }<commit_msg>Fix logic where only start pages should be excluded from close<commit_after>package acr.browser.lightning.browser;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;

import com.anthonycr.bonsai.CompletableOnSubscribe;
import com.anthonycr.bonsai.Schedulers;

import javax.inject.Inject;

import acr.browser.lightning.BuildConfig;
import acr.browser.lightning.R;
import acr.browser.lightning.activity.TabsManager;
import acr.browser.lightning.app.BrowserApp;
import acr.browser.lightning.constant.Constants;
import acr.browser.lightning.controller.UIController;
import acr.browser.lightning.preference.PreferenceManager;

import acr.browser.lightning.utils.UrlUtils;
import acr.browser.lightning.view.LightningView;

/**
 * Presenter in charge of keeping track of
 * the current tab and setting the current tab
 * of the
 */
public class BrowserPresenter {

    private static final String TAG = "BrowserPresenter";

    @NonNull private final TabsManager mTabsModel;
    @Inject PreferenceManager mPreferences;

    @NonNull private final BrowserView mView;
    @Nullable private LightningView mCurrentTab;

    private final boolean mIsIncognito;
    private boolean mShouldClose;

    public BrowserPresenter(@NonNull BrowserView view, boolean isIncognito) {
        BrowserApp.getAppComponent().inject(this);
        mTabsModel = ((UIController) view).getTabModel();
        mView = view;
        mIsIncognito = isIncognito;
        mTabsModel.setTabNumberChangedListener(new TabsManager.TabNumberChangedListener() {
            @Override
            public void tabNumberChanged(int newNumber) {
                mView.updateTabNumber(newNumber);
            }
        });
    }

    /**
     * Initializes the tab manager with the new intent
     * that is handed in by the BrowserActivity.
     *
     * @param intent the intent to handle, may be null.
     */
    public void setupTabs(@Nullable Intent intent) {
        mTabsModel.initializeTabs((Activity) mView, intent, mIsIncognito)
            .subscribeOn(Schedulers.main())
            .subscribe(new CompletableOnSubscribe() {
                @Override
                public void onComplete() {
                    // At this point we always have at least a tab in the tab manager
                    mView.notifyTabViewInitialized();
                    mView.updateTabNumber(mTabsModel.size());
                    tabChanged(mTabsModel.last());
                }
            });
    }

    /**
     * Notify the presenter that a change occurred to
     * the current tab. Currently doesn't do anything
     * other than tell the view to notify the adapter
     * about the change.
     *
     * @param tab the tab that changed, may be null.
     */
    public void tabChangeOccurred(@Nullable LightningView tab) {
        mView.notifyTabViewChanged(mTabsModel.indexOfTab(tab));
    }

    private void onTabChanged(@Nullable LightningView newTab) {
        Log.d(TAG, "On tab changed");
        if (newTab == null) {
            mView.removeTabView();
            if (mCurrentTab != null) {
                mCurrentTab.pauseTimers();
                mCurrentTab.onDestroy();
            }
        } else {
            if (newTab.getWebView() == null) {
                mView.removeTabView();
                if (mCurrentTab != null) {
                    mCurrentTab.pauseTimers();
                    mCurrentTab.onDestroy();
                }
            } else {
                if (mCurrentTab != null) {
                    // TODO: Restore this when Google fixes the bug where the WebView is
                    // blank after calling onPause followed by onResume.
                    // mCurrentTab.onPause();
                    mCurrentTab.setIsForegroundTab(false);
                }

                newTab.resumeTimers();
                newTab.onResume();
                newTab.setIsForegroundTab(true);

                mView.updateProgress(newTab.getProgress());
                mView.setBackButtonEnabled(newTab.canGoBack());
                mView.setForwardButtonEnabled(newTab.canGoForward());
                mView.updateUrl(newTab.getUrl(), true);
                mView.setTabView(newTab.getWebView());
                int index = mTabsModel.indexOfTab(newTab);
                if (index >= 0) {
                    mView.notifyTabViewChanged(mTabsModel.indexOfTab(newTab));
                }
            }
        }

        mCurrentTab = newTab;
    }

    /**
     * Closes all tabs but the current tab.
     */
    public void closeAllOtherTabs() {

        while (mTabsModel.last() != mTabsModel.indexOfCurrentTab()) {
            deleteTab(mTabsModel.last());
        }

        while (0 != mTabsModel.indexOfCurrentTab()) {
            deleteTab(0);
        }

    }

    /**
     * Deletes the tab at the specified position.
     *
     * @param position the position at which to
     *                 delete the tab.
     */
    public void deleteTab(int position) {
        Log.d(TAG, "delete Tab");
        final LightningView tabToDelete = mTabsModel.getTabAtPosition(position);

        if (tabToDelete == null) {
            return;
        }

        if (!UrlUtils.isSpecialUrl(tabToDelete.getUrl()) && !mIsIncognito) {
            mPreferences.setSavedUrl(tabToDelete.getUrl());
        }

        final boolean isShown = tabToDelete.isShown();
        boolean shouldClose = mShouldClose && isShown && tabToDelete.isNewTab();
        final LightningView currentTab = mTabsModel.getCurrentTab();
        if (mTabsModel.size() == 1 && currentTab != null &&
            (UrlUtils.isStartPageUrl(currentTab.getUrl()) ||
                currentTab.getUrl().equals(mPreferences.getHomepage()))) {
            mView.closeActivity();
            return;
        } else {
            if (isShown) {
                mView.removeTabView();
            }
            boolean currentDeleted = mTabsModel.deleteTab(position);
            if (currentDeleted) {
                tabChanged(mTabsModel.indexOfCurrentTab());
            }
        }

        final LightningView afterTab = mTabsModel.getCurrentTab();
        mView.notifyTabViewRemoved(position);

        if (afterTab == null) {
            mView.closeBrowser();
            return;
        } else if (afterTab != currentTab) {
            //TODO remove this?
//            switchTabs(currentTab, afterTab);
//            if (currentTab != null) {
//                currentTab.pauseTimers();
//            }
{'fraction_non_alphanumeric': 0.09487004622262636, 'fraction_numerical': 0.0006061983784193377, 'mean_word_length': 2.0417146808020283, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6542001', 'n_tokens_mistral': 3646, 'n_tokens_neox': 3496, 'n_words': 788}