private void open(IFile file) {
    IWorkbenchWindow dw = FMUIPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow();
    IWorkbenchPage page = dw.getActivePage();
    if (page != null) {
      IContentType contentType = null;
      try {
        IContentDescription description = file.getContentDescription();
        if (description != null) {
          contentType = description.getContentType();
        }
        IEditorDescriptor desc = null;
        if (contentType != null) {
          desc =
              PlatformUI.getWorkbench()
                  .getEditorRegistry()
                  .getDefaultEditor(file.getName(), contentType);
        } else {
          desc = PlatformUI.getWorkbench().getEditorRegistry().getDefaultEditor(file.getName());
        }

        if (desc != null) {
          page.openEditor(new FileEditorInput(file), desc.getId());
        }
      } catch (CoreException e) {
        FMUIPlugin.getDefault().logError(e);
      }
    }
  }
Esempio n. 2
0
 public void run() {
   try {
     if (element.getResource() instanceof IFile) {
       IFile file = (IFile) element.getResource();
       IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
       IDE.openEditor(page, file);
     } else {
       // 2012-04-13 sundl 添加处理引用包里的资源
       IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
       if (element instanceof ArchiveARESResource) {
         ArchiveARESResource aresfile = (ArchiveARESResource) element;
         ARESResourceEditorInput input = new ARESResourceEditorInput(aresfile);
         boolean active = OpenStrategy.activateOnOpen();
         try {
           IEditorDescriptor editor = IDE.getEditorDescriptor(aresfile.getElementName());
           if (editor != null) {
             IDE.openEditor(page, input, editor.getId(), active);
           }
         } catch (PartInitException e) {
           e.printStackTrace();
         }
       }
     }
   } catch (PartInitException e) {
     e.printStackTrace();
   }
 }
Esempio n. 3
0
  public static IEditorDescriptor getEditorDescription(IFile file) {
    IEditorRegistry editorReg = PlatformUI.getWorkbench().getEditorRegistry();

    IEditorDescriptor selectedDescriptor = null;

    String defaultEditorID = null;
    try {
      defaultEditorID = file.getPersistentProperty(IDE.EDITOR_KEY);
    } catch (CoreException e) {
    }
    if (defaultEditorID != null) selectedDescriptor = editorReg.findEditor(defaultEditorID);

    if (selectedDescriptor == null) {

      /*
      JastAddModel model = JastAddModelProvider.getModel(file);
      if (model != null) {
      */
      IEditorDescriptor[] descriptors = editorReg.getEditors(file.getName());
      for (IEditorDescriptor descriptor : descriptors)
        if (descriptor.getId().equals(JastAddJEditor.EDITOR_ID)) selectedDescriptor = descriptor;
      if (selectedDescriptor == null && descriptors.length > 0) selectedDescriptor = descriptors[0];
      // }
    }
    return selectedDescriptor;
  }
    @Override
    public ImageDescriptor getImageDescriptor(Object object) {
      if (object instanceof IFileStore) {
        IFileStore fileStore = (IFileStore) object;

        try {
          if (fileStore.fetchInfo().isDirectory()) {
            return PlatformUI.getWorkbench()
                .getSharedImages()
                .getImageDescriptor(ISharedImages.IMG_OBJ_FOLDER);
          }

          IEditorDescriptor descriptor = IDE.getEditorDescriptor(fileStore.getName());

          if (descriptor != null) {
            return descriptor.getImageDescriptor();
          } else {
            return PlatformUI.getWorkbench()
                .getSharedImages()
                .getImageDescriptor(ISharedImages.IMG_OBJ_FILE);
          }
        } catch (PartInitException e) {

        }
      }

      return null;
    }
 /** @generated */
 private static boolean openEditor(IWorkbench workbench, URI fileURI) {
   IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow();
   IWorkbenchPage page = workbenchWindow.getActivePage();
   IEditorDescriptor editorDescriptor =
       workbench.getEditorRegistry().getDefaultEditor(fileURI.toFileString());
   if (editorDescriptor == null) {
     MessageDialog.openError(
         workbenchWindow.getShell(),
         Messages.DiagramEditorActionBarAdvisor_DefaultFileEditorTitle,
         NLS.bind(
             Messages.DiagramEditorActionBarAdvisor_DefaultFileEditorMessage,
             fileURI.toFileString()));
     return false;
   } else {
     try {
       page.openEditor(new URIEditorInput(fileURI), editorDescriptor.getId());
     } catch (PartInitException exception) {
       MessageDialog.openError(
           workbenchWindow.getShell(),
           Messages.DiagramEditorActionBarAdvisor_DefaultEditorOpenErrorTitle,
           exception.getMessage());
       return false;
     }
   }
   return true;
 }
