@Override
  protected Object run(final Presentation context) {
    final FormComponentPresentation p = (FormComponentPresentation) context;
    final SapphirePart part = (SapphirePart) getPart();

    final Set<Property> properties = new LinkedHashSet<Property>();
    collectProperties(part, properties);

    for (Iterator<Property> itr = properties.iterator(); itr.hasNext(); ) {
      if (itr.next().empty()) {
        itr.remove();
      }
    }

    if (properties.isEmpty()) {
      MessageDialog.openInformation(p.shell(), dialogTitle.text(), nothingToDoMessage.text());
    } else {
      final Set<Property> selectedProperties = PromptDialog.open(p.shell(), properties);

      for (Property property : selectedProperties) {
        property.clear();
      }
    }

    return null;
  }
  @Override
  protected String browse(final Presentation context) {
    final Property property = property();

    final Shell parent = ((FormComponentPresentation) context).shell();
    final Rectangle bounds = parent.getBounds();

    // There is no means to compute the size of the color dialog. In the following
    // computations, measurements of the dialog on Windows 7 are used. Will need to
    // generalize in the future.

    final int x = bounds.x + bounds.width / 2 - 120;
    final int y = bounds.y + bounds.height / 2 - 170;

    final Shell shell = new Shell(parent);

    try {
      shell.setBounds(x, y, 0, 0);

      final ColorDialog dialog = new ColorDialog(shell);

      dialog.setText(property.definition().getLabel(false, CapitalizationType.TITLE_STYLE, false));
      dialog.setRGB(convert((Color) ((Value<?>) property).content()));

      final RGB pickedColor = dialog.open();

      if (pickedColor != null) {
        return convert(pickedColor).toString();
      }
    } finally {
      shell.dispose();
    }

    return null;
  }
  @Override
  public void init(final Property property) {
    super.init(property);

    this.possibleTypesService = property.service(PossibleTypesService.class);

    this.possibleTypesServiceListener =
        new Listener() {
          @Override
          public void handle(final Event event) {
            try {
              initBindingMetadata();
            } catch (Exception e) {
              final String msg =
                  failure.format(
                      property.element().type().getSimpleName(), property.name(), e.getMessage());
              Sapphire.service(LoggingService.class).logError(msg);
            }
          }
        };

    this.possibleTypesService.attach(this.possibleTypesServiceListener);

    try {
      initBindingMetadata();
    } catch (Exception e) {
      final String msg =
          failure.format(
              property.element().type().getSimpleName(), property.name(), e.getMessage());
      throw new RuntimeException(msg, e);
    }
  }
  @Override
  public void init(final SapphireAction action, final ActionHandlerDef def) {
    super.init(action, def);

    setId(ID);
    setLabel(Resources.label);
    addImage(IMG_FILE);

    final Property property = property();

    this.type = null;

    final String paramType = def.getParam(PARAM_TYPE);

    if (paramType != null) {
      if (paramType.equalsIgnoreCase("file")) {
        this.type = FileSystemResourceType.FILE;
      } else if (paramType.equalsIgnoreCase("folder")) {
        this.type = FileSystemResourceType.FOLDER;
      }
    } else {
      final ValidFileSystemResourceType validFileSystemResourceTypeAnnotation =
          property.definition().getAnnotation(ValidFileSystemResourceType.class);

      if (validFileSystemResourceTypeAnnotation != null) {
        this.type = validFileSystemResourceTypeAnnotation.value();
      }
    }

    final String staticFileExtensions = def.getParam(PARAM_EXTENSIONS);

    if (staticFileExtensions == null) {
      this.fileExtensionService = property.service(FileExtensionsService.class);

      if (this.fileExtensionService == null) {
        this.staticFileExtensionsList = Collections.emptyList();
      }
    } else {
      this.staticFileExtensionsList = new ArrayList<String>();

      for (String extension : staticFileExtensions.split(",")) {
        extension = extension.trim();

        if (extension.length() > 0) {
          this.staticFileExtensionsList.add(extension);
        }
      }
    }

    final String paramLeadingSlash = def.getParam(PARAM_LEADING_SLASH);

    if (paramLeadingSlash != null) {
      this.includeLeadingSlash = Boolean.parseBoolean(paramLeadingSlash);
    } else {
      this.includeLeadingSlash = false;
    }
  }
    @Override
    protected boolean evaluate(final PropertyEditorPart part) {
      final Property property = part.property();

      if (property instanceof Value && property.definition().isOfType(JavaTypeName.class)) {
        final Reference referenceAnnotation = property.definition().getAnnotation(Reference.class);

        return (referenceAnnotation != null
            && referenceAnnotation.target() == JavaType.class
            && property.element().adapt(IJavaProject.class) != null);
      }

      return false;
    }
  /*
   * (non-Javadoc)
   * @see org.eclipse.sapphire.modeling.PropertyBinding#init(org.eclipse.sapphire.modeling.Element,
   * org.eclipse.sapphire.modeling.Property, java.lang.String[])
   */
  @Override
  public void init(Property property) {
    super.init(property);

    this.params = property.definition().getAnnotation(CustomXmlValueBinding.class).params();
    this.path = new XmlPath(params[0], resource().getXmlNamespaceResolver());
  }
  @Override
  protected void initVersionCompatibilityService() {
    final Property parent = context(Element.class).parent();

    this.parentVersionCompatibilityService =
        parent.service(MasterVersionCompatibilityService.class);

    this.parentVersionCompatibilityServiceListener =
        new Listener() {
          @Override
          public void handle(final Event event) {
            refresh();
          }
        };

    this.parentVersionCompatibilityService.attach(this.parentVersionCompatibilityServiceListener);
  }
  @Override
  protected void initValidationService() {
    final Property property = context(Property.class);

    this.resourceMustExist = property.definition().hasAnnotation(MustExist.class);

    final ValidFileSystemResourceType validResourceTypeAnnotation =
        property.definition().getAnnotation(ValidFileSystemResourceType.class);
    this.validResourceType =
        (validResourceTypeAnnotation != null ? validResourceTypeAnnotation.value() : null);

    this.fileExtensionsService = property.service(FileExtensionsService.class);

    if (this.fileExtensionsService != null) {
      this.fileExtensionsService.attach(
          new Listener() {
            @Override
            public void handle(final Event event) {
              refresh();
            }
          });
    }
  }
