/**
   * @param type
   * @param min
   * @param createDef
   * @param manager - must not be null if min is not null
   * @param scope - must not be null if min is not null
   */
  private GrTypeComboBox(
      @Nullable PsiType type,
      @Nullable PsiType min,
      boolean createDef,
      @Nullable PsiManager manager,
      @Nullable GlobalSearchScope scope) {
    LOG.assertTrue(min == null || manager != null);
    LOG.assertTrue(min == null || scope != null);

    if (type instanceof PsiDisjunctionType) type = ((PsiDisjunctionType) type).getLeastUpperBound();

    Map<String, PsiType> types = Collections.emptyMap();
    if (type != null) {
      types = getCompatibleTypeNames(type, min, manager, scope);
    }

    if (createDef || types.isEmpty()) {
      addItem(new PsiTypeItem(null));
    }

    for (String typeName : types.keySet()) {
      addItem(new PsiTypeItem(types.get(typeName)));
    }

    if (createDef && getItemCount() > 1) {
      setSelectedIndex(1);
    }
  }
 /**
  * Prepare branch descriptors for existing configuration
  *
  * @param target the target
  * @param roots the vcs root
  * @return the list of branch descriptors
  * @throws VcsException in case of error
  */
 private List<BranchDescriptor> prepareBranchDescriptors(
     BranchConfiguration target, List<VirtualFile> roots) throws VcsException {
   Map<String, String> map =
       target == null ? Collections.<String, String>emptyMap() : target.getReferences();
   List<BranchDescriptor> rc = new ArrayList<BranchDescriptor>();
   for (VirtualFile root : roots) {
     BranchDescriptor d = new BranchDescriptor();
     d.root = root;
     d.storedReference = map.remove(root.getPath());
     if (d.storedReference != null) {
       d.storedRoot = d.root.getPath();
     }
     d.currentReference = myConfig.describeRoot(root);
     if (d.storedReference != null && !myModify) {
       d.referenceToCheckout = d.storedReference;
     } else {
       d.referenceToCheckout = d.currentReference;
     }
     Branch.listAsStrings(myProject, root, false, true, d.existingBranches, null);
     Branch.listAsStrings(myProject, root, true, true, d.referencesToSelect, null);
     d.updateStatus();
     rc.add(d);
   }
   for (Map.Entry<String, String> m : map.entrySet()) {
     String root = m.getKey();
     String ref = m.getValue();
     BranchDescriptor d = new BranchDescriptor();
     d.storedReference = ref;
     d.storedRoot = root;
     d.referenceToCheckout = ref;
     d.updateStatus();
     rc.add(d);
   }
   return rc;
 }
Esempio n. 3
0
  @NotNull
  private Map<String, CachedValue<XmlNSDescriptor>> computeNsDescriptorMap() {
    Map<String, CachedValue<XmlNSDescriptor>> map = null;
    // XSD aware attributes processing

    final String noNamespaceDeclaration =
        getAttributeValue("noNamespaceSchemaLocation", XmlUtil.XML_SCHEMA_INSTANCE_URI);
    final String schemaLocationDeclaration =
        getAttributeValue("schemaLocation", XmlUtil.XML_SCHEMA_INSTANCE_URI);

    if (noNamespaceDeclaration != null) {
      map = initializeSchema(XmlUtil.EMPTY_URI, null, noNamespaceDeclaration, map);
    }
    if (schemaLocationDeclaration != null) {
      final StringTokenizer tokenizer = new StringTokenizer(schemaLocationDeclaration);
      while (tokenizer.hasMoreTokens()) {
        final String uri = tokenizer.nextToken();
        if (tokenizer.hasMoreTokens()) {
          map = initializeSchema(uri, null, tokenizer.nextToken(), map);
        }
      }
    }
    // namespace attributes processing (XSD declaration via ExternalResourceManager)

    if (hasNamespaceDeclarations()) {
      for (final XmlAttribute attribute : getAttributes()) {
        if (attribute.isNamespaceDeclaration()) {
          String ns = attribute.getValue();
          if (ns == null) ns = XmlUtil.EMPTY_URI;
          ns = getRealNs(ns);

          if (map == null || !map.containsKey(ns)) {
            map = initializeSchema(ns, getNSVersion(ns, this), getNsLocation(ns), map);
          }
        }
      }
    }
    return map == null ? Collections.<String, CachedValue<XmlNSDescriptor>>emptyMap() : map;
  }
