<commit_before>/*
 * Copyright 2000-2016 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.intellij.vcs.log.impl;

import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import com.intellij.concurrency.JobScheduler;
import com.intellij.ide.PowerSaveMode;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.progress.PerformInBackgroundOption;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.progress.impl.CoreProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Disposer;
import com.intellij.util.Consumer;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.io.storage.HeavyProcessLatch;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

public class HeavyAwareExecutor implements Disposable {
  @NotNull private final Project myProject;
  @NotNull private final ExecutingHeavyOrPowerSaveListener myListener;
  private final int myLongActivityDurationMs;

  /**
   * Creates new HeavyAwareExecutor.
   *
   * @param project                target project
   * @param delayMs                delay in milliseconds to execute the task after a heavy activity is finished
   * @param longActivityDurationMs length of activity in milliseconds that cancels the task
   */
  public HeavyAwareExecutor(@NotNull Project project, int delayMs, int longActivityDurationMs, @NotNull Disposable parent) {
    myProject = project;
    myLongActivityDurationMs = longActivityDurationMs;
    myListener = new ExecutingHeavyOrPowerSaveListener(project, delayMs, this);

    Disposer.register(parent, this);
  }

  /**
   * Starts a task in background after heavy process is finished and there is no power save mode after.
   * Task is not started until there some amount of time has passed since the last heavy activity.
   * When a "long" heavy activity is started during task execution, task is cancelled.
   * Task is also cancelled when user turns power save mode on.
   *
   * @param task      task to execute
   * @param indicator progress indicator for executing the task
   */
  public Future<?> executeOutOfHeavyOrPowerSave(@NotNull Consumer<ProgressIndicator> task, @NotNull String title,
                                                @NotNull ProgressIndicator indicator) {
    return Futures.dereference(myListener.addTask(() -> {
                                 Disposable disposable = Disposer.newDisposable();
                                 ListenableFuture<?> future = runAsync(myProject, task, title, indicator, () -> Disposer.dispose(disposable));

                                 new CancellingOnHeavyOrPowerSaveListener(myProject, indicator, myLongActivityDurationMs, disposable);
                                 return future;
                               })
    );
  }

  @Override
  public void dispose() {
  }

  @NotNull
  private static ListenableFuture<?> runAsync(@NotNull Project project,
                                              @NotNull Consumer<ProgressIndicator> task,
                                              @NotNull String title,
                                              @NotNull ProgressIndicator indicator,
                                              @NotNull Runnable continuation) {
    SettableFuture<?> future = SettableFuture.create();
    Task.Backgroundable wrapper = new Task.Backgroundable(project, title, true, PerformInBackgroundOption.ALWAYS_BACKGROUND) {
      @Override
      public void run(@NotNull ProgressIndicator indicator) {
        try {
          task.consume(indicator);<commit_msg>[vcs-log] inline Futures.dereference since it is going to be removed<commit_after>/*
 * Copyright 2000-2016 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.intellij.vcs.log.impl;

import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import com.intellij.concurrency.JobScheduler;
import com.intellij.ide.PowerSaveMode;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.progress.PerformInBackgroundOption;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.progress.impl.CoreProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Disposer;
import com.intellij.util.Consumer;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.io.storage.HeavyProcessLatch;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

import static com.google.common.util.concurrent.MoreExecutors.directExecutor;

public class HeavyAwareExecutor implements Disposable {
  @NotNull private final Project myProject;
  @NotNull private final ExecutingHeavyOrPowerSaveListener myListener;
  private final int myLongActivityDurationMs;

  /**
   * Creates new HeavyAwareExecutor.
   *
   * @param project                target project
   * @param delayMs                delay in milliseconds to execute the task after a heavy activity is finished
   * @param longActivityDurationMs length of activity in milliseconds that cancels the task
   */
  public HeavyAwareExecutor(@NotNull Project project, int delayMs, int longActivityDurationMs, @NotNull Disposable parent) {
    myProject = project;
    myLongActivityDurationMs = longActivityDurationMs;
    myListener = new ExecutingHeavyOrPowerSaveListener(project, delayMs, this);

    Disposer.register(parent, this);
  }

  /**
   * Starts a task in background after heavy process is finished and there is no power save mode after.
   * Task is not started until there some amount of time has passed since the last heavy activity.
   * When a "long" heavy activity is started during task execution, task is cancelled.
   * Task is also cancelled when user turns power save mode on.
   *
   * @param task      task to execute
   * @param indicator progress indicator for executing the task
   */
  public Future<?> executeOutOfHeavyOrPowerSave(@NotNull Consumer<ProgressIndicator> task, @NotNull String title,
                                                @NotNull ProgressIndicator indicator) {
    return Futures.transformAsync(
      myListener.addTask(() -> {
        Disposable disposable = Disposer.newDisposable();
        ListenableFuture<?> future = runAsync(myProject, task, title, indicator, () -> Disposer.dispose(disposable));

        new CancellingOnHeavyOrPowerSaveListener(myProject, indicator, myLongActivityDurationMs, disposable);
        return future;
      }), input -> input, directExecutor());
  }

  @Override
  public void dispose() {
  }

  @NotNull
  private static ListenableFuture<?> runAsync(@NotNull Project project,
                                              @NotNull Consumer<ProgressIndicator> task,
                                              @NotNull String title,
                                              @NotNull ProgressIndicator indicator,
                                              @NotNull Runnable continuation) {
    SettableFuture<?> future = SettableFuture.create();
    Task.Backgroundable wrapper = new Task.Backgroundable(project, title, true, PerformInBackgroundOption.ALWAYS_BACKGROUND) {
      @Override
      public void run(@NotNull ProgressIndicator indicator) {
        try {
          task.consume(indicator);
{'fraction_non_alphanumeric': 0.07568906115417744, 'fraction_numerical': 0.002583979328165375, 'mean_word_length': 3.3124419684308264, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 20, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 24, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4247829', 'n_tokens_mistral': 2367, 'n_tokens_neox': 2309, 'n_words': 719}