Esempio n. 6
0
  /**
   * Saves the object state in the given memento.
   *
   * @param memento the memento to save the object state in
   */
  public IStatus saveState(IMemento memento) {
    if (!isRestored()) {
      memento.putMemento(this.memento);
    } else if (input != null) {

      IPersistableElement persistable = input.getPersistable();
      if (persistable != null) {
        /*
         * Store IPersistable of the IEditorInput in a separate section
         * since it could potentially use a tag already used in the parent
         * memento and thus overwrite data.
         */
        IMemento persistableMemento = memento.createChild(IWorkbenchConstants.TAG_PERSISTABLE);
        persistable.saveState(persistableMemento);
        memento.putString(IWorkbenchConstants.TAG_FACTORY_ID, persistable.getFactoryId());
        if (descriptor != null && descriptor.getId() != null) {
          memento.putString(IWorkbenchConstants.TAG_ID, descriptor.getId());
        }
        // save the name and tooltip separately so they can be restored
        // without having to instantiate the input, which can activate plugins
        memento.putString(IWorkbenchConstants.TAG_NAME, input.getName());
        memento.putString(IWorkbenchConstants.TAG_TOOLTIP, input.getToolTipText());
      }
    }
    return Status.OK_STATUS;
  }
  /*
   * @see org.eclipse.swt.dnd.DragSourceListener#dragStart
   */
  @Override
  public void dragStart(DragSourceEvent event) {
    fEditorInputDatas = new ArrayList<EditorInputData>();

    ISelection selection = fProvider.getSelection();
    if (selection instanceof IStructuredSelection) {
      IStructuredSelection structuredSelection = (IStructuredSelection) selection;
      for (Iterator<?> iter = structuredSelection.iterator(); iter.hasNext(); ) {
        Object element = iter.next();
        IEditorInput editorInput = EditorUtility.getEditorInput(element);
        if (editorInput != null && editorInput.getPersistable() != null) {
          try {
            String editorId = EditorUtility.getEditorID(editorInput);
            // see org.eclipse.ui.internal.ide.EditorAreaDropAdapter.openNonExternalEditor(..):
            IEditorRegistry editorReg = PlatformUI.getWorkbench().getEditorRegistry();
            IEditorDescriptor editorDesc = editorReg.findEditor(editorId);
            if (editorDesc != null && !editorDesc.isOpenExternal()) {
              fEditorInputDatas.add(
                  EditorInputTransfer.createEditorInputData(editorId, editorInput));
            }
          } catch (PartInitException e) {
            JavaPlugin.log(e);
          }
        }
      }
    }

    event.doit = fEditorInputDatas.size() > 0;
  }
