Java Code Examples for com.intellij.openapi.progress.Task

The following are top voted examples for showing how to use com.intellij.openapi.progress.Task. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: GitHub   File: DataWriter.java   View source code 6 votes vote down vote up
public void execute(ClassEntity targetClass) {
        this.targetClass = targetClass;
        ProgressManager.getInstance().run(new Task.Backgroundable(project, "GsonFormat") {

            @Override
            public void run(@NotNull ProgressIndicator progressIndicator) {
                progressIndicator.setIndeterminate(true);
                long currentTimeMillis = System.currentTimeMillis();
                execute();
                progressIndicator.setIndeterminate(false);
                progressIndicator.setFraction(1.0);
                StringBuffer sb = new StringBuffer();
                sb.append("GsonFormat [" + (System.currentTimeMillis() - currentTimeMillis) + " ms]\n");
//                sb.append("generate class : ( "+generateClassList.size()+" )\n");
//                for (String item: generateClassList) {
//                    sb.append("    at "+item+"\n");
//                }
//                sb.append("  \n");
//                NotificationCenter.info(sb.toString());
                Toast.make(project, MessageType.INFO, sb.toString());
            }
        });
    }
 
Example 2
Project: CodeGenerate   File: DataWriter.java   View source code 6 votes vote down vote up
public void execute(ClassEntity targetClass) {
        this.targetClass = targetClass;
        ProgressManager.getInstance().run(new Task.Backgroundable(project, "GsonFormat") {

            @Override
            public void run(@NotNull ProgressIndicator progressIndicator) {
                progressIndicator.setIndeterminate(true);
                long currentTimeMillis = System.currentTimeMillis();
                execute();
                progressIndicator.setIndeterminate(false);
                progressIndicator.setFraction(1.0);
                StringBuffer sb = new StringBuffer();
                sb.append("GsonFormat [" + (System.currentTimeMillis() - currentTimeMillis) + " ms]\n");
//                sb.append("generate class : ( "+generateClassList.size()+" )\n");
//                for (String item: generateClassList) {
//                    sb.append("    at "+item+"\n");
//                }
//                sb.append("  \n");
//                NotificationCenter.info(sb.toString());
                Toast.make(project, MessageType.INFO, sb.toString());
            }
        });
    }
 
Example 3
Project: jfrog-idea-plugin   File: ScanManager.java   View source code 6 votes vote down vote up
/**
 * Launch async dependency scan.
 */
public void asyncScanAndUpdateResults(boolean quickScan, @Nullable Collection<DataNode<LibraryDependencyData>> libraryDependencies) {
    Task.Backgroundable scanAndUpdateTask = new Task.Backgroundable(project, "Xray: Scanning for Vulnerabilities...") {
        @Override
        public void run(@NotNull ProgressIndicator indicator) {
            scanAndUpdate(quickScan, indicator, libraryDependencies);
            indicator.finishNonCancelableSection();
        }
    };
    // The progress manager is only good for foreground threads.
    if (SwingUtilities.isEventDispatchThread()) {
        ProgressManager.getInstance().run(scanAndUpdateTask);
    } else {
        // Run the scan task when the thread is in the foreground.
        SwingUtilities.invokeLater(() -> ProgressManager.getInstance().run(scanAndUpdateTask));
    }
}
 
