コード例 #1
0
  public void run(IAction action) {
    FastStringBuffer buf = new FastStringBuffer();
    try {
      PyEdit pyEdit = getPyEdit();

      PySelection pySelection = new PySelection(pyEdit);

      IPythonNature nature = pyEdit.getPythonNature();
      File editorFile = pyEdit.getEditorFile();

      if (editorFile != null) {
        if (nature != null) {
          String mod = nature.resolveModule(editorFile);
          if (mod != null) {
            buf.append(mod);

          } else {
            // Support for external files (not in PYTHONPATH).
            buf.append(FullRepIterable.getFirstPart(editorFile.getName()));
          }
        } else {
          buf.append(FullRepIterable.getFirstPart(editorFile.getName()));
        }
      }

      List<stmtType> path =
          FastParser.parseToKnowGloballyAccessiblePath(
              pySelection.getDoc(), pySelection.getStartLineIndex());
      for (stmtType stmtType : path) {
        if (buf.length() > 0) {
          buf.append('.');
        }
        buf.append(NodeUtils.getRepresentationString(stmtType));
      }

    } catch (MisconfigurationException e1) {
      Log.log(e1);
      return;
    }

    Transfer[] dataTypes = new Transfer[] {TextTransfer.getInstance()};
    Object[] data = new Object[] {buf.toString()};

    Clipboard clipboard = new Clipboard(EditorUtils.getShell().getDisplay());
    try {
      clipboard.setContents(data, dataTypes);
    } catch (SWTError e) {
      if (e.code != DND.ERROR_CANNOT_SET_CLIPBOARD) {
        throw e;
      }
      MessageDialog.openError(
          EditorUtils.getShell(), "Error copying to clipboard.", e.getMessage());
    } finally {
      clipboard.dispose();
    }
  }
コード例 #2
0
 private IInfo addAssignTargets(
     ASTEntry entry, String moduleName, int doOn, String path, boolean lastIsMethod) {
   String rep = NodeUtils.getFullRepresentationString(entry.node);
   if (lastIsMethod) {
     List<String> parts = StringUtils.dotSplit(rep);
     if (parts.size() >= 2) {
       // at least 2 parts are required
       if (parts.get(0).equals("self")) {
         rep = parts.get(1);
         // no intern construct (locked in the loop that calls this method)
         AttrInfo info =
             new AttrInfo(
                 ObjectsPool.internUnsynched(rep),
                 moduleName,
                 ObjectsPool.internUnsynched(path),
                 false);
         add(info, doOn);
         return info;
       }
     }
   } else {
     // no intern construct (locked in the loop that calls this method)
     AttrInfo info =
         new AttrInfo(
             ObjectsPool.internUnsynched(FullRepIterable.getFirstPart(rep)),
             moduleName,
             ObjectsPool.internUnsynched(path),
             false);
     add(info, doOn);
     return info;
   }
   return null;
 }
コード例 #3
0
ファイル: MessagesManager.java プロジェクト: alecmunro/Pydev
  /**
   * Checks if some token is actually undefined and changes its representation if needed
   *
   * @return a tuple indicating if it really is undefined and the representation that should be
   *     used.
   */
  protected Tuple<Boolean, String> isActuallyUndefined(IToken token, String rep) {
    String tokenRepresentation = token.getRepresentation();
    if (tokenRepresentation != null) {
      String firstPart = FullRepIterable.getFirstPart(tokenRepresentation);
      if (this.prefs.getTokensAlwaysInGlobals().contains(firstPart)) {
        return new Tuple<Boolean, String>(
            false, firstPart); // ok firstPart in not really undefined...
      }
    }

    boolean isActuallyUndefined = true;
    if (rep == null) {
      rep = tokenRepresentation;
    }

    int i;
    if ((i = rep.indexOf('.')) != -1) {
      rep = rep.substring(0, i);
    }

    String builtinType = NodeUtils.getBuiltinType(rep);
    if (builtinType != null) {
      isActuallyUndefined = false; // this is a builtin, so, it is defined after all
    }
    return new Tuple<Boolean, String>(isActuallyUndefined, rep);
  }