Esempio n. 8
0
 /**
  * Creates the menu item for the editor descriptor.
  *
  * @param menu the menu to add the item to
  * @param descriptor the editor descriptor, or null for the system editor
  * @param preferredEditor the descriptor of the preferred editor, or <code>null</code>
  */
 private MenuItem createMenuItem(
     Menu menu, final IEditorDescriptor descriptor, final IEditorDescriptor preferredEditor) {
   // XXX: Would be better to use bold here, but SWT does not support it.
   final MenuItem menuItem = new MenuItem(menu, SWT.RADIO);
   boolean isPreferred =
       preferredEditor != null && descriptor.getId().equals(preferredEditor.getId());
   menuItem.setSelection(isPreferred);
   menuItem.setText(descriptor.getLabel());
   Image image = getImage(descriptor);
   if (image != null) {
     menuItem.setImage(image);
   }
   Listener listener =
       new Listener() {
         public void handleEvent(Event event) {
           switch (event.type) {
             case SWT.Selection:
               if (menuItem.getSelection()) {
                 openEditor(descriptor, false);
               }
               break;
           }
         }
       };
   menuItem.addListener(SWT.Selection, listener);
   return menuItem;
 }
  /**
   * Register an editor to use for files with the given filename.
   *
   * <p>NOTE: this method uses internal, undocumented Eclipse functionality. It may therefore break
   * in a future version of Eclipse.
   *
   * @param fileName Filename to be registered. Use the form "*.ext" to register all files with a
   *     given extension.
   * @param editorId ID of the editor to use for the given filename.
   */
  private static void registerEditorForFilename(final String fileName, final String editorId) {

    final EditorDescriptor ed = getEditorDescriptor(editorId);
    if (ed == null) {
      return;
    }

    final IEditorRegistry reg = PlatformUI.getWorkbench().getEditorRegistry();
    final EditorRegistry ereg = (EditorRegistry) reg;
    final FileEditorMapping[] mappings = (FileEditorMapping[]) ereg.getFileEditorMappings();
    FileEditorMapping mapping = null;
    for (final FileEditorMapping fem : mappings) {
      if (fem.getLabel().equals(fileName)) {
        mapping = fem;
        break;
      }
    }

    if (mapping != null) {
      // found mapping for fileName
      // make sure it includes our editor
      for (final IEditorDescriptor editor : mapping.getEditors()) {
        if (editor.getId().equals(editorId)) {
          // already mapped
          return;
        }
      }

      // editor not in the list, so add it
      mapping.addEditor(ed);
      ereg.setFileEditorMappings(mappings);
      ereg.saveAssociations();

    } else {
      // no mapping found for the filename
      // let's add one
      String name = null;
      String ext = null;
      final int iDot = fileName.lastIndexOf('.');
      if (iDot == -1) {
        name = fileName;
      } else {
        name = fileName.substring(0, iDot);
        ext = fileName.substring(iDot + 1);
      }

      mapping = new FileEditorMapping(name, ext);
      final FileEditorMapping[] newMappings = new FileEditorMapping[mappings.length + 1];
      mapping.addEditor(ed);

      System.arraycopy(mappings, 0, newMappings, 0, mappings.length);
      newMappings[mappings.length] = mapping;
      ereg.setFileEditorMappings(newMappings);
      ereg.saveAssociations();
    }
  }
 /**
  * @see org.eclipse.debug.ui.ISourcePresentation#getEditorId(org.eclipse.ui.IEditorInput,
  *     java.lang.Object)
  */
 public String getEditorId(IEditorInput input, Object element) {
   if (input instanceof DisassemblyEditorInput) return "org.eclipse.ui.DefaultTextEditor";
   IEditorRegistry registry = PlatformUI.getWorkbench().getEditorRegistry();
   IEditorDescriptor descriptor = registry.getDefaultEditor(input.getName());
   if (descriptor != null) {
     return descriptor.getId();
   } else {
     return "org.eclipse.ui.DefaultTextEditor";
   }
 }
  /** Return the IEditorDescriptor for the given editor ID. */
  private static EditorDescriptor getEditorDescriptor(final String editorId) {
    final EditorRegistry reg = (EditorRegistry) PlatformUI.getWorkbench().getEditorRegistry();
    for (final IEditorDescriptor editor : reg.getSortedEditorsFromPlugins()) {
      if (editor.getId().equals(editorId)) {
        return (EditorDescriptor) editor;
      }
    }

    return null;
  }
 /**
  * Opens an external editor on an IEditorInput containing the file having filePath
  *
  * @param editorInput
  * @param filePath
  * @throws PartInitException
  */
 private IEditorPart openExternalEditor(IEditorInput editorInput, String filePath)
     throws PartInitException {
   // TODO Maybe this method could be improved by omitting filepath which comes from editorInput,
   // but "how?" should be defined here
   final IWorkbenchPage page = getViewSite().getPage();
   IEditorDescriptor desc =
       PlatformUI.getWorkbench().getEditorRegistry().getDefaultEditor(filePath);
   if (desc == null)
     desc = PlatformUI.getWorkbench().getEditorRegistry().getDefaultEditor(filePath + ".txt");
   return page.openEditor(editorInput, desc.getId());
 }
