@Override public Change createChange(IProgressMonitor monitor) throws CoreException, OperationCanceledException { IFolder assetsFolder = resource.getProject().getFolder("assets"); if (assetsFolder == null || !assetsFolder.exists()) { return null; } if (!"assets".equals(resource.getProjectRelativePath().segment(0))) { return null; } if (resource instanceof IFile && Assets.getAssetType(resource.getName()) == null) { return null; } IResource[] rootResources = RefractoringUtils.getSearchScopeRootResources(resource.getProject()); if (Values.isEmpty(rootResources)) { return null; } IPath assetsFolderPath = assetsFolder.getProjectRelativePath(); IPath oldResourcePath = resource.getProjectRelativePath().makeRelativeTo(assetsFolderPath); String newName = getArguments().getNewName(); IPath newResourcePath = oldResourcePath.removeLastSegments(1).append(newName); String regex = "(?<=[[:|\\s|\\r|\\n]{1}[\\s|\\r|\\n]{0,100}]|^)" + Pattern.quote(oldResourcePath.toString()) + "(?=\"|/|\\s|\\r|\\n|$)"; return RefractoringUtils.createChange( false, monitor, rootResources, regex, newResourcePath.toString()); }
private String getProjectRelaticePath(FileDiff diff) { IWorkspace workspace = ResourcesPlugin.getWorkspace(); IWorkspaceRoot root = workspace.getRoot(); IPath absolutePath = new Path(db.getWorkDir().getAbsolutePath()).append(diff.path); IResource resource = root.getFileForLocation(absolutePath); return resource.getProjectRelativePath().toString(); }
/** * Notifies this listener that the given breakpoint has been added to the breakpoint manager. * * @param breakpoint the added breakpoint * @since 2.0 */ public void breakpointAdded(IBreakpoint breakpoint) { if (!isAvailable()) { return; } if (supportsBreakpoint(breakpoint)) { try { if (breakpoint.isEnabled()) { // only add the breakpoint to the debugger when the // breakpoint is enabled int linenumber = breakpoint.getMarker().getAttribute(IMarker.LINE_NUMBER, -1); // TODO: get marker language type or get language from the // resource IResource r = breakpoint.getMarker().getResource(); String pRel = r.getProjectRelativePath().toOSString(); String filename = pRel; if (linenumber > 0) { // only linenumbers greater than 0 are valid as // linenumber is 1-based // convert the Eclipse breakpoint to an internal // representation of breakpoints AbstractBreakPoint bp = createBreakpoint(filename, linenumber); if (bp != null) { this.getVMContainer().addBreakpoint(bp); } } } } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
public IBreakpoint findIBreakpoint(String filename, int lineNumber) { IBreakpoint[] breakpoints = DebugPlugin.getDefault() .getBreakpointManager() .getBreakpoints(this.debugServiceFactory.getLIConstants().getDebugModel()); for (int i = 0; i < breakpoints.length; i++) { IBreakpoint breakpoint = breakpoints[i]; if (supportsBreakpoint(breakpoint)) { try { if (breakpoint.isEnabled()) { // only add the breakpoint to the debugger when the // breakpoint is enabled int l = breakpoint.getMarker().getAttribute(IMarker.LINE_NUMBER, -1); // TODO: get marker language type or get language from // the resource IResource r = breakpoint.getMarker().getResource(); String location = r.getProjectRelativePath().toOSString(); if (l > 0) { // only linenumbers greater than 0 are valid as // linenumber is 1-based if (location.equals(filename) && lineNumber == l) { return breakpoint; } } } } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return null; }
@Override public ICResourceDescription getResDesc(ICConfigurationDescription cf) { IAdaptable ad = getElement(); if (isForProject()) return cf.getRootFolderDescription(); ICResourceDescription out = null; IResource res = (IResource) ad; IPath p = res.getProjectRelativePath(); if (isForFolder() || isForFile()) { if (cf instanceof ICMultiItemsHolder) { out = cf.getResourceDescription(p, isForFolder()); // sic ! } else { out = cf.getResourceDescription(p, false); if (!p.equals(out.getPath())) { try { if (isForFolder()) out = cf.createFolderDescription(p, (ICFolderDescription) out); else out = cf.createFileDescription(p, out); } catch (CoreException e) { System.out.println( Messages.AbstractPage_10 + p.toOSString() + "\n" + e.getLocalizedMessage()); // $NON-NLS-1$ } } } } return out; }
public IPath getErlForYrl(final IResource resource) { final IPath path = resource.getProjectRelativePath(); if (!"yrl".equals(path.getFileExtension())) { return null; } IPath erl = path.removeFileExtension(); erl = erl.addFileExtension("erl").setDevice(null); return erl; }
/** * This operation scans the default project area for SerializedItems and loads them into the Core. * It returns false if it encounters and error and true if it is successful. * * @return True if the SerializedItems stored in the default project area were loaded * successfully, false otherwise. */ private boolean loadDefaultAreaItems() { // Local Declarations boolean status = false; ArrayList<String> serializedItemNames = new ArrayList<String>(); SerializedItemBuilder builder = null; IProject project; IResource[] resources = null; IResource currentResource = null; IFile file = null; String filename = null; // Get the default project and grab its contents project = projectTable.get("defaultUser"); if (project == null) { return status; } try { // Update the status status = true; // If the "jobProfiles" folder exists, loop over the resources and // get the serialized items if (project.getFolder("jobProfiles").exists()) { // Get the list of resources in the project resources = project.getFolder("jobProfiles").members(); for (int i = 0; i < resources.length; i++) { currentResource = resources[i]; filename = currentResource.getFullPath().toOSString(); // Grab PSF or XML file if (filename.endsWith(".psf") | filename.endsWith(".xml")) { // Get the file file = project.getFile(currentResource.getProjectRelativePath()); try { // Load the SerializedItemBuilder builder = new SerializedItemBuilder(file.getContents()); // Register the builder itemManager.registerBuilder(builder); } catch (IOException e) { // TODO Auto-generated catch block logger.error(getClass().getName() + " Exception!", e); status = false; } } } } else { // Otherwise create the folder and return since there is nothing // to load project.getFolder("jobProfiles").create(true, true, null); } } catch (CoreException e) { logger.error(getClass().getName() + " Exception!", e); } return status; }
/** * This method validates the resource. * * @param res The resource */ public void validateResource(final IResource res) { EclipseIssueLogger logger = new EclipseIssueLogger((IFile) res); try { InputStreamResource isr = new InputStreamResource( res.getProjectRelativePath().toPortableString(), ((IFile) res).getContents()); // Create a locator based on the Eclipse project root ResourceLocator locator = new ResourceLocator() { public Resource getResource(String name) { String filename = name.replace('.', java.io.File.separatorChar) + ".scr"; IFile file = res.getProject().getFile(filename); if (file != null) { try { return (new InputStreamResource(filename, file.getContents())); } catch (Exception e) { e.printStackTrace(); } } return null; } }; ProtocolParser pp = new ProtocolParser(); ProtocolModuleLoader loader = new ProtocolModuleLoader(pp, locator, logger); // Use console logger, to 'ignore' parser errors, as these will be detected and // reported by the XText generated Scribble editor. However the validation errors // should be reported via the Eclipse based logger Module module = pp.parse(isr, loader, new ConsoleIssueLogger()); if (module != null) { // Validate org.scribble.validation.ProtocolValidator pv = new org.scribble.validation.ProtocolValidator(); DefaultModuleContext context = new DefaultModuleContext(isr, module, loader); pv.validate(context, module, logger); } } catch (Exception e) { Activator.logError("Failed to record validation issue on resource '" + res + "'", e); } finally { logger.finished(); } }
@Override protected IStructureComparator createStructureComparator( Object input, IDocument document, ISharedDocumentAdapter sharedDocumentAdapter, IProgressMonitor monitor) throws CoreException { if (input instanceof CeylonDocumentRangeNode) { return (CeylonDocumentRangeNode) input; } final boolean isEditable; if (input instanceof IEditableContent) { IEditableContent ec = (IEditableContent) input; isEditable = ec.isEditable(); } else { isEditable = false; } StructureRootNode structureRootNode = new StructureRootNode(document, input, this, sharedDocumentAdapter) { @Override public boolean isEditable() { return isEditable; } }; CeylonParseController pc = new CeylonParseController(); if (input instanceof ResourceNode) { ResourceNode node = (ResourceNode) input; IResource file = node.getResource(); pc.initialize(file.getProjectRelativePath(), file.getProject(), null); } else { pc.initialize(null, null, null); } if (pc.parseAndTypecheck(document, 10, monitor, null) != null) { // now visit the model, creating TreeCompareNodes for each ModelTreeNode CeylonOutlineNode tree = new CeylonOutlineBuilder() { // don't create nodes for shortcut refinement // because we can't distinguish them w/o a // full typecheck public void visit(Tree.SpecifierStatement that) {} }.buildTree(pc); if (tree != null) { buildCompareTree(tree, structureRootNode, document); } } return structureRootNode; }
/** * Gets the associated models for the changed one and sets the CoWolf-Marker for them. * * @param changedRes to get the associated models from */ private void invalidateModels(IResource changedRes) { ModelAssociation ma = ModelAssociationFactory.eINSTANCE.getModelAssociation(changedRes.getProject()); Model model = ma.getModelByPath(changedRes.getProjectRelativePath().toString()); if (model == null) { return; } HashSet<IFile> targets = new HashSet<>(); for (Association assoc : model.getAllAssociations()) { // for (ModelVersion v : assoc.getSource()) { // // if (v.getModel().getModel() != changedRes.getProjectRelativePath().toString()) { // targets.add(v.getModel().getFile()); // } else { // break; // } // } for (ModelVersion v : assoc.getTarget()) { if (!v.getModel().getModel().equals(changedRes.getProjectRelativePath().toString())) { targets.add(v.getModel().getFile()); } else { break; } } } for (IFile target : targets) { if (!doesCowolfMarkerExist(target)) { setMarker(changedRes, target); } } }
/** * Create a Model with the supplied name, in the desired project * * @param targetProj the project resource under which to create the model * @param modelName the model name to create * @return the newly-created ModelResource */ public ModelResource constructModel(IResource targetRes, String sModelName) { String sFileName = getFileName(sModelName); IPath relativeModelPath = targetRes.getProjectRelativePath().append(sFileName); final IFile modelFile = targetRes.getProject().getFile(relativeModelPath); final ModelResource resrc = ModelerCore.create(modelFile); try { resrc.getModelAnnotation().setPrimaryMetamodelUri(newModelInfo.getModelURI()); resrc.getModelAnnotation().setModelType(newModelInfo.getModelType()); } catch (ModelWorkspaceException mwe) { mwe.printStackTrace(); } return resrc; }
/** Ensures that location and file are set. */ void dialogChanged() { IResource container = ResourcesPlugin.getWorkspace().getRoot().findMember(new Path(getContainerName())); String fileName = getFileName(); if (getContainerName().isEmpty()) { updateStatus(Messages.CmsisCodeTemplate_FileContainerNotSpecified); return; } if (container == null || (container.getType() & (IResource.PROJECT | IResource.FOLDER)) == 0) { updateStatus(Messages.CmsisCodeTemplate_FileContainerNotExist); return; } String[] segments = container.getFullPath().segments(); if (!segments[0].equals(getProjectName())) { updateStatus(Messages.CmsisCodeTemplateNewWizardPage_LocationNotUnderProject); return; } if (!container.isAccessible()) { updateStatus(Messages.CmsisCodeTemplate_ProjectNotWritable); return; } segments = container.getProjectRelativePath().segments(); if (segments.length > 0 && segments[0].equals(CmsisConstants.RTE)) { updateStatus(Messages.CmsisCodeTemplate_FileUnderRTEFolder); return; } if (fileName.length() == 0) { updateStatus(Messages.CmsisCodeTemplate_FileNameNotSpecified); return; } if (fileName.replace('\\', '/').indexOf('/', 1) > 0) { updateStatus(Messages.CmsisCodeTemplate_FileNameNotValid); return; } int dotLoc = fileName.lastIndexOf('.'); if (dotLoc == -1) { updateStatus(Messages.CmsisCodeTemplate_FileExtensionNotConsistent); return; } String ext = fileName.substring(dotLoc + 1); if (!extIsValid(ext)) { updateStatus(Messages.CmsisCodeTemplate_FileExtensionNotConsistent); return; } updateStatus(null); }
boolean filterExtraResource(IResource resource) { if (this.extraResourceFileFilters != null) { char[] name = resource.getName().toCharArray(); for (int i = 0, l = this.extraResourceFileFilters.length; i < l; i++) if (CharOperation.match(this.extraResourceFileFilters[i], name, true)) return true; } if (this.extraResourceFolderFilters != null) { IPath path = resource.getProjectRelativePath(); String pathName = path.toString(); int count = path.segmentCount(); if (resource.getType() == IResource.FILE) count--; for (int i = 0, l = this.extraResourceFolderFilters.length; i < l; i++) if (pathName.indexOf(this.extraResourceFolderFilters[i]) != -1) for (int j = 0; j < count; j++) if (this.extraResourceFolderFilters[i].equals(path.segment(j))) return true; } return false; }
/** * Notifies this listener that the given breakpoint has been removed from the breakpoint manager. * If the given breakpoint has been removed because it has been deleted, the associated marker * delta is also provided. * * @param breakpoint the removed breakpoint * @param delta the associated marker delta, or <code>null</code> when the breakpoint is removed * from the breakpoint manager without being deleted * @see org.eclipse.core.resources.IMarkerDelta * @since 2.0 */ public void breakpointRemoved(IBreakpoint breakpoint, IMarkerDelta delta) { if (!isAvailable()) { return; } if (supportsBreakpoint(breakpoint)) { // convert IBreakpoint to AbstractBreakPoint Breakpoint int linenumber = breakpoint.getMarker().getAttribute(IMarker.LINE_NUMBER, -1); IResource r = breakpoint.getMarker().getResource(); String pRel = r.getProjectRelativePath().toOSString(); String filename = pRel; if (linenumber > 0) { // only linenumbers greater than 0 are valid as linenumber is // 1-based AbstractBreakPoint bp = createBreakpoint(filename, linenumber); if (bp != null) { this.getVMContainer().removeBreakpoint(bp); } } } }
public static boolean projectHasCamelResource(final IProject project) { try { ArrayList<IResource> xmlResources = getAllXMLFilesInProject(project); for (Iterator<IResource> iterator = xmlResources.iterator(); iterator.hasNext(); ) { IResource item = iterator.next(); File testFile = new File(item.getLocationURI()); if (testFile.exists()) { boolean isValidCamel = CamelFileTypeHelper.isSupportedCamelFile( project, item.getProjectRelativePath().toPortableString()); if (isValidCamel) { return true; } } } } catch (final Exception e) { // ignore } return false; }
protected boolean findSourceFiles( IResourceDelta sourceDelta, ClasspathMultiDirectory md, int segmentCount) throws CoreException { // When a package becomes a type or vice versa, expect 2 deltas, // one on the folder & one on the source file IResource resource = sourceDelta.getResource(); // remember that if inclusion & exclusion patterns change then a full build is done boolean isExcluded = (md.exclusionPatterns != null || md.inclusionPatterns != null) && Util.isExcluded(resource, md.inclusionPatterns, md.exclusionPatterns); switch (resource.getType()) { case IResource.FOLDER: if (isExcluded && md.inclusionPatterns == null) return true; // no need to go further with this delta since its children cannot be // included switch (sourceDelta.getKind()) { case IResourceDelta.ADDED: if (!isExcluded) { IPath addedPackagePath = resource.getFullPath().removeFirstSegments(segmentCount); createFolder( addedPackagePath, md.binaryFolder); // ensure package exists in the output folder // see if any known source file is from the same package... classpath already includes // new package if (this.sourceLocations.length > 1 && this.newState.isKnownPackage(addedPackagePath.toString())) { if (JavaBuilder.DEBUG) System.out.println( "Skipped dependents of added package " + addedPackagePath); // $NON-NLS-1$ } else { if (JavaBuilder.DEBUG) System.out.println("Found added package " + addedPackagePath); // $NON-NLS-1$ addDependentsOf(addedPackagePath, true); } } // $FALL-THROUGH$ collect all the source files case IResourceDelta.CHANGED: IResourceDelta[] children = sourceDelta.getAffectedChildren(); for (int i = 0, l = children.length; i < l; i++) if (!findSourceFiles(children[i], md, segmentCount)) return false; return true; case IResourceDelta.REMOVED: if (isExcluded) { // since this folder is excluded then there is nothing to delete (from this md), but // must walk any included subfolders children = sourceDelta.getAffectedChildren(); for (int i = 0, l = children.length; i < l; i++) if (!findSourceFiles(children[i], md, segmentCount)) return false; return true; } IPath removedPackagePath = resource.getFullPath().removeFirstSegments(segmentCount); if (this.sourceLocations.length > 1) { for (int i = 0, l = this.sourceLocations.length; i < l; i++) { if (this.sourceLocations[i].sourceFolder.getFolder(removedPackagePath).exists()) { // only a package fragment was removed, same as removing multiple source files createFolder( removedPackagePath, md.binaryFolder); // ensure package exists in the output folder IResourceDelta[] removedChildren = sourceDelta.getAffectedChildren(); for (int j = 0, m = removedChildren.length; j < m; j++) if (!findSourceFiles(removedChildren[j], md, segmentCount)) return false; return true; } } } if ((sourceDelta.getFlags() & IResourceDelta.MOVED_TO) != 0) { // same idea as moving a source file // see bug 163200 IResource movedFolder = this.javaBuilder.workspaceRoot.getFolder(sourceDelta.getMovedToPath()); JavaBuilder.removeProblemsAndTasksFor(movedFolder); } IFolder removedPackageFolder = md.binaryFolder.getFolder(removedPackagePath); if (removedPackageFolder.exists()) removedPackageFolder.delete(IResource.FORCE, null); // add dependents even when the package thinks it does not exist to be on the safe side if (JavaBuilder.DEBUG) System.out.println("Found removed package " + removedPackagePath); // $NON-NLS-1$ addDependentsOf(removedPackagePath, true); this.newState.removePackage(sourceDelta); } return true; case IResource.FILE: if (isExcluded) return true; String resourceName = resource.getName(); // GROOVY start // determine if this is a Groovy project final boolean isInterestingProject = LanguageSupportFactory.isInterestingProject(this.javaBuilder.getProject()); // GROOVY end // GROOVY start /* old { if (org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(resourceName)) { } new */ // GRECLIPSE-404 must call 'isJavaLikeFile' directly in order to make the Scala-Eclipse // plugin's weaving happy if ((!isInterestingProject && org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(resourceName) && !LanguageSupportFactory.isInterestingSourceFile(resourceName)) || (isInterestingProject && LanguageSupportFactory.isSourceFile(resourceName, isInterestingProject))) { // GROOVY end IPath typePath = resource.getFullPath().removeFirstSegments(segmentCount).removeFileExtension(); String typeLocator = resource.getProjectRelativePath().toString(); switch (sourceDelta.getKind()) { case IResourceDelta.ADDED: if (JavaBuilder.DEBUG) System.out.println("Compile this added source file " + typeLocator); // $NON-NLS-1$ this.sourceFiles.add(new SourceFile((IFile) resource, md, true)); String typeName = typePath.toString(); if (!this.newState.isDuplicateLocator( typeName, typeLocator)) { // adding dependents results in 2 duplicate errors if (JavaBuilder.DEBUG) System.out.println("Found added source file " + typeName); // $NON-NLS-1$ addDependentsOf(typePath, true); } return true; case IResourceDelta.REMOVED: char[][] definedTypeNames = this.newState.getDefinedTypeNamesFor(typeLocator); if (definedTypeNames == null) { // defined a single type matching typePath removeClassFile(typePath, md.binaryFolder); if ((sourceDelta.getFlags() & IResourceDelta.MOVED_TO) != 0) { // remove problems and tasks for a compilation unit that is being moved (to // another package or renamed) // if the target file is a compilation unit, the new cu will be recompiled // if the target file is a non-java resource, then markers are removed // see bug 2857 IResource movedFile = this.javaBuilder.workspaceRoot.getFile(sourceDelta.getMovedToPath()); JavaBuilder.removeProblemsAndTasksFor(movedFile); } } else { if (JavaBuilder.DEBUG) System.out.println( "Found removed source file " + typePath.toString()); // $NON-NLS-1$ addDependentsOf( typePath, true); // add dependents of the source file since it may be involved in a name // collision if (definedTypeNames.length > 0) { // skip it if it failed to successfully define a type IPath packagePath = typePath.removeLastSegments(1); for (int i = 0, l = definedTypeNames.length; i < l; i++) removeClassFile( packagePath.append(new String(definedTypeNames[i])), md.binaryFolder); } } this.newState.removeLocator(typeLocator); return true; case IResourceDelta.CHANGED: if ((sourceDelta.getFlags() & IResourceDelta.CONTENT) == 0 && (sourceDelta.getFlags() & IResourceDelta.ENCODING) == 0) return true; // skip it since it really isn't changed if (JavaBuilder.DEBUG) System.out.println( "Compile this changed source file " + typeLocator); // $NON-NLS-1$ this.sourceFiles.add(new SourceFile((IFile) resource, md, true)); } return true; } else if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(resourceName)) { // perform full build if a managed class file has been changed if (this.makeOutputFolderConsistent) { IPath typePath = resource.getFullPath().removeFirstSegments(segmentCount).removeFileExtension(); if (this.newState.isKnownType(typePath.toString())) { if (JavaBuilder.DEBUG) System.out.println( "MUST DO FULL BUILD. Found change to class file " + typePath); // $NON-NLS-1$ return false; } } return true; } else if (md.hasIndependentOutputFolder) { if (this.javaBuilder.filterExtraResource(resource)) return true; // copy all other resource deltas to the output folder IPath resourcePath = resource.getFullPath().removeFirstSegments(segmentCount); IResource outputFile = md.binaryFolder.getFile(resourcePath); switch (sourceDelta.getKind()) { case IResourceDelta.ADDED: if (outputFile.exists()) { if (JavaBuilder.DEBUG) System.out.println("Deleting existing file " + resourcePath); // $NON-NLS-1$ outputFile.delete(IResource.FORCE, null); } if (JavaBuilder.DEBUG) System.out.println("Copying added file " + resourcePath); // $NON-NLS-1$ createFolder( resourcePath.removeLastSegments(1), md.binaryFolder); // ensure package exists in the output folder copyResource(resource, outputFile); return true; case IResourceDelta.REMOVED: if (outputFile.exists()) { if (JavaBuilder.DEBUG) System.out.println("Deleting removed file " + resourcePath); // $NON-NLS-1$ outputFile.delete(IResource.FORCE, null); } return true; case IResourceDelta.CHANGED: if ((sourceDelta.getFlags() & IResourceDelta.CONTENT) == 0 && (sourceDelta.getFlags() & IResourceDelta.ENCODING) == 0) return true; // skip it since it really isn't changed if (outputFile.exists()) { if (JavaBuilder.DEBUG) System.out.println("Deleting existing file " + resourcePath); // $NON-NLS-1$ outputFile.delete(IResource.FORCE, null); } if (JavaBuilder.DEBUG) System.out.println("Copying changed file " + resourcePath); // $NON-NLS-1$ createFolder( resourcePath.removeLastSegments(1), md.binaryFolder); // ensure package exists in the output folder copyResource(resource, outputFile); } return true; } } return true; }
/** * Updates the commands. * * @param commands */ private void updateCommands(ArrayList<TexCommandEntry> commands) { IResource resource = getFile(); if (resource == null) return; if (commandContainer.addRefSource(resource.getProjectRelativePath().toString(), commands)) commandContainer.organize(); }
/** * Updates the labels. * * @param labels */ private void updateLabels(List<ReferenceEntry> labels) { IResource resource = getFile(); if (resource == null) return; labelContainer.addRefSource(resource.getProjectRelativePath().toString(), labels); labelContainer.organize(); }
/** * Parses the LaTeX-document and adds error markers if there were any errors. Throws <code> * TexDocumentParseException</code> if there were fatal parse errors that prohibit building an * outline. * * @param monitor * @throws TexDocumentParseException */ private ArrayList<OutlineNode> doParse(IProgressMonitor monitor) throws TexDocumentParseException { if (this.parser == null) { this.parser = new TexParser(editor.getDocumentProvider().getDocument(editor.getEditorInput())); } if (projectOutline == null) { createProjectOutline(); } try { parser.parseDocument(sectionCheckEnabled); } catch (IOException e) { TexlipsePlugin.log("Can't read file.", e); throw new TexDocumentParseException(e); } pollCancel(monitor); List<ParseErrorMessage> errors = parser.getErrors(); List<ParseErrorMessage> tasks = parser.getTasks(); MarkerHandler marker = MarkerHandler.getInstance(); // somewhat inelegantly ensures that errors marked in createProjectDatastructs() // aren't removed immediately if (!firstRun) { marker.clearErrorMarkers(editor); marker.clearTaskMarkers(editor); } else { firstRun = false; } if (editor.getProject() != null && editor.getFullOutline() != null) { IResource res = (IResource) editor.getEditorInput().getAdapter(IResource.class); String fileName = res.getProjectRelativePath().toString(); projectOutline.addOutline(parser.getOutlineTree(), fileName); List<OutlineNode> fo = projectOutline.getFullOutline(); postParseJob.setFONodes(fo); } else { postParseJob.setFONodes(null); } pollCancel(monitor); processIncludes(parser.getInputs(), editor.getEditorInput()); if (errors.size() > 0) { marker.createErrorMarkers(editor, errors); } if (tasks.size() > 0) { marker.createTaskMarkers(editor, tasks); } if (parser.isFatalErrors()) { throw new TexDocumentParseException("Fatal errors in file, parsing aborted."); } updateReferences(monitor); List<DocumentReference> cites = parser.getCites(); List<DocumentReference> bibErrors = null; for (DocumentReference cite : cites) { if (!bibContainer.binTest(cite.getKey())) { if (bibErrors == null) bibErrors = new ArrayList<DocumentReference>(); bibErrors.add(cite); } } if (bibErrors != null) { marker.createReferencingErrorMarkers(editor, bibErrors); } List<DocumentReference> refs = parser.getRefs(); List<DocumentReference> refErrors = null; for (DocumentReference ref : refs) { if (!labelContainer.binTest(ref.getKey())) { if (refErrors == null) refErrors = new ArrayList<DocumentReference>(); refErrors.add(ref); } } if (refErrors != null) { marker.createReferencingErrorMarkers(editor, refErrors); } return this.parser.getOutlineTree(); }
/** * Creates a problem for a specific reference in the workspace * * @param reference reference * @param associated java project (with reference source location) * @return problem or <code>null</code> if none * @exception CoreException if something goes wrong */ protected IApiProblem createProblem(IReference reference, IJavaProject javaProject) { IProject project = javaProject.getProject(); if (ApiPlugin.getDefault().getSeverityLevel(getSeverityKey(), project) == ApiPlugin.SEVERITY_IGNORE) { return null; } try { String lookupName = getTypeName(reference.getMember()).replace('$', '.'); IType type = javaProject.findType(lookupName, new NullProgressMonitor()); if (type == null) { return null; } ICompilationUnit compilationUnit = type.getCompilationUnit(); if (compilationUnit == null) { return null; } IResource resource = Util.getResource(project, type); if (resource == null) { return null; } int charStart = -1; int charEnd = -1; int lineNumber = reference.getLineNumber(); IJavaElement element = compilationUnit; if (!Util.isManifest(resource.getProjectRelativePath()) && !type.isBinary()) { IDocument document = Util.getDocument(compilationUnit); // retrieve line number, char start and char end if (lineNumber > 0) { lineNumber--; } // get the source range for the problem try { Position pos = getSourceRange(type, document, reference); if (pos != null) { charStart = pos.getOffset(); if (charStart != -1) { charEnd = charStart + pos.getLength(); lineNumber = document.getLineOfOffset(charStart); } } } catch (CoreException e) { ApiPlugin.log(e); return null; } catch (BadLocationException e) { ApiPlugin.log(e); return null; } if (charStart > -1) { element = compilationUnit.getElementAt(charStart); } } return ApiProblemFactory.newApiUsageProblem( resource.getProjectRelativePath().toPortableString(), type.getFullyQualifiedName(), getMessageArgs(reference), new String[] { IApiMarkerConstants.MARKER_ATTR_HANDLE_ID, IApiMarkerConstants.API_MARKER_ATTR_ID }, new Object[] { (element == null ? compilationUnit.getHandleIdentifier() : element.getHandleIdentifier()), new Integer(IApiMarkerConstants.API_USAGE_MARKER_ID) }, lineNumber, charStart, charEnd, getElementType(reference), getProblemKind(), getProblemFlags(reference)); } catch (CoreException e) { ApiPlugin.log(e); } return null; }
static boolean mustBeVisited(final IResource resource) { return (resource instanceof IFile && hasCorrectExtension(resource.getProjectRelativePath()) && isInSourceFolder((IFile) resource)); }
/** * Called by {@link NewXmlFileWizard} to initialize the page with the selection received by the * wizard -- typically the current user workbench selection. * * <p>Things we expect to find out from the selection: * * <ul> * <li>The project name, valid if it's an android nature. * <li>The current folder, valid if it's a folder under /res * <li>An existing filename, in which case the user will be asked whether to override it. * </ul> * * <p>The selection can also be set to a {@link Pair} of {@link IProject} and a workspace resource * path (where the resource path does not have to exist yet, such as res/anim/). * * @param selection The selection when the wizard was initiated. */ private boolean initializeFromSelection(IStructuredSelection selection) { if (selection == null) { return false; } // Find the best match in the element list. In case there are multiple selected elements // select the one that provides the most information and assign them a score, // e.g. project=1 + folder=2 + file=4. IProject targetProject = null; String targetWsFolderPath = null; String targetFileName = null; int targetScore = 0; for (Object element : selection.toList()) { if (element instanceof IAdaptable) { IResource res = (IResource) ((IAdaptable) element).getAdapter(IResource.class); IProject project = res != null ? res.getProject() : null; // Is this an Android project? try { if (project == null || !project.hasNature(AdtConstants.NATURE_DEFAULT)) { continue; } } catch (CoreException e) { // checking the nature failed, ignore this resource continue; } int score = 1; // we have a valid project at least IPath wsFolderPath = null; String fileName = null; assert res != null; // Eclipse incorrectly thinks res could be null, so tell it no if (res.getType() == IResource.FOLDER) { wsFolderPath = res.getProjectRelativePath(); } else if (res.getType() == IResource.FILE) { if (SdkUtils.endsWithIgnoreCase(res.getName(), DOT_XML)) { fileName = res.getName(); } wsFolderPath = res.getParent().getProjectRelativePath(); } // Disregard this folder selection if it doesn't point to /res/something if (wsFolderPath != null && wsFolderPath.segmentCount() > 1 && SdkConstants.FD_RESOURCES.equals(wsFolderPath.segment(0))) { score += 2; } else { wsFolderPath = null; fileName = null; } score += fileName != null ? 4 : 0; if (score > targetScore) { targetScore = score; targetProject = project; targetWsFolderPath = wsFolderPath != null ? wsFolderPath.toString() : null; targetFileName = fileName; } } else if (element instanceof Pair<?, ?>) { // Pair of Project/String @SuppressWarnings("unchecked") Pair<IProject, String> pair = (Pair<IProject, String>) element; targetScore = 1; targetProject = pair.getFirst(); targetWsFolderPath = pair.getSecond(); targetFileName = ""; } } if (targetProject == null) { // Try to figure out the project from the active editor IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (window != null) { IWorkbenchPage page = window.getActivePage(); if (page != null) { IEditorPart activeEditor = page.getActiveEditor(); if (activeEditor instanceof AndroidXmlEditor) { Object input = ((AndroidXmlEditor) activeEditor).getEditorInput(); if (input instanceof FileEditorInput) { FileEditorInput fileInput = (FileEditorInput) input; targetScore = 1; IFile file = fileInput.getFile(); targetProject = file.getProject(); IPath path = file.getParent().getProjectRelativePath(); targetWsFolderPath = path != null ? path.toString() : null; } } } } } if (targetProject == null) { // If we didn't find a default project based on the selection, check how many // open Android projects we can find in the current workspace. If there's only // one, we'll just select it by default. IJavaProject[] projects = AdtUtils.getOpenAndroidProjects(); if (projects != null && projects.length == 1) { targetScore = 1; targetProject = projects[0].getProject(); } } // Now set the UI accordingly if (targetScore > 0) { mValues.project = targetProject; mValues.folderPath = targetWsFolderPath; mProjectButton.setSelectedProject(targetProject); mFileNameTextField.setText(targetFileName != null ? targetFileName : ""); // $NON-NLS-1$ // If the current selection context corresponds to a specific file type, // select it. if (targetWsFolderPath != null) { int pos = targetWsFolderPath.lastIndexOf(WS_SEP_CHAR); if (pos >= 0) { targetWsFolderPath = targetWsFolderPath.substring(pos + 1); } String[] folderSegments = targetWsFolderPath.split(RES_QUALIFIER_SEP); if (folderSegments.length > 0) { mValues.configuration = FolderConfiguration.getConfig(folderSegments); String folderName = folderSegments[0]; selectTypeFromFolder(folderName); } } } return true; }