コード例 #4
0
ファイル: PyEditTitle.java プロジェクト: pmahoney/Pydev
  /**
   * @param input
   * @return a tuple with the part name to be used and a boolean indicating if the maximum level has
   *     been reached for this path.
   */
  private Tuple<String, Boolean> getPartNameInLevel(
      int level,
      IPath path,
      String initHandling,
      String djangoModulesHandling,
      IEditorInput input) {
    String classStr = input.getClass().toString();
    if (classStr.endsWith("RemoteFileStoreEditorInput") && classStr.indexOf("com.aptana") != -1) {
      return new Tuple<String, Boolean>(input.getName(), true);
    }
    String[] segments = path.segments();
    if (segments.length == 0) {
      return new Tuple<String, Boolean>("", true);
    }
    if (segments.length == 1) {
      return new Tuple<String, Boolean>(segments[1], true);
    }
    String lastSegment = segments[segments.length - 1];

    boolean handled = isDjangoHandledModule(djangoModulesHandling, input, lastSegment);
    if (handled
        && djangoModulesHandling
            == PyTitlePreferencesPage.TITLE_EDITOR_DJANGO_MODULES_SHOW_PARENT_AND_DECORATE) {
      String[] dest = new String[segments.length - 1];
      System.arraycopy(segments, 0, dest, 0, dest.length);
      segments = dest;

    } else if (initHandling != PyTitlePreferencesPage.TITLE_EDITOR_INIT_HANDLING_IN_TITLE) {
      if (lastSegment.startsWith("__init__.")) {
        // remove the __init__.
        String[] dest = new String[segments.length - 1];
        System.arraycopy(segments, 0, dest, 0, dest.length);
        segments = dest;
      }
    }

    int startAt = segments.length - level;
    if (startAt < 0) {
      startAt = 0;
    }

    int endAt = segments.length - 1;

    String modulePart = StringUtils.join(".", segments, startAt, endAt);

    String name = segments[segments.length - 1];
    if (!PyTitlePreferencesPage.getTitleShowExtension()) {
      String initial = name;
      name = FullRepIterable.getFirstPart(name);
      if (name.length() == 0) {
        name = initial;
      }
    }
    if (modulePart.length() > 0) {
      return new Tuple<String, Boolean>(name + " (" + modulePart + ")", startAt == 0);
    } else {
      return new Tuple<String, Boolean>(name, startAt == 0);
    }
  }
コード例 #5
0
ファイル: PyCodeCompletion.java プロジェクト: leosoto/Pydev
  /**
   * Does a code-completion that will retrieve the all matches for some token in the module
   *
   * @throws MisconfigurationException
   */
  private void doTokenCompletion(
      CompletionRequest request,
      ICodeCompletionASTManager astManager,
      List<Object> tokensList,
      String trimmed,
      ICompletionState state)
      throws CompletionRecursionException, MisconfigurationException {
    if (request.activationToken.endsWith(".")) {
      request.activationToken =
          request.activationToken.substring(0, request.activationToken.length() - 1);
    }

    final String initialActivationToken = request.activationToken;
    int parI = request.activationToken.indexOf('(');
    if (parI != -1) {
      request.activationToken = request.activationToken.substring(0, parI);
    }

    char[] toks = new char[] {'.', ' '};
    List<Object> completions = new ArrayList<Object>();

    boolean lookInGlobals = true;

    if (trimmed.equals("self") || FullRepIterable.getFirstPart(trimmed, toks).equals("self")) {
      lookInGlobals = !getSelfOrClsCompletions(request, tokensList, state, false, true, "self");

    } else if (trimmed.equals("cls") || FullRepIterable.getFirstPart(trimmed, toks).equals("cls")) {
      lookInGlobals = !getSelfOrClsCompletions(request, tokensList, state, false, true, "cls");
    }

    if (lookInGlobals) {
      state.setActivationToken(initialActivationToken);

      // Ok, looking for a token in globals.
      IToken[] comps = astManager.getCompletionsForToken(request.editorFile, request.doc, state);
      tokensList.addAll(Arrays.asList(comps));
    }
    tokensList.addAll(completions);
  }
