/**
  * Returns the defined encoding for the given module.
  *
  * <pre>
  * The search for the encoding is done in this order:
  * 1. Check the encoding that is set specifically to a LocalModule.
  * 2. Check the workspace default charset.
  * 3. If all the above fails, get ResourcesPlugin.getEncoding(), which actually gets the encoding from the system.
  * </pre>
  *
  * @param module an {@link IModule}.
  * @return The module's encoding.
  */
 public static String getModuleEncoding(IModule module) {
   String charset = null;
   try {
     if (module instanceof LocalModule) {
       IFile file = ((LocalModule) module).getFile();
       if (file != null) {
         String fileCharset = file.getCharset(true);
         if (fileCharset != null) {
           charset = fileCharset;
         }
       }
     }
   } catch (Throwable e) {
     // If there is any error, return the default
     IdeLog.logInfo(
         PHPEditorPlugin.getDefault(),
         "PHP encoding utils - Returning the default encoding due to an error (getModuleEncoding)", //$NON-NLS-1$
         e,
         PHPEditorPlugin.DEBUG_SCOPE);
   }
   if (charset == null) {
     try {
       IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
       charset = workspaceRoot.getDefaultCharset(true);
     } catch (CoreException ce) {
       charset = WorkbenchEncoding.getWorkbenchDefaultEncoding();
     }
   }
   if (charset == null) {
     // Use the system's encoding
     charset = ResourcesPlugin.getEncoding();
   }
   return charset;
 }
Exemplo n.º 2
0
 /**
  * Locates a PHPDoc comment above the offset in the document specified. In case the given entry is
  * a parameter variable, the search for the documentation will include the documentation of the
  * parameter's wrapping function.
  *
  * @param entry
  * @param document
  * @param offset
  * @return A {@link PHPDocBlock}, or <code>null</code>.
  */
 public static PHPDocBlock findFunctionPHPDocComment(
     IElementEntry entry, IDocument document, int offset) {
   boolean isParameter =
       ((entry.getValue() instanceof VariablePHPEntryValue)
           && ((VariablePHPEntryValue) entry.getValue()).isParameter());
   if (entry.getModule() != null) {
     return findFunctionPHPDocComment(entry.getModule(), document, offset, isParameter);
   }
   // In case that the entry module is null, it's probably a PHP API documentation item, so
   // parse the right item.
   try {
     String entryPath = entry.getEntryPath();
     if (entryPath != null) {
       InputStream stream = PHPBuiltins.getInstance().getBuiltinResourceStream(entryPath);
       if (stream != null) {
         BufferedReader reader =
             new BufferedReader(new InputStreamReader(stream)); // $codepro.audit.disable
         // closeWhereCreated
         return innerParsePHPDoc(offset, reader, isParameter);
       }
     }
   } catch (Exception ex) {
     IdeLog.logError(
         PHPEditorPlugin.getDefault(), "Failed locating the PHP function doc", ex); // $NON-NLS-1$
     return null;
   }
   return null;
 }
Exemplo n.º 3
0
  public void updateTaskTags(
      final String contents, final Program program, final List<Comment> comments, IModule module) {
    try {
      if (module instanceof LocalModule) {
        LocalModule lm = (LocalModule) module;
        final IFile file = lm.getFile();
        // TODO get project level task tags/prefs when we support them.
        Collection<TaskTag> tags = TaskTag.getTaskTags();
        boolean isCaseSensitive = TaskTag.isCaseSensitive();
        program.setLineEndTable(Util.lineEndTable(new Document(contents)));

        // visit the comment nodes and parse for tasks!
        Collection<Task> tasks = new ArrayList<Task>();
        for (Comment comment : comments) {
          tasks.addAll(processCommentNode(program, contents, isCaseSensitive, tags, comment));
        }
        final Task[] finalTasks = tasks.toArray(new Task[tasks.size()]);
        IWorkspaceRunnable runnable =
            new IWorkspaceRunnable() {
              public void run(IProgressMonitor monitor) {
                doHandleErrorsJob(finalTasks, file);
              }
            };

        ResourcesPlugin.getWorkspace()
            .run(runnable, getMarkerRule(file), IWorkspace.AVOID_UPDATE, new NullProgressMonitor());
      }
    } catch (Exception e) {
      IdeLog.logWarning(
          PHPEditorPlugin.getDefault(),
          "Error updating the PHP task-tags.",
          e,
          PHPEditorPlugin.DEBUG_SCOPE); // $NON-NLS-1$
    }
  }
