private void compileFinished(int exitValue, final ModuleChunk chunk, final String outputDir) {
    if (exitValue != 0
        && !myCompileContext.getProgressIndicator().isCanceled()
        && myCompileContext.getMessageCount(CompilerMessageCategory.ERROR) == 0) {
      myCompileContext.addMessage(
          CompilerMessageCategory.ERROR,
          CompilerBundle.message("error.compiler.internal.error", exitValue),
          null,
          -1,
          -1);
    }

    myCompiler.compileFinished();
    final List<File> toRefresh = new ArrayList<File>();
    final Map<String, Collection<TranslatingCompiler.OutputItem>> results =
        new HashMap<String, Collection<TranslatingCompiler.OutputItem>>();
    try {
      final FileTypeManager typeManager = FileTypeManager.getInstance();
      final String outputDirPath = outputDir.replace(File.separatorChar, '/');
      try {
        for (final Module module : chunk.getModules()) {
          for (final VirtualFile root : chunk.getSourceRoots(module)) {
            final String packagePrefix = myProjectFileIndex.getPackageNameByDirectory(root);
            if (LOG.isDebugEnabled()) {
              LOG.debug(
                  "Building output items for "
                      + root.getPresentableUrl()
                      + "; output dir = "
                      + outputDirPath
                      + "; packagePrefix = \""
                      + packagePrefix
                      + "\"");
            }
            buildOutputItemsList(
                outputDirPath, module, root, typeManager, root, packagePrefix, toRefresh, results);
          }
        }
      } catch (CacheCorruptedException e) {
        myCompileContext.requestRebuildNextTime(
            CompilerBundle.message("error.compiler.caches.corrupted"));
        if (LOG.isDebugEnabled()) {
          LOG.debug(e);
        }
      }
    } finally {
      CompilerUtil.refreshIOFiles(toRefresh);
      for (Iterator<Map.Entry<String, Collection<TranslatingCompiler.OutputItem>>> it =
              results.entrySet().iterator();
          it.hasNext(); ) {
        Map.Entry<String, Collection<TranslatingCompiler.OutputItem>> entry = it.next();
        mySink.add(entry.getKey(), entry.getValue(), VirtualFile.EMPTY_ARRAY);
        it.remove(); // to free memory
      }
    }
    myFileNameToSourceMap.clear(); // clear the map before the next use
  }
  @Override
  public final void action() throws Exception {
    if (LOG.isDebugEnabled()) {
      LOG.debug("trying " + this);
    }

    final SuspendContextImpl suspendContext = getSuspendContext();
    if (suspendContext == null) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("skip processing - context is null " + this);
      }
      notifyCancelled();
      return;
    }

    if (suspendContext.myInProgress) {
      suspendContext.postponeCommand(this);
    } else {
      try {
        if (!suspendContext.isResumed()) {
          suspendContext.myInProgress = true;
          contextAction(suspendContext);
        } else {
          notifyCancelled();
        }
      } finally {
        suspendContext.myInProgress = false;
        if (suspendContext.isResumed()) {
          for (SuspendContextCommandImpl postponed = suspendContext.pollPostponedCommand();
              postponed != null;
              postponed = suspendContext.pollPostponedCommand()) {
            postponed.notifyCancelled();
          }
        } else {
          SuspendContextCommandImpl postponed = suspendContext.pollPostponedCommand();
          if (postponed != null) {
            final Stack<SuspendContextCommandImpl> stack = new Stack<>();
            while (postponed != null) {
              stack.push(postponed);
              postponed = suspendContext.pollPostponedCommand();
            }
            final DebuggerManagerThreadImpl managerThread =
                suspendContext.getDebugProcess().getManagerThread();
            while (!stack.isEmpty()) {
              managerThread.pushBack(stack.pop());
            }
          }
        }
      }
    }
  }
  public PsiElement getTarget(@NotNull final DataContext dataContext) {
    final Project project = CommonDataKeys.PROJECT.getData(dataContext);
    if (project == null) return null;

    final Editor editor = CommonDataKeys.EDITOR.getData(dataContext);
    if (LOG.isDebugEnabled()) {
      LOG.debug("editor " + editor);
    }
    if (editor != null) {
      final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
      if (file == null) return null;

      final PsiElement targetElement =
          TargetElementUtilBase.findTargetElement(
              editor,
              TargetElementUtilBase.ELEMENT_NAME_ACCEPTED
                  | TargetElementUtilBase.REFERENCED_ELEMENT_ACCEPTED
                  | TargetElementUtilBase.LOOKUP_ITEM_ACCEPTED);
      if (LOG.isDebugEnabled()) {
        LOG.debug("target element " + targetElement);
      }
      if (targetElement instanceof PsiClass) {
        return targetElement;
      }

      final int offset = editor.getCaretModel().getOffset();
      PsiElement element = file.findElementAt(offset);
      while (element != null) {
        if (LOG.isDebugEnabled()) {
          LOG.debug("context element " + element);
        }
        if (element instanceof PsiFile) {
          if (!(element instanceof PsiClassOwner)) return null;
          final PsiClass[] classes = ((PsiClassOwner) element).getClasses();
          return classes.length == 1 ? classes[0] : null;
        }
        if (element instanceof PsiClass
            && !(element instanceof PsiAnonymousClass)
            && !(element instanceof PsiSyntheticClass)) {
          return element;
        }
        element = element.getParent();
      }

      return null;
    } else {
      final PsiElement element = CommonDataKeys.PSI_ELEMENT.getData(dataContext);
      return element instanceof PsiClass ? (PsiClass) element : null;
    }
  }
 @Override
 public void browserActivated(@NotNull HierarchyBrowser browser) {
   if (LOG.isDebugEnabled()) {
     LOG.debug("browserActivated " + browser);
   }
   ((MethodHierarchyBrowser) browser).changeView(MethodHierarchyBrowserBase.METHOD_TYPE);
 }
  public Process createProcess() throws ExecutionException {
    if (LOG.isDebugEnabled()) {
      LOG.debug("Executing [" + getCommandLineString() + "]");
    }

    List<String> commands;
    try {
      checkWorkingDirectory();

      if (StringUtil.isEmptyOrSpaces(myExePath)) {
        throw new ExecutionException(
            IdeBundle.message("run.configuration.error.executable.not.specified"));
      }

      commands = CommandLineUtil.toCommandLine(myExePath, myProgramParams.getList());
    } catch (ExecutionException e) {
      LOG.info(e);
      throw e;
    }

    try {
      return startProcess(commands);
    } catch (IOException e) {
      LOG.info(e);
      throw new ProcessNotCreatedException(e.getMessage(), e, this);
    }
  }
 @NotNull
 public static FontInfo getFontAbleToDisplay(
     int codePoint, @JdkConstants.FontStyle int style, @NotNull FontPreferences preferences) {
   boolean tryDefaultFont = true;
   List<String> fontFamilies = preferences.getEffectiveFontFamilies();
   FontInfo result;
   //noinspection ForLoopReplaceableByForEach
   for (int i = 0, len = fontFamilies.size();
       i < len;
       ++i) { // avoid foreach, it instantiates ArrayList$Itr, this traversal happens very often
     final String fontFamily = fontFamilies.get(i);
     result =
         doGetFontAbleToDisplay(codePoint, preferences.getSize(fontFamily), style, fontFamily);
     if (result != null) {
       return result;
     }
     tryDefaultFont &= !FontPreferences.DEFAULT_FONT_NAME.equals(fontFamily);
   }
   int size = FontPreferences.DEFAULT_FONT_SIZE;
   if (!fontFamilies.isEmpty()) {
     size = preferences.getSize(fontFamilies.get(0));
   }
   if (tryDefaultFont) {
     result = doGetFontAbleToDisplay(codePoint, size, style, FontPreferences.DEFAULT_FONT_NAME);
     if (result != null) {
       return result;
     }
   }
   result = doGetFontAbleToDisplay(codePoint, size, style);
   if (LOG.isDebugEnabled()) {
     LOG.debug("Fallback font: " + result.getFont().getFontName());
   }
   return result;
 }
 private static void logFrame(ProtocolFrame frame, boolean out) {
   if (LOG.isDebugEnabled()) {
     LOG.debug(
         String.format(
             "%1$tH:%1$tM:%1$tS.%1$tL %2$s %3$s\n", new Date(), (out ? "<<<" : ">>>"), frame));
   }
 }
  public void startLongProcessAndFork(Runnable process) {
    startNewWorkerThread();

    try {
      process.run();
    } finally {
      final WorkerThreadRequest request = getCurrentThreadRequest();

      if (LOG.isDebugEnabled()) {
        LOG.debug("Switching back to " + request);
      }

      super.invokeAndWait(
          new DebuggerCommandImpl() {
            protected void action() throws Exception {
              switchToRequest(request);
            }

            protected void commandCancelled() {
              if (LOG.isDebugEnabled()) {
                LOG.debug("Event queue was closed, killing request");
              }
              request.interrupt();
            }
          });
    }
  }
 @Override
 public void buildStarted(CompileContext context) {
   final JpsProject project = context.getProjectDescriptor().getProject();
   final JpsJavaCompilerConfiguration config =
       JpsJavaExtensionService.getInstance().getCompilerConfiguration(project);
   final String compilerId = config == null ? JavaCompilers.JAVAC_ID : config.getJavaCompilerId();
   if (LOG.isDebugEnabled()) {
     LOG.debug("Java compiler ID: " + compilerId);
   }
   final boolean isJavac =
       JavaCompilers.JAVAC_ID.equalsIgnoreCase(compilerId)
           || JavaCompilers.JAVAC_API_ID.equalsIgnoreCase(compilerId);
   final boolean isEclipse =
       JavaCompilers.ECLIPSE_ID.equalsIgnoreCase(compilerId)
           || JavaCompilers.ECLIPSE_EMBEDDED_ID.equalsIgnoreCase(compilerId);
   IS_ENABLED.set(context, isJavac || isEclipse);
   String messageText = null;
   if (isJavac) {
     messageText =
         "Using javac " + System.getProperty("java.version") + " to compile java sources";
   } else if (isEclipse) {
     messageText = "Using eclipse compiler to compile java sources";
   }
   COMPILER_VERSION_INFO.set(context, new AtomicReference<String>(messageText));
 }
