Search in sources :

Example 1 with Alarm

use of com.intellij.util.Alarm in project intellij-community by JetBrains.

the class EDTGuard method create.

@NotNull
public static <T, O extends Watchable> T create(@NotNull final O target, final ProcessHandler process) {
    final Pair<LinkedBlockingQueue<Call>, LinkedBlockingQueue<Call.Result>> queue = Pair.create(new LinkedBlockingQueue<Call>(10), new LinkedBlockingQueue<Call.Result>());
    final Thread thread = new Thread("Async Invocation Thread for " + process) {

        @Override
        public void run() {
            try {
                while (!Thread.currentThread().isInterrupted()) {
                    final Call call = queue.first.take();
                    if (call != null) {
                        queue.second.offer(call.invoke());
                    }
                }
            } catch (InterruptedException e) {
            // break
            }
        }
    };
    thread.start();
    final AtomicBoolean ref = new AtomicBoolean();
    final Disposable d = new Disposable() {

        boolean disposed;

        @Override
        public void dispose() {
            if (!disposed) {
                disposed = true;
                ref.set(true);
                thread.interrupt();
            }
        }
    };
    process.addProcessListener(new ProcessAdapter() {

        @Override
        public void processTerminated(ProcessEvent event) {
            synchronized (d) {
                Disposer.dispose(d);
            }
        }

        @Override
        public void processWillTerminate(ProcessEvent event, boolean willBeDestroyed) {
            if (!willBeDestroyed) {
                synchronized (d) {
                    Disposer.dispose(d);
                }
            }
        }
    });
    final Alarm alarm = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, d);
    final Alarm alarm2 = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, alarm);
    final Runnable watchdog = () -> ref.set(true);
    final Runnable ping = new Runnable() {

        @Override
        public void run() {
            synchronized (d) {
                if (alarm.isDisposed()) {
                    return;
                }
                alarm2.addRequest(watchdog, 200);
                try {
                    ref.set(!target.ping());
                } catch (Exception e) {
                    ref.set(true);
                } finally {
                    alarm2.cancelRequest(watchdog);
                    alarm.addRequest(this, 500);
                }
            }
        }
    };
    alarm.addRequest(ping, 500);
    final EDTGuard guard = new EDTGuard(target, queue, ref);
    final ClassLoader classLoader = target.getClass().getClassLoader();
    final Class<?>[] interfaces = target.getClass().getInterfaces();
    //noinspection unchecked
    return (T) Proxy.newProxyInstance(classLoader, interfaces, guard);
}
Also used : Disposable(com.intellij.openapi.Disposable) ProcessAdapter(com.intellij.execution.process.ProcessAdapter) ProcessEvent(com.intellij.execution.process.ProcessEvent) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) InvocationTargetException(java.lang.reflect.InvocationTargetException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Alarm(com.intellij.util.Alarm) NotNull(org.jetbrains.annotations.NotNull)

Example 2 with Alarm

use of com.intellij.util.Alarm in project intellij-community by JetBrains.

the class IpnbFilePanel method saveToFile.

public void saveToFile(boolean synchronize) {
    mySynchronize = synchronize;
    final String oldText = myDocument.getText();
    final String newText = IpnbParser.newDocumentText(this);
    if (newText == null)
        return;
    if (oldText.equals(newText) && mySynchronize) {
        new Alarm().addRequest(new MySynchronizeRequest(), 10, ModalityState.stateForComponent(this));
        mySynchronize = false;
        return;
    }
    try {
        final ReplaceInfo replaceInfo = findFragmentToChange(oldText, newText);
        if (replaceInfo.getStartOffset() != -1) {
            myDocument.replaceString(replaceInfo.getStartOffset(), replaceInfo.getEndOffset(), replaceInfo.getReplacement());
        }
    } catch (Exception e) {
        myDocument.replaceString(0, oldText.length(), newText);
    }
}
Also used : Alarm(com.intellij.util.Alarm) IOException(java.io.IOException)

Example 3 with Alarm

use of com.intellij.util.Alarm in project intellij-community by JetBrains.

the class SearchCommand method findUsages.

public void findUsages(final Processor<Usage> processor) {
    final ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator();
    final MatchResultSink sink = new MatchResultSink() {

        int count;

        public void setMatchingProcess(MatchingProcess _process) {
            process = _process;
            findStarted();
        }

        public void processFile(PsiFile element) {
            final VirtualFile virtualFile = element.getVirtualFile();
            if (virtualFile != null)
                progress.setText(SSRBundle.message("looking.in.progress.message", virtualFile.getPresentableName()));
        }

        public void matchingFinished() {
            if (mySearchContext.getProject().isDisposed())
                return;
            findEnded();
            progress.setText(SSRBundle.message("found.progress.message", count));
        }

        public ProgressIndicator getProgressIndicator() {
            return progress;
        }

        public void newMatch(MatchResult result) {
            UsageInfo info;
            if (MatchResult.MULTI_LINE_MATCH.equals(result.getName())) {
                int start = -1;
                int end = -1;
                PsiElement parent = result.getMatch().getParent();
                for (final MatchResult matchResult : ((MatchResultImpl) result).getMatches()) {
                    PsiElement el = matchResult.getMatch();
                    final int elementStart = el.getTextRange().getStartOffset();
                    if (start == -1 || start > elementStart) {
                        start = elementStart;
                    }
                    final int newend = elementStart + el.getTextLength();
                    if (newend > end) {
                        end = newend;
                    }
                }
                final int parentStart = parent.getTextRange().getStartOffset();
                int startOffset = start - parentStart;
                info = new UsageInfo(parent, startOffset, end - parentStart);
            } else {
                info = new UsageInfo(StructuralSearchUtil.getPresentableElement(result.getMatch()));
            }
            Usage usage = new UsageInfo2UsageAdapter(info);
            processor.process(usage);
            foundUsage(result, usage);
            ++count;
        }
    };
    try {
        new Matcher(mySearchContext.getProject()).findMatches(sink, myConfiguration.getMatchOptions());
    } catch (final StructuralSearchException e) {
        final Alarm alarm = new Alarm();
        alarm.addRequest(() -> NotificationGroup.toolWindowGroup("Structural Search", ToolWindowId.FIND).createNotification(SSRBundle.message("problem", e.getMessage()), MessageType.ERROR).notify(mySearchContext.getProject()), 100, ModalityState.NON_MODAL);
    }
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) FindProgressIndicator(com.intellij.find.FindProgressIndicator) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) Alarm(com.intellij.util.Alarm) MatchResultImpl(com.intellij.structuralsearch.impl.matcher.MatchResultImpl) PsiFile(com.intellij.psi.PsiFile) UsageInfo(com.intellij.usageView.UsageInfo) PsiElement(com.intellij.psi.PsiElement)