Exemplo n.º 4
0
  void doHandleErrorsJob(Task[] errors, IFile file) {
    synchronized (this) // prevent simultaneous error updates on the same file
    {
      if (ResourcesPlugin.getWorkspace().isTreeLocked()) {
        IdeLog.logWarning(
            PHPEditorPlugin.getDefault(),
            "Error updating the document errors. The workspace tree is locked.",
            PHPEditorPlugin.DEBUG_SCOPE); // $NON-NLS-1$
      }

      if (file == null || !file.exists()) {
        return;
      }
      int depth = IResource.DEPTH_INFINITE;
      try {

        IMarker[] problemMarkers = file.findMarkers(IMarker.TASK, true, depth);
        for (IMarker m : problemMarkers) {
          Object attribute2 = m.getAttribute(APTANA_TASK);
          if (attribute2 != null && attribute2.equals("true")) // $NON-NLS-1$
          {
            m.delete();
          }
        }
        for (Task t : errors) {
          IMarker problemMarker = file.createMarker(IMarker.TASK);
          problemMarker.setAttribute(IMarker.PRIORITY, t.getPriority());
          problemMarker.setAttribute(IMarker.CHAR_START, t.getStart());
          problemMarker.setAttribute(IMarker.CHAR_END, t.getEnd());
          problemMarker.setAttribute(APTANA_TASK, Boolean.TRUE.toString());
          problemMarker.setAttribute(IMarker.MESSAGE, t.getDescription());
          problemMarker.setAttribute(IMarker.LINE_NUMBER, t.getLineNumber());
        }
      } catch (Exception e) {
        IdeLog.logWarning(
            PHPEditorPlugin.getDefault(),
            "Error updating the PHP task-tags.",
            e,
            PHPEditorPlugin.DEBUG_SCOPE); // $NON-NLS-1$
      }
    }
  }
 /**
  * Select a PHP version.
  *
  * @param phpAlias The version alias.
  */
 private void setSelectedVersion(String phpAlias) {
   int index = PHPVersionConfigurationBlock.PHP_ALIASES.indexOf(phpAlias);
   if (index < 0) {
     IdeLog.logWarning(
         PHPEditorPlugin.getDefault(),
         "Unresolved PHP version: " + phpAlias,
         new Exception("Unresolved PHP version"),
         PHPEditorPlugin.DEBUG_SCOPE); // $NON-NLS-1$ //$NON-NLS-2$
     index = 0;
   }
   fPHPVersions.select(index);
 }
  /**
   * Constructs include path from one module to another.
   *
   * @param from - module to construct include path from.
   * @param to - module to construct include path to.
   * @return constructed include path
   */
  public static ConstructedIncludePath constructIncludePath(IModule from, IModule to) {
    IBuildPath fromBuildPath = from.getBuildPath();
    IBuildPath toBuildPath = to.getBuildPath();
    Set<IBuildPath> fromDependencies = fromBuildPath.getDependencies();
    if (fromDependencies.equals(toBuildPath)) {
      String includePath = constructPathFromRoot(to);
      return new ConstructedIncludePath(includePath, null, null);
    }
    // if "from" build-path directly depends from "to" build-path
    if (fromDependencies.contains(toBuildPath)) {
      String includePath = constructPathFromRoot(to);
      return new ConstructedIncludePath(includePath, null, null);
    } else {
      // for local modules using its project-based build-path instead of native module build-path
      if (to instanceof LocalModule) {
        IFile file = ((LocalModule) to).getFile();
        if (!file.isSynchronized(1)) {
          try {
            file.refreshLocal(1, new NullProgressMonitor());
            if (file.exists()) {
              IProject project = file.getProject();
              IBuildPath projectBuildPath =
                  BuildPathManager.getInstance().getBuildPathByResource(project);
              if (projectBuildPath != null) {
                IModule alternativeToModule = projectBuildPath.getModule(file);
                if (alternativeToModule != null) {
                  String includePath = constructPathFromRoot(alternativeToModule);
                  return new ConstructedIncludePath(includePath, fromBuildPath, projectBuildPath);
                }
              }
            }
          } catch (CoreException e) {
            IdeLog.logWarning(
                PHPEditorPlugin.getDefault(),
                "PHP Refactoring - Error while constructing an include-path (constructIncludePath)", //$NON-NLS-1$
                e,
                PHPEditorPlugin.DEBUG_SCOPE);
          }
        }
      }

      // in other case, using original build-paths for reporting unsatisfied state
      String includePath = constructPathFromRoot(to);
      return new ConstructedIncludePath(includePath, fromBuildPath, toBuildPath);
    }
  }
 /*
  * @seeorg.eclipse.ui.IWindowListener#windowActivated(org.eclipse.ui. IWorkbenchWindow)
  * @since 3.1
  */
 public void windowActivated(IWorkbenchWindow window) {
   if (window == editor.getEditorSite().getWorkbenchWindow()
       && fMarkOccurrenceAnnotations
       && editor.isActiveEditor()) {
     fForcedMarkOccurrencesSelection = editor.getSelectionProvider().getSelection();
     IModelElement sourceModule = editor.getSourceModule();
     if (sourceModule != null && sourceModule.getElementType() == IModelElement.MODULE) {
       try {
         updateOccurrenceAnnotations(
             (ITextSelection) fForcedMarkOccurrencesSelection,
             SharedASTProvider.getAST(
                 (ISourceModule) sourceModule,
                 SharedASTProvider.WAIT_NO,
                 editor.getProgressMonitor()));
       } catch (Exception e) {
         IdeLog.logError(
             PHPEditorPlugin.getDefault(), "PHP code-scanner - Update error", e); // $NON-NLS-1$
       }
     }
   }
 }
  protected void installOccurrencesFinder(boolean forceUpdate) {
    fMarkOccurrenceAnnotations = true;

    fPostSelectionListenerWithAST =
        new ISelectionListenerWithAST() {
          public void selectionChanged(
              IEditorPart part, ITextSelection selection, Program astRoot) {
            updateOccurrenceAnnotations(selection, astRoot);
          }
        };
    SelectionListenerWithASTManager.getDefault().addListener(editor, fPostSelectionListenerWithAST);
    if (forceUpdate && editor.getSelectionProvider() != null) {
      fForcedMarkOccurrencesSelection = editor.getSelectionProvider().getSelection();
      IModelElement source = editor.getSourceModule();
      if (source != null) {
        try {
          final Program ast =
              SharedASTProvider.getAST(
                  (ISourceModule) source, SharedASTProvider.WAIT_NO, editor.getProgressMonitor());
          updateOccurrenceAnnotations((ITextSelection) fForcedMarkOccurrencesSelection, ast);
        } catch (Exception e) {
          IdeLog.logError(
              PHPEditorPlugin.getDefault(),
              "Error installing the PHP occurrences finder",
              e); //$NON-NLS-1$
        }
      }
    }

    if (fOccurrencesFinderJobCanceler == null) {
      fOccurrencesFinderJobCanceler = new OccurrencesFinderJobCanceler();
      fOccurrencesFinderJobCanceler.install();
    }

    // TODO Do we need some way to hook into reconciling to force an update? Won't typing changed
    // the "selection"
    // anyhow?
  }