Example 4
Project: AndroidSourceViewer   File: GlobalSearchAction.java   View source code 6 votes vote down vote up
@Override
public void OnResult(String result) {
    int extPos = result.lastIndexOf('/');
    if (extPos < 0 && extPos != result.length() - 1) {
        return;
    }
    String fileName = result.substring(extPos + 1);
    String title = "Download:" + fileName;
    File downloadFile = new File(Constant.CACHE_PATH + "search/" + fileName);
    ProgressManager.getInstance().run(new Task.Backgroundable(project, title) {
        @Override
        public void run(@NotNull ProgressIndicator progressIndicator) {
            try {
                DownloadUtil.downloadAtomically(null, result, downloadFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (downloadFile.exists()) {
                Utils.openFileInPanel(downloadFile.getPath(), project);
            }
        }
    });

}
 
Example 5
Project: educational-plugin   File: StepicAdaptiveReactionsPanel.java   View source code 6 votes vote down vote up
public ReactionButtonPanel(@NotNull final String text,
                           @NotNull final String enabledTooltip,
                           int reaction) {
  com.jetbrains.edu.learning.courseFormat.tasks.Task task = StudyUtils.getTaskFromSelectedEditor(myProject);
  final boolean isEnabled = task != null && task.getStatus() != StudyStatus.Solved;

  myLabel = new JLabel(text);

  myButtonPanel = new JPanel();
  myButtonPanel.setLayout(new BoxLayout(myButtonPanel, BoxLayout.PAGE_AXIS));
  myButtonPanel.setToolTipText(isEnabled && task.getStatus() == StudyStatus.Solved ? enabledTooltip : SOLVED_TASK_TOOLTIP);
  myButtonPanel.add(Box.createVerticalStrut(5));
  myButtonPanel.add(myLabel);
  myButtonPanel.add(Box.createVerticalStrut(5));

  setEnabledRecursive(isEnabled);

  setLayout(new GridBagLayout());
  setBorder(BorderFactory.createEtchedBorder());
  add(myButtonPanel);
  addMouseListener(reaction);
}
 
Example 6
Project: educational-plugin   File: StepicAdaptiveReactionsPanel.java   View source code 6 votes vote down vote up
@Override
public void mouseClicked(MouseEvent e) {
  if (e.getClickCount() == 1 && isEnabled()) {
    final com.jetbrains.edu.learning.courseFormat.tasks.Task task = StudyUtils.getCurrentTask(myProject);
    if (task != null && task.getStatus() != StudyStatus.Solved) {
      final ProgressIndicatorBase progress = new ProgressIndicatorBase();
      progress.setText(EduAdaptiveStepicConnector.LOADING_NEXT_RECOMMENDATION);
      ProgressManager.getInstance().run(new Task.Backgroundable(myProject,
                                                                EduAdaptiveStepicConnector.LOADING_NEXT_RECOMMENDATION) {
        @Override
        public void run(@NotNull ProgressIndicator indicator) {
          StepicAdaptiveReactionsPanel.this.setEnabledRecursive(false);
          ApplicationManager.getApplication().invokeLater(()->setBackground(UIUtil.getLabelBackground()));
          EduAdaptiveStepicConnector.addNextRecommendedTask(StepicAdaptiveReactionsPanel.this.myProject, task.getLesson(), indicator,
                                                            myReaction);
          StepicAdaptiveReactionsPanel.this.setEnabledRecursive(true);
        }
      });
    }
  }
}
 
Example 7
Project: educational-plugin   File: CCGetCourseFromStepic.java   View source code 6 votes vote down vote up
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
  final IdeView view = e.getData(LangDataKeys.IDE_VIEW);
  final Project project = e.getData(CommonDataKeys.PROJECT);
  if (view == null || project == null) {
    return;
  }
  final String courseId = Messages.showInputDialog("Please, enter course id", "Get Course From Stepik", null);
  if (StringUtil.isNotEmpty(courseId)) {
    ProgressManager.getInstance().run(new Task.Modal(project, "Creating Course", true) {
      @Override
      public void run(@NotNull final ProgressIndicator indicator) {
        createCourse(project, courseId);
      }
    });
  }
}
 
Example 8
Project: intellij-ce-playground   File: HgCreateNewBranchFromLogAction.java   View source code 6 votes vote down vote up
@Override
protected void actionPerformed(@NotNull final HgRepository repository, @NotNull VcsFullCommitDetails commit) {
  final Hash revisionHash = commit.getId();
  final Project project = repository.getProject();
  FileDocumentManager.getInstance().saveAllDocuments();
  String shortHash = revisionHash.toShortString();
  final String name = getNewBranchNameFromUser(repository, "Create New Branch From " + shortHash);
  if (name != null) {
    new Task.Backgroundable(project, HgVcsMessages.message("hg4idea.progress.updatingTo", shortHash)) {
      @Override
      public void run(@NotNull ProgressIndicator indicator) {
        if (HgUpdateCommand.updateRepoToInCurrentThread(project, repository.getRoot(), revisionHash.asString(), false)) {
          new HgBranchPopupActions.HgNewBranchAction(project, Collections.singletonList(repository), repository)
            .createNewBranch(name);
        }
      }
    }.queue();
  }
}
 
Example 9
Project: intellij-ce-playground   File: HgAbortRebaseAction.java   View source code 6 votes vote down vote up
@Override
protected void execute(@NotNull final Project project,
                       @NotNull Collection<HgRepository> repositories,
                       @Nullable final HgRepository selectedRepo) {

  new Task.Backgroundable(project, "Abort Rebasing...") {
    @Override
    public void run(@NotNull ProgressIndicator indicator) {
      if (selectedRepo != null) {
        HgRebaseCommand rebaseCommand = new HgRebaseCommand(project, selectedRepo);
        HgCommandResult result = rebaseCommand.abortRebase();
        if (HgErrorUtil.isAbort(result)) {
          new HgCommandResultNotifier(project).notifyError(result, "Hg Error", "Couldn't abort rebasing");
        }
        HgErrorUtil.markDirtyAndHandleErrors(project, selectedRepo.getRoot());
      }
    }
  }.queue();
}
 
Example 10
Project: intellij-ce-playground   File: UsageViewManagerImpl.java   View source code 6 votes vote down vote up
private UsageView doSearchAndShow(@NotNull final UsageTarget[] searchFor,
                                  @NotNull final Factory<UsageSearcher> searcherFactory,
                                  @NotNull final UsageViewPresentation presentation,
                                  @NotNull final FindUsagesProcessPresentation processPresentation,
                                  @Nullable final UsageViewStateListener listener) {
  final SearchScope searchScopeToWarnOfFallingOutOf = getMaxSearchScopeToWarnOfFallingOutOf(searchFor);
  final AtomicReference<UsageViewImpl> usageViewRef = new AtomicReference<UsageViewImpl>();

  Task.Backgroundable task = new Task.Backgroundable(myProject, getProgressTitle(presentation), true, new SearchInBackgroundOption()) {
    @Override
    public void run(@NotNull final ProgressIndicator indicator) {
      new SearchForUsagesRunnable(UsageViewManagerImpl.this, UsageViewManagerImpl.this.myProject, usageViewRef, presentation, searchFor, searcherFactory,
                                  processPresentation, searchScopeToWarnOfFallingOutOf, listener).run();
    }

    @Override
    @Nullable
    public NotificationInfo getNotificationInfo() {
      String notification = usageViewRef.get() != null ? usageViewRef.get().getUsagesCount() + " Usage(s) Found" : "No Usages Found";
      return new NotificationInfo("Find Usages", "Find Usages Finished", notification);
    }
  };
  ProgressManager.getInstance().run(task);
  return usageViewRef.get();
}
 
Example 11
Project: intellij-ce-playground   File: HistoryDialog.java   View source code 6 votes vote down vote up
protected ContentDiffRequest createDifference(final FileDifferenceModel m) {
  final Ref<ContentDiffRequest> requestRef = new Ref<ContentDiffRequest>();

  new Task.Modal(myProject, message("message.processing.revisions"), false) {
    public void run(@NotNull final ProgressIndicator i) {
      ApplicationManager.getApplication().runReadAction(new Runnable() {
        @Override
        public void run() {
          RevisionProcessingProgressAdapter p = new RevisionProcessingProgressAdapter(i);
          p.processingLeftRevision();
          DiffContent left = m.getLeftDiffContent(p);

          p.processingRightRevision();
          DiffContent right = m.getRightDiffContent(p);

          requestRef.set(new SimpleDiffRequest(m.getTitle(), left, right, m.getLeftTitle(p), m.getRightTitle(p)));
        }
      });
    }
  }.queue();

  return requestRef.get();
}
 
Example 12
Project: intellij-ce-playground   File: HgCheckinEnvironment.java   View source code 6 votes vote down vote up
public List<VcsException> scheduleMissingFileForDeletion(List<FilePath> files) {
  final List<HgFile> filesWithRoots = new ArrayList<HgFile>();
  for (FilePath filePath : files) {
    VirtualFile vcsRoot = VcsUtil.getVcsRootFor(myProject, filePath);
    if (vcsRoot == null) {
      continue;
    }
    filesWithRoots.add(new HgFile(vcsRoot, filePath));
  }
  new Task.Backgroundable(myProject, "Removing files...") {
    @Override
    public void run(@NotNull ProgressIndicator indicator) {
      HgRemoveCommand command = new HgRemoveCommand(myProject);
      command.execute(filesWithRoots);
    }
  }.queue();
  return null;
}
 
Example 13
Project: intellij-ce-playground   File: AddManyTestProcesses.java   View source code 6 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
  final Project project = e.getData(CommonDataKeys.PROJECT);
  for (int i = 0; i < 100; i++) {
    new Task.Backgroundable(project, "Test Process", true, PerformInBackgroundOption.ALWAYS_BACKGROUND) {
      public void run(@NotNull final ProgressIndicator indicator) {
        for (int j = 0; j < 10000; j++) {
          TimeoutUtil.sleep(1);
          indicator.setText("foo " + j);
        }
      }
    }.queue();

  }

}
 