Esempio n. 13
0
 /** execute action on the file */
 protected void execute(IFile file, IAction action) {
   String conflictResourceLocalCopy =
       RegistryCheckInClientUtils.getConflictResourceServerCopy(file.getLocation().toOSString());
   IFile conflictFile =
       file.getWorkspace().getRoot().getFileForLocation(new Path(conflictResourceLocalCopy));
   try {
     IEditorDescriptor defaultEditor = IDE.getEditorDescriptor(file);
     IWorkbenchPage activePage =
         PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
     activePage.openEditor(new FileEditorInput(conflictFile), defaultEditor.getId());
   } catch (PartInitException e) {
     log.error(e);
   }
 }
 public static IEditorPart openEditor(IProject project, IFile file) {
   try {
     IEditorDescriptor toolEditor =
         PlatformUI.getWorkbench().getEditorRegistry().getDefaultEditor(file.getName());
     return PlatformUI.getWorkbench()
         .getActiveWorkbenchWindow()
         .getActivePage()
         .openEditor(new FileEditorInput(file), toolEditor.getId());
   } catch (PartInitException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
     return null;
   }
 }
 public static String getEditorID(IEditorInput input) throws PartInitException {
   Assert.isNotNull(input);
   IEditorDescriptor editorDescriptor;
   if (input instanceof IFileEditorInput) {
     editorDescriptor = IDE.getEditorDescriptor(((IFileEditorInput) input).getFile());
   } else {
     String name = input.getName();
     if (name == null) {
       throwPartInitException(DartEditorMessages.EditorUtility_could_not_find_editorId);
     }
     editorDescriptor = IDE.getEditorDescriptor(name);
   }
   return editorDescriptor.getId();
 }
 public IEditorPart openEditor(IWorkbenchPage page, IFile file, Item item, boolean forceReadOnly) {
   try {
     IEditorDescriptor editorDesc = IDE.getEditorDescriptor(file);
     RepositoryEditorInput repositoryEditorInput = new RepositoryEditorInput(file, item);
     repositoryEditorInput.setReadOnly(forceReadOnly);
     repositoryEditorInput.setRepositoryNode(null);
     IEditorPart editorPart = IDE.openEditor(page, repositoryEditorInput, editorDesc.getId());
     editors.put(editorPart, repositoryEditorInput);
     return editorPart;
   } catch (PartInitException e) {
     // e.printStackTrace();
     ExceptionHandler.process(e);
   }
   return null;
 }
Esempio n. 17
0
 /** Returns the image descriptor for the given editor descriptor, or null if it has no image. */
 private ImageDescriptor getImageDescriptor(IEditorDescriptor editorDesc) {
   ImageDescriptor imageDesc = null;
   if (editorDesc == null) {
     imageDesc = registry.getImageDescriptor(getFileRevision().getName());
     // TODO: is this case valid, and if so, what are the implications
     // for content-type editor bindings?
   } else {
     imageDesc = editorDesc.getImageDescriptor();
   }
   if (imageDesc == null) {
     if (editorDesc.getId().equals(IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID)) {
       imageDesc = registry.getSystemExternalEditorImageDescriptor(getFileRevision().getName());
     }
   }
   return imageDesc;
 }
  /**
   * Opens the new module in an editor, plus selects and reveals it in every open windows.
   *
   * @param newModule the module to be revealed
   */
  private void selectAndRevealNewModule(final IFile newModule) {
    IWorkbench workbench = getWorkbench();
    IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
    if (window != null) {
      IEditorDescriptor desc = ConfigTextEditor.findCFGEditor(workbench);
      IWorkbenchPage page = window.getActivePage();
      try {
        page.openEditor(new FileEditorInput(newModule), desc.getId());
      } catch (PartInitException e) {
        ErrorReporter.logExceptionStackTrace(e);
      }
    }

    // select and reveal the new file in every window open
    selectAndReveal(newModule);
  }