Exemplo n.º 9
0
  /**
   * Finds a PHPDoc comment above the offset in the source that is read from the given
   * BufferedReader.
   *
   * @param offset
   * @param reader
   * @param isParameter Indicate that the docs we are looking for are for a parameter.
   * @return
   * @throws IOException
   * @throws Exception
   */
  private static PHPDocBlock innerParsePHPDoc(
      int offset, BufferedReader reader, boolean isParameter)
      throws IOException, Exception // $codepro.audit.disable
      {
    StringBuffer moduleData = new StringBuffer();
    try {
      char[] buf = new char[1024];
      int numRead = 0;
      while ((numRead = reader.read(buf)) != -1) // $codepro.audit.disable
      {
        String readData = String.valueOf(buf, 0, numRead);
        moduleData.append(readData);
      }
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException e) {
          IdeLog.logWarning(
              PHPEditorPlugin.getDefault(),
              "Error closing a BufferedReader in the PDTPHPModuleIndexer",
              e, //$NON-NLS-1$
              PHPEditorPlugin.INDEXER_SCOPE);
        }
      }
    }

    String contents = moduleData.toString();
    int b = -1;
    for (int a = offset; a >= 0; a--) {
      char c = contents.charAt(a);
      if (c == '(') {
        b = a;
        break;
      }
      if (c == '\r' || c == '\n') {
        b = a;
        break;
      }
    }
    if (b != -1) {
      String str = contents.substring(b, offset);
      if (str.indexOf(';') == -1) {
        offset = b;
      }
      // System.out.println(str);
    }
    // TODO: Shalom - Get the version from the module?
    PHPVersion version = PHPVersionProvider.getDefaultPHPVersion();
    // TODO - Perhaps we'll need to pass a preference value for the 'short-tags' instead of passing
    // 'true' by
    // default.
    ASTParser parser =
        ASTParser.newParser(new StringReader(contents), version, true); // $codepro.audit.disable
    // closeWhereCreated
    Program program = parser.createAST(null);

    CommentsVisitor commentsVisitor = new CommentsVisitor();
    program.accept(commentsVisitor);
    List<Comment> _comments = commentsVisitor.getComments();

    PHPDocBlock docBlock = findPHPDocComment(_comments, offset, contents);
    if (docBlock == null && isParameter) {
      // We could not locate a doc right before the given offset, so we traverse up to locate the
      // docs for the
      // wrapping function. The includeWrappingFunction is true only when the entry we are looking
      // for is a
      // parameter variable, so there is a function that wraps it.
      ASTNode node = program.getElementAt(offset);
      if (node instanceof FunctionDeclaration) {
        offset = node.getStart();
        if (node.getParent() instanceof MethodDeclaration) {
          offset = node.getParent().getStart();
        }
        docBlock = findPHPDocComment(_comments, offset, contents);
      }
    }
    return docBlock;
  }