Esempio n. 4
0
  public Map<String, ValidationResult.Option> askUser(
      final List<ValidationResult> validationResults) throws OperationCancelledException {
    if (validationResults.isEmpty()) return Collections.emptyMap();

    final Map<String, ValidationResult.Option> result =
        new HashMap<String, ValidationResult.Option>();
    try {
      SwingUtilities.invokeAndWait(
          new Runnable() {
            public void run() {
              final JDialog dialog = new JDialog(myFrame, TITLE, true);
              dialog.setLayout(new BorderLayout());
              dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);

              JPanel buttonsPanel = new JPanel();
              buttonsPanel.setBorder(BUTTONS_BORDER);
              buttonsPanel.setLayout(new BoxLayout(buttonsPanel, BoxLayout.X_AXIS));
              buttonsPanel.add(Box.createHorizontalGlue());
              JButton proceedButton = new JButton(PROCEED_BUTTON_TITLE);
              proceedButton.addActionListener(
                  new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                      dialog.setVisible(false);
                    }
                  });

              JButton cancelButton = new JButton(CANCEL_BUTTON_TITLE);
              cancelButton.addActionListener(
                  new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                      isCancelled.set(true);
                      myCancelButton.setEnabled(false);
                      dialog.setVisible(false);
                    }
                  });

              buttonsPanel.add(proceedButton);
              buttonsPanel.add(cancelButton);

              dialog.getRootPane().setDefaultButton(proceedButton);

              JTable table = new JTable();

              table.setCellSelectionEnabled(true);
              table.setDefaultEditor(ValidationResult.Option.class, new MyCellEditor());
              table.setDefaultRenderer(Object.class, new MyCellRenderer());
              MyTableModel model = new MyTableModel(validationResults);
              table.setModel(model);

              for (int i = 0; i < table.getColumnModel().getColumnCount(); i++) {
                TableColumn each = table.getColumnModel().getColumn(i);
                each.setPreferredWidth(
                    MyTableModel.getColumnWidth(i, new Dimension(600, 400).width));
              }

              String message =
                  "<html>There are some conflicts found in the installation.<br><br>"
                      + "Please select desired solutions from the "
                      + MyTableModel.COLUMNS[MyTableModel.OPTIONS_COLUMN_INDEX]
                      + " column and press "
                      + PROCEED_BUTTON_TITLE
                      + ".<br>"
                      + "If you do not want to proceed with the update, please press "
                      + CANCEL_BUTTON_TITLE
                      + ".</html>";

              JLabel label = new JLabel(message);
              label.setBorder(LABEL_BORDER);
              dialog.add(label, BorderLayout.NORTH);
              dialog.add(new JScrollPane(table), BorderLayout.CENTER);
              dialog.add(buttonsPanel, BorderLayout.SOUTH);

              dialog.getRootPane().setBorder(FRAME_BORDER);

              dialog.setSize(new Dimension(600, 400));
              dialog.setLocationRelativeTo(null);
              dialog.setVisible(true);

              result.putAll(model.getResult());
            }
          });
    } catch (InterruptedException e) {
      throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
      throw new RuntimeException(e);
    }
    checkCancelled();
    return result;
  }