Esempio n. 19
0
  @Override
  public Image getImage(Object element) {
    if (element instanceof SampleCategory) {
      String iconFile = ((SampleCategory) element).getIconFile();
      if (iconFile != null) {
        File file = new File(iconFile);
        if (file.exists()) {
          String iconFilename = file.getAbsolutePath();
          Image image = imageRegistry.get(iconFilename);
          if (image == null) {
            image = new Image(Display.getDefault(), iconFilename);
            imageRegistry.put(iconFilename, image);
          }
          return image;
        }
      }
      // uses folder as the default image
      return IMAGE_FOLDER;
    }
    if (element instanceof SampleEntry) {
      File file = ((SampleEntry) element).getFile();
      if (file != null) {
        if (file.isDirectory()) {
          return IMAGE_FOLDER;
        }

        IEditorDescriptor editorDescriptor =
            WorkbenchPlugin.getDefault().getEditorRegistry().getDefaultEditor(file.getName());
        if (editorDescriptor == null || editorDescriptor.getImageDescriptor() == null) {
          return IMAGE_FILE;
        }
        String key = editorDescriptor.getId();
        Image image = imageRegistry.get(key);
        if (image == null) {
          image = editorDescriptor.getImageDescriptor().createImage();
          imageRegistry.put(key, image);
        }
        return image;
      }
    }
    if (element instanceof SamplesReference) {
      return SamplesUIPlugin.getImage(ICON_REMOTE);
    }
    return super.getImage(element);
  }
 @Override
 public IStatus runInUIThread(final IProgressMonitor monitor) {
   try {
     final IEditorDescriptor desc =
         PlatformUI.getWorkbench()
             .getEditorRegistry()
             .getDefaultEditor(this.phpInfoTxt.getName());
     PlatformUI.getWorkbench()
         .getActiveWorkbenchWindow()
         .getActivePage()
         .openEditor(new FileEditorInput(this.phpInfoTxt), desc.getId());
   } catch (Exception ex) {
     // TODO Exception handling
   }
   monitor.done();
   this.done(Status.OK_STATUS);
   return Status.OK_STATUS;
 }