Exemplo n.º 10
0
  @Override
  @NotNull
  public StubTree getStubTree() {
    ApplicationManager.getApplication().assertReadAccessAllowed();

    StubTree stubTree = dereference(myStub);
    if (stubTree != null) return stubTree;

    // build newStub out of lock to avoid deadlock
    StubTree newStubTree =
        (StubTree) StubTreeLoader.getInstance().readOrBuild(getProject(), getVirtualFile(), this);
    if (newStubTree == null) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("No stub for class file in index: " + getVirtualFile().getPresentableUrl());
      }
      newStubTree = new StubTree(new PsiJavaFileStubImpl("corrupted.classfiles", true));
    }

    synchronized (myStubLock) {
      stubTree = dereference(myStub);
      if (stubTree != null) return stubTree;

      stubTree = newStubTree;

      @SuppressWarnings("unchecked")
      PsiFileStubImpl<PsiFile> fileStub = (PsiFileStubImpl) stubTree.getRoot();
      fileStub.setPsi(this);

      myStub = new SoftReference<StubTree>(stubTree);
    }

    return stubTree;
  }
 static void log(
     ProgressIndicator progressIndicator,
     TextEditorHighlightingPass pass,
     @NonNls @NotNull Object... info) {
   if (LOG.isDebugEnabled()) {
     CharSequence docText =
         pass == null || pass.getDocument() == null
             ? ""
             : ": '" + StringUtil.first(pass.getDocument().getCharsSequence(), 10, true) + "'";
     synchronized (PassExecutorService.class) {
       String infos = StringUtil.join(info, Functions.TO_STRING(), " ");
       String message =
           StringUtil.repeatSymbol(' ', getThreadNum() * 4)
               + " "
               + pass
               + " "
               + infos
               + "; progress="
               + (progressIndicator == null ? null : progressIndicator.hashCode())
               + " "
               + (progressIndicator == null ? "?" : progressIndicator.isCanceled() ? "X" : "V")
               + docText;
       LOG.debug(message);
       // System.out.println(message);
     }
   }
 }