Example 14
Project: intellij-ce-playground   File: UpdateChecker.java   View source code 6 votes vote down vote up
/**
 * For manual update checks (Help | Check for Updates, Settings | Updates | Check Now)
 * (the latter action may pass customised update settings).
 */
public static void updateAndShowResult(@Nullable Project project, @Nullable UpdateSettings customSettings) {
  final UpdateSettings settings = customSettings != null ? customSettings : UpdateSettings.getInstance();
  final boolean fromSettings = customSettings != null;

  ProgressManager.getInstance().run(new Task.Backgroundable(project, IdeBundle.message("updates.checking.progress"), true) {
    @Override
    public void run(@NotNull ProgressIndicator indicator) {
      doUpdateAndShowResult(getProject(), fromSettings, true, settings, indicator, null);
    }

    @Override
    public boolean isConditionalModal() {
      return fromSettings;
    }

    @Override
    public boolean shouldStartInBackground() {
      return !fromSettings;
    }
  });
}
 
Example 15
Project: intellij-ce-playground   File: BackgroundableProcessIndicator.java   View source code 6 votes vote down vote up
public BackgroundableProcessIndicator(@NotNull Task.Backgroundable task) {
  this(task.getProject(), task, task);

  myDumbModeAction = task.getDumbModeAction();
  if (myDumbModeAction == DumbModeAction.CANCEL) {
    task.getProject().getMessageBus().connect(this).subscribe(DumbService.DUMB_MODE, new DumbService.DumbModeListener() {

      @Override
      public void enteredDumbMode() {
        cancel();
      }

      @Override
      public void exitDumbMode() {
      }
    });
  }
}
 