Esempio n. 21
0
  public static String getEditorID(final IEditorInput input, final Object inputObject) {
    IEditorDescriptor editorDescriptor;
    try {
      if (input instanceof IFileEditorInput) {
        editorDescriptor = IDE.getEditorDescriptor(((IFileEditorInput) input).getFile());
      } else {
        editorDescriptor = IDE.getEditorDescriptor(input.getName());
      }
    } catch (final PartInitException e) {
      return null;
    }

    if (editorDescriptor != null) {
      return editorDescriptor.getId();
    }

    return null;
  }
  private static IEditorPart openInEditor(IFile file, boolean activate) throws PartInitException {

    UIInstrumentationBuilder instrumentation =
        UIInstrumentation.builder("EditorUtility.openInEditor-IFile");
    try {

      if (file == null) {
        throwPartInitException(DartEditorMessages.EditorUtility_file_must_not_be_null);
      }

      instrumentation.data("FileName", file.getName());
      instrumentation.data("FilePath", file.getFullPath().toOSString());
      instrumentation.metric("activate", activate);

      IWorkbenchPage p = DartToolsPlugin.getActivePage();
      if (p == null) {
        throwPartInitException(DartEditorMessages.EditorUtility_no_active_WorkbenchPage);
      }

      IEditorDescriptor desc = IDE.getEditorDescriptor(file, true);

      String editorId = desc.getId();
      boolean isTooComplex = false;
      editorId = maybeSwapDefaultEditorDescriptor(editorId);
      if (DartUI.isTooComplexDartFile(file)) {
        isTooComplex = true;
        editorId = EditorsUI.DEFAULT_TEXT_EDITOR_ID;
      }

      IEditorPart editor = IDE.openEditor(p, file, editorId, activate);
      if (isTooComplex) {
        DartUI.showTooComplexDartFileWarning(editor);
      }
      initializeHighlightRange(editor);
      return editor;
    } catch (RuntimeException e) {
      instrumentation.metric("Exception", e.getClass().toString());
      instrumentation.data("Exception", e.toString());
      throw e;
    } finally {
      instrumentation.log();
    }
  }
 private static Map<String, String> getAptanaEditorFiletypeMap() {
   // finds the editors we contribute and the file extension each maps to
   Map<String, String> editorMap = new TreeMap<String, String>();
   IFileEditorMapping[] mappings =
       PlatformUI.getWorkbench().getEditorRegistry().getFileEditorMappings();
   IEditorDescriptor[] editors;
   IContentTypeMatcher matcher = null;
   IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
   if (projects != null && projects.length > 0) {
     try {
       matcher = projects[0].getContentTypeMatcher();
     } catch (CoreException e) {
       // ignore
     }
   }
   String extension;
   for (IFileEditorMapping mapping : mappings) {
     editors = mapping.getEditors();
     extension = mapping.getExtension();
     if (matcher != null) {
       IContentType type = matcher.findContentTypeFor("new_file." + extension); // $NON-NLS-1$
       if (type != null) {
         String[] extensions = type.getFileSpecs(IContentType.FILE_EXTENSION_SPEC);
         if (extensions != null && extensions.length > 0) {
           extension = extensions[0];
         }
       }
     }
     for (IEditorDescriptor editor : editors) {
       if (editor.getId().startsWith(APTANA_EDITOR_PREFIX)) {
         String name = editor.getLabel();
         // grabs the first word as it will be used to link the editor type with the bundle's name
         // (e.g. HTML Editor -> HTML)
         name = (new StringTokenizer(name)).nextToken();
         if (!editorMap.containsKey(name)) {
           editorMap.put(name, extension);
         }
       }
     }
   }
   return editorMap;
 }
  /**
   * Opens the given file in the registered editor for the file type, or in the default text editor
   * if no editor is registered. This differs from the openInEditor() method in that the system
   * editor will never be opened.
   *
   * @param file the file to open
   * @return an open editor
   * @throws PartInitException if the editor could not be opened or the input element is not valid
   */
  public static IEditorPart openInTextEditor(IFile file, boolean activate)
      throws PartInitException {

    UIInstrumentationBuilder instrumentation =
        UIInstrumentation.builder("EditorUtility.openInTextEditor");
    try {

      if (file == null) {
        instrumentation.metric("Problem", "file is null");
        throwPartInitException(DartEditorMessages.EditorUtility_file_must_not_be_null);
      }

      instrumentation.data("FileName", file.getName());
      instrumentation.data("FilePath", file.getFullPath().toOSString());

      IWorkbenchPage p = DartToolsPlugin.getActivePage();
      if (p == null) {
        instrumentation.metric("Problem", "no active workbench page");
        throwPartInitException(DartEditorMessages.EditorUtility_no_active_WorkbenchPage);
      }

      IEditorDescriptor desc = IDE.getEditorDescriptor(file, true);

      if (desc.getId() == IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID) {
        IEditorRegistry editorReg = PlatformUI.getWorkbench().getEditorRegistry();

        desc = editorReg.findEditor(EditorsUI.DEFAULT_TEXT_EDITOR_ID);
      }

      IEditorPart editorPart =
          IDE.openEditor(p, file, maybeSwapDefaultEditorDescriptor(desc.getId()), activate);
      initializeHighlightRange(editorPart);
      return editorPart;

    } catch (RuntimeException e) {
      instrumentation.metric("Exception", e.getClass().toString());
      instrumentation.data("Exception", e.toString());
      throw e;
    } finally {
      instrumentation.log();
    }
  }
Esempio n. 25
0
  private void initializeTitle(IEditorInput input) {

    Image oldImage = fTitleImage;
    fTitleImage = null;
    String title = ""; // $NON-NLS-1$

    if (input != null) {
      IEditorRegistry editorRegistry = PlatformUI.getWorkbench().getEditorRegistry();
      IEditorDescriptor editorDesc = editorRegistry.findEditor(getSite().getId());
      ImageDescriptor imageDesc = editorDesc != null ? editorDesc.getImageDescriptor() : null;

      fTitleImage = imageDesc != null ? imageDesc.createImage() : null;
      title = input.getName();
    }

    setTitleImage(fTitleImage);
    setPartName(title);

    firePropertyChange(PROP_DIRTY);

    if (oldImage != null && !oldImage.isDisposed()) oldImage.dispose();
  }
  @SuppressWarnings("unused")
  private static IEditorPart openInEditor(URI file, boolean activate) throws PartInitException {

    UIInstrumentationBuilder instrumentation =
        UIInstrumentation.builder("EditorUtility.openInEditor-URI");
    try {

      if (file == null) {
        throwPartInitException(DartEditorMessages.EditorUtility_file_must_not_be_null);
      }

      instrumentation.data("File", file.getPath());
      instrumentation.metric("activate", activate);

      IWorkbenchPage p = DartToolsPlugin.getActivePage();
      if (p == null) {
        throwPartInitException(DartEditorMessages.EditorUtility_no_active_WorkbenchPage);
      }

      IEditorDescriptor desc =
          PlatformUI.getWorkbench().getEditorRegistry().getDefaultEditor(file.getPath());
      if (desc == null) {
        throwPartInitException(DartEditorMessages.EditorUtility_cantFindEditor + file.toString());
      }

      IEditorPart editorPart =
          IDE.openEditor(p, file, maybeSwapDefaultEditorDescriptor(desc.getId()), activate);
      initializeHighlightRange(editorPart);
      return editorPart;
    } catch (RuntimeException e) {
      instrumentation.metric("Exception", e.getClass().toString());
      instrumentation.data("Exception", e.toString());
      throw e;
    } finally {
      instrumentation.log();
    }
  }