Example 4 with Alarm

use of com.intellij.util.Alarm in project intellij-community by JetBrains.

the class SearchForUsagesRunnable method searchUsages.

private void searchUsages(@NotNull final AtomicBoolean findStartedBalloonShown) {
    ProgressIndicator indicator = ProgressWrapper.unwrap(ProgressManager.getInstance().getProgressIndicator());
    assert indicator != null : "must run find usages under progress";
    TooManyUsagesStatus.createFor(indicator);
    Alarm findUsagesStartedBalloon = new Alarm();
    findUsagesStartedBalloon.addRequest(() -> {
        notifyByFindBalloon(null, MessageType.WARNING, myProcessPresentation, myProject, Collections.singletonList(StringUtil.escapeXml(UsageViewManagerImpl.getProgressTitle(myPresentation))));
        findStartedBalloonShown.set(true);
    }, 300, ModalityState.NON_MODAL);
    UsageSearcher usageSearcher = mySearcherFactory.create();
    usageSearcher.generate(usage -> {
        ProgressIndicator indicator1 = ProgressWrapper.unwrap(ProgressManager.getInstance().getProgressIndicator());
        assert indicator1 != null : "must run find usages under progress";
        if (indicator1.isCanceled())
            return false;
        if (!UsageViewManagerImpl.isInScope(usage, mySearchScopeToWarnOfFallingOutOf)) {
            myOutOfScopeUsages.incrementAndGet();
            return true;
        }
        boolean incrementCounter = !UsageViewManager.isSelfUsage(usage, mySearchFor);
        if (incrementCounter) {
            final int usageCount = myUsageCountWithoutDefinition.incrementAndGet();
            if (usageCount == 1 && !myProcessPresentation.isShowPanelIfOnlyOneUsage()) {
                myFirstUsage.compareAndSet(null, usage);
            }
            final UsageViewImpl usageView = getUsageView(indicator1);
            TooManyUsagesStatus tooManyUsagesStatus = TooManyUsagesStatus.getFrom(indicator1);
            if (usageCount > UsageLimitUtil.USAGES_LIMIT && tooManyUsagesStatus.switchTooManyUsagesStatus()) {
                UsageViewManagerImpl.showTooManyUsagesWarning(myProject, tooManyUsagesStatus, indicator1, myPresentation, usageCount, usageView);
            }
            tooManyUsagesStatus.pauseProcessingIfTooManyUsages();
            if (usageView != null) {
                ApplicationManager.getApplication().runReadAction(() -> usageView.appendUsage(usage));
            }
        }
        return !indicator1.isCanceled();
    });
    if (getUsageView(indicator) != null) {
        ApplicationManager.getApplication().invokeLater(() -> myUsageViewManager.showToolWindow(true), myProject.getDisposed());
    }
    Disposer.dispose(findUsagesStartedBalloon);
    ApplicationManager.getApplication().invokeLater(() -> {
        if (findStartedBalloonShown.get()) {
            Balloon balloon = ToolWindowManager.getInstance(myProject).getToolWindowBalloon(ToolWindowId.FIND);
            if (balloon != null) {
                balloon.hide();
            }
        }
    }, myProject.getDisposed());
}
Also used : ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) Alarm(com.intellij.util.Alarm) Balloon(com.intellij.openapi.ui.popup.Balloon) TooManyUsagesStatus(com.intellij.openapi.progress.util.TooManyUsagesStatus)