Exemplo n.º 12
0
 private static void retainOnlyJarsAndDirectories(List<VirtualFile> woSdk) {
   for (Iterator<VirtualFile> iterator = woSdk.iterator(); iterator.hasNext(); ) {
     VirtualFile file = iterator.next();
     final VirtualFile local = ArchiveVfsUtil.getVirtualFileForJar(file);
     final boolean dir = file.isDirectory();
     final String name = file.getName();
     if (LOG.isDebugEnabled()) {
       LOG.debug(
           "Considering: "
               + file.getPath()
               + "; local="
               + local
               + "; dir="
               + dir
               + "; name="
               + name);
     }
     if (dir || local != null) {
       continue;
     }
     if (name.endsWith(".jar")) {
       continue;
     }
     LOG.debug("Removing");
     iterator.remove();
   }
 }
Exemplo n.º 13
0
  @Nullable
  public PsiElement[] getElements(boolean[] isCopied) {
    try {
      Transferable content = myCopyPasteManager.getContents();
      if (content == null) {
        return null;
      }

      Object transferData;
      try {
        transferData = content.getTransferData(ourDataFlavor);
      } catch (UnsupportedFlavorException e) {
        return null;
      } catch (IOException e) {
        return null;
      }

      if (!(transferData instanceof MyData)) {
        return null;
      }
      MyData dataProxy = (MyData) transferData;
      if (!Comparing.equal(dataProxy, myRecentData)) {
        return null;
      }
      if (isCopied != null) {
        isCopied[0] = myRecentData.isCopied();
      }
      return myRecentData.getElements();
    } catch (Exception e) {
      if (LOG.isDebugEnabled()) {
        LOG.debug(e);
      }
      return null;
    }
  }
  public DaemonCodeAnalyzerImpl(
      @NotNull Project project,
      DaemonCodeAnalyzerSettings daemonCodeAnalyzerSettings,
      EditorTracker editorTracker) {
    myProject = project;

    mySettings = daemonCodeAnalyzerSettings;
    myEditorTracker = editorTracker;
    myLastSettings = (DaemonCodeAnalyzerSettings) mySettings.clone();

    myFileStatusMap = new FileStatusMap(myProject);
    myPassExecutorService =
        new PassExecutorService(myProject) {
          @Override
          protected void afterApplyInformationToEditor(
              final TextEditorHighlightingPass pass,
              @NotNull final FileEditor fileEditor,
              final ProgressIndicator updateProgress) {
            if (fileEditor instanceof TextEditor) {
              log(updateProgress, pass, "Apply ");
              Editor editor = ((TextEditor) fileEditor).getEditor();
              repaintErrorStripeRenderer(editor);
            }
          }

          @Override
          protected boolean isDisposed() {
            return myDisposed || super.isDisposed();
          }
        };
    Disposer.register(project, myPassExecutorService);
    Disposer.register(project, myFileStatusMap);
    DaemonProgressIndicator.setDebug(LOG.isDebugEnabled());
  }
  public Process createProcess() throws ExecutionException {
    if (LOG.isDebugEnabled()) {
      LOG.debug("Executing [" + getCommandLineString() + "]");
    }

    List<String> commands;
    try {
      checkWorkingDirectory();

      if (StringUtil.isEmptyOrSpaces(myExePath)) {
        throw new ExecutionException(
            IdeBundle.message("run.configuration.error.executable.not.specified"));
      }

      commands = CommandLineUtil.toCommandLine(myExePath, myProgramParams.getList());
    } catch (ExecutionException e) {
      LOG.warn(e);
      throw e;
    }

    try {
      ProcessBuilder builder = new ProcessBuilder(commands);
      setupEnvironment(builder.environment());
      builder.directory(myWorkDirectory);
      builder.redirectErrorStream(myRedirectErrorStream);
      return builder.start();
    } catch (IOException e) {
      LOG.warn(e);
      throw new ProcessNotCreatedException(e.getMessage(), e, this);
    }
  }
 @Override
 protected void addNamedLibrary(
     JpsModule rootModel,
     Collection<String> unknownLibraries,
     boolean exported,
     String name,
     boolean applicationLevel) {
   if (LOG.isDebugEnabled()) {
     LOG.debug(
         "loading "
             + rootModel.getName()
             + ": adding "
             + (applicationLevel ? "application" : "project")
             + " library '"
             + name
             + "'");
   }
   JpsElementFactory factory = JpsElementFactory.getInstance();
   JpsLibraryReference libraryReference;
   final String level = myLibLevels.get(name);
   libraryReference =
       level != null
           ? factory.createLibraryReference(
               name, JpsLibraryTableSerializer.createLibraryTableReference(level))
           : factory.createLibraryReference(name, factory.createGlobalReference());
   final JpsLibraryDependency dependency =
       rootModel.getDependenciesList().addLibraryDependency(libraryReference);
   setLibraryEntryExported(dependency, exported);
 }
  public void scan() {
    List<VirtualFile> workQueue = myWorkQueue;
    myWorkQueue = new ArrayList<VirtualFile>();
    boolean hasEventsToFire = myFinishRunnable != null || !myEvents.isEmpty();

    if (!workQueue.isEmpty()) {
      LocalFileSystemImpl fs = (LocalFileSystemImpl) LocalFileSystem.getInstance();
      fs.markSuspiciousFilesDirty(workQueue);
      FileWatcher watcher = fs.getFileWatcher();

      for (VirtualFile file : workQueue) {
        NewVirtualFile nvf = (NewVirtualFile) file;
        if (!myIsRecursive
            && (!myIsAsync
                || !watcher.isWatched(
                    nvf))) { // We're unable to definitely refresh synchronously by means of file
                             // watcher.
          nvf.markDirty();
        }

        RefreshWorker worker = new RefreshWorker(file, myIsRecursive);
        long t = LOG.isDebugEnabled() ? System.currentTimeMillis() : 0;
        worker.scan();
        List<VFileEvent> events = worker.getEvents();
        if (t != 0) {
          t = System.currentTimeMillis() - t;
          LOG.debug(file + " scanned in " + t + " ms, events: " + events);
        }
        myEvents.addAll(events);
        if (!events.isEmpty()) hasEventsToFire = true;
      }
    }
    iHaveEventsToFire = hasEventsToFire;
  }