Esempio n. 27
0
  /** Opens the given editor on the selected file revision. */
  protected void openEditor(IEditorDescriptor editorDescriptor, boolean openUsingDescriptor) {
    IFileRevision fileRevision = getFileRevision();
    if (fileRevision == null) {
      return;
    }
    try {
      IProgressMonitor monitor = new NullProgressMonitor();
      IStorage storage = fileRevision.getStorage(monitor);
      boolean isFile = storage instanceof IFile;

      if (openUsingDescriptor) {
        // discouraged access to open system editors
        ((WorkbenchPage) (page.getSite().getPage()))
            .openEditorFromDescriptor(
                isFile
                    ? new FileEditorInput((IFile) storage)
                    : (IEditorInput)
                        FileRevisionEditorInput.createEditorInputFor(fileRevision, monitor),
                editorDescriptor,
                true,
                null);
      } else {
        String editorId =
            editorDescriptor == null
                ? IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID
                : editorDescriptor.getId();
        page.getSite()
            .getPage()
            .openEditor(
                isFile
                    ? new FileEditorInput((IFile) storage)
                    : (IEditorInput)
                        FileRevisionEditorInput.createEditorInputFor(fileRevision, monitor),
                editorId,
                true,
                MATCH_BOTH);
      }
    } catch (PartInitException e) {
      StatusAdapter statusAdapter = new StatusAdapter(e.getStatus());
      statusAdapter.setProperty(
          IStatusAdapterConstants.TITLE_PROPERTY, TeamUIMessages.LocalHistoryPage_OpenEditorError);
      StatusManager.getManager().handle(statusAdapter, StatusManager.SHOW);
    } catch (CoreException e) {
      StatusAdapter statusAdapter = new StatusAdapter(e.getStatus());
      statusAdapter.setProperty(
          IStatusAdapterConstants.TITLE_PROPERTY, TeamUIMessages.LocalHistoryPage_OpenEditorError);
      StatusManager.getManager().handle(statusAdapter, StatusManager.LOG);
    }
  }
  private void openDirectory(StatusBean bean) {
    try {
      final IWorkbenchPage page = Util.getPage();

      final File fdir = new File(Util.getSanitizedPath(bean.getRunDirectory()));
      if (!fdir.exists()) {
        MessageDialog.openConfirm(
            getSite().getShell(),
            "Directory Not There",
            "The directory '"
                + bean.getRunDirectory()
                + "' has been moved or deleted.\n\nPlease contact your support representative.");
        return;
      }

      if (Util.isWindowsOS()) { // Open inside DAWN
        final String dir = fdir.getAbsolutePath();
        IEditorDescriptor desc =
            PlatformUI.getWorkbench().getEditorRegistry().getDefaultEditor(dir + "/fred.html");
        final IEditorInput edInput = Util.getExternalFileStoreEditorInput(dir);
        page.openEditor(edInput, desc.getId());

      } else { // Linux cannot be relied on to open the browser on a directory.
        Util.browse(fdir);
      }

    } catch (Exception e1) {
      ErrorDialog.openError(
          getSite().getShell(),
          "Internal Error",
          "Cannot open "
              + bean.getRunDirectory()
              + ".\n\nPlease contact your support representative.",
          new Status(IStatus.ERROR, Activator.PLUGIN_ID, e1.getMessage()));
    }
  }
  /**
   *
   * <!-- begin-user-doc -->
   * <!-- end-user-doc -->
   *
   * @generated
   */
  public static boolean openEditor(IWorkbench workbench, URI uri) {
    IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow();
    IWorkbenchPage page = workbenchWindow.getActivePage();

    IEditorDescriptor editorDescriptor = EditUIUtil.getDefaultEditor(uri, null);
    if (editorDescriptor == null) {
      MessageDialog.openError(
          workbenchWindow.getShell(),
          getString("_UI_Error_title"),
          getString("_WARN_No_Editor", uri.lastSegment()));
      return false;
    } else {
      try {
        page.openEditor(new URIEditorInput(uri), editorDescriptor.getId());
      } catch (PartInitException exception) {
        MessageDialog.openError(
            workbenchWindow.getShell(),
            getString("_UI_OpenEditorError_label"),
            exception.getMessage());
        return false;
      }
    }
    return true;
  }