Example 16
Project: intellij-ce-playground   File: HgContinueRebaseAction.java   View source code 6 votes vote down vote up
@Override
protected void execute(@NotNull final Project project,
                       @NotNull Collection<HgRepository> repositories,
                       @Nullable final HgRepository selectedRepo) {

  new Task.Backgroundable(project, "Continue Rebasing...") {
    @Override
    public void run(@NotNull ProgressIndicator indicator) {
      if (selectedRepo != null) {
        HgRebaseCommand rebaseCommand = new HgRebaseCommand(project, selectedRepo);
        HgCommandResult result = rebaseCommand.continueRebase();
        if (HgErrorUtil.isAbort(result)) {
          new HgCommandResultNotifier(project).notifyError(result, "Hg Error", "Couldn't continue rebasing");
        }
        HgErrorUtil.markDirtyAndHandleErrors(project, selectedRepo.getRoot());
      }
    }
  }.queue();
}
 
Example 17
Project: intellij-ce-playground   File: SendStatisticsAction.java   View source code 6 votes vote down vote up
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
  final Project project = CommonDataKeys.PROJECT.getData(e.getDataContext());
  if (project == null) {
    return;
  }

  ProgressManager.getInstance().run(new Task.Backgroundable(project, "Sending Statistics", false) {
    @Override
    public void run(@NotNull ProgressIndicator indicator) {
      StatisticsService service = StatisticsUploadAssistant.getStatisticsService();
      final StatisticsResult result = service.send();

      ApplicationManager.getApplication().invokeLater(new Runnable() {
        @Override
        public void run() {
          Messages.showMultilineInputDialog(project, "Result: " + result.getCode(), "Statistics Result",
                                            StringUtil.replace(result.getDescription(), ";", "\n"),
                                            null, null);
        }
      }, ModalityState.NON_MODAL, project.getDisposed());
    }
  });
}
 
Example 18
Project: intellij-ce-playground   File: CreateDesktopEntryAction.java   View source code 6 votes vote down vote up
@Override
public void actionPerformed(@NotNull AnActionEvent event) {
  if (!isAvailable()) return;

  Project project = event.getProject();
  CreateDesktopEntryDialog dialog = new CreateDesktopEntryDialog(project);
  if (!dialog.showAndGet()) {
    return;
  }

  final boolean globalEntry = dialog.myGlobalEntryCheckBox.isSelected();
  ProgressManager.getInstance().run(new Task.Backgroundable(project, ApplicationBundle.message("desktop.entry.title")) {
    @Override
    public void run(@NotNull ProgressIndicator indicator) {
      createDesktopEntry(getProject(), indicator, globalEntry);
    }
  });
}
 
Example 19
Project: intellij-ce-playground   File: AbstractTerminalRunner.java   View source code 6 votes vote down vote up
public void run() {
  ProgressManager.getInstance().run(new Task.Backgroundable(myProject, "Running the terminal", false) {
    public void run(@NotNull final ProgressIndicator indicator) {
      indicator.setText("Running the terminal...");
      try {
        doRun();
      }
      catch (final Exception e) {
        LOG.warn("Error running terminal", e);

        UIUtil.invokeLaterIfNeeded(new Runnable() {

          @Override
          public void run() {
            Messages.showErrorDialog(AbstractTerminalRunner.this.getProject(), e.getMessage(), getTitle());
          }
        });
      }
    }
  });
}
 
Example 20
Project: intellij-ce-playground   File: IdeErrorsDialog.java   View source code 6 votes vote down vote up
private void loadDevelopersAsynchronously() {
  Task.Backgroundable task = new Task.Backgroundable(null, "Loading Developers List", true) {
    private final Collection[] myDevelopers = new Collection[]{Collections.emptyList()};

    @Override
    public void run(@NotNull ProgressIndicator indicator) {
      try {
        myDevelopers[0] = DevelopersLoader.fetchDevelopers(indicator);
      } catch (IOException e) {
        //Notifications.Bus.register("Error reporter", NotificationDisplayType.BALLOON);
        //Notifications.Bus.notify(new Notification("Error reporter", "Communication error",
        //                                          "Unable to load developers list from server.", NotificationType.WARNING));
      }
    }

    @Override
    public void onSuccess() {
      Collection<Developer> developers = myDevelopers[0];
      myDetailsTabForm.setDevelopers(developers);
      //noinspection AssignmentToStaticFieldFromInstanceMethod
      ourDevelopersList = developers;
    }
  };
  ProgressManager.getInstance().run(task);
}
 
