@Override
  protected void collectAdditionalElementsToRename(List<Pair<PsiElement, TextRange>> stringUsages) {
    if (isReplaceAllOccurrences()) {
      for (E expression : getOccurrences()) {
        LOG.assertTrue(expression.isValid(), expression.getText());
        stringUsages.add(
            Pair.<PsiElement, TextRange>create(
                expression, new TextRange(0, expression.getTextLength())));
      }
    } else if (getExpr() != null) {
      correctExpression();
      final E expr = getExpr();
      LOG.assertTrue(expr.isValid(), expr.getText());
      stringUsages.add(
          Pair.<PsiElement, TextRange>create(expr, new TextRange(0, expr.getTextLength())));
    }

    final V localVariable = getLocalVariable();
    if (localVariable != null) {
      final PsiElement nameIdentifier = localVariable.getNameIdentifier();
      if (nameIdentifier != null) {
        int length = nameIdentifier.getTextLength();
        stringUsages.add(
            Pair.<PsiElement, TextRange>create(nameIdentifier, new TextRange(0, length)));
      }
    }
  }
 public void actionPerformed(AnActionEvent e) {
   final PackageDependenciesNode leftNode = myLeftTree.getSelectedNode();
   final PackageDependenciesNode rightNode = myRightTree.getSelectedNode();
   if (leftNode != null && rightNode != null) {
     boolean hasDirectDependencies = myTransitiveBorder == 0;
     if (myTransitiveBorder > 0) {
       final Set<PsiFile> searchIn = getSelectedScope(myLeftTree);
       final Set<PsiFile> searchFor = getSelectedScope(myRightTree);
       for (DependenciesBuilder builder : myBuilders) {
         if (hasDirectDependencies) break;
         for (PsiFile from : searchIn) {
           if (hasDirectDependencies) break;
           for (PsiFile to : searchFor) {
             if (hasDirectDependencies) break;
             final List<List<PsiFile>> paths = builder.findPaths(from, to);
             for (List<PsiFile> path : paths) {
               if (path.isEmpty()) {
                 hasDirectDependencies = true;
                 break;
               }
             }
           }
         }
       }
     }
     final PatternDialectProvider provider =
         PatternDialectProvider.getInstance(mySettings.SCOPE_TYPE);
     PackageSet leftPackageSet = provider.createPackageSet(leftNode, true);
     if (leftPackageSet == null) {
       leftPackageSet = provider.createPackageSet(leftNode, false);
     }
     LOG.assertTrue(leftPackageSet != null);
     PackageSet rightPackageSet = provider.createPackageSet(rightNode, true);
     if (rightPackageSet == null) {
       rightPackageSet = provider.createPackageSet(rightNode, false);
     }
     LOG.assertTrue(rightPackageSet != null);
     if (hasDirectDependencies) {
       DependencyValidationManager.getInstance(myProject)
           .addRule(
               new DependencyRule(
                   new NamedScope.UnnamedScope(leftPackageSet),
                   new NamedScope.UnnamedScope(rightPackageSet),
                   true));
       rebuild();
     } else {
       Messages.showErrorDialog(
           DependenciesPanel.this,
           "Rule was not added.\n There is no direct dependency between \'"
               + leftPackageSet.getText()
               + "\' and \'"
               + rightPackageSet.getText()
               + "\'",
           AnalysisScopeBundle.message("mark.dependency.illegal.text"));
     }
   }
 }
    /** @see Runnable#run() */
    public void run() {
      try {
        jasper(id);

        ComponentUtils.centerComponentOnScreen(AbstractJasperViewerDialog.this);

        setVisible(true);
      } catch (Exception e) {
        if (LOG.isErrorEnabled()) {
          LOG.error(e.getMessage(), e);
        }
        e.printStackTrace();
      }
    }
    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
      final OrderEntry selectedEntry = getSelectedEntry();
      GlobalSearchScope targetScope;
      if (selectedEntry instanceof ModuleOrderEntry) {
        final Module module = ((ModuleOrderEntry) selectedEntry).getModule();
        LOG.assertTrue(module != null);
        targetScope = GlobalSearchScope.moduleScope(module);
      } else {
        Library library = ((LibraryOrderEntry) selectedEntry).getLibrary();
        LOG.assertTrue(library != null);
        targetScope = new LibraryScope(getProject(), library);
      }
      new AnalyzeDependenciesOnSpecifiedTargetHandler(
          getProject(), new AnalysisScope(myState.getRootModel().getModule()), targetScope) {
        @Override
        protected boolean shouldShowDependenciesPanel(List<DependenciesBuilder> builders) {
          for (DependenciesBuilder builder : builders) {
            for (Set<PsiFile> files : builder.getDependencies().values()) {
              if (!files.isEmpty()) {
                Messages.showInfoMessage(
                    myProject,
                    "Dependencies were successfully collected in \""
                        + ToolWindowId.DEPENDENCIES
                        + "\" toolwindow",
                    FindBundle.message("find.pointcut.applications.not.found.title"));
                return true;
              }
            }
          }
          String message = "No code dependencies were found.";
          if (DependencyVisitorFactory.VisitorOptions.fromSettings(myProject).skipImports()) {
            message += " ";
            message += AnalysisScopeBundle.message("dependencies.in.imports.message");
          }
          message += " Would you like to remove the dependency?";
          if (Messages.showOkCancelDialog(
                  myProject, message, CommonBundle.getWarningTitle(), Messages.getWarningIcon())
              == Messages.OK) {
            removeSelectedItems(TableUtil.removeSelectedItems(myEntryTable));
          }
          return false;
        }

        @Override
        protected boolean canStartInBackground() {
          return false;
        }
      }.analyze();
    }
 public void actionPerformed(final AnActionEvent e) {
   final AnalysisScope scope = getScope();
   LOG.assertTrue(scope != null);
   final DependenciesBuilder builder;
   if (!myForward) {
     builder = new BackwardDependenciesBuilder(myProject, scope, myScopeOfInterest);
   } else {
     builder = new ForwardDependenciesBuilder(myProject, scope, myTransitiveBorder);
   }
   ProgressManager.getInstance()
       .runProcessWithProgressAsynchronously(
           myProject,
           AnalysisScopeBundle.message("package.dependencies.progress.title"),
           new Runnable() {
             public void run() {
               builder.analyze();
             }
           },
           new Runnable() {
             public void run() {
               myBuilders.add(builder);
               myDependencies.putAll(builder.getDependencies());
               myIllegalDependencies.putAll(builder.getIllegalDependencies());
               exclude(myExcluded);
               rebuild();
             }
           },
           null,
           new PerformAnalysisInBackgroundOption(myProject));
 }
    @Override
    @NotNull
    public NewColorAndFontPanel createPanel(@NotNull ColorAndFontOptions options) {
      final DiffOptionsPanel optionsPanel = new DiffOptionsPanel(options);
      SchemesPanel schemesPanel = new SchemesPanel(options);
      PreviewPanel previewPanel;
      try {
        final DiffPreviewPanel diffPreviewPanel = new DiffPreviewPanel(myDisposable);
        diffPreviewPanel.setMergeRequest(null);
        schemesPanel.addListener(
            new ColorAndFontSettingsListener.Abstract() {
              @Override
              public void schemeChanged(final Object source) {
                diffPreviewPanel.setColorScheme(getSelectedScheme());
                optionsPanel.updateOptionsList();
                diffPreviewPanel.updateView();
              }
            });
        previewPanel = diffPreviewPanel;
      } catch (FilesTooBigForDiffException e) {
        LOG.info(e);
        previewPanel = new PreviewPanel.Empty();
      }

      return new NewColorAndFontPanel(
          schemesPanel, optionsPanel, previewPanel, DIFF_GROUP, null, null);
    }