Esempio n. 30
0
  public void fill(Menu menu, int index) {
    final IFileRevision fileRevision = getFileRevision();
    if (fileRevision == null) {
      return;
    }

    IEditorDescriptor defaultTextEditor =
        registry.findEditor("org.eclipse.ui.DefaultTextEditor"); // $NON-NLS-1$
    IEditorDescriptor preferredEditor = Utils.getDefaultEditor(fileRevision);

    Object[] editors = Utils.getEditors(fileRevision);
    Collections.sort(Arrays.asList(editors), comparer);
    boolean defaultFound = false;

    // Check that we don't add it twice. This is possible
    // if the same editor goes to two mappings.
    ArrayList alreadyMapped = new ArrayList();

    for (int i = 0; i < editors.length; i++) {
      IEditorDescriptor editor = (IEditorDescriptor) editors[i];
      if (!alreadyMapped.contains(editor)) {
        createMenuItem(menu, editor, preferredEditor);
        if (defaultTextEditor != null && editor.getId().equals(defaultTextEditor.getId())) {
          defaultFound = true;
        }
        alreadyMapped.add(editor);
      }
    }

    // Only add a separator if there is something to separate
    if (editors.length > 0) {
      new MenuItem(menu, SWT.SEPARATOR);
    }

    // Add default editor. Check it if it is saved as the preference.
    if (!defaultFound && defaultTextEditor != null) {
      createMenuItem(menu, defaultTextEditor, preferredEditor);
    }

    // TODO : We might perhaps enable inplace and system external editors menu items
    /*// Add system editor
    IEditorDescriptor descriptor = registry
    		.findEditor(IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID);
    final MenuItem systemEditorMenuItem = createMenuItem(menu, descriptor,
    		preferredEditor);
    systemEditorMenuItem.setEnabled(false);

    // Add system in-place editor
    descriptor = registry
    		.findEditor(IEditorRegistry.SYSTEM_INPLACE_EDITOR_ID);

    final MenuItem inPlaceEditorMenuItem = (descriptor != null) ? createMenuItem(
    		menu, descriptor, preferredEditor)
    		: null;
    if (inPlaceEditorMenuItem != null)
    	inPlaceEditorMenuItem.setEnabled(false);

    Job job = new Job("updateOpenWithMenu") { //$NON-NLS-1$
    	protected IStatus run(IProgressMonitor monitor) {
    		try {
    			final boolean isFile = fileRevision.getStorage(monitor) instanceof IFile;
    			Display.getDefault().asyncExec(new Runnable() {
    				public void run() {
    					if (inPlaceEditorMenuItem != null
    							&& !inPlaceEditorMenuItem.isDisposed())
    						inPlaceEditorMenuItem.setEnabled(isFile);
    					if (!systemEditorMenuItem.isDisposed())
    						systemEditorMenuItem.setEnabled(isFile);
    				}
    			});
    			return Status.OK_STATUS;
    		} catch (CoreException e) {
    			return new Status(IStatus.WARNING, TeamUIPlugin.ID, null, e);
    		}
    	};
    };
    job.setSystem(true);
    job.schedule();*/

    createDefaultMenuItem(menu, fileRevision);

    // add Other... menu item
    createOtherMenuItem(menu);
  }