Example 21
Project: intellij-ce-playground   File: ApplicationImplTest.java   View source code 6 votes vote down vote up
public void testAsyncProgressVsReadAction() throws Throwable {
  Future<?> future = ((ProgressManagerImpl)ProgressManager.getInstance()).runProcessWithProgressAsynchronously(
    new Task.Backgroundable(getProject(), "xx") {
      @Override
      public void run(@NotNull ProgressIndicator indicator) {
        try {
          assertFalse(ApplicationManager.getApplication().isReadAccessAllowed());
          assertFalse(ApplicationManager.getApplication().isDispatchThread());
        }
        catch (Exception e) {
          exception = e;
        }
      }
    });
  future.get();
  if (exception != null) throw exception;
}
 
Example 22
Project: intellij-ce-playground   File: HgRemoteStatusUpdater.java   View source code 6 votes vote down vote up
public void update(final Project project, @Nullable final VirtualFile root) {
  if (!isCheckingEnabled() || myUpdateStarted.get()) {
    return;
  }
  myUpdateStarted.set(true);
  ApplicationManager.getApplication().invokeLater(new Runnable() {
    public void run() {
      new Task.Backgroundable(project, getProgressTitle(), true) {
        public void run(@NotNull ProgressIndicator indicator) {
          if (project.isDisposed()) return;
          final VirtualFile[] roots =
            root != null ? new VirtualFile[]{root} : ProjectLevelVcsManager.getInstance(project).getRootsUnderVcs(myVcs);
          updateChangesetStatus(project, roots, myIncomingStatus, true);
          updateChangesetStatus(project, roots, myOutgoingStatus, false);

          project.getMessageBus().syncPublisher(HgVcs.INCOMING_OUTGOING_CHECK_TOPIC).update();

          indicator.stop();
          myUpdateStarted.set(false);
        }
      }.queue();
    }
  });
}
 
Example 23
Project: intellij-ce-playground   File: ZipAndQueue.java   View source code 6 votes vote down vote up
public ZipAndQueue(final Project project, final int interval, final String title, final Runnable runnable) {
  final int correctedInterval = interval <= 0 ? 300 : interval;
  myZipperUpdater = new ZipperUpdater(correctedInterval, project);
  myQueue = new BackgroundTaskQueue(project, title);
  myInZipper = new Runnable() {
    @Override
    public void run() {
      myQueue.run(myInvokedOnQueue);
    }
  };
  myInvokedOnQueue = new Task.Backgroundable(project, title, false, BackgroundFromStartOption.getInstance()) {
    @Override
    public void run(@NotNull ProgressIndicator indicator) {
      runnable.run();
    }
  };
  Disposer.register(project, new Disposable() {
    @Override
    public void dispose() {
      myZipperUpdater.stop();
    }
  });
}
 
Example 24
Project: intellij-ce-playground   File: HgPullAction.java   View source code 6 votes vote down vote up
@Override
protected void execute(@NotNull final Project project, @NotNull Collection<HgRepository> repos, @Nullable HgRepository selectedRepo) {
  final HgPullDialog dialog = new HgPullDialog(project, repos, selectedRepo);
  if (dialog.showAndGet()) {
    final String source = dialog.getSource();
    final HgRepository hgRepository = dialog.getRepository();
    new Task.Backgroundable(project, "Pulling changes from " + source, false) {

      @Override
      public void run(@NotNull ProgressIndicator indicator) {
        executePull(project, hgRepository, source);
        HgErrorUtil.markDirtyAndHandleErrors(project, hgRepository.getRoot());
      }
    }.queue();
  }
}
 
Example 25
Project: intellij-ce-playground   File: AbstractRefreshablePanel.java   View source code 6 votes vote down vote up
protected AbstractRefreshablePanel(final Project project, final String loadingTitle, final BackgroundTaskQueue queue) {
  myQueue = queue;
  myTicket = new Ticket();
  myDetailsPanel = new DetailsPanel();
  myDetailsPanel.loading();
  myDetailsPanel.layout();
  
  myDetailsLoader = new GenericDetailsLoader<Ticket, T>(new Consumer<Ticket>() {
    @Override
    public void consume(Ticket ticket) {
      final Loader loader = new Loader(project, loadingTitle, myTicket.copy());
      loader.runSteadily(new Consumer<Task.Backgroundable>() {
        @Override
        public void consume(Task.Backgroundable backgroundable) {
          myQueue.run(backgroundable);
        }
      });
    }
  }, new PairConsumer<Ticket, T>() {
    @Override
    public void consume(Ticket ticket, T t) {
      acceptData(t);
    }
  });
}
 