Example #7
0
      @Override
      public void setGlassPane(final Component glass) {
        if (myGlassPaneIsSet) {
          LOG.warn("Setting of glass pane for DialogWrapper is prohibited", new Exception());
          return;
        }

        super.setGlassPane(glass);
      }
Example #8
0
 public final ImageIcon loadIcon(final String aIconID) {
   final ImageIcon icon = loadIcon("icons", aIconID);
   if (icon != null) return icon;
   final ImageIcon small = loadIcon("small", aIconID);
   if (small != null) return small;
   final ImageIcon image = loadIcon(".", aIconID);
   if (image != null) return image;
   LOG.debug("missing icon for %s", aIconID);
   return null;
 }
 @Override
 public void contentsChanged(VirtualFileEvent event) {
   if (event.isFromSave()) { // commit
     assertThread();
     VirtualFile file = event.getFile();
     LOG.assertTrue(file.isValid());
     if (myFile.equals(file)) {
       updateModifiedProperty();
     }
   }
 }
Example #10
0
    @Override
    public void run() {
      try {
        if (myDisposed) {
          return;
        }
        synchronized (LOCK) {
          if (myTask == null) return;
        }

        final Runnable scheduledTask =
            new Runnable() {
              @Override
              public void run() {
                final Runnable task;
                synchronized (LOCK) {
                  task = myTask;
                  if (task == null) return;
                  myTask = null;

                  myRequests.remove(Request.this);
                }

                if (myThreadToUse == ThreadToUse.SWING_THREAD && !isEdt()) {
                  try {
                    SwingUtilities.invokeAndWait(task);
                  } catch (Exception e) {
                    LOG.error(e);
                  }
                } else {
                  try {
                    task.run();
                  } catch (Exception e) {
                    LOG.error(e);
                  }
                }
              }
            };

        if (myModalityState == null) {
          myFuture = myExecutorService.submit(scheduledTask);
        } else {
          final Application app = ApplicationManager.getApplication();
          if (app != null) {
            app.invokeLater(scheduledTask, myModalityState);
          } else {
            SwingUtilities.invokeLater(scheduledTask);
          }
        }
      } catch (Throwable e) {
        LOG.error(e);
      }
    }