/** @author Eugene.Kudelevsky */
public class CreateXmlResourceDialog extends DialogWrapper {
  private JPanel myPanel;
  private JTextField myNameField;
  private JComboBox myModuleCombo;
  private JBLabel myModuleLabel;
  private JPanel myDirectoriesPanel;
  private JBLabel myDirectoriesLabel;
  private JTextField myValueField;
  private JBLabel myValueLabel;
  private JBLabel myNameLabel;
  private JComboBox myFileNameCombo;

  private final Module myModule;
  private final ResourceType myResourceType;

  private Map<String, JCheckBox> myCheckBoxes = Collections.emptyMap();
  private String[] myDirNames = ArrayUtil.EMPTY_STRING_ARRAY;

  private final CheckBoxList myDirectoriesList;
  private VirtualFile myResourceDir;

  public CreateXmlResourceDialog(
      @NotNull Module module,
      @NotNull ResourceType resourceType,
      @Nullable String predefinedName,
      @Nullable String predefinedValue,
      boolean chooseName) {
    this(module, resourceType, predefinedName, predefinedValue, chooseName, null);
  }

  public CreateXmlResourceDialog(
      @NotNull Module module,
      @NotNull ResourceType resourceType,
      @Nullable String predefinedName,
      @Nullable String predefinedValue,
      boolean chooseName,
      @Nullable VirtualFile defaultFile) {
    super(module.getProject());
    myResourceType = resourceType;

    if (predefinedName != null && predefinedName.length() > 0) {
      if (!chooseName) {
        myNameLabel.setVisible(false);
        myNameField.setVisible(false);
      }
      myNameField.setText(predefinedName);
    }

    if (predefinedValue != null && predefinedValue.length() > 0) {
      myValueLabel.setVisible(false);
      myValueField.setVisible(false);
      myValueField.setText(predefinedValue);
    }
    final Set<Module> modulesSet = new HashSet<Module>();
    modulesSet.add(module);

    for (AndroidFacet depFacet : AndroidUtils.getAllAndroidDependencies(module, true)) {
      modulesSet.add(depFacet.getModule());
    }

    assert modulesSet.size() > 0;

    if (modulesSet.size() == 1) {
      myModule = module;
      myModuleLabel.setVisible(false);
      myModuleCombo.setVisible(false);
    } else {
      myModule = null;

      final Module[] modules = modulesSet.toArray(new Module[modulesSet.size()]);
      Arrays.sort(
          modules,
          new Comparator<Module>() {
            @Override
            public int compare(Module m1, Module m2) {
              return m1.getName().compareTo(m2.getName());
            }
          });

      myModuleCombo.setModel(new DefaultComboBoxModel(modules));
      myModuleCombo.setSelectedItem(module);
      myModuleCombo.setRenderer(new ModuleListCellRendererWrapper(myModuleCombo.getRenderer()));
    }

    if (defaultFile == null) {
      final String defaultFileName = AndroidResourceUtil.getDefaultResourceFileName(resourceType);

      if (defaultFileName != null) {
        myFileNameCombo.getEditor().setItem(defaultFileName);
      }
    }
    myDirectoriesList = new CheckBoxList();
    myDirectoriesLabel.setLabelFor(myDirectoriesList);
    final ToolbarDecorator decorator = ToolbarDecorator.createDecorator(myDirectoriesList);

    decorator.setEditAction(null);
    decorator.disableUpDownActions();

    decorator.setAddAction(
        new AnActionButtonRunnable() {
          @Override
          public void run(AnActionButton button) {
            doAddNewDirectory();
          }
        });

    decorator.setRemoveAction(
        new AnActionButtonRunnable() {
          @Override
          public void run(AnActionButton button) {
            doDeleteDirectory();
          }
        });

    final AnActionButton selectAll =
        new AnActionButton("Select All", null, PlatformIcons.SELECT_ALL_ICON) {
          @Override
          public void actionPerformed(AnActionEvent e) {
            doSelectAllDirs();
          }
        };
    decorator.addExtraAction(selectAll);

    final AnActionButton unselectAll =
        new AnActionButton("Unselect All", null, PlatformIcons.UNSELECT_ALL_ICON) {
          @Override
          public void actionPerformed(AnActionEvent e) {
            doUnselectAllDirs();
          }
        };
    decorator.addExtraAction(unselectAll);

    myDirectoriesPanel.add(decorator.createPanel());

    updateDirectories(true);

    myModuleCombo.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            updateDirectories(true);
          }
        });
    final JCheckBox valuesCheckBox = myCheckBoxes.get(SdkConstants.FD_RES_VALUES);
    if (valuesCheckBox != null) {
      valuesCheckBox.setSelected(true);
    }

    if (defaultFile != null) {
      resetFromFile(defaultFile, module.getProject());
    }
    init();
  }

  private void resetFromFile(@NotNull VirtualFile file, @NotNull Project project) {
    final Module moduleForFile = ModuleUtilCore.findModuleForFile(file, project);
    if (moduleForFile == null) {
      return;
    }

    final VirtualFile parent = file.getParent();
    if (parent == null) {
      return;
    }

    if (myModule == null) {
      final Object prev = myModuleCombo.getSelectedItem();
      myModuleCombo.setSelectedItem(moduleForFile);

      if (!moduleForFile.equals(myModuleCombo.getSelectedItem())) {
        myModuleCombo.setSelectedItem(prev);
        return;
      }
    } else if (!myModule.equals(moduleForFile)) {
      return;
    }

    final JCheckBox checkBox = myCheckBoxes.get(parent.getName());
    if (checkBox == null) {
      return;
    }

    for (JCheckBox checkBox1 : myCheckBoxes.values()) {
      checkBox1.setSelected(false);
    }
    checkBox.setSelected(true);
    myFileNameCombo.getEditor().setItem(file.getName());
  }

  private void doDeleteDirectory() {
    if (myResourceDir == null) {
      return;
    }

    final int selectedIndex = myDirectoriesList.getSelectedIndex();
    if (selectedIndex < 0) {
      return;
    }

    final String selectedDirName = myDirNames[selectedIndex];
    final VirtualFile selectedDir = myResourceDir.findChild(selectedDirName);
    if (selectedDir == null) {
      return;
    }

    final VirtualFileDeleteProvider provider = new VirtualFileDeleteProvider();
    provider.deleteElement(
        new DataContext() {
          @Override
          public Object getData(@NonNls String dataId) {
            if (PlatformDataKeys.VIRTUAL_FILE_ARRAY.getName().equals(dataId)) {
              return new VirtualFile[] {selectedDir};
            } else {
              return null;
            }
          }
        });
    updateDirectories(false);
  }

  private void doSelectAllDirs() {
    for (JCheckBox checkBox : myCheckBoxes.values()) {
      checkBox.setSelected(true);
    }
    myDirectoriesList.repaint();
  }

  private void doUnselectAllDirs() {
    for (JCheckBox checkBox : myCheckBoxes.values()) {
      checkBox.setSelected(false);
    }
    myDirectoriesList.repaint();
  }

  private void doAddNewDirectory() {
    if (myResourceDir == null) {
      return;
    }
    final Module module = getModule();
    if (module == null) {
      return;
    }
    final Project project = module.getProject();
    final PsiDirectory psiResDir = PsiManager.getInstance(project).findDirectory(myResourceDir);

    if (psiResDir != null) {
      final PsiElement[] createdElements =
          new CreateResourceDirectoryAction(ResourceFolderType.VALUES)
              .invokeDialog(project, psiResDir);

      if (createdElements.length > 0) {
        updateDirectories(false);
      }
    }
  }

  private void updateDirectories(boolean updateFileCombo) {
    final Module module = getModule();
    List<VirtualFile> valuesDirs = Collections.emptyList();

    if (module != null) {
      final AndroidFacet facet = AndroidFacet.getInstance(module);

      if (facet != null) {
        myResourceDir = AndroidRootUtil.getResourceDir(facet);

        if (myResourceDir != null) {
          valuesDirs =
              AndroidResourceUtil.getResourceSubdirs(
                  ResourceFolderType.VALUES.getName(), new VirtualFile[] {myResourceDir});
        }
      }
    }

    Collections.sort(
        valuesDirs,
        new Comparator<VirtualFile>() {
          @Override
          public int compare(VirtualFile f1, VirtualFile f2) {
            return f1.getName().compareTo(f2.getName());
          }
        });

    final Map<String, JCheckBox> oldCheckBoxes = myCheckBoxes;
    final int selectedIndex = myDirectoriesList.getSelectedIndex();
    final String selectedDirName = selectedIndex >= 0 ? myDirNames[selectedIndex] : null;

    final List<JCheckBox> checkBoxList = new ArrayList<JCheckBox>();
    myCheckBoxes = new HashMap<String, JCheckBox>();
    myDirNames = new String[valuesDirs.size()];

    int newSelectedIndex = -1;

    int i = 0;

    for (VirtualFile dir : valuesDirs) {
      final String dirName = dir.getName();
      final JCheckBox oldCheckBox = oldCheckBoxes.get(dirName);
      final boolean selected = oldCheckBox != null && oldCheckBox.isSelected();
      final JCheckBox checkBox = new JCheckBox(dirName, selected);
      checkBoxList.add(checkBox);
      myCheckBoxes.put(dirName, checkBox);
      myDirNames[i] = dirName;

      if (dirName.equals(selectedDirName)) {
        newSelectedIndex = i;
      }
      i++;
    }
    myDirectoriesList.setModel(new CollectionListModel<JCheckBox>(checkBoxList));

    if (newSelectedIndex >= 0) {
      myDirectoriesList.setSelectedIndex(newSelectedIndex);
    }

    if (checkBoxList.size() == 1) {
      checkBoxList.get(0).setSelected(true);
    }

    if (updateFileCombo) {
      final Object oldItem = myFileNameCombo.getEditor().getItem();
      final Set<String> fileNameSet = new HashSet<String>();

      for (VirtualFile valuesDir : valuesDirs) {
        for (VirtualFile file : valuesDir.getChildren()) {
          fileNameSet.add(file.getName());
        }
      }
      final List<String> fileNames = new ArrayList<String>(fileNameSet);
      Collections.sort(fileNames);
      myFileNameCombo.setModel(new DefaultComboBoxModel(fileNames.toArray()));
      myFileNameCombo.getEditor().setItem(oldItem);
    }
  }

  @Override
  protected ValidationInfo doValidate() {
    final String resourceName = getResourceName();
    final Module selectedModule = getModule();
    final List<String> directoryNames = getDirNames();
    final String fileName = getFileName();

    if (resourceName.length() == 0) {
      return new ValidationInfo("specify resource name", myNameField);
    } else if (!AndroidResourceUtil.isCorrectAndroidResourceName(resourceName)) {
      return new ValidationInfo(resourceName + " is not correct resource name", myNameField);
    } else if (fileName.length() == 0) {
      return new ValidationInfo("specify file name", myFileNameCombo);
    } else if (selectedModule == null) {
      return new ValidationInfo("specify module", myModuleCombo);
    } else if (directoryNames.size() == 0) {
      return new ValidationInfo("choose directories", myDirectoriesList);
    }

    final ValidationInfo info =
        checkIfResourceAlreadyExists(
            selectedModule, resourceName, myResourceType, directoryNames, fileName);
    if (info != null) {
      return info;
    }
    return null;
  }

  @Nullable
  public static ValidationInfo checkIfResourceAlreadyExists(
      @NotNull Module selectedModule,
      @NotNull String resourceName,
      @NotNull ResourceType resourceType,
      @NotNull List<String> dirNames,
      @NotNull String fileName) {
    if (resourceName.length() == 0 || dirNames.size() == 0 || fileName.length() == 0) {
      return null;
    }

    final AndroidFacet facet = AndroidFacet.getInstance(selectedModule);
    final VirtualFile resourceDir = facet != null ? AndroidRootUtil.getResourceDir(facet) : null;
    if (resourceDir == null) {
      return null;
    }

    for (String directoryName : dirNames) {
      final VirtualFile resourceSubdir = resourceDir.findChild(directoryName);
      if (resourceSubdir == null) {
        continue;
      }

      final VirtualFile resFile = resourceSubdir.findChild(fileName);
      if (resFile == null) {
        continue;
      }

      if (resFile.getFileType() != StdFileTypes.XML) {
        return new ValidationInfo(
            "File " + FileUtil.toSystemDependentName(resFile.getPath()) + " is not XML file");
      }

      final Resources resources =
          AndroidUtils.loadDomElement(selectedModule, resFile, Resources.class);
      if (resources == null) {
        return new ValidationInfo(
            AndroidBundle.message(
                "not.resource.file.error", FileUtil.toSystemDependentName(resFile.getPath())));
      }

      for (ResourceElement element :
          AndroidResourceUtil.getValueResourcesFromElement(resourceType.getName(), resources)) {
        if (resourceName.equals(element.getName().getValue())) {
          return new ValidationInfo(
              "resource '"
                  + resourceName
                  + "' already exists in "
                  + FileUtil.toSystemDependentName(resFile.getPath()));
        }
      }
    }
    return null;
  }

  @Override
  public JComponent getPreferredFocusedComponent() {
    if (myNameField.getText().length() == 0) {
      return myNameField;
    } else if (myValueField.isVisible()) {
      return myValueField;
    } else if (myModuleCombo.isVisible()) {
      return myModuleCombo;
    } else {
      return myFileNameCombo;
    }
  }

  @Override
  protected void doOKAction() {
    final String resourceName = getResourceName();
    final String fileName = getFileName();
    final List<String> dirNames = getDirNames();
    final Module module = getModule();

    if (resourceName.length() == 0) {
      Messages.showErrorDialog(
          myPanel, "Resource name is not specified", CommonBundle.getErrorTitle());
    } else if (!AndroidResourceUtil.isCorrectAndroidResourceName(resourceName)) {
      Messages.showErrorDialog(
          myPanel, resourceName + " is not correct resource name", CommonBundle.getErrorTitle());
    } else if (fileName.length() == 0) {
      Messages.showErrorDialog(myPanel, "File name is not specified", CommonBundle.getErrorTitle());
    } else if (dirNames.size() == 0) {
      Messages.showErrorDialog(
          myPanel, "Directories are not selected", CommonBundle.getErrorTitle());
    } else if (module == null) {
      Messages.showErrorDialog(myPanel, "Module is not specified", CommonBundle.getErrorTitle());
    } else {
      super.doOKAction();
    }
  }

  @Override
  protected String getDimensionServiceKey() {
    return "AndroidCreateXmlResourceDialog";
  }

  @NotNull
  public String getResourceName() {
    return myNameField.getText().trim();
  }

  @NotNull
  public List<String> getDirNames() {
    final List<String> selectedDirs = new ArrayList<String>();

    for (Map.Entry<String, JCheckBox> entry : myCheckBoxes.entrySet()) {
      if (entry.getValue().isSelected()) {
        selectedDirs.add(entry.getKey());
      }
    }
    return selectedDirs;
  }

  @NotNull
  public String getFileName() {
    return ((String) myFileNameCombo.getEditor().getItem()).trim();
  }

  @NotNull
  public String getName() {
    return myNameField.getText().trim();
  }

  @NotNull
  public String getValue() {
    return myValueField.getText().trim();
  }

  @Nullable
  public Module getModule() {
    return myModule != null ? myModule : (Module) myModuleCombo.getSelectedItem();
  }

  @Override
  protected JComponent createCenterPanel() {
    return myPanel;
  }
}