Example 26
Project: intellij-ce-playground   File: LogConsoleBase.java   View source code 6 votes vote down vote up
@Override
public JComponent getSearchComponent() {
  myLogFilterCombo.setModel(new DefaultComboBoxModel(myFilters.toArray(new LogFilter[myFilters.size()])));
  resetLogFilter();
  myLogFilterCombo.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
      final LogFilter filter = (LogFilter)myLogFilterCombo.getSelectedItem();
      final Task.Backgroundable task = new Task.Backgroundable(myProject, APPLYING_FILTER_TITLE) {
        @Override
        public void run(@NotNull ProgressIndicator indicator) {
          myModel.selectFilter(filter);
        }
      };
      ProgressManager.getInstance().run(task);
    }
  });
  myTextFilterWrapper.removeAll();
  myTextFilterWrapper.add(getTextFilterComponent());
  return mySearchComponent;
}
 
Example 27
Project: intellij-ce-playground   File: PydevConsoleCommunication.java   View source code 6 votes vote down vote up
/**
 * Stops the communication with the client (passes message for it to quit).
 */
public synchronized void close() {
  if (this.myClient != null) {
    new Task.Backgroundable(myProject, "Close console communication", true) {
      @Override
      public void run(@NotNull ProgressIndicator indicator) {
        try {
          PydevConsoleCommunication.this.myClient.execute(CLOSE, new Object[0]);
        }
        catch (Exception e) {
          //Ok, we can ignore this one on close.
        }
        PydevConsoleCommunication.this.myClient = null;
      }
    }.queue();
  }

  if (myWebServer != null) {
    myWebServer.shutdown();
    myWebServer = null;
  }
}
 
Example 28
Project: intellij-ce-playground   File: PydevConsoleRunner.java   View source code 6 votes vote down vote up
private void rerun() {
  new Task.Backgroundable(getProject(), "Restarting console", true) {
    @Override
    public void run(@NotNull ProgressIndicator indicator) {
      UIUtil.invokeLaterIfNeeded(new Runnable() {
        @Override
        public void run() {
          closeCommunication();
        }
      });

      myProcessHandler.waitFor();

      UIUtil.invokeLaterIfNeeded(new Runnable() {
        @Override
        public void run() {
          PydevConsoleRunner.this.run();
        }
      });
    }
  }.queue();
}
 
Example 29
Project: intellij-ce-playground   File: CCPushLesson.java   View source code 6 votes vote down vote up
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
  final IdeView view = e.getData(LangDataKeys.IDE_VIEW);
  final Project project = e.getData(CommonDataKeys.PROJECT);
  if (view == null || project == null) {
    return;
  }
  final Course course = CCProjectService.getInstance(project).getCourse();
  if (course == null) {
    return;
  }
  PsiDirectory lessonDir = DirectoryChooserUtil.getOrChooseDirectory(view);
  if (lessonDir == null || !lessonDir.getName().contains("lesson")) {
    return;
  }
  final Lesson lesson = course.getLesson(lessonDir.getName());
  if (lesson == null) {
    return;
  }
  ProgressManager.getInstance().run(new Task.Modal(project, "Uploading Lesson", true) {
    @Override
    public void run(@NotNull ProgressIndicator indicator) {
      indicator.setText("Uploading lesson to http://stepic.org");
      EduStepicConnector.updateLesson(project, lesson, indicator);
    }});
}
 
Example 30
Project: intellij-ce-playground   File: ExportSignedPackageWizard.java   View source code 6 votes vote down vote up
private void buildAndSignIntellijProject() {
  CompilerManager.getInstance(myProject).make(myCompileScope, new CompileStatusNotification() {
    @Override
    public void finished(boolean aborted, int errors, int warnings, CompileContext compileContext) {
      if (aborted || errors != 0) {
        return;
      }

      final String title = AndroidBundle.message("android.extract.package.task.title");
      ProgressManager.getInstance().run(new Task.Backgroundable(myProject, title, true, null) {
        @Override
        public void run(@NotNull ProgressIndicator indicator) {
          createAndAlignApk(myApkPath);
        }
      });
    }
  });
}
 