Example #11
0
 public final Action action(final String aActionID) {
   if (!myActions.containsKey(aActionID)) {
     try {
       final Action action = createAction(aActionID);
       myActions.put(aActionID, action);
     } catch (final Exception e) {
       LOG.error("failed creating action: %s", e);
       throw new RuntimeException(e);
     }
   }
   return myActions.get(aActionID);
 }
 ReadAccessToken(boolean explicit) {
   myExplicit = explicit;
   LOG.assertTrue(
       !Thread.holdsLock(PsiLock.LOCK),
       "Thread must not hold PsiLock while performing readAction");
   try {
     myActionsLock.readLock().acquire();
     if (myExplicit) acquired();
   } catch (InterruptedException e) {
     throw new RuntimeInterruptedException(e);
   }
 }
Example #13
0
 private void moveMousePointerOnButton(final JButton button) {
   Application application = ApplicationManager.getApplication();
   if (application != null && application.hasComponent(UISettings.class)) {
     if (button != null && UISettings.getInstance().MOVE_MOUSE_ON_DEFAULT_BUTTON) {
       Point p = button.getLocationOnScreen();
       Rectangle r = button.getBounds();
       try {
         Robot robot = new Robot();
         robot.mouseMove(p.x + r.width / 2, p.y + r.height / 2);
       } catch (AWTException e) {
         LOG.warn(e);
       }
     }
   }
 }
Example #14
0
  private Action createAction(final String aActionID) throws Exception {
    final String actionClassName = getActionClassName(aActionID);
    final Class actionClass = Class.forName(actionClassName);

    {
      final Action action = tryEmptyConstructor(actionClass);
      if (action != null) return action;
    }
    {
      final Action action = tryDefaultConstructor(actionClass);
      if (action != null) return action;
    }

    LOG.error("action class not found or incompatible: %s", aActionID);
    throw new IllegalArgumentException(aActionID);
  }
