/*
   * (non-Javadoc)
   *
   * @see IJavaSearchScope#encloses(IModelElement)
   */
  public boolean encloses(IModelElement element) {
    IDLTKLanguageToolkit elementToolkit = DLTKLanguageManager.getLanguageToolkit(element);
    if (!toolkit.getNatureId().equals(elementToolkit.getNatureId())) {
      return false;
    }

    if (this.elements != null) {
      for (int i = 0, length = this.elements.size(); i < length; i++) {
        IModelElement scopeElement = this.elements.get(i);
        IModelElement searchedElement = element;
        while (searchedElement != null) {
          if (searchedElement.equals(scopeElement)) return true;
          searchedElement = searchedElement.getParent();
        }
      }
      return false;
    }
    IProjectFragment root = (IProjectFragment) element.getAncestor(IModelElement.PROJECT_FRAGMENT);
    if (root != null && root.isArchive()) {
      // external or internal archive
      IPath rootPath = root.getPath();
      String rootPathToString = rootPath.toString();
      IPath relativePath = getPath(element, true /* relative path */);
      return indexOf(rootPathToString, relativePath.toString()) >= 0;
    }
    // resource in workspace
    String fullResourcePathString = getPath(element, false /* full path */).toString();
    return indexOf(fullResourcePathString) >= 0;
  }
  private ISelection restoreSelectionState(IMemento memento) {
    if (memento == null) return null;

    IMemento childMem;
    childMem = memento.getChild(TAG_SELECTED_ELEMENTS);
    if (childMem != null) {
      ArrayList list = new ArrayList();
      IMemento[] elementMem = childMem.getChildren(TAG_SELECTED_ELEMENT);
      for (int i = 0; i < elementMem.length; i++) {
        String javaElementHandle = elementMem[i].getString(TAG_SELECTED_ELEMENT_PATH);
        if (javaElementHandle == null) {
          // logical package
          IMemento[] packagesMem = elementMem[i].getChildren(TAG_LOGICAL_PACKAGE);
          LogicalPackage lp = null;
          for (int j = 0; j < packagesMem.length; j++) {
            javaElementHandle = packagesMem[j].getString(TAG_SELECTED_ELEMENT_PATH);
            Object pack = DLTKCore.create(javaElementHandle);
            if (pack instanceof IScriptFolder && ((IScriptFolder) pack).exists()) {
              if (lp == null) lp = new LogicalPackage((IScriptFolder) pack);
              else lp.add((IScriptFolder) pack);
            }
          }
          if (lp != null) list.add(lp);
        } else {
          IModelElement element = DLTKCore.create(javaElementHandle);
          if (element != null && element.exists()) list.add(element);
        }
      }
      return new StructuredSelection(list);
    }
    return null;
  }
  void adjustInputAndSetSelection(Object o) {
    if (!(o instanceof IModelElement || o instanceof List)) {
      if (o == null) setInput(null);
      setSelection(StructuredSelection.EMPTY, true);
      return;
    }
    if (o instanceof IModelElement) {
      IModelElement je = (IModelElement) o;
      IModelElement elementToSelect = findElementToSelect(je);
      IModelElement newInput = findInputForJavaElement(je);
      IModelElement oldInput = null;
      if (getInput() instanceof IModelElement) oldInput = (IModelElement) getInput();

      if (elementToSelect == null
          && !isValidInput(newInput)
          && (newInput == null && !isAncestorOf(je, oldInput)))
        // Clear input
        setInput(null);
      else if (mustSetNewInput(elementToSelect, oldInput, newInput)) {
        // Adjust input to selection
        setInput(newInput);
      }

      if (elementToSelect != null && elementToSelect.exists())
        setSelection(new StructuredSelection(elementToSelect), true);
      else setSelection(StructuredSelection.EMPTY, true);
    } else {
      setSelection(new StructuredSelection(o), true);
      setInput(o);
    }
  }
 /**
  * Answers if the given <code>element</code> is a valid element for this part.
  *
  * @param element the object to test
  * @return <true> if the given element is a valid element
  */
 protected boolean isValidElement(Object element) {
   if (element instanceof IScriptFolder) {
     IModelElement parent = ((IScriptFolder) element).getParent();
     if (parent != null)
       return super.isValidElement(parent) || super.isValidElement(parent.getScriptProject());
   }
   return false;
 }
 /**
  * Compute if a new input must be set.
  *
  * @param elementToSelect the element to select
  * @param oldInput old input
  * @param newInput new input
  * @return <code>true</code> if the input has to be set
  * @since 3.0
  */
 private boolean mustSetNewInput(
     IModelElement elementToSelect, IModelElement oldInput, IModelElement newInput) {
   return (newInput == null || !newInput.equals(oldInput))
       && (elementToSelect == null
           || oldInput == null
           || (!((elementToSelect instanceof IPackageDeclaration)
               && (elementToSelect.getParent().equals(oldInput.getParent()))
               && (!isAncestorOf(getViewPartInput(), elementToSelect)))));
 }
 protected IModelElement findInputForJavaElement(IModelElement je) {
   // null check has to take place here as well (not only in
   // findInputForJavaElement(IJavaElement, boolean) since we
   // are accessing the Java element
   if (je == null) return null;
   if (je.getElementType() == IModelElement.PROJECT_FRAGMENT
       || je.getElementType() == IModelElement.SCRIPT_PROJECT)
     return findInputForJavaElement(je, true);
   else return findInputForJavaElement(je, false);
 }
 public boolean isModelChangesProvidedFor(IModelElement modelElement, String name) {
   IScriptProject project = modelElement.getScriptProject();
   if (!"ModelMembersq".equals(project.getElementName())) {
     return false;
   }
   if (modelElement.getElementType() == IModelElement.PROJECT_FRAGMENT) {
     return true;
   }
   return false;
 }
 @Override
 public void processDelta(IModelElementDelta delta) {
   if (this.needsInitialize) return;
   IModelElement element = delta.getElement();
   switch (element.getElementType()) {
     case IModelElement.SCRIPT_MODEL:
       IModelElementDelta[] children = delta.getAffectedChildren();
       for (int i = 0, length = children.length; i < length; i++) {
         IModelElementDelta child = children[i];
         this.processDelta(child);
       }
       break;
     case IModelElement.SCRIPT_PROJECT:
       int kind = delta.getKind();
       switch (kind) {
         case IModelElementDelta.ADDED:
         case IModelElementDelta.REMOVED:
           this.needsInitialize = true;
           break;
         case IModelElementDelta.CHANGED:
           int flags = delta.getFlags();
           if ((flags & IModelElementDelta.F_CLOSED) != 0
               || (flags & IModelElementDelta.F_OPENED) != 0) {
             this.needsInitialize = true;
           } else {
             children = delta.getAffectedChildren();
             for (int i = 0, length = children.length; i < length; i++) {
               IModelElementDelta child = children[i];
               this.processDelta(child);
             }
           }
           break;
       }
       break;
     case IModelElement.PROJECT_FRAGMENT:
       kind = delta.getKind();
       switch (kind) {
         case IModelElementDelta.ADDED:
         case IModelElementDelta.REMOVED:
           this.needsInitialize = true;
           break;
         case IModelElementDelta.CHANGED:
           int flags = delta.getFlags();
           if ((flags & IModelElementDelta.F_ADDED_TO_BUILDPATH) > 0
               || (flags & IModelElementDelta.F_REMOVED_FROM_BUILDPATH) > 0) {
             this.needsInitialize = true;
           }
           break;
       }
       break;
   }
 }
  /*
   * (non-Javadoc)
   *
   * @see org.eclipse.jdt.internal.ui.browsing.JavaBrowsingPart#findElementToSelect(org.eclipse.jdt.core.IJavaElement)
   */
  protected IModelElement findElementToSelect(IModelElement je) {
    if (je == null) return null;

    switch (je.getElementType()) {
      case IModelElement.SCRIPT_FOLDER:
        return je;
      case IModelElement.SOURCE_MODULE:
        return ((ISourceModule) je).getParent();
      case IModelElement.TYPE:
        return ((IType) je).getScriptFolder();
      default:
        return findElementToSelect(je.getParent());
    }
  }
  public void process(IProject project, String pattern) {
    // test code, right now, I used the PHPSearchEngine class cut from another project
    ///////// Note: there is an real library API org.eclipse.php.internal.core.util.PHPSearchEngine.
    // I need to check details
    System.out.println("begining a iteration for pattern " + pattern);
    String elementName = null;
    SearchMatch[] newMatches = null;
    SearchMatch[] matches =
        PHPSearchEngine.findMethodCall(pattern, PHPSearchEngine.createProjectScope(project));
    // must distinguish between method declaration and method call!!!!
    IModelElement iModelElement;
    Object obj = null;
    if (matches.length > 0) {
      for (SearchMatch match : matches) {
        obj = match.getElement();
        if (obj instanceof IModelElement) {
          iModelElement = (IModelElement) obj;
          elementName = iModelElement.getElementName();
          System.out.println(
              "iModelElement.getElementName() = "
                  + elementName
                  + " --path= "
                  + iModelElement.getPath().toString());
          if (!elementName.equals(
              pattern)) { // avoid recursive, or iterative method, temp implementation, should be
                          // modified!!!!
            pattern = elementName;
            System.out.println("begining next iteration");
            process(project, pattern);
            System.out.println("return from an iteration");
          } else { // it is recursive/iterative, we regard it as the top level method call (temp
                   // implementation!!!!!)
            System.out.println(
                "Top Level(recursive reason): "
                    + "iModelElement.getElementName() = "
                    + elementName
                    + " --path= "
                    + iModelElement.getPath().toString());
          }
        }
      }
    } else { // if there is no callers, then means it is the top level

      System.out.println("Top Level(real reason): " + "pattern = " + pattern);
    }
    System.out.println("end of an iteration");
  }
  /**
   * Returns all of the openables defined in the region of this type hierarchy. Returns a map from
   * IJavaProject to ArrayList of Openable
   */
  private HashMap determineOpenablesInRegion(IProgressMonitor monitor) {

    try {
      HashMap allOpenables = new HashMap();
      IModelElement[] roots = ((RegionBasedTypeHierarchy) this.hierarchy).region.getElements();
      int length = roots.length;
      if (monitor != null) {
        monitor.beginTask("", length); // $NON-NLS-1$
      }
      for (int i = 0; i < length; i++) {
        IModelElement root = roots[i];
        IScriptProject javaProject = root.getScriptProject();
        ArrayList openables = (ArrayList) allOpenables.get(javaProject);
        if (openables == null) {
          openables = new ArrayList();
          allOpenables.put(javaProject, openables);
        }
        switch (root.getElementType()) {
          case IModelElement.SCRIPT_PROJECT:
            injectAllOpenablesForJavaProject((IScriptProject) root, openables);
            break;
          case IModelElement.PROJECT_FRAGMENT:
            injectAllOpenablesForPackageFragmentRoot((IProjectFragment) root, openables);
            break;
          case IModelElement.SCRIPT_FOLDER:
            injectAllOpenablesForPackageFragment((IScriptFolder) root, openables);
            break;
          case IModelElement.SOURCE_MODULE:
            openables.add(root);
            break;
          case IModelElement.TYPE:
            IType type = (IType) root;
            openables.add(type.getSourceModule());
            break;
          default:
            break;
        }
        worked(monitor, 1);
      }
      return allOpenables;
    } finally {
      if (monitor != null) {
        monitor.done();
      }
    }
  }
  /* package */ void handleAffectedChildren(
      final IModelElementDelta delta,
      final IModelElement element,
      final Collection<Runnable> runnables)
      throws ModelException {
    int count = 0;

    IResourceDelta[] resourceDeltas = delta.getResourceDeltas();
    if (resourceDeltas != null) {
      for (int i = 0; i < resourceDeltas.length; i++) {
        int kind = resourceDeltas[i].getKind();
        if (kind == IResourceDelta.ADDED || kind == IResourceDelta.REMOVED) {
          count++;
        }
      }
    }
    IModelElementDelta[] affectedChildren = delta.getAffectedChildren();
    for (int i = 0; i < affectedChildren.length; i++) {
      int kind = affectedChildren[i].getKind();
      if (kind == IModelElementDelta.ADDED || kind == IModelElementDelta.REMOVED) {
        count++;
      }
    }

    if (count > 1) {
      // more than one child changed, refresh from here downwards
      if (element instanceof IScriptFolder) {
        // a package fragment might become non empty refresh from the
        // parent
        IModelElement parent = (IModelElement) internalGetParent(element);
        // 1GE8SI6: ITPJUI:WIN98 - Rename is not shown in Packages View
        // avoid posting a refresh to an invisible parent
        if (element.equals(fInput)) {
          postRefresh(element, ScriptExplorerContentProvider.ORIGINAL, element, runnables);
        } else {
          postRefresh(parent, ScriptExplorerContentProvider.PARENT, element, runnables);
        }
      } else if (element instanceof IProjectFragment) {
        Object toRefresh = internalGetParent(element);
        postRefresh(toRefresh, ScriptExplorerContentProvider.ORIGINAL, toRefresh, runnables);
      } else {
        postRefresh(element, ScriptExplorerContentProvider.ORIGINAL, element, runnables);
      }
      return;
    }
    if (resourceDeltas != null) {
      for (int i = 0; i < resourceDeltas.length; i++) {
        if (processResourceDelta(resourceDeltas[i], element, runnables)) {
          return; // early return, element got refreshed
        }
      }
    }
    for (int i = 0; i < affectedChildren.length; i++) {
      if (processDelta(affectedChildren[i], runnables)) {
        return; // early return, element got refreshed
      }
    }
  }
  protected IModelElement findInputForJavaElement(IModelElement je, boolean canChangeInputType) {
    if (je == null || !je.exists()) return null;

    if (isValidInput(je)) {

      // don't update if input must be project (i.e. project is used as
      // source folder)
      if (canChangeInputType)
        fLastInputWasProject = je.getElementType() == IModelElement.SCRIPT_PROJECT;
      return je;
    } else if (fLastInputWasProject) {
      IProjectFragment packageFragmentRoot =
          (IProjectFragment) je.getAncestor(IModelElement.PROJECT_FRAGMENT);
      if (!packageFragmentRoot.isExternal()) return je.getScriptProject();
    }

    return findInputForJavaElement(je.getParent(), canChangeInputType);
  }
  /*
   * Overridden from JavaBrowsingPart to handel LogicalPackages and tree
   * structure.
   *
   * @see org.eclipse.jdt.internal.ui.browsing.JavaBrowsingPart#adjustInputAndSetSelection(org.eclipse.jdt.core.IJavaElement)
   */
  void adjustInputAndSetSelection(IModelElement je) {

    IModelElement jElementToSelect = findElementToSelect(je);
    LogicalPackagesProvider p = (LogicalPackagesProvider) fWrappedViewer.getContentProvider();

    Object elementToSelect = jElementToSelect;
    if (jElementToSelect != null
        && jElementToSelect.getElementType() == IModelElement.SCRIPT_FOLDER) {
      IScriptFolder pkgFragment = (IScriptFolder) jElementToSelect;
      elementToSelect = p.findLogicalPackage(pkgFragment);
      if (elementToSelect == null) elementToSelect = pkgFragment;
    }

    IModelElement newInput = findInputForJavaElement(je);
    if (elementToSelect == null && !isValidInput(newInput)) setInput(null);
    else if (elementToSelect == null || getViewer().testFindItem(elementToSelect) == null) {

      // optimization, if you are in the same project but expansion hasn't
      // happened
      Object input = getViewer().getInput();
      if (elementToSelect != null && newInput != null) {
        if (newInput.equals(input)) {
          getViewer().reveal(elementToSelect);
          // Adjust input to selection
        } else {
          setInput(newInput);
          getViewer().reveal(elementToSelect);
        }
      } else setInput(newInput);

      if (elementToSelect instanceof IScriptFolder) {
        IScriptFolder pkgFragment = (IScriptFolder) elementToSelect;
        elementToSelect = p.findLogicalPackage(pkgFragment);
        if (elementToSelect == null) elementToSelect = pkgFragment;
      }
    }

    ISelection selection;
    if (elementToSelect != null) selection = new StructuredSelection(elementToSelect);
    else selection = StructuredSelection.EMPTY;
    setSelection(selection, true);
  }
 private static IScriptFolder findSinglePackageChild(
     final IScriptFolder fragment, final IModelElement[] children) {
   String prefix = fragment.getElementName() + IScriptFolder.PACKAGE_DELIMITER;
   int prefixLen = prefix.length();
   IScriptFolder found = null;
   for (int i = 0; i < children.length; i++) {
     IModelElement element = children[i];
     String name = element.getElementName();
     if (name.startsWith(prefix)
         && name.length() > prefixLen
         && name.indexOf(IScriptFolder.PACKAGE_DELIMITER, prefixLen) == -1) {
       if (found == null) {
         found = (IScriptFolder) element;
       } else {
         return null;
       }
     }
   }
   return found;
 }
 public static SearchPattern createOrPattern(
     IModelElement[] elements, int limitTo, IDLTKLanguageToolkit toolkit) {
   if (elements == null || elements.length == 0) return null;
   Set<IModelElement> set = new HashSet<IModelElement>(Arrays.asList(elements));
   Iterator<IModelElement> iter = set.iterator();
   IModelElement first = iter.next();
   SearchPattern pattern =
       SearchPattern.createPattern(
           first, limitTo, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE, toolkit);
   if (pattern == null) // check for bug 90138
   throw new IllegalArgumentException(
         "Invalid element: "
             + first.getHandleIdentifier()
             + "\n"
             + first.toString()); // $NON-NLS-1$ //$NON-NLS-2$
   while (iter.hasNext()) {
     IModelElement each = (IModelElement) iter.next();
     SearchPattern nextPattern =
         SearchPattern.createPattern(
             each, limitTo, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE, toolkit);
     if (nextPattern == null) // check for bug 90138
     throw new IllegalArgumentException(
           "Invalid element: "
               + each.getHandleIdentifier()
               + "\n"
               + each.toString()); // $NON-NLS-1$ //$NON-NLS-2$
     pattern = SearchPattern.createOrPattern(pattern, nextPattern);
   }
   return pattern;
 }
 public void processDelta(IModelElementDelta delta) {
   switch (delta.getKind()) {
     case IModelElementDelta.CHANGED:
       IModelElementDelta[] children = delta.getAffectedChildren();
       for (int i = 0, length = children.length; i < length; i++) {
         IModelElementDelta child = children[i];
         this.processDelta(child);
       }
       break;
     case IModelElementDelta.REMOVED:
       IModelElement element = delta.getElement();
       if (this.encloses(element)) {
         if (this.elements != null) {
           this.elements.remove(element);
         }
         IPath path = null;
         switch (element.getElementType()) {
           case IModelElement.SCRIPT_PROJECT:
             path = ((IScriptProject) element).getProject().getFullPath();
           case IModelElement.PROJECT_FRAGMENT:
             if (path == null) {
               path = ((IProjectFragment) element).getPath();
             }
             int toRemove = -1;
             for (int i = 0; i < this.pathsCount; i++) {
               if (this.relativePaths[i].equals(path.toString())) {
                 toRemove = i;
                 break;
               }
             }
             if (toRemove != -1) {
               this.relativePaths[toRemove] = null;
               rehash();
             }
         }
       }
       break;
   }
 }
  @Override
  protected IScriptCompletionProposal createScriptCompletionProposal(CompletionProposal proposal) {

    IModelElement element = proposal.getModelElement();

    if (element == null) {
      return null;
    }

    // creates a proposal for a route
    if (element.getClass() == Tag.class) {
      return createTagProposal(proposal);
    } else if (element.getClass() == Filter.class) {
      return createFilterProposal(proposal);
    } else if (element.getClass() == Function.class) {
      return createFunctionProposal(proposal);
    } else if (element.getClass() == Test.class) {
      return createTestProposal(proposal);
    }

    return super.createScriptCompletionProposal(proposal);
  }
  public static boolean isLanguageModelElement(IModelElement element) {
    if (element != null) {
      final IProjectFragment fragment =
          (IProjectFragment) element.getAncestor(IModelElement.PROJECT_FRAGMENT);
      if (fragment != null && fragment.isExternal()) {
        final IPath path = fragment.getPath();

        // see getTargetLocation() below for description:
        if (path.segmentCount() > 2) {
          return "__language__".equals(path.segment(path.segmentCount() - 2));
        }
      }
    }
    return false;
  }
 private IPath getPath(IModelElement element, boolean relativeToRoot) {
   switch (element.getElementType()) {
     case IModelElement.SCRIPT_MODEL:
       return Path.EMPTY;
     case IModelElement.SCRIPT_PROJECT:
       return element.getPath();
     case IModelElement.PROJECT_FRAGMENT:
       if (relativeToRoot) return Path.EMPTY;
       return element.getPath();
     case IModelElement.SCRIPT_FOLDER:
       String relativePath = element.getElementName() + '/';
       return getPath(element.getParent(), relativeToRoot).append(new Path(relativePath));
     case IModelElement.SOURCE_MODULE:
       return getPath(element.getParent(), relativeToRoot)
           .append(new Path(element.getElementName()));
     default:
       return getPath(element.getParent(), relativeToRoot);
   }
 }
  private static boolean hasReadOnlyResourcesAndSubResources(IModelElement modelElement)
      throws CoreException {
    switch (modelElement.getElementType()) {
      case IModelElement.SOURCE_MODULE:
        IResource resource = ReorgUtils.getResource(modelElement);
        return (resource != null && Resources.isReadOnly(resource));
      case IModelElement.SCRIPT_FOLDER:
        IResource packResource = ReorgUtils.getResource(modelElement);
        if (packResource == null) return false;
        IScriptFolder pack = (IScriptFolder) modelElement;
        if (Resources.isReadOnly(packResource)) return true;
        Object[] nonScript = pack.getForeignResources();
        for (int i = 0; i < nonScript.length; i++) {
          Object object = nonScript[i];
          if (object instanceof IResource
              && hasReadOnlyResourcesAndSubResources((IResource) object)) return true;
        }
        return hasReadOnlyResourcesAndSubResources(pack.getChildren());
      case IModelElement.PROJECT_FRAGMENT:
        IProjectFragment root = (IProjectFragment) modelElement;
        if (root.isArchive()) return false;
        IResource pfrResource = ReorgUtils.getResource(modelElement);
        if (pfrResource == null) return false;
        if (Resources.isReadOnly(pfrResource)) return true;
        Object[] nonScript1 = root.getForeignResources();
        for (int i = 0; i < nonScript1.length; i++) {
          Object object = nonScript1[i];
          if (object instanceof IResource
              && hasReadOnlyResourcesAndSubResources((IResource) object)) return true;
        }
        return hasReadOnlyResourcesAndSubResources(root.getChildren());

      case IModelElement.FIELD:
        //			case IModelElement.IMPORT_CONTAINER:
        //			case IModelElement.IMPORT_DECLARATION:
        //			case IModelElement.INITIALIZER:
      case IModelElement.METHOD:
        //			case IModelElement.PACKAGE_DECLARATION:
      case IModelElement.TYPE:
        return false;
      default:
        Assert.isTrue(false); // not handled here
        return false;
    }
  }
 public void provideModelChanges(IModelElement parentElement, List children) {
   IScriptProject project = parentElement.getScriptProject();
   if (!"ModelMembersq".equals(project.getElementName())) {
     return;
   }
   switch (parentElement.getElementType()) {
     case IModelElement.PROJECT_FRAGMENT:
       List addon = new ArrayList();
       for (Iterator iterator = children.iterator(); iterator.hasNext(); ) {
         IModelElement el = (IModelElement) iterator.next();
         if (el.getElementType() == IModelElement.SCRIPT_FOLDER) {
           addon.add(
               new TestFolder(
                   (ModelElement) parentElement,
                   el.getPath().removeFirstSegments(el.getParent().getPath().segmentCount())));
         }
       }
       children.addAll(addon);
       break;
     case IModelElement.SCRIPT_FOLDER:
       break;
   }
 }
 private boolean internalIsAncestorOf(IModelElement ancestor, IModelElement element) {
   if (element != null)
     return element.equals(ancestor) || internalIsAncestorOf(ancestor, element.getParent());
   else return false;
 }
 /**
  * Finds the closest Java element which can be used as input for this part and has the given Java
  * element as child
  *
  * @param je the Java element for which to search the closest input
  * @return the closest Java element used as input for this part
  */
 protected IModelElement findInputForJavaElement(IModelElement je) {
   if (je == null || !je.exists()) return null;
   if (isValidInput(je)) return je;
   return findInputForJavaElement(je.getParent());
 }
  @Override
  public Image getImage(Object element) {
    IModelElement modelElement = null;
    if (element instanceof ExternalProjectFragment) {
      return PHPPluginImages.get(PHPPluginImages.IMG_OBJS_LIBRARY);
    }

    if (element instanceof IncludePath) {
      Object entry = ((IncludePath) element).getEntry();

      // An included PHP project
      if (entry instanceof IBuildpathEntry) {
        int entryKind = ((IBuildpathEntry) entry).getEntryKind();
        if (entryKind == IBuildpathEntry.BPE_PROJECT) {
          return PHPPluginImages.get(PHPPluginImages.IMG_OBJS_PHP_PROJECT);
        }
        // A library
        if (entryKind == IBuildpathEntry.BPE_LIBRARY
            || entryKind == IBuildpathEntry.BPE_CONTAINER) {
          return PHPPluginImages.get(PHPPluginImages.IMG_OBJS_LIBRARY);
        }
      }

      if (entry instanceof ExternalProjectFragment) {
        return PHPPluginImages.get(PHPPluginImages.IMG_OBJS_LIBRARY);
      }

      // Folder in the include path, should have same image as in the PHP
      // Explorer .
      if (entry instanceof IFolder) {
        IModelElement createdScriptFolder = DLTKCore.create((IFolder) entry);
        if (null == createdScriptFolder) return getImage(entry);
        return getImage(createdScriptFolder);
      }

      if (entry instanceof IResource) {
        return (getImage((IResource) entry));
      }
      return null;
    }

    if (element instanceof IResource) {
      modelElement = DLTKCore.create((IResource) element);
    } else if (element instanceof IModelElement) {
      modelElement = (IModelElement) element;
    }

    if (modelElement != null) {
      IScriptProject project = modelElement.getScriptProject();
      if (!project.isOnBuildpath(modelElement)) { // not in build path,
        // hence: hollow,
        // non-pakg icons
        if (modelElement.getElementType() == IModelElement.SOURCE_MODULE)
          return PHPPluginImages.get(PHPPluginImages.IMG_OBJS_CUNIT_RESOURCE);
        if (modelElement.getElementType() == IModelElement.PROJECT_FRAGMENT
            || modelElement.getElementType() == IModelElement.SCRIPT_FOLDER)
          return PHPPluginImages.get(PHPPluginImages.IMG_OBJS_PHP_FOLDER);
      } else { // in build path ...
        if (modelElement.getElementType() == IModelElement.SCRIPT_FOLDER
            || element instanceof IFolder)
          return PHPPluginImages.get(PHPPluginImages.IMG_OBJS_PHPFOLDER_ROOT);
      }
    }
    try {
      if (element instanceof IType && PHPFlags.isTrait(((IType) element).getFlags())) {
        return PHPPluginImages.get(PHPPluginImages.IMG_OBJS_TRAIT);
      }
    } catch (ModelException e) {
    }

    if (element != null) {
      for (ILabelProvider provider :
          TreeContentProviderRegistry.getInstance().getLabelProviders()) {
        Image image = provider.getImage(element);

        if (image != null) {
          return image;
        }
      }
    }

    return super.getImage(element);
  }
  @SuppressWarnings("rawtypes")
  @Override
  public Object execute(ExecutionEvent event) throws ExecutionException {

    IModelElement element = getCurrentModelElement(event);

    if (element == null) {
      return null;
    }

    if (!(element instanceof SourceType)) {
      while (element.getParent() != null) {
        element = element.getParent();
        if (element instanceof SourceType) {
          break;
        }
      }
    }

    if (element == null || !(element instanceof SourceType)) {
      return null;
    }

    type = (SourceType) element;

    try {

      if (type.getFields().length == 0) return null;

      initialize(event, element);

      Map fields = getFields();
      final Shell p = DLTKUIPlugin.getActiveWorkbenchShell();
      GetterSetterContentProvider cp = new GetterSetterContentProvider(fields);
      GetterSetterDialog dialog =
          new GetterSetterDialog(p, new GetterSetterLabelProvider(), cp, type);

      dialog.setContainerMode(true);
      dialog.setInput(type);
      dialog.setTitle("Generate Getters and Setters");

      if (dialog.open() == Window.OK) {

        List<GetterSetterEntry> entries = new ArrayList<GetterSetterEntry>();
        Object[] dialogResult = dialog.getResult();

        for (Object o : dialogResult) {
          if (o instanceof GetterSetterEntry) {
            entries.add((GetterSetterEntry) o);
          }
        }

        insertFirst = false;
        insertAfter = null;

        if (dialog.insertAsFirstMember()) insertFirst = true;
        else if (dialog.insertAsLastMember()) {
        } else insertAfter = dialog.getInsertionPoint();

        generate(entries, dialog.getModifier(), dialog.doGenerateComments());
      }

    } catch (Exception e) {
      e.printStackTrace();
    }

    return null;
  }
  @Override
  public void apply(ICompletionReporter reporter) throws BadLocationException {

    ViewPathArgumentContext context = (ViewPathArgumentContext) getContext();
    CompletionRequestor req = context.getCompletionRequestor();

    if (req.getClass() == PHPCompletionProposalCollector.class) {
      return;
    }

    if (workaroundCount == 0) {
      workaroundCount++;

    } else {
      workaroundCount = 0;
      return;
    }

    SymfonyModelAccess model = SymfonyModelAccess.getDefault();
    ISourceModule module = context.getSourceModule();
    ViewPath viewPath = context.getViewPath();

    String bundle = viewPath.getBundle();
    String controller = viewPath.getController();
    String template = viewPath.getTemplate();
    SourceRange range = getReplacementRange(context);
    IDLTKSearchScope projectScope =
        SearchEngine.createSearchScope(context.getSourceModule().getScriptProject());

    String prefix = context.getPrefix();

    // complete the bundle part
    if (bundle == null && controller == null && template == null) {

      List<Bundle> bundles = model.findBundles(context.getSourceModule().getScriptProject());

      for (Bundle b : bundles) {

        IType[] bundleTypes =
            PhpModelAccess.getDefault()
                .findTypes(b.getElementName(), MatchRule.EXACT, 0, 0, projectScope, null);

        if (bundleTypes.length == 1) {

          ModelElement bType = (ModelElement) bundleTypes[0];

          if (CodeAssistUtils.startsWithIgnoreCase(bType.getElementName(), prefix)) {
            Bundle bundleType = new Bundle(bType, b.getElementName());
            reporter.reportType(bundleType, ":", range);
          }
        }
      }

      // complete the controller part: "Bundle:|
    } else if (controller == null && template == null) {

      IType[] controllers = model.findBundleControllers(bundle, module.getScriptProject());

      if (controllers != null) {
        for (IType ctrl : controllers) {

          String name = ctrl.getElementName().replace("Controller", "");
          if (!name.endsWith("\\")) {
            Controller con = new Controller((ModelElement) ctrl, name);
            reporter.reportType(con, ":", range);
          }
        }
      }

      // complete template path: "Bundle:Controller:|
    } else if (bundle != null && controller != null && template == null) {

      IModelElement[] templates =
          model.findTemplates(bundle, controller, module.getScriptProject());

      if (templates != null) {
        for (IModelElement tpl : templates) {

          if (CodeAssistUtils.startsWithIgnoreCase(tpl.getElementName(), prefix)) {
            Template t = new Template((ModelElement) tpl, tpl.getElementName());
            reporter.reportType(t, "", range);
          }
        }
      }

      // project root: "::|
    } else if (bundle == null && controller == null && template != null) {

      IModelElement[] templates = model.findRootTemplates(module.getScriptProject());

      if (templates != null) {
        for (IModelElement tpl : templates) {

          if (CodeAssistUtils.startsWithIgnoreCase(tpl.getElementName(), prefix)) {
            Template t = new Template((ModelElement) tpl, tpl.getElementName());
            reporter.reportType(t, "", range);
          }
        }
      }

      // bundle root: "AcmeDemoBundle::|
    } else if (bundle != null && controller == null && template != null) {

      IModelElement[] templates = model.findBundleRootTemplates(bundle, module.getScriptProject());

      if (templates != null) {
        for (IModelElement tpl : templates) {

          if (CodeAssistUtils.startsWithIgnoreCase(tpl.getElementName(), prefix)) {
            Template t = new Template((ModelElement) tpl, tpl.getElementName());
            reporter.reportType(t, "", range);
          }
        }
      }
    }
  }
  /**
   * Get IMember from Item <br>
   * AST => DLTK Model
   */
  public static IMember getIMember(ISourceModule sourceModule, Item item) {
    LuaASTNode parent = item.getParent();
    if (LuaASTUtils.isTypeField(item)) {
      // support record field
      IType iType = getIType(sourceModule, (RecordTypeDef) parent);
      if (iType != null) {
        try {
          for (IModelElement child : iType.getChildren()) {
            if (child.getElementName().equals(item.getName()) && child instanceof IMember)
              return (IMember) child;
          }
        } catch (ModelException e) {
          Activator.logWarning(
              "unable to get IMember corresponding to the given item " + item, e); // $NON-NLS-1$
        }
      }
    } else if (LuaASTUtils.isLocal(item)) {
      // TODO retrieve local var which are in the model (so the local var in the first block)
      // support local variable
      // ------------------------------------------------------------------------------------

      // manage method
      TypeDef resolvedtype = LuaASTUtils.resolveTypeLocaly(sourceModule, item);
      if (resolvedtype != null && resolvedtype instanceof FunctionTypeDef) {
        FunctionTypeDef functionResolvedType = (FunctionTypeDef) resolvedtype;
        String[] parametersName = new String[functionResolvedType.getParameters().size()];
        for (int i = 0; i < parametersName.length; i++) {
          parametersName[i] = functionResolvedType.getParameters().get(i).getName();
        }
        return new FakeMethod(
            sourceModule,
            item.getName(),
            item.sourceStart(),
            item.getName().length(),
            parametersName,
            Declaration.AccPrivate,
            item);
      }
      // manage field
      return new FakeField(
          sourceModule,
          item.getName(),
          item.sourceStart(),
          item.getName().length(),
          Declaration.AccPrivate,
          item);
    } else if (LuaASTUtils.isGlobal(item)) {
      // support global var
      try {
        for (IModelElement child : sourceModule.getChildren()) {
          if (child.getElementName().equals(item.getName()) && child instanceof IMember)
            return (IMember) child;
        }
      } catch (ModelException e) {
        Activator.logWarning(
            "unable to get IMember corresponding to the given item " + item, e); // $NON-NLS-1$
      }
    } else if (LuaASTUtils.isUnresolvedGlobal(item)) {
      return new FakeField(
          sourceModule,
          item.getName(),
          item.sourceStart(),
          item.getName().length(),
          Declaration.AccGlobal,
          item);
    }
    return null;
  }
  private void initRelativeNamespace(ISourceModule sourceModule, int offset, String lastWord) {
    String nsName = lastWord;
    String fullName = lastWord;
    nsPrefix = null;
    if (lastWord.lastIndexOf(NamespaceReference.NAMESPACE_SEPARATOR) > 0) {
      nsPrefix =
          lastWord.substring(0, lastWord.lastIndexOf(NamespaceReference.NAMESPACE_SEPARATOR));
      nsName = nsName.substring(0, nsName.lastIndexOf(NamespaceReference.NAMESPACE_SEPARATOR) + 1);

      try {
        namespaces = PHPModelUtils.getNamespaceOf(nsName, sourceModule, offset, null, null);
      } catch (ModelException e) {
        if (DLTKCore.DEBUG) {
          e.printStackTrace();
        }
      }
    } else {
      namespaces = PhpModelAccess.NULL_TYPES;
    }
    if (lastWord.startsWith(NamespaceReference.NAMESPACE_DELIMITER)) {
      nsPrefix = null;
    } else {

      currentNS = null;
      try {
        IModelElement enclosingElement = getEnclosingElement();
        if (enclosingElement != null) {
          IType type = (IType) enclosingElement.getAncestor(IModelElement.TYPE);
          if (type != null && type.getParent() instanceof IType) {
            type = (IType) type.getParent();
          }
          if (type != null && (PHPFlags.isNamespace(type.getFlags()))) {
            currentNS = type;
            fullName =
                NamespaceReference.NAMESPACE_SEPARATOR
                    + currentNS.getElementName()
                    + NamespaceReference.NAMESPACE_SEPARATOR
                    + lastWord;
          } else {

          }
        }
      } catch (ModelException e1) {
        e1.printStackTrace();
      }
      if (currentNS != null) {
        if (nsPrefix == null) {
          nsPrefix = currentNS.getElementName();
        } else {
          nsPrefix = currentNS.getElementName() + NamespaceReference.NAMESPACE_SEPARATOR + nsPrefix;
        }
      }
    }

    IDLTKSearchScope scope = SearchEngine.createSearchScope(sourceModule.getScriptProject());
    if (fullName.startsWith(NamespaceReference.NAMESPACE_DELIMITER)) {
      fullName = fullName.substring(1);
    }
    possibleNamespaces =
        PhpModelAccess.getDefault()
            .findNamespaces(null, fullName, MatchRule.PREFIX, 0, 0, scope, null);
  }
 /**
  * Returns the package fragment root corresponding to a given resource path.
  *
  * @param resourcePathString path of expected package fragment root.
  * @return the {@link IProjectFragment package fragment root} which path match the given one or
  *     <code>null</code> if none was found.
  */
 public IProjectFragment projectFragment(String resourcePathString) {
   int index = -1;
   int separatorIndex = resourcePathString.indexOf(FILE_ENTRY_SEPARATOR);
   boolean isZIPFile = separatorIndex != -1;
   boolean isSpecial = resourcePathString.startsWith(IBuildpathEntry.BUILDPATH_SPECIAL);
   if (isZIPFile) {
     // internal or external jar (case 3, 4, or 5)
     String zipPath = resourcePathString.substring(0, separatorIndex);
     String relativePath = resourcePathString.substring(separatorIndex + 1);
     index = indexOf(zipPath, relativePath);
   } else {
     // resource in workspace (case 1 or 2)
     index = indexOf(resourcePathString);
   }
   if (index >= 0) {
     int idx = projectIndexes[index];
     String projectPath = idx == -1 ? null : (String) this.projectPaths.get(idx);
     if (projectPath != null) {
       IScriptProject project =
           DLTKCore.create(ResourcesPlugin.getWorkspace().getRoot().getProject(projectPath));
       if (isZIPFile) {
         return project.getProjectFragment(this.containerPaths[index]);
       }
       if (isSpecial) {
         return project.getProjectFragment(this.containerPaths[index]);
       }
       Object target =
           Model.getTarget(
               ResourcesPlugin.getWorkspace().getRoot(),
               Path.fromPortableString(
                   this.containerPaths[index] + '/' + this.relativePaths[index]),
               false);
       if (target instanceof IProject) {
         return project.getProjectFragment((IProject) target);
       }
       if (target instanceof IResource) {
         IModelElement element = DLTKCore.create((IResource) target);
         return (IProjectFragment) element.getAncestor(IModelElement.PROJECT_FRAGMENT);
       }
       if (target instanceof IFileHandle) {
         try {
           IProjectFragment[] fragments = project.getProjectFragments();
           IFileHandle t = (IFileHandle) target;
           IPath absPath = t.getFullPath();
           for (int i = 0; i < fragments.length; ++i) {
             IProjectFragment f = fragments[i];
             if (f.isExternal()) {
               IPath pPath = f.getPath();
               if (pPath.isPrefixOf(absPath) && !Util.isExcluded(absPath, f, t.isDirectory())) {
                 return f;
               }
             }
           }
         } catch (ModelException e) {
           e.printStackTrace();
           return null;
         }
       }
     }
   }
   return null;
 }