Example 31
Project: intellij-ce-playground   File: GithubOpenInBrowserAction.java   View source code 6 votes vote down vote up
@Nullable
private static String getCurrentFileRevisionHash(@NotNull final Project project, @NotNull final VirtualFile file) {
  final Ref<GitRevisionNumber> ref = new Ref<GitRevisionNumber>();
  ProgressManager.getInstance().run(new Task.Modal(project, "Getting last revision", true) {
    @Override
    public void run(@NotNull ProgressIndicator indicator) {
      try {
        ref.set((GitRevisionNumber)GitHistoryUtils.getCurrentRevision(project, VcsUtil.getFilePath(file), "HEAD"));
      }
      catch (VcsException e) {
        LOG.warn(e);
      }
    }

    @Override
    public void onCancel() {
      throw new ProcessCanceledException();
    }
  });
  if (ref.isNull()) return null;
  return ref.get().getRev();
}
 
Example 32
Project: intellij-ce-playground   File: GithubCreatePullRequestWorker.java   View source code 6 votes vote down vote up
public void createPullRequest(@NotNull final BranchInfo branch,
                              @NotNull final String title,
                              @NotNull final String description) {
  new Task.Backgroundable(myProject, "Creating pull request...") {
    @Override
    public void run(@NotNull ProgressIndicator indicator) {
      LOG.info("Pushing current branch");
      indicator.setText("Pushing current branch...");
      GitCommandResult result = myGit.push(myGitRepository, myRemoteName, myRemoteUrl, myCurrentBranch, true);
      if (!result.success()) {
        GithubNotifications.showError(myProject, CANNOT_CREATE_PULL_REQUEST, "Push failed:<br/>" + result.getErrorOutputAsHtmlString());
        return;
      }

      LOG.info("Creating pull request");
      indicator.setText("Creating pull request...");
      GithubPullRequest request = doCreatePullRequest(indicator, branch, title, description);
      if (request == null) {
        return;
      }

      GithubNotifications.showInfoURL(myProject, "Successfully created pull request",
                                      "Pull request #" + request.getNumber(), request.getHtmlUrl());
    }
  }.queue();
}
 
Example 33
Project: intellij-ce-playground   File: MavenIndicesManager.java   View source code 6 votes vote down vote up
private void scheduleUpdate(final Project projectOrNull, List<MavenIndex> indices, final boolean fullUpdate) {
  final List<MavenIndex> toSchedule = new ArrayList<MavenIndex>();

  synchronized (myUpdatingIndicesLock) {
    for (MavenIndex each : indices) {
      if (myWaitingIndices.contains(each)) continue;
      toSchedule.add(each);
    }

    myWaitingIndices.addAll(toSchedule);
  }
  if (toSchedule.isEmpty()) return;
  myUpdatingQueue.run(new Task.Backgroundable(projectOrNull, IndicesBundle.message("maven.indices.updating"), true) {
    public void run(@NotNull ProgressIndicator indicator) {
      try {
        doUpdateIndices(projectOrNull, toSchedule, fullUpdate, new MavenProgressIndicator(indicator));
      }
      catch (MavenProcessCanceledException ignore) {
      }
    }
  });
}
 
Example 34
Project: intellij-ce-playground   File: GitResetAction.java   View source code 6 votes vote down vote up
@Override
protected void actionPerformed(@NotNull final Project project, @NotNull final Map<GitRepository, VcsFullCommitDetails> commits) {
  GitVcsSettings settings = GitVcsSettings.getInstance(project);
  GitResetMode defaultMode = ObjectUtils.notNull(settings.getResetMode(), GitResetMode.getDefault());
  GitNewResetDialog dialog = new GitNewResetDialog(project, commits, defaultMode);
  if (dialog.showAndGet()) {
    final GitResetMode selectedMode = dialog.getResetMode();
    settings.setResetMode(selectedMode);
    new Task.Backgroundable(project, "Git reset", true) {
      @Override
      public void run(@NotNull ProgressIndicator indicator) {
        new GitResetOperation(project, commits, selectedMode, indicator).execute();
      }
    }.queue();
  }
}
 
Example 35
Project: intellij-ce-playground   File: HgMqUnAppliedPatchesPanel.java   View source code 6 votes vote down vote up
@CalledInAwt
public void updatePatchSeriesInBackground(@Nullable final Runnable runAfterUpdate) {
  final String newContent = myNeedToUpdateFileContent ? getContentFromModel() : null;
  myNeedToUpdateFileContent = false;
  new Task.Backgroundable(myProject, "Updating patch series for " + myRepository.getPresentableUrl()) {
    @Override
    public void run(@NotNull ProgressIndicator indicator) {
      if (newContent != null) {
        writeSeriesFile(newContent);
      }
      if (runAfterUpdate != null) {
        runAfterUpdate.run();
      }
    }
  }.queue();
}
 
