public void testAutoImportCaretLocation2() throws Throwable {
    boolean old = CodeInsightSettings.getInstance().ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY;
    try {
      CodeInsightSettings.getInstance().ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY = true;
      configureByText(StdFileTypes.JAVA, "class X { <caret>ArrayList c = new ArrayList(); }");
      ((UndoManagerImpl) UndoManager.getInstance(getProject())).flushCurrentCommandMerger();
      ((UndoManagerImpl) UndoManager.getInstance(getProject()))
          .clearUndoRedoQueueInTests(getFile().getVirtualFile());
      type(" ");
      backspace();

      assertEquals(2, highlightErrors().size());
      UIUtil.dispatchAllInvocationEvents();

      int offset = myEditor.getCaretModel().getOffset();
      PsiReference ref = myFile.findReferenceAt(offset);
      assertTrue(ref instanceof PsiJavaCodeReferenceElement);

      ImportClassFixBase.Result result =
          new ImportClassFix((PsiJavaCodeReferenceElement) ref).doFix(getEditor(), true, false);
      assertEquals(ImportClassFixBase.Result.CLASS_AUTO_IMPORTED, result);
      UIUtil.dispatchAllInvocationEvents();

      assertEmpty(highlightErrors());
    } finally {
      CodeInsightSettings.getInstance().ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY = old;
    }
  }
 /**
  * Show the dialog if needed
  *
  * @param project the project
  * @param root the vcs root
  * @return true if showing is not needed or operation completed successfully
  */
 public static boolean showIfNeeded(final Project project, final VirtualFile root) {
   final ArrayList<String> files = new ArrayList<String>();
   try {
     scanFiles(project, root, files);
     final AtomicBoolean rc = new AtomicBoolean(true);
     if (!files.isEmpty()) {
       UIUtil.invokeAndWaitIfNeeded(
           new Runnable() {
             public void run() {
               GitUpdateLocallyModifiedDialog d =
                   new GitUpdateLocallyModifiedDialog(project, root, files);
               d.show();
               rc.set(d.isOK());
             }
           });
       if (rc.get()) {
         if (!files.isEmpty()) {
           revertFiles(project, root, files);
         }
       }
     }
     return rc.get();
   } catch (final VcsException e) {
     UIUtil.invokeAndWaitIfNeeded(
         new Runnable() {
           public void run() {
             GitUIUtil.showOperationError(project, e, "Checking for locally modified files");
           }
         });
     return false;
   }
 }
 private JTextField createColorField(boolean hex) {
   final NumberDocument doc = new NumberDocument(hex);
   int lafFix = UIUtil.isUnderWindowsLookAndFeel() || UIUtil.isUnderDarcula() ? 1 : 0;
   UIManager.LookAndFeelInfo info = LafManager.getInstance().getCurrentLookAndFeel();
   if (info != null
       && (info.getName().startsWith("IDEA") || info.getName().equals("Windows Classic")))
     lafFix = 1;
   final JTextField field;
   if (SystemInfo.isMac && UIUtil.isUnderIntelliJLaF()) {
     field = new JTextField("");
     field.setDocument(doc);
     field.setPreferredSize(new Dimension(hex ? 60 : 40, 26));
   } else {
     field = new JTextField(doc, "", (hex ? 5 : 2) + lafFix);
     field.setSize(50, -1);
   }
   doc.setSource(field);
   field.getDocument().addDocumentListener(this);
   field.addFocusListener(
       new FocusAdapter() {
         @Override
         public void focusGained(final FocusEvent e) {
           field.selectAll();
         }
       });
   return field;
 }
  public Component getTreeCellRendererComponent(
      JTree tree,
      Object value,
      boolean selected,
      boolean expanded,
      boolean leaf,
      int row,
      boolean hasFocus) {
    setText(tree.convertValueToText(value, selected, expanded, leaf, row, hasFocus));
    setFont(UIUtil.getTreeFont());
    setIcon(null);

    if (WideSelectionTreeUI.isWideSelection(tree)) {
      setOpaque(false);
      myIsSelected = false;
      myHasFocus = false;
      setDoNotHighlight(selected && hasFocus);
      setForeground(
          selected && hasFocus ? UIUtil.getTreeSelectionForeground() : UIUtil.getTreeForeground());
    } else {
      setOpaque(true);
      myIsSelected = selected;
      myHasFocus = hasFocus;
      setDoNotHighlight(false);
    }

    myHasFocus = hasFocus;
    return this;
  }
  private static ImageIcon makeColorIconForColor(final Color color) {
    final int size = UIUtil.isRetina() ? 8 : 16;
    final int halfSize = size / 2;

    final Image img = UIUtil.createImage(size, size, BufferedImage.TYPE_INT_RGB);
    final Graphics gfx = img.getGraphics();
    try {
      if (color == null) {
        gfx.setColor(IdeaUtils.isDarkTheme() ? Color.darkGray : Color.white);
        gfx.fillRect(0, 0, size, size);
        gfx.setColor(IdeaUtils.isDarkTheme() ? Color.yellow : Color.black);
        gfx.drawRect(0, 0, size - 1, size - 1);
        gfx.drawLine(0, 0, size - 1, size - 1);
      } else if (color == DIFF_COLORS) {
        gfx.setColor(Color.red);
        gfx.fillRect(0, 0, halfSize, halfSize);
        gfx.setColor(Color.green);
        gfx.fillRect(halfSize, 0, halfSize, halfSize);
        gfx.setColor(Color.blue);
        gfx.fillRect(0, halfSize, halfSize, halfSize);
        gfx.setColor(Color.yellow);
        gfx.fillRect(halfSize, halfSize, halfSize, halfSize);
      } else {
        gfx.setColor(color);
        gfx.fillRect(0, 0, size, size);
        gfx.setColor(Color.black);
        gfx.drawRect(0, 0, size - 1, size - 1);
      }
    } finally {
      gfx.dispose();
    }
    return new ImageIcon(img);
  }
  public static List<Pair<String, Integer>> getFileNames(@NotNull String file) {
    final boolean dark = UIUtil.isUnderDarcula();
    final boolean retina = UIUtil.isRetina();
    if (retina || dark) {
      List<Pair<String, Integer>> answer = new ArrayList<Pair<String, Integer>>(4);

      final String name = FileUtil.getNameWithoutExtension(file);
      final String ext = FileUtilRt.getExtension(file);
      if (dark && retina) {
        answer.add(Pair.create(name + "@2x_dark." + ext, 2));
      }

      if (dark) {
        answer.add(Pair.create(name + "_dark." + ext, 1));
      }

      if (retina) {
        answer.add(Pair.create(name + "@2x." + ext, 2));
      }

      answer.add(Pair.create(file, 1));

      return answer;
    }

    return Collections.singletonList(Pair.create(file, 1));
  }
  private JTextField createField(final String text) {
    final JTextField field =
        new JTextField(text) {
          public Dimension getPreferredSize() {
            Dimension preferredSize = super.getPreferredSize();
            return new Dimension(preferredSize.width, myTextHeight);
          }
        };
    field.setBackground(UIUtil.getPanelBackground());
    field.setEditable(false);
    final Border lineBorder = BorderFactory.createLineBorder(UIUtil.getPanelBackground());
    final DottedBorder dotted = new DottedBorder(UIUtil.getActiveTextColor());
    field.setBorder(lineBorder);
    // field.setFocusable(false);
    field.setHorizontalAlignment(JTextField.RIGHT);
    field.setCaretPosition(0);
    field.addFocusListener(
        new FocusAdapter() {
          public void focusGained(FocusEvent e) {
            field.setBorder(dotted);
          }

          public void focusLost(FocusEvent e) {
            field.setBorder(lineBorder);
          }
        });
    return field;
  }
  /**
   * Gets (creates if necessary) disabled icon based on the passed one.
   *
   * @return <code>ImageIcon</code> constructed from disabled image of passed icon.
   */
  @Nullable
  public static Icon getDisabledIcon(Icon icon) {
    if (icon instanceof LazyIcon) icon = ((LazyIcon) icon).getOrComputeIcon();
    if (icon == null) return null;

    Icon disabledIcon = ourIcon2DisabledIcon.get(icon);
    if (disabledIcon == null) {
      if (!isGoodSize(icon)) {
        LOG.error(icon); // # 22481
        return EMPTY_ICON;
      }
      final int scale = UIUtil.isRetina() ? 2 : 1;
      @SuppressWarnings("UndesirableClassUsage")
      BufferedImage image =
          new BufferedImage(
              scale * icon.getIconWidth(),
              scale * icon.getIconHeight(),
              BufferedImage.TYPE_INT_ARGB);
      final Graphics2D graphics = image.createGraphics();

      graphics.setColor(UIUtil.TRANSPARENT_COLOR);
      graphics.fillRect(0, 0, icon.getIconWidth(), icon.getIconHeight());
      graphics.scale(scale, scale);
      icon.paintIcon(LabelHolder.ourFakeComponent, graphics, 0, 0);

      graphics.dispose();

      Image img = ImageUtil.filter(image, UIUtil.getGrayFilter());
      if (UIUtil.isRetina()) img = RetinaImage.createFrom(img, 2, ImageLoader.ourComponent);

      disabledIcon = new JBImageIcon(img);
      ourIcon2DisabledIcon.put(icon, disabledIcon);
    }
    return disabledIcon;
  }
 protected Color defaultActionForeground(boolean isSelected, Presentation presentation) {
   return isSelected
       ? UIUtil.getListSelectionForeground()
       : presentation.isEnabled() && presentation.isVisible()
           ? UIUtil.getListForeground()
           : UIUtil.getInactiveTextColor();
 }
  protected JComponent createCenterPanel() {
    final JPanel panel = new JPanel(new BorderLayout());

    final JPanel exprPanel = new JPanel(new BorderLayout());
    exprPanel.add(
        new JLabel(DebuggerBundle.message("label.evaluate.dialog.expression")), BorderLayout.WEST);
    exprPanel.add(getExpressionCombo(), BorderLayout.CENTER);
    final JLabel help =
        new JLabel(
            "Press Enter to Evaluate or Control+Enter to evaluate and add to the Watches",
            SwingConstants.RIGHT);
    help.setBorder(IdeBorderFactory.createEmptyBorder(2, 0, 6, 0));
    UIUtil.applyStyle(UIUtil.ComponentStyle.MINI, help);
    help.setForeground(UIUtil.getInactiveTextColor());
    exprPanel.add(help, BorderLayout.SOUTH);

    final JPanel resultPanel = new JPanel(new BorderLayout());
    // resultPanel.add(new JLabel(DebuggerBundle.message("label.evaluate.dialog.result")),
    // BorderLayout.NORTH);
    resultPanel.add(getEvaluationPanel(), BorderLayout.CENTER);

    panel.add(exprPanel, BorderLayout.NORTH);
    panel.add(resultPanel, BorderLayout.CENTER);

    return panel;
  }
  public void testDocumentGced() throws Exception {
    VirtualFile vFile = createFile();
    PsiDocumentManagerImpl documentManager = getPsiDocumentManager();
    long id = System.identityHashCode(documentManager.getDocument(getPsiManager().findFile(vFile)));

    documentManager.commitAllDocuments();
    UIUtil.dispatchAllInvocationEvents();
    UIUtil.dispatchAllInvocationEvents();
    assertEmpty(documentManager.getUncommittedDocuments());

    LeakHunter.checkLeak(documentManager, DocumentImpl.class);
    LeakHunter.checkLeak(
        documentManager,
        PsiFileImpl.class,
        new Processor<PsiFileImpl>() {
          @Override
          public boolean process(PsiFileImpl psiFile) {
            return psiFile.getViewProvider().getVirtualFile().getFileSystem()
                instanceof LocalFileSystem;
          }
        });
    // Class.forName("com.intellij.util.ProfilingUtil").getDeclaredMethod("forceCaptureMemorySnapshot").invoke(null);

    Reference<Document> reference = vFile.getUserData(FileDocumentManagerImpl.DOCUMENT_KEY);
    assertNotNull(reference);
    for (int i = 0; i < 1000; i++) {
      UIUtil.dispatchAllInvocationEvents();
      if (reference.get() == null) break;
      System.gc();
    }
    assertNull(documentManager.getCachedDocument(getPsiManager().findFile(vFile)));

    Document newDoc = documentManager.getDocument(getPsiManager().findFile(vFile));
    assertTrue(id != System.identityHashCode(newDoc));
  }