Exemplo n.º 18
0
 /** Print pretty-formatted XML to {@code logger}, if its level is DEBUG or below. */
 public static void prettyFormatXmlToLog(@NotNull Logger logger, @NotNull Element element) {
   if (logger.isDebugEnabled()) {
     // alternatively
     // new XMLOutputter(Format.getPrettyFormat()).outputString(root)
     logger.debug("\n" + JDOMUtil.createOutputter("\n").outputString(element));
   }
 }
 private void logRoots(final List<VirtualFile> roots) {
   if (LOG.isDebugEnabled()) {
     LOG.debug("Roots for committed changes load:\n");
     for (VirtualFile root : roots) {
       LOG.debug(root.getPath() + ", ");
     }
   }
 }
Exemplo n.º 20
0
 public void childrenChanged(@NotNull PsiTreeChangeEventImpl event) {
   event.setCode(PsiTreeChangeEventImpl.PsiEventType.CHILDREN_CHANGED);
   if (LOG.isDebugEnabled()) {
     LOG.debug("childrenChanged: parent = " + event.getParent());
   }
   fireEvent(event);
   afterChange(true);
 }
Exemplo n.º 21
0
 public void childRemoved(@NotNull PsiTreeChangeEventImpl event) {
   event.setCode(PsiTreeChangeEventImpl.PsiEventType.CHILD_REMOVED);
   if (LOG.isDebugEnabled()) {
     LOG.debug("childRemoved: child = " + event.getChild() + ", parent = " + event.getParent());
   }
   fireEvent(event);
   afterChange(true);
 }