Example 5 with Alarm

use of com.intellij.util.Alarm in project intellij-community by JetBrains.

the class DarculaLaf method initialize.

@Override
public void initialize() {
    try {
        base.initialize();
    } catch (Exception ignore) {
    }
    myDisposable = Disposer.newDisposable();
    Application application = ApplicationManager.getApplication();
    if (application != null) {
        Disposer.register(application, myDisposable);
    }
    myMnemonicAlarm = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, myDisposable);
    IdeEventQueue.getInstance().addDispatcher(e -> {
        if (e instanceof KeyEvent && ((KeyEvent) e).getKeyCode() == KeyEvent.VK_ALT) {
            myAltPressed = e.getID() == KeyEvent.KEY_PRESSED;
            myMnemonicAlarm.cancelAllRequests();
            final Component focusOwner = IdeFocusManager.findInstance().getFocusOwner();
            if (focusOwner != null) {
                myMnemonicAlarm.addRequest(() -> repaintMnemonics(focusOwner, myAltPressed), 10);
            }
        }
        return false;
    }, myDisposable);
}
Also used : KeyEvent(java.awt.event.KeyEvent) Alarm(com.intellij.util.Alarm) Application(com.intellij.openapi.application.Application) IOException(java.io.IOException)

Aggregations

Alarm (com.intellij.util.Alarm)49 NotNull (org.jetbrains.annotations.NotNull)9 Disposable (com.intellij.openapi.Disposable)6 RelativePoint (com.intellij.ui.awt.RelativePoint)6 MouseEvent (java.awt.event.MouseEvent)6 DumbAwareAction (com.intellij.openapi.project.DumbAwareAction)4 JBPopup (com.intellij.openapi.ui.popup.JBPopup)4 VirtualFile (com.intellij.openapi.vfs.VirtualFile)4 PsiElement (com.intellij.psi.PsiElement)4 UsageInfo (com.intellij.usageView.UsageInfo)4 ListSelectionEvent (javax.swing.event.ListSelectionEvent)4 ListSelectionListener (javax.swing.event.ListSelectionListener)4 ProgressIndicator (com.intellij.openapi.progress.ProgressIndicator)3 Project (com.intellij.openapi.project.Project)3 PopupChooserBuilder (com.intellij.openapi.ui.popup.PopupChooserBuilder)3 CommonActionsManager (com.intellij.ide.CommonActionsManager)2 TreeExpander (com.intellij.ide.TreeExpander)2 PsiElementListCellRenderer (com.intellij.ide.util.PsiElementListCellRenderer)2 Language (com.intellij.lang.Language)2 Editor (com.intellij.openapi.editor.Editor)2