Example #9
0
  @Override
  protected PropertyBinding createBinding(final Property property) {
    final PropertyDef pdef = property.definition();

    if (pdef == IAttendee.PROP_NAME) {
      return new ValuePropertyBinding() {
        @Override
        public String read() {
          return getBase().getName().text(false);
        }

        @Override
        public void write(final String value) {
          getBase().setName(value);
        }
      };
    } else if (pdef == IAttendee.PROP_TYPE) {
      return new ValuePropertyBinding() {
        @Override
        public String read() {
          return getBase().getType().text(false);
        }

        @Override
        public void write(final String value) {
          getBase().setType(value);
        }
      };
    } else if (pdef == IAttendee.PROP_E_MAIL) {
      return new ValuePropertyBinding() {
        @Override
        public String read() {
          final Contact c = findContactRecord(false);
          return (c != null ? c.getEMail().text() : null);
        }

        @Override
        public void write(final String value) {
          final Contact c = findContactRecord(value != null);

          if (c != null) {
            c.setEMail(value);
          }
        }
      };
    } else if (pdef == IAttendee.PROP_IN_CONTACT_REPOSITORY) {
      return new ValuePropertyBinding() {
        @Override
        public String read() {
          return (findContactRecord(false) != null ? Boolean.TRUE.toString() : null);
        }

        @Override
        public void write(final String value) {
          throw new UnsupportedOperationException();
        }
      };
    }

    return null;
  }
  @Override
  protected String browse(final SapphireRenderingContext context) {
    final Property property = property();
    final List<Path> roots = getBasePaths();
    String selectedAbsolutePath = null;

    final List<String> extensions;

    if (this.fileExtensionService == null) {
      extensions = this.staticFileExtensionsList;
    } else {
      extensions = this.fileExtensionService.extensions();
    }

    if (enclosed()) {
      final List<IContainer> baseContainers = new ArrayList<IContainer>();

      for (Path path : roots) {
        final IContainer baseContainer = getWorkspaceContainer(path.toFile());

        if (baseContainer != null) {
          baseContainers.add(baseContainer);
        } else {
          break;
        }
      }

      final ITreeContentProvider contentProvider;
      final ILabelProvider labelProvider;
      final ViewerComparator viewerComparator;
      final Object input;

      if (roots.size() == baseContainers.size()) {
        // All paths are in the Eclipse Workspace. Use the available content and label
        // providers.

        contentProvider = new WorkspaceContentProvider(baseContainers);
        labelProvider = new WorkbenchLabelProvider();
        viewerComparator = new ResourceComparator();
        input = ResourcesPlugin.getWorkspace().getRoot();
      } else {
        // At least one of the roots is not in the Eclipse Workspace. Use custom file
        // system content and label providers.

        contentProvider = new FileSystemContentProvider(roots);
        labelProvider = new FileSystemLabelProvider(context);
        viewerComparator = new FileSystemNodeComparator();
        input = new Object();
      }

      final ElementTreeSelectionDialog dialog =
          new ElementTreeSelectionDialog(context.getShell(), labelProvider, contentProvider);

      dialog.setTitle(property.definition().getLabel(false, CapitalizationType.TITLE_STYLE, false));
      dialog.setMessage(
          createBrowseDialogMessage(
              property.definition().getLabel(true, CapitalizationType.NO_CAPS, false)));
      dialog.setAllowMultiple(false);
      dialog.setHelpAvailable(false);
      dialog.setInput(input);
      dialog.setComparator(viewerComparator);

      final Path currentPathAbsolute = convertToAbsolute((Path) ((Value<?>) property).content());

      if (currentPathAbsolute != null) {
        Object initialSelection = null;

        if (contentProvider instanceof WorkspaceContentProvider) {
          final URI uri = currentPathAbsolute.toFile().toURI();
          final IWorkspaceRoot wsroot = ResourcesPlugin.getWorkspace().getRoot();

          final IFile[] files = wsroot.findFilesForLocationURI(uri);

          if (files.length > 0) {
            final IFile file = files[0];

            if (file.exists()) {
              initialSelection = file;
            }
          }

          if (initialSelection == null) {
            final IContainer[] containers = wsroot.findContainersForLocationURI(uri);

            if (containers.length > 0) {
              final IContainer container = containers[0];

              if (container.exists()) {
                initialSelection = container;
              }
            }
          }
        } else {
          initialSelection =
              ((FileSystemContentProvider) contentProvider).find(currentPathAbsolute);
        }

        if (initialSelection != null) {
          dialog.setInitialSelection(initialSelection);
        }
      }

      if (this.type == FileSystemResourceType.FILE) {
        dialog.setValidator(new FileSelectionStatusValidator());
      } else if (this.type == FileSystemResourceType.FOLDER) {
        dialog.addFilter(new ContainersOnlyViewerFilter());
      }

      if (!extensions.isEmpty()) {
        dialog.addFilter(new ExtensionBasedViewerFilter(extensions));
      }

      if (dialog.open() == Window.OK) {
        final Object firstResult = dialog.getFirstResult();

        if (firstResult instanceof IResource) {
          selectedAbsolutePath = ((IResource) firstResult).getLocation().toString();
        } else {
          selectedAbsolutePath = ((FileSystemNode) firstResult).getFile().getPath();
        }
      }
    } else if (this.type == FileSystemResourceType.FOLDER) {
      final DirectoryDialog dialog = new DirectoryDialog(context.getShell());
      dialog.setText(
          property.definition().getLabel(true, CapitalizationType.FIRST_WORD_ONLY, false));
      dialog.setMessage(
          createBrowseDialogMessage(
              property.definition().getLabel(true, CapitalizationType.NO_CAPS, false)));

      final Value<?> value = (Value<?>) property;
      final Path path = (Path) value.content();

      if (path != null) {
        dialog.setFilterPath(path.toOSString());
      } else if (roots.size() > 0) {
        dialog.setFilterPath(roots.get(0).toOSString());
      }

      selectedAbsolutePath = dialog.open();
    } else {
      final FileDialog dialog = new FileDialog(context.getShell());
      dialog.setText(
          property.definition().getLabel(true, CapitalizationType.FIRST_WORD_ONLY, false));

      final Value<?> value = (Value<?>) property;
      final Path path = (Path) value.content();

      if (path != null && path.segmentCount() > 1) {
        dialog.setFilterPath(path.removeLastSegments(1).toOSString());
        dialog.setFileName(path.lastSegment());
      } else if (roots.size() > 0) {
        dialog.setFilterPath(roots.get(0).toOSString());
      }

      if (!extensions.isEmpty()) {
        final StringBuilder buf = new StringBuilder();

        for (String extension : extensions) {
          if (buf.length() > 0) {
            buf.append(';');
          }

          buf.append("*.");
          buf.append(extension);
        }

        dialog.setFilterExtensions(new String[] {buf.toString()});
      }

      selectedAbsolutePath = dialog.open();
    }

    if (selectedAbsolutePath != null) {
      final Path relativePath = convertToRelative(new Path(selectedAbsolutePath));

      if (relativePath != null) {
        String result = relativePath.toPortableString();

        if (this.includeLeadingSlash) {
          result = "/" + result;
        }

        return result;
      }
    }

    return null;
  }
  @Override
  public String browse(final Presentation context) {
    final Property property = property();

    final EnumSet<JavaTypeKind> kinds = EnumSet.noneOf(JavaTypeKind.class);

    if (this.paramKinds != null) {
      for (String kindString : this.paramKinds.split(",")) {
        kindString = kindString.trim();

        if (kindString.equalsIgnoreCase(JavaTypeKind.CLASS.name())) {
          kinds.add(JavaTypeKind.CLASS);
        } else if (kindString.equalsIgnoreCase(JavaTypeKind.ABSTRACT_CLASS.name())) {
          kinds.add(JavaTypeKind.ABSTRACT_CLASS);
        } else if (kindString.equalsIgnoreCase(JavaTypeKind.INTERFACE.name())) {
          kinds.add(JavaTypeKind.INTERFACE);
        } else if (kindString.equalsIgnoreCase(JavaTypeKind.ANNOTATION.name())) {
          kinds.add(JavaTypeKind.ANNOTATION);
        } else if (kindString.equalsIgnoreCase(JavaTypeKind.ENUM.name())) {
          kinds.add(JavaTypeKind.ENUM);
        } else {
          final String msg = typeKindNotRecognized.format(kindString);
          Sapphire.service(LoggingService.class).logError(msg);
        }
      }
    } else {
      final JavaTypeConstraintService javaTypeConstraintService =
          property.service(JavaTypeConstraintService.class);

      if (javaTypeConstraintService != null) {
        kinds.addAll(javaTypeConstraintService.kinds());
      }
    }

    int browseDialogStyle = IJavaElementSearchConstants.CONSIDER_ALL_TYPES;
    int count = kinds.size();

    if (count == 1) {
      final JavaTypeKind kind = kinds.iterator().next();

      switch (kind) {
        case CLASS:
          browseDialogStyle = IJavaElementSearchConstants.CONSIDER_CLASSES;
          break;
        case ABSTRACT_CLASS:
          browseDialogStyle = IJavaElementSearchConstants.CONSIDER_CLASSES;
          break;
        case INTERFACE:
          browseDialogStyle = IJavaElementSearchConstants.CONSIDER_INTERFACES;
          break;
        case ANNOTATION:
          browseDialogStyle = IJavaElementSearchConstants.CONSIDER_ANNOTATION_TYPES;
          break;
        case ENUM:
          browseDialogStyle = IJavaElementSearchConstants.CONSIDER_ENUMS;
          break;
        default:
          throw new IllegalStateException();
      }
    } else if (count == 2) {
      if (kinds.contains(JavaTypeKind.CLASS) || kinds.contains(JavaTypeKind.ABSTRACT_CLASS)) {
        if (kinds.contains(JavaTypeKind.INTERFACE)) {
          browseDialogStyle = IJavaElementSearchConstants.CONSIDER_CLASSES_AND_INTERFACES;
        } else if (kinds.contains(JavaTypeKind.ENUM)) {
          browseDialogStyle = IJavaElementSearchConstants.CONSIDER_CLASSES_AND_ENUMS;
        }
      }
    }

    final IProject project = property.element().adapt(IProject.class);

    try {
      final SelectionDialog dlg =
          JavaUI.createTypeDialog(
              ((FormComponentPresentation) context).shell(),
              null,
              project,
              browseDialogStyle,
              false);

      dlg.setTitle(
          dialogTitle.format(
              property.definition().getLabel(true, CapitalizationType.TITLE_STYLE, false)));

      if (dlg.open() == SelectionDialog.OK) {
        Object results[] = dlg.getResult();
        assert results != null && results.length == 1;
        if (results[0] instanceof IType) {
          return ((IType) results[0]).getFullyQualifiedName();
        }
      }
    } catch (JavaModelException e) {
      Sapphire.service(LoggingService.class).log(e);
    }

    return null;
  }