Exemplo n.º 22
0
 public void beforeChildrenChange(@NotNull PsiTreeChangeEventImpl event) {
   beforeChange(true);
   event.setCode(PsiTreeChangeEventImpl.PsiEventType.BEFORE_CHILDREN_CHANGE);
   if (LOG.isDebugEnabled()) {
     LOG.debug("beforeChildrenChange: parent = " + event.getParent());
   }
   fireEvent(event);
 }
 @NotNull
 @Override
 public HierarchyBrowser createHierarchyBrowser(PsiElement element) {
   if (LOG.isDebugEnabled()) {
     LOG.debug("createHierarchyBrowser " + element);
   }
   return new HaxeMethodHierarchyBrowser(element.getProject(), (PsiMethod) element);
 }
Exemplo n.º 24
0
 @Override
 public void beforeChildAddition(@NotNull PsiTreeChangeEventImpl event) {
   beforeChange(true);
   event.setCode(PsiTreeChangeEventImpl.PsiEventType.BEFORE_CHILD_ADDITION);
   if (LOG.isDebugEnabled()) {
     LOG.debug("beforeChildAddition: parent = " + event.getParent());
   }
   fireEvent(event);
 }
 @Nullable
 @Override
 public PsiElement getTarget(@NotNull DataContext context) {
   if (LOG.isDebugEnabled()) {
     LOG.debug("getTarget " + context);
   }
   HaxeMethod foundMethod = HaxeHierarchyUtils.getTargetMethod(context);
   return foundMethod;
 }