Example 36
Project: intellij-ce-playground   File: CreateExternalAction.java   View source code 6 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
  final ActionExecuteHelper helper = new ActionExecuteHelper();
  checkState(e, helper);
  if (! helper.isOk()) return;

  final DataContext dc = e.getDataContext();
  final Project project = CommonDataKeys.PROJECT.getData(dc);
  final VirtualFile vf = CommonDataKeys.VIRTUAL_FILE.getData(dc);

  //1 select target
  final SelectCreateExternalTargetDialog dialog = new SelectCreateExternalTargetDialog(project, vf);
  dialog.show();
  if (DialogWrapper.OK_EXIT_CODE != dialog.getExitCode()) return;

  final String url = dialog.getSelectedURL();
  final boolean checkout = dialog.isCheckout();
  final String target = dialog.getLocalTarget().trim();

  ProgressManager.getInstance().run(new Task.Backgroundable(project, "Creating External", true, null) {
    @Override
    public void run(@NotNull ProgressIndicator indicator) {
      doInBackground(project, vf, url, checkout, target);
    }
  });
}
 
Example 37
Project: AndroidSourceViewer   File: SourceViewerAction.java   View source code 5 votes vote down vote up
@Override
public void OnItemClick(int position, final String version) {
    String title = "Download:" + version + " - " + packageName;
    ProgressManager.getInstance().run(new Task.Backgroundable(project, title) {
        @Override
        public void run(@NotNull ProgressIndicator progressIndicator) {
            final ClassEntity entity = new ClassEntity(packageName, version);
            DownloadManager.getInstance().downloadFile(new ClassEntity[]{entity},
                    new File(Constant.CACHE_PATH + entity.getParentPath()),
                    new DownloadResult<File>() {
                        @Override
                        public void onSuccess(List<File> output) {
                            Log.debug("success: length=" + output.size());
                            if (output.isEmpty()) {
                                NotificationUtils.errorNotification("Error: Download " + entity.getPackageName()
                                + " Failure");
                                return;
                            }
                            Utils.openFileInPanel(output.get(0).getPath(), SourceViewerAction.this.project);
                        }

                        @Override
                        public void onFailure(String msg, Throwable throwable) {
                            NotificationUtils.errorNotification("Error:" + msg);
                        }
                    });
            progressIndicator.setFraction(0.5);
        }
    });
}
 
Example 38
Project: educational-plugin   File: StepicAdaptiveReactionsPanel.java   View source code 5 votes vote down vote up
private void addFileListener() {
  final FileEditorManagerListener editorManagerListener = new FileEditorManagerListener() {
    @Override
    public void selectionChanged(@NotNull FileEditorManagerEvent event) {
      final com.jetbrains.edu.learning.courseFormat.tasks.Task task = StudyUtils.getTaskFromSelectedEditor(myProject);
      final boolean isEnabled = task != null && task.getStatus() != StudyStatus.Solved;
      StepicAdaptiveReactionsPanel.this.setEnabledRecursive(isEnabled);
    }
  };
  myProject.getMessageBus().connect().subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, editorManagerListener);
}
 
Example 39
Project: educational-plugin   File: StepicAdaptiveReactionsPanel.java   View source code 5 votes vote down vote up
@Override
public void mouseEntered(MouseEvent e) {
  final com.jetbrains.edu.learning.courseFormat.tasks.Task task = StudyUtils.getCurrentTask(myProject);
  if (task != null && task.getStatus() != StudyStatus.Solved && myPanel.isEnabled()) {
    setBackground(JBColor.GRAY);
  }
}
 
Example 40
Project: educational-plugin   File: CCPushLesson.java   View source code 5 votes vote down vote up
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
  final IdeView view = e.getData(LangDataKeys.IDE_VIEW);
  final Project project = e.getData(CommonDataKeys.PROJECT);
  if (view == null || project == null) {
    return;
  }
  final Course course = StudyTaskManager.getInstance(project).getCourse();
  if (course == null || !(course instanceof RemoteCourse)) {
    return;
  }
  final PsiDirectory[] directories = view.getDirectories();
  if (directories.length == 0 || directories.length > 1) {
    return;
  }

  final PsiDirectory lessonDir = directories[0];
  if (lessonDir == null || !lessonDir.getName().contains("lesson")) {
    return;
  }
  final Lesson lesson = course.getLesson(lessonDir.getName());
  if (lesson == null) {
    return;
  }
  ProgressManager.getInstance().run(new Task.Modal(project, "Uploading Lesson", true) {
    @Override
    public void run(@NotNull ProgressIndicator indicator) {
      indicator.setText("Uploading lesson to " + EduStepicNames.STEPIC_URL);
      if (lesson.getId() > 0) {
        CCStepicConnector.updateLesson(project, lesson);
      }
      else {
        final int lessonId = CCStepicConnector.postLesson(project, lesson);
        final List<Integer> sections = ((RemoteCourse)course).getSections();
        final Integer sectionId = sections.get(sections.size()-1);
        CCStepicConnector.postUnit(lessonId, lesson.getIndex(), sectionId, project);
      }
    }});
}