コード例 #6
0
  /**
   * This method passes through all the java packages and calls the filter callback passed on each
   * package found.
   *
   * <p>If true is returned on the callback, the children of each package (classes) will also be
   * visited, otherwise, they'll be skipped.
   */
  private void filterJavaPackages(IFilter filter) {
    IClasspathEntry[] rawClasspath;
    try {
      rawClasspath = this.javaProject.getRawClasspath();
      FastStringBuffer buffer = new FastStringBuffer();
      for (IClasspathEntry entry : rawClasspath) {
        int entryKind = entry.getEntryKind();
        IClasspathEntry resolvedClasspathEntry = JavaCore.getResolvedClasspathEntry(entry);
        if (entryKind != IClasspathEntry.CPE_CONTAINER) {
          // ignore if it's in the system classpath...
          IPackageFragmentRoot[] roots =
              javaProject.findPackageFragmentRoots(resolvedClasspathEntry);

          // get the package roots
          for (IPackageFragmentRoot root : roots) {
            IJavaElement[] children = root.getChildren();

            // get the actual packages
            for (IJavaElement child : children) {
              IPackageFragment childPackage = (IPackageFragment) child;
              String elementName = childPackage.getElementName();

              // and if the java package is 'accepted'
              if (filter.accept(elementName, root, childPackage)) {
                buffer.clear();
                buffer.append(elementName);
                int packageNameLen = buffer.length();
                if (packageNameLen > 0) {
                  buffer.append('.');
                  packageNameLen++;
                }

                // traverse its classes
                for (IJavaElement class_ : childPackage.getChildren()) {
                  buffer.append(FullRepIterable.getFirstPart(class_.getElementName()));
                  filter.accept(buffer.toString(), root, class_);
                  buffer.setCount(
                      packageNameLen); // leave only the package part for the next append
                }
              }
            }
          }
        }
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
コード例 #7
0
 private IInfo addAssignTargets(
     ASTEntry entry, String moduleName, int doOn, String path, boolean lastIsMethod) {
   String rep = NodeUtils.getFullRepresentationString(entry.node);
   if (lastIsMethod) {
     List<String> parts = StringUtils.dotSplit(rep);
     if (parts.size() >= 2) {
       // at least 2 parts are required
       if (parts.get(0).equals("self")) {
         rep = parts.get(1);
         return addAttribute(rep, moduleName, doOn, path);
       }
     }
   } else {
     return addAttribute(FullRepIterable.getFirstPart(rep), moduleName, doOn, path);
   }
   return null;
 }
コード例 #8
0
 /**
  * Get the completions based on the arguments received
  *
  * @param state this is the state used for the completion
  * @param localScope this is the scope we're currently on (may be null)
  */
 public static Collection<AbstractToken> getCompletionsForTokenWithUndefinedType(
     CompletionState state, LocalScope localScope) {
   AbstractToken[] localTokens = localScope.getLocalTokens(-1, -1, false); // only to get the
   // args
   String activationToken = state.getActivationToken();
   String firstPart = FullRepIterable.getFirstPart(activationToken);
   for (AbstractToken token : localTokens) {
     if (token.getRepresentation().equals(firstPart)) {
       Collection<AbstractToken> interfaceForLocal =
           localScope.getInterfaceForLocal(state.getActivationToken());
       Collection<AbstractToken> argsCompletionFromParticipants =
           getCompletionsForTokenWithUndefinedTypeFromParticipants(
               state, localScope, interfaceForLocal);
       return argsCompletionFromParticipants;
     }
   }
   return getCompletionsForTokenWithUndefinedTypeFromParticipants(state, localScope, null);
 }
コード例 #9
0
 /**
  * Get the completions based on the arguments received
  *
  * @param state this is the state used for the completion
  * @param localScope this is the scope we're currently on (may be null)
  */
 public static Collection<AbstractToken> getCompletionsForMethodParameter(
     CompletionState state, LocalScope localScope) {
   AbstractToken[] args = localScope.getLocalTokens(-1, -1, true); // only to get the args
   String activationToken = state.getActivationToken();
   String firstPart = FullRepIterable.getFirstPart(activationToken);
   for (AbstractToken token : args) {
     if (token.getRepresentation().equals(firstPart)) {
       Collection<AbstractToken> interfaceForLocal =
           localScope.getInterfaceForLocal(state.getActivationToken());
       Collection<AbstractToken> argsCompletionFromParticipants =
           getCompletionsForMethodParameterFromParticipants(state, localScope, interfaceForLocal);
       for (AbstractToken t : interfaceForLocal) {
         if (!t.getRepresentation().equals(state.getQualifier())) {
           argsCompletionFromParticipants.add(t);
         }
       }
       return argsCompletionFromParticipants;
     }
   }
   return new ArrayList<AbstractToken>();
 }
コード例 #10
0
ファイル: LocalScope.java プロジェクト: GitAngel/Pydev
  public Collection<IToken> getInterfaceForLocal(
      String activationToken, boolean addAttributeAccess, boolean addLocalsFromHasAttr) {
    Set<SourceToken> comps = new HashSet<SourceToken>();

    Iterator<SimpleNode> it = this.scope.topDownIterator();
    if (!it.hasNext()) {
      return new ArrayList<IToken>();
    }

    SimpleNode element = it.next();

    String dottedActTok = activationToken + '.';
    // ok, that's the scope we have to analyze
    SequencialASTIteratorVisitor visitor = SequencialASTIteratorVisitor.create(element);

    ArrayList<Class> classes = new ArrayList<Class>(2);
    if (addAttributeAccess) {
      classes.add(Attribute.class);
    }
    if (addLocalsFromHasAttr) {
      classes.add(Call.class);
    }
    Iterator<ASTEntry> iterator = visitor.getIterator(classes.toArray(new Class[classes.size()]));

    while (iterator.hasNext()) {
      ASTEntry entry = iterator.next();
      if (entry.node instanceof Attribute) {
        String rep = NodeUtils.getFullRepresentationString(entry.node);
        if (rep.startsWith(dottedActTok)) {
          rep = rep.substring(dottedActTok.length());
          if (NodeUtils.isValidNameRepresentation(
              rep)) { // that'd be something that can happen when trying to recreate the parsing
            comps.add(
                new SourceToken(
                    entry.node,
                    FullRepIterable.getFirstPart(rep),
                    "",
                    "",
                    "",
                    IToken.TYPE_OBJECT_FOUND_INTERFACE));
          }
        }
      } else if (entry.node instanceof Call) {
        Call call = (Call) entry.node;
        if ("hasattr".equals(NodeUtils.getFullRepresentationString(call.func))
            && call.args != null
            && call.args.length == 2) {
          String rep = NodeUtils.getFullRepresentationString(call.args[0]);
          if (rep.equals(activationToken)) {
            exprType node = call.args[1];
            if (node instanceof Str) {
              Str str = (Str) node;
              String attrName = str.s;
              if (NodeUtils.isValidNameRepresentation(attrName)) {
                comps.add(
                    new SourceToken(
                        node, attrName, "", "", "", IToken.TYPE_OBJECT_FOUND_INTERFACE));
              }
            }
          }
        }
      }
    }
    return new ArrayList<IToken>(comps);
  }
コード例 #11
0
ファイル: CompiledModule.java プロジェクト: sffjunkie/Pydev
  /**
   * @param findInfo
   * @see
   *     org.python.pydev.editor.codecompletion.revisited.modules.AbstractModule#findDefinition(java.lang.String,
   *     int, int)
   */
  public Definition[] findDefinition(
      ICompletionState state, int line, int col, IPythonNature nature) throws Exception {
    String token = state.getActivationToken();

    if (TRACE_COMPILED_MODULES) {
      System.out.println("CompiledModule.findDefinition:" + token);
    }
    Definition[] found = this.definitionsFoundCache.getObj(token);
    if (found != null) {
      if (TRACE_COMPILED_MODULES) {
        System.out.println("CompiledModule.findDefinition: found in cache.");
      }
      return found;
    }

    AbstractShell shell = AbstractShell.getServerShell(nature, AbstractShell.COMPLETION_SHELL);
    synchronized (shell) {
      Tuple<String[], int[]> def =
          shell.getLineCol(
              this.name,
              token,
              nature
                  .getAstManager()
                  .getModulesManager()
                  .getCompletePythonPath(
                      nature.getProjectInterpreter(),
                      nature.getRelatedInterpreterManager())); // default
      if (def == null) {
        if (TRACE_COMPILED_MODULES) {
          System.out.println("CompiledModule.findDefinition:" + token + " = empty");
        }
        this.definitionsFoundCache.add(token, EMPTY_DEFINITION);
        return EMPTY_DEFINITION;
      }
      String fPath = def.o1[0];
      if (fPath.equals("None")) {
        if (TRACE_COMPILED_MODULES) {
          System.out.println("CompiledModule.findDefinition:" + token + " = None");
        }
        Definition[] definition =
            new Definition[] {new Definition(def.o2[0], def.o2[1], token, null, null, this)};
        this.definitionsFoundCache.add(token, definition);
        return definition;
      }
      File f = new File(fPath);
      String foundModName = nature.resolveModule(f);
      String foundAs = def.o1[1];

      IModule mod;
      if (foundModName == null) {
        // this can happen in a case where we have a definition that's found from a compiled file
        // which actually
        // maps to a file that's outside of the pythonpath known by Pydev.
        String n = FullRepIterable.getFirstPart(f.getName());
        mod = AbstractModule.createModule(n, f, nature, true);
      } else {
        mod = nature.getAstManager().getModule(foundModName, nature, true);
      }

      if (TRACE_COMPILED_MODULES) {
        System.out.println("CompiledModule.findDefinition: found at:" + mod.getName());
      }
      int foundLine = def.o2[0];
      if (foundLine == 0
          && foundAs != null
          && foundAs.length() > 0
          && mod != null
          && state.canStillCheckFindSourceFromCompiled(mod, foundAs)) {
        // TODO: The nature (and so the grammar to be used) must be defined by the file we'll parse
        // (so, we need to know the system modules manager that actually created it to know the
        // actual nature)
        IModule sourceMod =
            AbstractModule.createModuleFromDoc(
                mod.getName(), f, new Document(REF.getFileContents(f)), nature, true);
        if (sourceMod instanceof SourceModule) {
          Definition[] definitions =
              (Definition[])
                  sourceMod.findDefinition(state.getCopyWithActTok(foundAs), -1, -1, nature);
          if (definitions.length > 0) {
            this.definitionsFoundCache.add(token, definitions);
            return definitions;
          }
        }
      }
      if (mod == null) {
        mod = this;
      }
      int foundCol = def.o2[1];
      if (foundCol < 0) {
        foundCol = 0;
      }
      if (TRACE_COMPILED_MODULES) {
        System.out.println("CompiledModule.findDefinition: found compiled at:" + mod.getName());
      }
      Definition[] definitions =
          new Definition[] {new Definition(foundLine + 1, foundCol + 1, token, null, null, mod)};
      this.definitionsFoundCache.add(token, definitions);
      return definitions;
    }
  }