Example #12
0
  @NotNull
  public static Icon colorize(@NotNull final Icon source, @NotNull Color color, boolean keepGray) {
    float[] base = Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), null);

    final BufferedImage image =
        UIUtil.createImage(source.getIconWidth(), source.getIconHeight(), Transparency.TRANSLUCENT);
    final Graphics2D g = image.createGraphics();
    source.paintIcon(null, g, 0, 0);
    g.dispose();

    final BufferedImage img =
        UIUtil.createImage(source.getIconWidth(), source.getIconHeight(), Transparency.TRANSLUCENT);
    int[] rgba = new int[4];
    float[] hsb = new float[3];
    for (int y = 0; y < image.getRaster().getHeight(); y++) {
      for (int x = 0; x < image.getRaster().getWidth(); x++) {
        image.getRaster().getPixel(x, y, rgba);
        if (rgba[3] != 0) {
          Color.RGBtoHSB(rgba[0], rgba[1], rgba[2], hsb);
          int rgb = Color.HSBtoRGB(base[0], base[1] * (keepGray ? hsb[1] : 1f), base[2] * hsb[2]);
          img.getRaster()
              .setPixel(x, y, new int[] {rgb >> 16 & 0xff, rgb >> 8 & 0xff, rgb & 0xff, rgba[3]});
        }
      }
    }

    return createImageIcon(img);
  }
  /**
   * Updates LAF of all windows. The method also updates font of components as it's configured in
   * <code>UISettings</code>.
   */
  @Override
  public void updateUI() {
    final UIDefaults uiDefaults = UIManager.getLookAndFeelDefaults();

    fixPopupWeight();

    fixGtkPopupStyle();

    fixTreeWideSelection(uiDefaults);

    fixMenuIssues(uiDefaults);

    if (UIUtil.isUnderAquaLookAndFeel()) {
      uiDefaults.put("Panel.opaque", Boolean.TRUE);
    } else if (UIUtil.isWinLafOnVista()) {
      uiDefaults.put("ComboBox.border", null);
    }

    initInputMapDefaults(uiDefaults);

    uiDefaults.put("Button.defaultButtonFollowsFocus", Boolean.FALSE);

    patchFileChooserStrings(uiDefaults);

    patchLafFonts(uiDefaults);

    patchOptionPaneIcons(uiDefaults);

    fixSeparatorColor(uiDefaults);

    for (Frame frame : Frame.getFrames()) {
      updateUI(frame);
    }
    fireLookAndFeelChanged();
  }
 @NotNull
 public static JEditorPane createTipBrowser() {
   JEditorPane browser = new JEditorPane();
   browser.setEditable(false);
   browser.setBackground(UIUtil.getTextFieldBackground());
   browser.addHyperlinkListener(
       new HyperlinkListener() {
         public void hyperlinkUpdate(HyperlinkEvent e) {
           if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
             BrowserUtil.browse(e.getURL());
           }
         }
       });
   URL resource =
       ResourceUtil.getResource(
           TipUIUtil.class,
           "/tips/css/",
           UIUtil.isUnderDarcula() ? "tips_darcula.css" : "tips.css");
   final StyleSheet styleSheet = UIUtil.loadStyleSheet(resource);
   HTMLEditorKit kit =
       new HTMLEditorKit() {
         @Override
         public StyleSheet getStyleSheet() {
           return styleSheet != null ? styleSheet : super.getStyleSheet();
         }
       };
   browser.setEditorKit(kit);
   return browser;
 }
  private JComponent createSettingsPanel() {
    JPanel result = new JPanel(new FlowLayout(FlowLayout.RIGHT, 3, 0));
    result.add(new JLabel(ApplicationBundle.message("label.font.size")));
    myFontSizeSlider = new JSlider(JSlider.HORIZONTAL, 0, FontSize.values().length - 1, 3);
    myFontSizeSlider.setMinorTickSpacing(1);
    myFontSizeSlider.setPaintTicks(true);
    myFontSizeSlider.setPaintTrack(true);
    myFontSizeSlider.setSnapToTicks(true);
    UIUtil.setSliderIsFilled(myFontSizeSlider, true);
    result.add(myFontSizeSlider);
    result.setBorder(BorderFactory.createLineBorder(UIUtil.getBorderColor(), 1));

    myFontSizeSlider.addChangeListener(
        new ChangeListener() {
          @Override
          public void stateChanged(ChangeEvent e) {
            if (myIgnoreFontSizeSliderChange) {
              return;
            }
            EditorColorsManager colorsManager = EditorColorsManager.getInstance();
            EditorColorsScheme scheme = colorsManager.getGlobalScheme();
            scheme.setQuickDocFontSize(FontSize.values()[myFontSizeSlider.getValue()]);
            applyFontSize();
          }
        });

    String tooltipText = ApplicationBundle.message("quickdoc.tooltip.font.size.by.wheel");
    result.setToolTipText(tooltipText);
    myFontSizeSlider.setToolTipText(tooltipText);
    result.setVisible(false);
    result.setOpaque(true);
    myFontSizeSlider.setOpaque(true);
    return result;
  }
        @NotNull
        @Override
        public Component getTreeCellRendererComponent(
            @NotNull JTree tree,
            Object value,
            boolean selected,
            boolean expanded,
            boolean leaf,
            int row,
            boolean hasFocus) {
          if (value instanceof MyTreeNode) {
            MyTreeNode node = (MyTreeNode) value;
            myLabel.setText(getRenamedTitle(node.getKey().field.getName(), node.getText()));
            myLabel.setFont(
                myLabel
                    .getFont()
                    .deriveFont(node.getKey().groupName == null ? Font.BOLD : Font.PLAIN));
            myLabel.setEnabled(node.isEnabled());
          } else {
            myLabel.setText(getRenamedTitle(value.toString(), value.toString()));
            myLabel.setFont(myLabel.getFont().deriveFont(Font.BOLD));
            myLabel.setEnabled(true);
          }

          Color foreground =
              selected ? UIUtil.getTableSelectionForeground() : UIUtil.getTableForeground();
          myLabel.setForeground(foreground);

          return myLabel;
        }
  private JPanel createFieldPanel() {
    myDoNotReplaceRadioButton =
        new JBRadioButton(UIUtil.replaceMnemonicAmpersand("Do n&ot replace"));
    myReplaceFieldsInaccessibleInRadioButton =
        new JBRadioButton(
            UIUtil.replaceMnemonicAmpersand("Replace fields &inaccessible in usage context"));
    myReplaceAllFieldsRadioButton =
        new JBRadioButton(UIUtil.replaceMnemonicAmpersand("&Replace all fields"));

    myDoNotReplaceRadioButton.setFocusable(false);
    myReplaceFieldsInaccessibleInRadioButton.setFocusable(false);
    myReplaceAllFieldsRadioButton.setFocusable(false);

    final ButtonGroup group = new ButtonGroup();
    group.add(myDoNotReplaceRadioButton);
    group.add(myReplaceFieldsInaccessibleInRadioButton);
    group.add(myReplaceAllFieldsRadioButton);

    final JPanel panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
    panel.add(myDoNotReplaceRadioButton);
    panel.add(myReplaceFieldsInaccessibleInRadioButton);
    panel.add(myReplaceAllFieldsRadioButton);

    panel.setBorder(
        IdeBorderFactory.createTitledBorder(
            "Replace fields used in expression with their getters", true));
    return panel;
  }
    public void customizeCellRenderer(
        JTree tree,
        Object value,
        boolean selected,
        boolean expanded,
        boolean leaf,
        int row,
        boolean hasFocus) {
      if (value instanceof PackageDependenciesNode) {
        PackageDependenciesNode node = (PackageDependenciesNode) value;
        setIcon(node.getIcon());

        setForeground(
            selected && hasFocus
                ? UIUtil.getTreeSelectionForeground()
                : UIUtil.getTreeForeground());
        if (!(selected && hasFocus)
            && node.hasMarked()
            && !DependencyUISettings.getInstance().UI_FILTER_LEGALS) {
          setForeground(node.hasUnmarked() ? PARTIAL_INCLUDED : WHOLE_INCLUDED);
        }
        append(node.toString(), SimpleTextAttributes.REGULAR_ATTRIBUTES);
        final String locationString = node.getComment();
        if (!StringUtil.isEmpty(locationString)) {
          append(" (" + locationString + ")", SimpleTextAttributes.GRAY_ATTRIBUTES);
        }
      }
    }
  private JPanel createNamePanel() {
    final GridBag c =
        new GridBag().setDefaultAnchor(GridBagConstraints.WEST).setDefaultInsets(1, 1, 1, 1);
    final JPanel namePanel = new JPanel(new GridBagLayout());

    final JLabel typeLabel = new JLabel(UIUtil.replaceMnemonicAmpersand("&Type:"));
    c.nextLine().next().weightx(0).fillCellNone();
    namePanel.add(typeLabel, c);

    myTypeComboBox =
        createTypeComboBox(
            GroovyIntroduceParameterUtil.findVar(myInfo),
            GroovyIntroduceParameterUtil.findExpr(myInfo),
            findStringPart());
    c.next().weightx(1).fillCellHorizontally();
    namePanel.add(myTypeComboBox, c);
    typeLabel.setLabelFor(myTypeComboBox);

    final JLabel nameLabel = new JLabel(UIUtil.replaceMnemonicAmpersand("&Name:"));
    c.nextLine().next().weightx(0).fillCellNone();
    namePanel.add(nameLabel, c);

    myNameSuggestionsField = createNameField(GroovyIntroduceParameterUtil.findVar(myInfo));
    c.next().weightx(1).fillCellHorizontally();
    namePanel.add(myNameSuggestionsField, c);
    nameLabel.setLabelFor(myNameSuggestionsField);

    GrTypeComboBox.registerUpDownHint(myNameSuggestionsField, myTypeComboBox);

    return namePanel;
  }
 public ActionButtonWithText(
     final AnAction action,
     final Presentation presentation,
     final String place,
     final Dimension minimumSize) {
   super(action, presentation, place, minimumSize);
   setFont(UIUtil.getLabelFont());
   setForeground(UIUtil.getLabelForeground());
   myPresentation.addPropertyChangeListener(
       new PropertyChangeListener() {
         @Override
         public void propertyChange(PropertyChangeEvent evt) {
           if (evt.getPropertyName().equals(Presentation.PROP_MNEMONIC_KEY)) {
             Integer oldValue =
                 evt.getOldValue() instanceof Integer ? (Integer) evt.getOldValue() : 0;
             Integer newValue =
                 evt.getNewValue() instanceof Integer ? (Integer) evt.getNewValue() : 0;
             updateMnemonic(oldValue, newValue);
           }
         }
       });
   getActionMap()
       .put(
           "doClick",
           new AbstractAction() {
             @Override
             public void actionPerformed(ActionEvent e) {
               click();
             }
           });
   updateMnemonic(0, myPresentation.getMnemonic());
 }
 @Nullable
 @Override
 public JComponent createComponent() {
   myEnabled = new JBCheckBox("Enable EditorConfig support");
   final JPanel result = new JPanel();
   result.setLayout(new BoxLayout(result, BoxLayout.LINE_AXIS));
   final JPanel panel = new JPanel(new VerticalFlowLayout());
   result.setBorder(IdeBorderFactory.createTitledBorder("EditorConfig", false));
   panel.add(myEnabled);
   final JLabel warning = new JLabel("EditorConfig may override the IDE code style settings");
   warning.setFont(UIUtil.getLabelFont(UIUtil.FontSize.SMALL));
   warning.setBorder(IdeBorderFactory.createEmptyBorder(0, 20, 0, 0));
   panel.add(warning);
   panel.setAlignmentY(Component.TOP_ALIGNMENT);
   result.add(panel);
   final JButton export = new JButton("Export");
   export.addActionListener(
       (event) -> {
         final Component parent = UIUtil.findUltimateParent(result);
         if (parent instanceof IdeFrame) {
           Utils.export(((IdeFrame) parent).getProject());
         }
       });
   export.setAlignmentY(Component.TOP_ALIGNMENT);
   result.add(export);
   return result;
 }
    @Override
    protected void customizeCellRenderer(
        JList list, Object value, int index, boolean selected, boolean hasFocus) {
      setIcon(myListEntryIcon);
      if (myUseIdeaEditor) {
        int max = list.getModel().getSize();
        String indexString = String.valueOf(index + 1);
        int count = String.valueOf(max).length() - indexString.length();
        char[] spaces = new char[count];
        Arrays.fill(spaces, ' ');
        String prefix = indexString + new String(spaces) + "  ";
        append(prefix, SimpleTextAttributes.GRAYED_ATTRIBUTES);
      } else if (UIUtil.isUnderGTKLookAndFeel()) {
        // Fix GTK background
        Color background =
            selected ? UIUtil.getListSelectionBackground() : UIUtil.getListBackground();
        UIUtil.changeBackGround(this, background);
      }
      String text = ((Item) value).shortText;

      FontMetrics metrics = list.getFontMetrics(list.getFont());
      int charWidth = metrics.charWidth('m');
      int maxLength = list.getParent().getParent().getWidth() * 3 / charWidth / 2;
      text = StringUtil.first(text, maxLength, true); // do not paint long strings
      append(text, SimpleTextAttributes.REGULAR_ATTRIBUTES);
    }
 private static void drawLine(Graphics2D g, float x1, int y1, float x2, int y2, boolean rounded) {
   if (rounded) {
     UIUtil.drawLinePickedOut(g, (int) x1, y1, (int) x2, y2);
   } else {
     UIUtil.drawLine(g, (int) x1, y1, (int) x2, y2);
   }
 }
 private void updateComponents() {
   boolean archetypesEnabled = myUseArchetypeCheckBox.isSelected();
   myAddArchetypeButton.setEnabled(archetypesEnabled);
   myArchetypesTree.setEnabled(archetypesEnabled);
   myArchetypesTree.setBackground(
       archetypesEnabled ? UIUtil.getListBackground() : UIUtil.getPanelBackground());
 }
  private List<String> runCompiler(final Consumer<ErrorReportingCallback> runnable) {
    final Semaphore semaphore = new Semaphore();
    semaphore.down();
    final ErrorReportingCallback callback = new ErrorReportingCallback(semaphore);
    UIUtil.invokeAndWaitIfNeeded(
        new Runnable() {
          @Override
          public void run() {
            try {
              if (useJps()) {
                getProject().save();
                CompilerTestUtil.saveSdkTable();
                File ioFile = VfsUtil.virtualToIoFile(myModule.getModuleFile());
                if (!ioFile.exists()) {
                  getProject().save();
                  assert ioFile.exists() : "File does not exist: " + ioFile.getPath();
                }
              }
              runnable.consume(callback);
            } catch (Exception e) {
              throw new RuntimeException(e);
            }
          }
        });

    // tests run in awt
    while (!semaphore.waitFor(100)) {
      if (SwingUtilities.isEventDispatchThread()) {
        UIUtil.dispatchAllInvocationEvents();
      }
    }
    callback.throwException();
    return callback.getMessages();
  }
  private static void patchGtkDefaults(UIDefaults defaults) {
    if (!UIUtil.isUnderGTKLookAndFeel()) return;

    Map<String, Icon> map =
        ContainerUtil.newHashMap(
            Arrays.asList(
                "OptionPane.errorIcon",
                "OptionPane.informationIcon",
                "OptionPane.warningIcon",
                "OptionPane.questionIcon"),
            Arrays.asList(
                AllIcons.General.ErrorDialog,
                AllIcons.General.InformationDialog,
                AllIcons.General.WarningDialog,
                AllIcons.General.QuestionDialog));
    // GTK+ L&F keeps icons hidden in style
    SynthStyle style = SynthLookAndFeel.getStyle(new JOptionPane(""), Region.DESKTOP_ICON);
    for (String key : map.keySet()) {
      if (defaults.get(key) != null) continue;

      Object icon = style == null ? null : style.get(null, key);
      defaults.put(key, icon instanceof Icon ? icon : map.get(key));
    }

    Color fg = defaults.getColor("Label.foreground");
    Color bg = defaults.getColor("Label.background");
    if (fg != null && bg != null) {
      defaults.put("Label.disabledForeground", UIUtil.mix(fg, bg, 0.5));
    }
  }
  private void paintBackgroundAndFoldingLine(Graphics g, Rectangle clipBounds) {
    Graphics2D g2d = (Graphics2D) g;
    g.setColor(getBackground());
    g.fillRect(
        clipBounds.x,
        clipBounds.y,
        Math.min(clipBounds.width, myFoldingLineX - clipBounds.x),
        clipBounds.height);
    g.setColor(getEditorComponent().getBackground());
    g.fillRect(
        Math.max(clipBounds.x, myFoldingLineX),
        clipBounds.y,
        clipBounds.width - Math.max(0, myFoldingLineX - clipBounds.x),
        clipBounds.height);

    // same as in EditorComponent.paint() method
    EditorCell deepestCell = myEditorComponent.getDeepestSelectedCell();
    if (deepestCell instanceof EditorCell_Label) {
      int selectedCellY = deepestCell.getY();
      int selectedCellHeight =
          deepestCell.getHeight() - deepestCell.getTopInset() - deepestCell.getBottomInset();
      if (g.hitClip(clipBounds.x, selectedCellY, clipBounds.width, selectedCellHeight)) {
        g.setColor(EditorSettings.getInstance().getCaretRowColor());
        g.fillRect(clipBounds.x, selectedCellY, clipBounds.width, selectedCellHeight);
        // Drawing folding line
        UIUtil.drawVDottedLine(
            g2d,
            myFoldingLineX,
            clipBounds.y,
            selectedCellY,
            getBackground(),
            EditorSettings.getInstance().getLeftHighlighterTearLineColor());
        UIUtil.drawVDottedLine(
            g2d,
            myFoldingLineX,
            selectedCellY,
            selectedCellY + selectedCellHeight,
            EditorSettings.getInstance().getCaretRowColor(),
            EditorSettings.getInstance().getLeftHighlighterTearLineColor());
        UIUtil.drawVDottedLine(
            g2d,
            myFoldingLineX,
            selectedCellY + selectedCellHeight,
            clipBounds.y + clipBounds.height,
            getBackground(),
            EditorSettings.getInstance().getLeftHighlighterTearLineColor());
        return;
      }
    }
    // Drawing folding line
    // COLORS: Remove hardcoded color
    UIUtil.drawVDottedLine(
        g2d,
        myFoldingLineX,
        clipBounds.y,
        clipBounds.y + clipBounds.height,
        getBackground(),
        Color.gray);
  }
