コード例 #1
0
  protected void performSaveAs(IProgressMonitor progressMonitor) {
    FileEditorInput input = (FileEditorInput) getEditorInput();
    String path = input.getFile().getFullPath().toString();
    ResourceSet resourceSet = getResourceSet();
    URI platformURI = URI.createPlatformResourceURI(path, true);
    Resource oldFile = resourceSet.getResource(platformURI, true);

    super.performSaveAs(progressMonitor);

    // load and resave - input has been changed to new path by super
    FileEditorInput newInput = (FileEditorInput) getEditorInput();
    String newPath = newInput.getFile().getFullPath().toString();
    URI newPlatformURI = URI.createPlatformResourceURI(newPath, true);
    Resource newFile = resourceSet.createResource(newPlatformURI);
    // if the extension is the same, saving was already performed by super by saving
    // the plain text
    if (platformURI.fileExtension().equals(newPlatformURI.fileExtension())) {
      oldFile.unload();
      // save code folding state, is it possible with a new name
      codeFoldingManager.saveCodeFoldingStateFile(getResource().getURI().toString());
    } else {
      newFile.getContents().clear();
      newFile.getContents().addAll(oldFile.getContents());
      try {
        oldFile.unload();
        if (newFile.getErrors().isEmpty()) {
          newFile.save(null);
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
コード例 #2
0
  public boolean matches(IEditorReference editorRef, IEditorInput input) {
    // first check that the file being opened is a layout file.
    if (input instanceof FileEditorInput) {
      FileEditorInput fileInput = (FileEditorInput) input;

      // get the IFile object and check it's in one of the layout folders.
      IFile iFile = fileInput.getFile();
      ResourceFolder resFolder = ResourceManager.getInstance().getResourceFolder(iFile);

      // if it's a layout, we know check the name of the fileInput against the name of the
      // file being currently edited by the editor since those are independent of the config.
      if (resFolder != null && resFolder.getType() == ResourceFolderType.LAYOUT) {
        try {
          IEditorInput editorInput = editorRef.getEditorInput();
          if (editorInput instanceof FileEditorInput) {
            FileEditorInput editorFileInput = (FileEditorInput) editorInput;
            IFile editorIFile = editorFileInput.getFile();

            return editorIFile.getProject().equals(iFile.getProject())
                && editorIFile.getName().equals(iFile.getName());
          }
        } catch (PartInitException e) {
          // we do nothing, we'll just return false.
        }
      }
    }
    return false;
  }
コード例 #3
0
  @Override
  public void init(IEditorSite site, IEditorInput input) throws PartInitException {
    setSite(site);
    setInput(input);
    setPartName(input.getName());

    // The contract of init() mentions we need to fail if we can't
    // understand the input.
    if (input instanceof FileEditorInput) {
      // We try to open a file that is part of the current workspace
      mFileEditorInput = (FileEditorInput) input;
      mFileName = mFileEditorInput.getName();
      mProject = mFileEditorInput.getFile().getProject();
    } else {
      throw new PartInitException(
          "Input is not of type FileEditorInput "
                      + //$NON-NLS-1$
                      "nor FileStoreEditorInput: "
                      + //$NON-NLS-1$
                      input
                  == null
              ? "null"
              : input.toString()); // $NON-NLS-1$
    }
  }
コード例 #4
0
 private void saveOrDiscardIfNeeded(FileEditorInput file) {
   TextFileDocumentProvider docProvider = file == null ? null : getTextDocumentProvider(file);
   if (docProvider != null && file != null && file.exists() && inputConnected) {
     if (docProvider.canSaveDocument(file)
         && ui.confirmOperation(
                 "Changes Detected",
                 "Manifest file '"
                     + file.getFile().getFullPath().toOSString()
                     + "' has been changed. Do you want to save changes or discard them?",
                 new String[] {"Save", "Discard"},
                 0)
             == 0) {
       try {
         docProvider.saveDocument(
             new NullProgressMonitor(), file, docProvider.getDocument(file), true);
       } catch (CoreException e) {
         Log.log(e);
         ui.errorPopup("Failed Saving File", ExceptionUtil.getMessage(e));
       }
     } else {
       try {
         docProvider.resetDocument(file);
       } catch (CoreException e) {
         Log.log(e);
       }
     }
     disconnect(docProvider, file);
   }
 }
コード例 #5
0
 @Override
 protected String computeLayoutFileName(IEditorInput editorInput)
     throws CoreException, IOException {
   String fileName = null;
   if (editorInput instanceof FileEditorInput) {
     FileEditorInput fileEditorInput = (FileEditorInput) editorInput;
     IFile ifile = fileEditorInput.getFile();
     fileName = ifile.getName();
   } else if (editorInput instanceof FileStoreEditorInput) {
     FileStoreEditorInput fileStoreInput = (FileStoreEditorInput) editorInput;
     IFileStore store = EFS.getStore(fileStoreInput.getURI());
     File localFile = store.toLocalFile(EFS.NONE, null);
     // if no local file is available, obtain a cached file
     if (localFile == null) localFile = store.toLocalFile(EFS.CACHE, null);
     if (localFile == null) throw new IllegalArgumentException();
     fileName = localFile.getName();
   }
   if (fileName != null && fileName.endsWith(".xml")) {
     fileName = fileName.substring(0, fileName.indexOf(".xml"));
   }
   if (fileName != null) {
     fileName += ".layout";
   }
   return fileName;
 }
コード例 #6
0
  private IProject guessProject(IStructuredSelection selection) {
    if (selection == null) {
      return null;
    }

    for (Object element : selection.toList()) {
      if (element instanceof IAdaptable) {
        IResource res = (IResource) ((IAdaptable) element).getAdapter(IResource.class);
        IProject project = res != null ? res.getProject() : null;

        // Is this an Android project?
        try {
          if (project == null || !project.hasNature(AdtConstants.NATURE_DEFAULT)) {
            continue;
          }
        } catch (CoreException e) {
          // checking the nature failed, ignore this resource
          continue;
        }

        return project;
      } else if (element instanceof Pair<?, ?>) {
        // Pair of Project/String
        @SuppressWarnings("unchecked")
        Pair<IProject, String> pair = (Pair<IProject, String>) element;
        return pair.getFirst();
      }
    }

    // Try to figure out the project from the active editor
    IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
    if (window != null) {
      IWorkbenchPage page = window.getActivePage();
      if (page != null) {
        IEditorPart activeEditor = page.getActiveEditor();
        if (activeEditor instanceof AndroidXmlEditor) {
          Object input = ((AndroidXmlEditor) activeEditor).getEditorInput();
          if (input instanceof FileEditorInput) {
            FileEditorInput fileInput = (FileEditorInput) input;
            return fileInput.getFile().getProject();
          }
        }
      }
    }

    IJavaProject[] projects =
        BaseProjectHelper.getAndroidProjects(
            new IProjectFilter() {
              public boolean accept(IProject project) {
                return project.isAccessible();
              }
            });

    if (projects != null && projects.length == 1) {
      return projects[0].getProject();
    }

    return null;
  }
コード例 #7
0
  public void setInput(FileEditorInput input) {
    if (input != null) {
      m_compilationUnit = Workspace.getInstance().getCompilationUnit(input.getFile());
    } else {
      m_compilationUnit = null;
    }

    update();
  }
コード例 #8
0
ファイル: ToscaFileService.java プロジェクト: CELAR/c-Eclipse
  public static IFile getDataFileForInput(final IEditorInput input) {
    final IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();

    if (input instanceof ToscaDiagramEditorInput) {
      final ToscaDiagramEditorInput tdei = (ToscaDiagramEditorInput) input;

      return tdei.getToscaFile();
    } else if (input instanceof DiagramEditorInput) {
      final DiagramEditorInput dei = (DiagramEditorInput) input;

      IPath path = new Path(dei.getUri().trimFragment().toPlatformString(true));

      return recreateDataFile(path);
    } else if (input instanceof FileEditorInput) {
      final FileEditorInput fei = (FileEditorInput) input;

      return fei.getFile();
    } else if (input instanceof IURIEditorInput) {
      // opened externally to Eclipse
      final IURIEditorInput uei = (IURIEditorInput) input;
      final java.net.URI uri = uei.getURI();
      final String path = uri.getPath();

      try {
        final IProject importProject = root.getProject("import"); // $NON-NLS-1$
        if (!importProject.exists()) {
          importProject.create(null);
        }

        importProject.open(null);

        final InputStream is = new FileInputStream(path);

        final String fileName;
        if (path.contains("/")) { // $NON-NLS-1$
          fileName = path.substring(path.lastIndexOf("/") + 1); // $NON-NLS-1$
        } else {
          fileName = path.substring(path.lastIndexOf("\\") + 1); // $NON-NLS-1$
        }

        IFile importFile = importProject.getFile(fileName);
        if (importFile.exists()) {
          importFile.delete(true, null);
        }

        importFile.create(is, true, null);

        return importProject.getFile(fileName);
      } catch (CoreException exception) {
        exception.printStackTrace();
      } catch (FileNotFoundException exception) {
        exception.printStackTrace();
      }
    }

    return null;
  }
コード例 #9
0
 private void disconnect(TextFileDocumentProvider provider, FileEditorInput input) {
   if (inputConnected) {
     provider.disconnect(input);
     inputConnected = false;
   } else {
     throw new IllegalStateException(
         "Attempting to disconnect input '"
             + input.getFile().getName()
             + "' while no inputs are connected");
   }
 }
コード例 #10
0
  /**
   * Test method for {@link
   * org.talend.dataprofiler.core.CorePlugin#itemIsOpening(org.talend.core.model.properties.Item,
   * boolean)}.
   */
  @Test
  public void testItemIsOpeningItemBoolean() {
    try {
      CorePlugin cpMock = mock(CorePlugin.class);
      PowerMockito.mockStatic(CorePlugin.class);
      when(CorePlugin.getDefault()).thenReturn(cpMock);

      IWorkbench workbenchMock = mock(IWorkbench.class);
      when(cpMock.getWorkbench()).thenReturn(workbenchMock);

      IWorkbenchWindow workbenchWindowMock = mock(IWorkbenchWindow.class);
      when(workbenchMock.getActiveWorkbenchWindow()).thenReturn(workbenchWindowMock);

      IWorkbenchPage workbenchPageMock = mock(IWorkbenchPage.class);
      when(workbenchWindowMock.getActivePage()).thenReturn(workbenchPageMock);

      IEditorReference editorRefMock = mock(IEditorReference.class);
      IEditorReference[] editorRefMocks = new IEditorReference[] {editorRefMock};
      when(workbenchPageMock.getEditorReferences()).thenReturn(editorRefMocks);

      FileEditorInput fileEditorInputMock = mock(FileEditorInput.class);
      when(editorRefMock.getEditorInput()).thenReturn(fileEditorInputMock);

      String path1 = "/abc1"; // $NON-NLS-1$
      String path2 = "/abc2"; // $NON-NLS-1$

      IFile inputFileMock = mock(IFile.class);
      when(fileEditorInputMock.getFile()).thenReturn(inputFileMock);

      IPath inputFilePathMock = mock(IPath.class);
      when(inputFileMock.getFullPath()).thenReturn(inputFilePathMock);

      when(inputFilePathMock.toString()).thenReturn(path1);

      Item itemMock = mock(Item.class);
      Property propertyMock = mock(Property.class);
      when(itemMock.getProperty()).thenReturn(propertyMock);

      Resource resourceMock = mock(Resource.class);
      when(propertyMock.eResource()).thenReturn(resourceMock);

      IPath ipathMock = mock(IPath.class);
      PowerMockito.mockStatic(PropertyHelper.class);
      when(PropertyHelper.getItemPath(propertyMock)).thenReturn(ipathMock);
      when(ipathMock.toString()).thenReturn(path2);

      CorePlugin cp = new CorePlugin();
      assertFalse(cp.itemIsOpening(itemMock, false));
    } catch (PartInitException e) {
      fail(e.getMessage());
    }
  }
コード例 #11
0
 private void initializeResourceObjectFromFile(FileEditorInput input) {
   IFile inputFile = input.getFile();
   com.github.funthomas424242.rezeptsammler.rezept.resource.rezept.mopp.RezeptNature.activate(
       inputFile.getProject());
   String path = inputFile.getFullPath().toString();
   URI uri = URI.createPlatformResourceURI(path, true);
   ResourceSet resourceSet = getResourceSet();
   com.github.funthomas424242.rezeptsammler.rezept.resource.rezept.IRezeptTextResource
       loadedResource =
           (com.github.funthomas424242.rezeptsammler.rezept.resource.rezept.IRezeptTextResource)
               resourceSet.getResource(uri, false);
   if (loadedResource == null) {
     try {
       Resource demandLoadedResource = null;
       // here we do not use getResource(), because 'resource' might be null, which is ok
       // when initializing the resource object
       com.github.funthomas424242.rezeptsammler.rezept.resource.rezept.IRezeptTextResource
           currentResource = this.resource;
       if (currentResource != null
           && !currentResource.getURI().fileExtension().equals(uri.fileExtension())) {
         // do not attempt to load if file extension has changed in a 'save as' operation
       } else {
         demandLoadedResource = resourceSet.getResource(uri, true);
       }
       if (demandLoadedResource
           instanceof
           com.github.funthomas424242.rezeptsammler.rezept.resource.rezept.IRezeptTextResource) {
         setResource(
             (com.github.funthomas424242.rezeptsammler.rezept.resource.rezept.IRezeptTextResource)
                 demandLoadedResource);
       } else {
         // the resource was not loaded by an EMFText resource, but some other EMF resource
         com.github.funthomas424242.rezeptsammler.rezept.resource.rezept.ui.RezeptUIPlugin
             .showErrorDialog(
                 "Invalid resource.",
                 "The file '"
                     + uri.lastSegment()
                     + "' of type '"
                     + uri.fileExtension()
                     + "' can not be handled by the RezeptEditor.");
         // close this editor because it can not present the resource
         close(false);
       }
     } catch (Exception e) {
       com.github.funthomas424242.rezeptsammler.rezept.resource.rezept.ui.RezeptUIPlugin.logError(
           "Exception while loading resource in " + this.getClass().getSimpleName() + ".", e);
     }
   } else {
     setResource(loadedResource);
   }
 }
コード例 #12
0
  protected Property getProperty() {
    Property property = null;
    if (getEditorInput() instanceof AbstractItemEditorInput) {
      AbstractItemEditorInput editorInput = (AbstractItemEditorInput) getEditorInput();
      if (editorInput.getItem() != null) {
        property = editorInput.getItem().getProperty();
      }
    } else if (getEditorInput() instanceof FileEditorInput) {
      FileEditorInput editorInput = (FileEditorInput) getEditorInput();
      property = PropertyHelper.getProperty(editorInput.getFile());
    }

    return property;
  }
コード例 #13
0
  @Override
  public void launch(IEditorPart editor, final String mode) {
    Activator.logInfo("launch shortcut: editor" + editor.getTitle() + " mode " + mode);

    IEditorInput ei = editor.getEditorInput();

    if (ei != null && ei instanceof FileEditorInput) {
      FileEditorInput fei = (FileEditorInput) ei;
      IFile file = fei.getFile();
      final String fName = file.getProjectRelativePath().toOSString();
      final String pName = file.getProject().getName();
      launch(pName, fName, mode);
    }
  }
コード例 #14
0
 private void connect(TextFileDocumentProvider provider, FileEditorInput input) {
   if (!inputConnected) {
     try {
       provider.connect(input);
       inputConnected = true;
     } catch (CoreException e) {
       Log.log(e);
     }
   } else {
     throw new IllegalStateException(
         "Attempting to connect input '"
             + input.getFile().getName()
             + "' while previous input is still connected.");
   }
 }
コード例 #15
0
  private IPath showSaveAsDialog() {
    SaveAsDialog dialog = new SaveAsDialog(AndmoreAndroidPlugin.getDisplay().getActiveShell());

    IFile dest =
        mProject.getFile(
            NinePatchedImage.getNinePatchedFileName(
                mFileEditorInput.getFile().getProjectRelativePath().toOSString()));
    dialog.setOriginalFile(dest);

    dialog.create();

    if (dialog.open() == Window.CANCEL) {
      return null;
    }

    return dialog.getResult();
  }
コード例 #16
0
  /**
   * Initializes the combo containing all feature projects.<br>
   * Selects the feature project corresponding to the selected resource.
   */
  private void initComboProject() {
    final Object obj = selection.getFirstElement();
    // TODO: Check for projects in other languages than java
    if (obj instanceof JavaElement) {
      IProject project = ((JavaElement) obj).getJavaProject().getProject();
      featureProject = CorePlugin.getFeatureProject(project);
      if (featureProject != null) {
        comboProject.setText(featureProject.getProjectName());
        checkcontainer(featureProject, project);
      }
    } else if (obj instanceof IResource) {
      IResource resource = (IResource) obj;
      featureProject = CorePlugin.getFeatureProject(resource);
      if (featureProject != null) {
        comboProject.setText(featureProject.getProjectName());
        checkcontainer(featureProject, resource);
      }
    } else if (featureProject == null) {
      IWorkbenchWindow editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
      IEditorPart part = null;
      if (editor != null) {
        IWorkbenchPage page = editor.getActivePage();
        if (page != null) {
          part = page.getActiveEditor();
          if (part != null) {
            FileEditorInput inputFile = (FileEditorInput) part.getEditorInput();
            featureProject = CorePlugin.getFeatureProject(inputFile.getFile());

            if (featureProject != null) {
              IResource res =
                  ResourcesPlugin.getWorkspace()
                      .getRoot()
                      .findMember(featureProject.getProjectName());
              checkcontainer(featureProject, res);
            }
          }
        }
      }

      if (featureProject != null) {
        comboProject.setText(featureProject.getProjectName());
      }
    }
    comboProjectText = comboProject.getText();
  }
コード例 #17
0
 /**
  * PDE editors should call this when they are closing down.
  *
  * @param editor the pde editor to disconnect from
  */
 public static void disconnect(PDEFormEditor editor) {
   IProject project = editor.getCommonProject();
   if (project == null) {
     // getCommonProject will return null when project is deleted with editor open - bug 226788
     // Solution is to use editor input if it is a FileEditorInput.
     IEditorInput input = editor.getEditorInput();
     if (input != null && input instanceof FileEditorInput) {
       FileEditorInput fei = (FileEditorInput) input;
       IFile file = fei.getFile();
       project = file.getProject();
     }
   }
   if (project == null) return;
   if (!fOpenPDEEditors.containsKey(project)) return;
   ArrayList list = (ArrayList) fOpenPDEEditors.get(project);
   list.remove(editor);
   if (list.size() == 0) fOpenPDEEditors.remove(project);
 }
コード例 #18
0
 @Override
 protected FileEditorInput compute() {
   IFile file = getFile();
   FileEditorInput currentInput = getValue();
   boolean changed = currentInput == null || !currentInput.getFile().equals(file);
   if (changed) {
     saveOrDiscardIfNeeded(currentInput);
     if (file != null) {
       FileEditorInput input = new FileEditorInput(file);
       // Connect input to doc provider here when editor input has changed
       TextFileDocumentProvider provider = getTextDocumentProvider(input);
       if (provider != null) {
         connect(provider, input);
       }
       return input;
     }
   }
   return null;
 }
コード例 #19
0
  protected void applyChanges() {
    try {
      m_ymlFile.save();

      IEditorInput editorInput = getEditorInput();

      if (!(editorInput instanceof IFileEditorInput)) return;

      FileEditorInput fileEditor = (FileEditorInput) editorInput;

      m_editor.updatePartControl(fileEditor);

      fileEditor.getFile().getProject().refreshLocal(IResource.DEPTH_INFINITE, null);
    } catch (CoreException e) {
      e.printStackTrace();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
  }
コード例 #20
0
 public boolean equals(Object o) {
   getXModelObject();
   if (this == o) return true;
   if (o instanceof FileEditorInput) {
     if (getFile() == null) return false;
     FileEditorInput other = (FileEditorInput) o;
     IFile f1 = getFile();
     IFile f2 = other.getFile();
     if (f1 == null || f2 == null) return f1 == f2;
     if (f1.equals(f2)) return true;
     IPath loc1 = f1.getLocation();
     IPath loc2 = f2.getLocation();
     if (loc1 == null || loc2 == null) return loc1 == loc2;
     return loc1.equals(loc2);
   }
   if (o instanceof XModelObjectEditorInput) {
     return object.equals(((XModelObjectEditorInput) o).getXModelObject());
   }
   return false;
 }
コード例 #21
0
  /**
   * Tests if the current workbench selection is a suitable
   *
   * <p>container to use.
   */
  private void initialize() {

    if (selection != null
        && selection.isEmpty() == false
        && selection instanceof IStructuredSelection) {

      IStructuredSelection ssel = (IStructuredSelection) selection;

      if (ssel.size() > 1) return;

      Object obj = ssel.getFirstElement();

      if (obj instanceof IResource) {

        IContainer container;

        if (obj instanceof IContainer) container = (IContainer) obj;
        else container = ((IResource) obj).getParent();

        containerText.setText(container.getFullPath().toString());
      }

    } else if (this.editor != null) {

      if (editor.getEditorInput() instanceof FileEditorInput) {

        FileEditorInput input = (FileEditorInput) editor.getEditorInput();

        containerText.setText(input.getFile().getParent().getFullPath().toString());
      }
    }

    // TODO: this works if you do a right click but not if you come here from a select your page
    // type page

    fileText.setText("untitled.cfm");

    setFilenameFocus();
  }
コード例 #22
0
  @Override
  public void doSave(final IProgressMonitor monitor) {
    boolean hasNinePatchExtension = mFileName.endsWith(DOT_9PNG);
    boolean doConvert = false;

    if (!hasNinePatchExtension) {
      String patchedName = NinePatchedImage.getNinePatchedFileName(mFileName);
      doConvert =
          MessageDialog.openQuestion(
              AndmoreAndroidPlugin.getDisplay().getActiveShell(),
              "Warning",
              String.format(
                  "The file \"%s\" doesn't seem to be a 9-patch file. \n"
                      + "Do you want to convert and save as \"%s\" ?",
                  mFileName, patchedName));

      if (doConvert) {
        IFile destFile =
            mProject.getFile(
                NinePatchedImage.getNinePatchedFileName(
                    mFileEditorInput.getFile().getProjectRelativePath().toOSString()));
        if (!destFile.exists()) {
          mFileEditorInput = new FileEditorInput(destFile);
          mFileName = mFileEditorInput.getName();
        } else {
          IPath relativePath = null;
          if ((relativePath = showSaveAsDialog()) != null) {
            mFileEditorInput =
                new FileEditorInput(ResourcesPlugin.getWorkspace().getRoot().getFile(relativePath));
            mFileName = mFileEditorInput.getName();
          } else {
            doConvert = false;
          }
        }
      }
    }

    if (hasNinePatchExtension || doConvert) {
      ImageLoader loader = new ImageLoader();
      loader.data = new ImageData[] {mNinePatchedImage.getRawImageData()};

      IFile file = mFileEditorInput.getFile();

      ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
      loader.save(outputStream, SWT.IMAGE_PNG);
      byte[] byteArray = outputStream.toByteArray();

      try {
        if (file.exists()) {
          file.setContents(new ByteArrayInputStream(byteArray), true, false, monitor);
        } else {
          file.create(new ByteArrayInputStream(byteArray), true, monitor);
        }

        mNinePatchedImage.clearDirtyFlag();

        AndmoreAndroidPlugin.getDisplay()
            .asyncExec(
                new Runnable() {
                  @Override
                  public void run() {
                    setPartName(mFileName);
                    firePropertyChange(PROP_DIRTY);
                  }
                });
      } catch (CoreException e) {
        AndmoreAndroidPlugin.log(e, null);
      }
    }
  }
コード例 #23
0
ファイル: PreviewViewPart.java プロジェクト: ralfebert/swtxml
 private File getProjectRootDir(FileEditorInput input) {
   return new File(input.getFile().getProject().getLocationURI());
 }
コード例 #24
0
 public IFile getFile() {
   return innerEidtorInput.getFile();
 }
コード例 #25
0
 public IPersistableElement getPersistable() {
   // if the file has been deleted,return null will make this EidtorInput be removed from
   // NavigationHistory
   if (!innerEidtorInput.getFile().exists()) return null;
   return innerEidtorInput.getPersistable();
 }
コード例 #26
0
ファイル: PageDataModelBuilder.java プロジェクト: eclipse/edt
  private void fillPageDataModel(EGLEditor editor, PageDataModel model) {
    if (editor != null) {
      IEditorInput editorInput = editor.getEditorInput();
      if (editorInput instanceof FileEditorInput) {
        FileEditorInput fileEditorInput = (FileEditorInput) editorInput;

        // process handler
        HandlerFieldsResolver handlerFieldsResolver =
            new HandlerFieldsResolver(fileEditorInput.getFile());
        handlerFieldsResolver.resolve();
        Handler handler = handlerFieldsResolver.getRUIHandler();
        if (handler != null) {
          HandlerPageDataNode handlerPageDataNode =
              (HandlerPageDataNode)
                  PageDataNodeFactory.newPageDataNode(
                      getName(handler), PageDataNodeFactory.HANDLER_PAGE_DATA_NODE);
          model.addRootPageDataNode(handlerPageDataNode);

          // process class fields
          List contents = handler.getContents();
          for (int i = 0; i < contents.size(); i++) {
            if (contents.get(i) instanceof ClassDataDeclaration) {
              ClassDataDeclaration classDataDeclaration = (ClassDataDeclaration) contents.get(i);
              List names = classDataDeclaration.getNames();
              for (int j = 0; j < names.size(); j++) {
                Object oName = names.get(j);
                if (oName instanceof SimpleName) {
                  SimpleName simpleName = (SimpleName) oName;
                  Member dataBinding = simpleName.resolveMember();
                  Type typeBinding = simpleName.resolveType();
                  if (dataBinding != null) {
                    if (typeBinding != null && isAcceptType(typeBinding)) {
                      if (typeBinding instanceof ParameterizedType) {
                        typeBinding = ((ParameterizedType) typeBinding).getParameterizableType();
                      }

                      // Single
                      if (TypeUtils.isPrimitive(typeBinding)
                          //													|| typeBinding.getKind() == ITypeBinding.DATAITEM_BINDING
                          || typeBinding instanceof Record) {
                        if (!TypeUtils.Type_ANY.equals(typeBinding)) {
                          DataFieldPageDataNode dataFieldPageDataNode = null;
                          if (classDataDeclaration.isPrivate()) {
                            dataFieldPageDataNode =
                                (DataFieldPageDataNode)
                                    PageDataNodeFactory.newPageDataNode(
                                        getName(dataBinding),
                                        PageDataNodeFactory.DATA_FIELD_PAGE_DATA_NODE_PRIVATE);
                          } else {
                            dataFieldPageDataNode =
                                (DataFieldPageDataNode)
                                    PageDataNodeFactory.newPageDataNode(
                                        getName(dataBinding),
                                        PageDataNodeFactory.DATA_FIELD_PAGE_DATA_NODE_PUBLIC);
                          }
                          dataFieldPageDataNode.setDataBindingName(
                              dataBinding.getCaseSensitiveName());
                          handlerPageDataNode.addChild(dataFieldPageDataNode);
                        }
                      }
                      // Array
                      if (typeBinding instanceof ArrayType) {
                        ArrayType arrayTypeBinding = (ArrayType) typeBinding;
                        Type elementTypeBinding = arrayTypeBinding.getElementType();
                        if (TypeUtils.isPrimitive(elementTypeBinding)
                            //														|| elementTypeBinding.getKind() ==
                            // ITypeBinding.DATAITEM_BINDING
                            || elementTypeBinding instanceof Record) {
                          if (!TypeUtils.Type_ANY.equals(elementTypeBinding)) {
                            DataFieldPageDataNode dataFieldPageDataNode = null;
                            if (classDataDeclaration.isPrivate()) {
                              dataFieldPageDataNode =
                                  (DataFieldPageDataNode)
                                      PageDataNodeFactory.newPageDataNode(
                                          getName(dataBinding),
                                          PageDataNodeFactory.DATA_FIELD_PAGE_DATA_NODE_PRIVATE);
                            } else {
                              dataFieldPageDataNode =
                                  (DataFieldPageDataNode)
                                      PageDataNodeFactory.newPageDataNode(
                                          getName(dataBinding),
                                          PageDataNodeFactory.DATA_FIELD_PAGE_DATA_NODE_PUBLIC);
                            }
                            dataFieldPageDataNode.setDataBindingName(
                                dataBinding.getCaseSensitiveName());
                            handlerPageDataNode.addChild(dataFieldPageDataNode);
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
コード例 #27
0
  /**
   * Called by {@link NewXmlFileWizard} to initialize the page with the selection received by the
   * wizard -- typically the current user workbench selection.
   *
   * <p>Things we expect to find out from the selection:
   *
   * <ul>
   *   <li>The project name, valid if it's an android nature.
   *   <li>The current folder, valid if it's a folder under /res
   *   <li>An existing filename, in which case the user will be asked whether to override it.
   * </ul>
   *
   * <p>The selection can also be set to a {@link Pair} of {@link IProject} and a workspace resource
   * path (where the resource path does not have to exist yet, such as res/anim/).
   *
   * @param selection The selection when the wizard was initiated.
   */
  private boolean initializeFromSelection(IStructuredSelection selection) {
    if (selection == null) {
      return false;
    }

    // Find the best match in the element list. In case there are multiple selected elements
    // select the one that provides the most information and assign them a score,
    // e.g. project=1 + folder=2 + file=4.
    IProject targetProject = null;
    String targetWsFolderPath = null;
    String targetFileName = null;
    int targetScore = 0;
    for (Object element : selection.toList()) {
      if (element instanceof IAdaptable) {
        IResource res = (IResource) ((IAdaptable) element).getAdapter(IResource.class);
        IProject project = res != null ? res.getProject() : null;

        // Is this an Android project?
        try {
          if (project == null || !project.hasNature(AdtConstants.NATURE_DEFAULT)) {
            continue;
          }
        } catch (CoreException e) {
          // checking the nature failed, ignore this resource
          continue;
        }

        int score = 1; // we have a valid project at least

        IPath wsFolderPath = null;
        String fileName = null;
        assert res != null; // Eclipse incorrectly thinks res could be null, so tell it no
        if (res.getType() == IResource.FOLDER) {
          wsFolderPath = res.getProjectRelativePath();
        } else if (res.getType() == IResource.FILE) {
          if (SdkUtils.endsWithIgnoreCase(res.getName(), DOT_XML)) {
            fileName = res.getName();
          }
          wsFolderPath = res.getParent().getProjectRelativePath();
        }

        // Disregard this folder selection if it doesn't point to /res/something
        if (wsFolderPath != null
            && wsFolderPath.segmentCount() > 1
            && SdkConstants.FD_RESOURCES.equals(wsFolderPath.segment(0))) {
          score += 2;
        } else {
          wsFolderPath = null;
          fileName = null;
        }

        score += fileName != null ? 4 : 0;

        if (score > targetScore) {
          targetScore = score;
          targetProject = project;
          targetWsFolderPath = wsFolderPath != null ? wsFolderPath.toString() : null;
          targetFileName = fileName;
        }
      } else if (element instanceof Pair<?, ?>) {
        // Pair of Project/String
        @SuppressWarnings("unchecked")
        Pair<IProject, String> pair = (Pair<IProject, String>) element;
        targetScore = 1;
        targetProject = pair.getFirst();
        targetWsFolderPath = pair.getSecond();
        targetFileName = "";
      }
    }

    if (targetProject == null) {
      // Try to figure out the project from the active editor
      IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
      if (window != null) {
        IWorkbenchPage page = window.getActivePage();
        if (page != null) {
          IEditorPart activeEditor = page.getActiveEditor();
          if (activeEditor instanceof AndroidXmlEditor) {
            Object input = ((AndroidXmlEditor) activeEditor).getEditorInput();
            if (input instanceof FileEditorInput) {
              FileEditorInput fileInput = (FileEditorInput) input;
              targetScore = 1;
              IFile file = fileInput.getFile();
              targetProject = file.getProject();
              IPath path = file.getParent().getProjectRelativePath();
              targetWsFolderPath = path != null ? path.toString() : null;
            }
          }
        }
      }
    }

    if (targetProject == null) {
      // If we didn't find a default project based on the selection, check how many
      // open Android projects we can find in the current workspace. If there's only
      // one, we'll just select it by default.
      IJavaProject[] projects = AdtUtils.getOpenAndroidProjects();
      if (projects != null && projects.length == 1) {
        targetScore = 1;
        targetProject = projects[0].getProject();
      }
    }

    // Now set the UI accordingly
    if (targetScore > 0) {
      mValues.project = targetProject;
      mValues.folderPath = targetWsFolderPath;
      mProjectButton.setSelectedProject(targetProject);
      mFileNameTextField.setText(targetFileName != null ? targetFileName : ""); // $NON-NLS-1$

      // If the current selection context corresponds to a specific file type,
      // select it.
      if (targetWsFolderPath != null) {
        int pos = targetWsFolderPath.lastIndexOf(WS_SEP_CHAR);
        if (pos >= 0) {
          targetWsFolderPath = targetWsFolderPath.substring(pos + 1);
        }
        String[] folderSegments = targetWsFolderPath.split(RES_QUALIFIER_SEP);
        if (folderSegments.length > 0) {
          mValues.configuration = FolderConfiguration.getConfig(folderSegments);
          String folderName = folderSegments[0];
          selectTypeFromFolder(folderName);
        }
      }
    }

    return true;
  }
コード例 #28
0
  /*
   * @see org.eclipse.jface.action.Action#run()
   */
  @Override
  public void run() {
    // update has been called by the framework
    if (!isEnabled()) return;

    if (!CoreUtility.builderEnabledCheck(errorTitle)) {
      return;
    }

    final CALEditor textEditor = (CALEditor) getTextEditor();
    final ITextSelection selection = ActionUtilities.getSelection(textEditor);
    final IDocument document = ActionUtilities.getDocument(textEditor);

    if (document != null) {
      final int offset = selection.getOffset();
      try {
        CoreUtility.initializeCALBuilder(null, 100, 100);

        final int firstLine = document.getLineOfOffset(offset);
        final int column = offset - document.getLineOffset(firstLine);
        CALModelManager cmm = CALModelManager.getCALModelManager();
        FileEditorInput ei = (FileEditorInput) textEditor.getEditorInput();
        final IFile memberFile = ei.getFile();
        ModuleName moduleName = cmm.getModuleName(memberFile);
        if (moduleName == null) {
          final String errorMessage =
              Messages.format(
                  ActionMessages.error_invalidFileName_message, textEditor.getStorage().getName());
          CoreUtility.showMessage(errorTitle, errorMessage, IStatus.ERROR);
          return;
        }
        CompilerMessageLogger messageLogger = new MessageLogger();
        final SourceRange range;
        if (direction == Direction.Previous) {
          range =
              sourceMetrics.findPreviousTopLevelElement(
                  moduleName, firstLine + 1, column + 1, messageLogger);
        } else if (direction == Direction.Next) {
          range =
              sourceMetrics.findNextTopLevelElement(
                  moduleName, firstLine + 1, column + 1, messageLogger);
        } else {
          throw new IllegalArgumentException();
        }
        if (range != null) {
          IStorage definitionFile = cmm.getInputSourceFile(moduleName);
          IEditorPart editorPart = CoreUtility.openInEditor(definitionFile, true);
          CoreUtility.showPosition(editorPart, definitionFile, range, true);
        }
      } catch (BadLocationException e) {
        // will only happen on concurrent modification
        CALEclipseUIPlugin.log(
            new Status(
                IStatus.ERROR, CALEclipseUIPlugin.PLUGIN_ID, IStatus.OK, "", e)); // $NON-NLS-1$
        return;
      } catch (PartInitException e) {
        CALEclipseUIPlugin.log(
            new Status(
                IStatus.ERROR, CALEclipseUIPlugin.PLUGIN_ID, IStatus.OK, "", e)); // $NON-NLS-1$
        return;
      }
    }
  }