Example #15
0
 @Override
 public Component getTreeCellEditorComponent(
     JTree tree, Object value, boolean isSelected, boolean expanded, boolean leaf, int row) {
   final JTextField field =
       (JTextField)
           super.getTreeCellEditorComponent(tree, value, isSelected, expanded, leaf, row);
   final Object node = ((DefaultMutableTreeNode) value).getUserObject();
   final PackagingElement<?> element = ((PackagingElementNode) node).getElementIfSingle();
   LOG.assertTrue(element != null);
   final String name = ((RenameablePackagingElement) element).getName();
   field.setText(name);
   int i = name.lastIndexOf('.');
   field.setSelectionStart(0);
   field.setSelectionEnd(i != -1 ? i : name.length());
   return field;
 }
  @Override
  protected void addHighlights(
      @NotNull Map<TextRange, TextAttributes> ranges,
      @NotNull Editor editor,
      @NotNull Collection<RangeHighlighter> highlighters,
      @NotNull HighlightManager highlightManager) {
    final TextAttributes attributes =
        EditorColorsManager.getInstance()
            .getGlobalScheme()
            .getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
    final V variable = getVariable();
    if (variable != null) {
      final String name = variable.getName();
      LOG.assertTrue(name != null, variable);
      final int variableNameLength = name.length();
      if (isReplaceAllOccurrences()) {
        for (RangeMarker marker : getOccurrenceMarkers()) {
          final int startOffset = marker.getStartOffset();
          highlightManager.addOccurrenceHighlight(
              editor,
              startOffset,
              startOffset + variableNameLength,
              attributes,
              0,
              highlighters,
              null);
        }
      } else if (getExpr() != null) {
        final int startOffset = getExprMarker().getStartOffset();
        highlightManager.addOccurrenceHighlight(
            editor,
            startOffset,
            startOffset + variableNameLength,
            attributes,
            0,
            highlighters,
            null);
      }
    }

    for (RangeHighlighter highlighter : highlighters) {
      highlighter.setGreedyToLeft(true);
      highlighter.setGreedyToRight(true);
    }
  }
    public WriteAccessToken(Class _clazz) {
      clazz = _clazz;
      assertCanRunWriteAction();

      ActivityTracker.getInstance().inc();
      fireBeforeWriteActionStart(_clazz);
      final AtomicBoolean stopped = new AtomicBoolean(false);

      if (ourDumpThreadsOnLongWriteActionWaiting > 0) {
        executeOnPooledThread(
            new Runnable() {
              @Override
              public void run() {
                while (!stopped.get()) {
                  try {
                    Thread.sleep(ourDumpThreadsOnLongWriteActionWaiting);
                    if (!stopped.get()) {
                      PerformanceWatcher.getInstance().dumpThreads(true);
                    }
                  } catch (InterruptedException ignored) {
                  }
                }
              }
            });
      }

      LOG.assertTrue(
          myActionsLock.isWriteLockAcquired(Thread.currentThread())
              || !Thread.holdsLock(PsiLock.LOCK),
          "Thread must not hold PsiLock while performing writeAction");
      try {
        myActionsLock.writeLock().acquire();
        acquired();
      } catch (InterruptedException e) {
        throw new RuntimeInterruptedException(e);
      }
      stopped.set(true);

      myWriteActionsStack.push(_clazz);

      fireWriteActionStarted(_clazz);
    }
    @Override
    protected VirtualFile[] doAddItems() {
      Project project =
          CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(myPanel));
      try {
        String[] files =
            PythonRemoteInterpreterManager.getInstance()
                .chooseRemoteFiles(
                    project, (PyRemoteSdkAdditionalDataBase) mySdk.getSdkAdditionalData(), false);

        final String sourcesLocalPath = PySdkUtil.getRemoteSourcesLocalPath(mySdk.getHomePath());

        VirtualFile[] vFiles = new VirtualFile[files.length];

        int i = 0;
        for (String file : files) {
          String localRoot = PyRemoteSourceItem.localPathForRemoteRoot(sourcesLocalPath, file);

          myNewMappings.add(new PathMappingSettings.PathMapping(localRoot, file));
          myRemoteSdkData.getPathMappings().addMappingCheckUnique(localRoot, file);

          if (!new File(localRoot).exists()) {
            new File(localRoot).mkdirs();
          }
          vFiles[i++] =
              LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(localRoot));
        }

        vFiles = adjustAddedFileSet(myPanel, vFiles);
        List<VirtualFile> added = new ArrayList<VirtualFile>(vFiles.length);
        for (VirtualFile vFile : vFiles) {
          if (addElement(vFile)) {
            added.add(vFile);
          }
        }
        return VfsUtilCore.toVirtualFileArray(added);
      } catch (Exception e) {
        LOG.error(e);
      }
      return new VirtualFile[0];
    }
 @Nullable
 private AnalysisScope getScope() {
   final Set<PsiFile> selectedScope = getSelectedScope(myRightTree);
   Set<PsiFile> result = new HashSet<PsiFile>();
   ((PackageDependenciesNode) myLeftTree.getModel().getRoot())
       .fillFiles(result, !mySettings.UI_FLATTEN_PACKAGES);
   selectedScope.removeAll(result);
   if (selectedScope.isEmpty()) return null;
   List<VirtualFile> files = new ArrayList<VirtualFile>();
   final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex();
   for (PsiFile psiFile : selectedScope) {
     final VirtualFile file = psiFile.getVirtualFile();
     LOG.assertTrue(file != null);
     if (fileIndex.isInContent(file)) {
       files.add(file);
     }
   }
   if (!files.isEmpty()) {
     return new AnalysisScope(myProject, files);
   }
   return null;
 }
    @Override
    protected JPanel processFiles(@NotNull List<Element> fileElements, final JPanel context) {
      final Ref<EditorWindow> windowRef = new Ref<EditorWindow>();
      UIUtil.invokeAndWaitIfNeeded(
          new Runnable() {
            @Override
            public void run() {
              windowRef.set(context == null ? createEditorWindow() : findWindowWith(context));
            }
          });
      final EditorWindow window = windowRef.get();
      LOG.assertTrue(window != null);
      VirtualFile focusedFile = null;

      for (int i = 0; i < fileElements.size(); i++) {
        final Element file = fileElements.get(i);
        if (i == 0) {
          EditorTabbedContainer tabbedPane = window.getTabbedPane();
          if (tabbedPane != null) {
            try {
              int limit =
                  Integer.parseInt(
                      file.getParentElement()
                          .getAttributeValue(
                              JBTabsImpl.SIDE_TABS_SIZE_LIMIT_KEY.toString(),
                              String.valueOf(JBTabsImpl.DEFAULT_MAX_TAB_WIDTH)));
              UIUtil.putClientProperty(
                  tabbedPane.getComponent(), JBTabsImpl.SIDE_TABS_SIZE_LIMIT_KEY, limit);
            } catch (NumberFormatException e) {
              // ignore
            }
          }
        }
        try {
          final FileEditorManagerImpl fileEditorManager = getManager();
          Element historyElement = file.getChild(HistoryEntry.TAG);
          final HistoryEntry entry =
              HistoryEntry.createLight(fileEditorManager.getProject(), historyElement);
          final VirtualFile virtualFile = entry.getFile();
          if (virtualFile == null)
            throw new InvalidDataException("No file exists: " + entry.getFilePointer().getUrl());
          Document document =
              ApplicationManager.getApplication()
                  .runReadAction(
                      new Computable<Document>() {
                        @Override
                        public Document compute() {
                          return virtualFile.isValid()
                              ? FileDocumentManager.getInstance().getDocument(virtualFile)
                              : null;
                        }
                      });
          final boolean isCurrentInTab =
              Boolean.valueOf(file.getAttributeValue(CURRENT_IN_TAB)).booleanValue();
          Boolean pin = Boolean.valueOf(file.getAttributeValue(PINNED));
          fileEditorManager.openFileImpl4(
              window, virtualFile, entry, isCurrentInTab, isCurrentInTab, pin, i);
          if (isCurrentInTab) {
            focusedFile = virtualFile;
          }
          if (document != null) {
            // This is just to make sure document reference is kept on stack till this point
            // so that document is available for folding state deserialization in HistoryEntry
            // constructor
            // and that document will be created only once during file opening
            document.putUserData(DUMMY_KEY, null);
          }
          updateProgress();
        } catch (InvalidDataException e) {
          if (ApplicationManager.getApplication().isUnitTestMode()) {
            LOG.error(e);
          }
        }
      }
      if (focusedFile != null) {
        getManager().addSelectionRecord(focusedFile, window);
      }
      return window.myPanel;
    }