Example #28
0
 public void setEnabled(boolean enabled) {
   super.setEnabled(enabled);
   if (myToggleHistoryLabel != null) {
     final Color bg = enabled ? UIUtil.getTextFieldBackground() : UIUtil.getPanelBackground();
     myToggleHistoryLabel.setBackground(bg);
     myClearFieldLabel.setBackground(bg);
   }
 }
 @Override
 protected void paintComponent(@NotNull Graphics g) {
   super.paintComponent(g);
   if (UIUtil.isUnderDarcula()) {
     g.setColor(UIUtil.getControlColor().brighter());
     g.fillRect(0, 0, getWidth(), getHeight());
   }
 }
 private void paintTextEffect(
     Graphics2D g, float xFrom, float xTo, int y, Color effectColor, EffectType effectType) {
   int xStart = (int) xFrom;
   int xEnd = (int) xTo;
   g.setColor(effectColor);
   if (effectType == EffectType.LINE_UNDERSCORE) {
     UIUtil.drawLine(g, xStart, y + 1, xEnd, y + 1);
   } else if (effectType == EffectType.BOLD_LINE_UNDERSCORE) {
     int height = JBUI.scale(Registry.intValue("editor.bold.underline.height", 2));
     g.fillRect(xStart, y, xEnd - xStart, height);
   } else if (effectType == EffectType.STRIKEOUT) {
     int y1 = y - myView.getCharHeight() / 2;
     UIUtil.drawLine(g, xStart, y1, xEnd, y1);
   } else if (effectType == EffectType.WAVE_UNDERSCORE) {
     UIUtil.drawWave(g, new Rectangle(xStart, y + 1, xEnd - xStart, myView.getDescent() - 1));
   } else if (effectType == EffectType.BOLD_DOTTED_LINE) {
     UIUtil.drawBoldDottedLine(
         g,
         xStart,
         xEnd,
         SystemInfo.isMac ? y : y + 1,
         myEditor.getBackgroundColor(),
         g.getColor(),
         false);
   }
 }