Exemplo n.º 26
0
 private static void clearContinuation(CompileContext context, ModuleChunk chunk) {
   GroovycContinuation continuation = takeContinuation(context, chunk);
   if (continuation != null) {
     if (Utils.IS_TEST_MODE || LOG.isDebugEnabled()) {
       LOG.info("clearing continuation for " + chunk);
     }
     continuation.buildAborted();
   }
 }
  public ControlFlowWrapper(Project project, PsiElement codeFragment, PsiElement[] elements)
      throws PrepareFailedException {
    try {
      myControlFlow =
          ControlFlowFactory.getInstance(project)
              .getControlFlow(
                  codeFragment, new LocalsControlFlowPolicy(codeFragment), false, false);
    } catch (AnalysisCanceledException e) {
      throw new PrepareFailedException(
          RefactoringBundle.message("extract.method.control.flow.analysis.failed"),
          e.getErrorElement());
    }

    if (LOG.isDebugEnabled()) {
      LOG.debug(myControlFlow.toString());
    }

    int flowStart = -1;
    int index = 0;
    while (index < elements.length) {
      flowStart = myControlFlow.getStartOffset(elements[index]);
      if (flowStart >= 0) break;
      index++;
    }
    int flowEnd;
    if (flowStart < 0) {
      // no executable code
      flowStart = 0;
      flowEnd = 0;
    } else {
      index = elements.length - 1;
      while (true) {
        flowEnd = myControlFlow.getEndOffset(elements[index]);
        if (flowEnd >= 0) break;
        index--;
      }
    }
    myFlowStart = flowStart;
    myFlowEnd = flowEnd;
    if (LOG.isDebugEnabled()) {
      LOG.debug("start offset:" + myFlowStart);
      LOG.debug("end offset:" + myFlowEnd);
    }
  }
Exemplo n.º 28
0
 private static Set<String> getPathsToCompile(List<File> toCompile) {
   final Set<String> toCompilePaths = new LinkedHashSet<String>();
   for (File file : toCompile) {
     if (LOG.isDebugEnabled()) {
       LOG.debug("Path to compile: " + file.getPath());
     }
     toCompilePaths.add(FileUtil.toSystemIndependentName(file.getPath()));
   }
   return toCompilePaths;
 }
  private void writeLine(final String line) throws IOException {
    if (LOG.isDebugEnabled()) {
      LOG.debug("<< " + line);
    }

    final MyProcessHandler processHandler = myProcessHandler;
    if (processHandler != null) {
      processHandler.writeLine(line);
    }
  }
Exemplo n.º 30
0
 @Override
 public void beforeChildRemoval(@NotNull PsiTreeChangeEventImpl event) {
   beforeChange(true);
   event.setCode(PsiTreeChangeEventImpl.PsiEventType.BEFORE_CHILD_REMOVAL);
   if (LOG.isDebugEnabled()) {
     LOG.debug(
         "beforeChildRemoval: child = " + event.getChild() + ", parent = " + event.getParent());
   }
   fireEvent(event);
 }