/** * Creates configuration by given adaptable * * @param adaptable * must provide {@link ColorManager} and {@link IFile} */ public BatchSourceViewerConfiguration(IAdaptable adaptable) { IPreferenceStore generalTextStore = EditorsUI.getPreferenceStore(); this.fPreferenceStore = new ChainedPreferenceStore( new IPreferenceStore[] { getPreferences().getPreferenceStore(), generalTextStore }); Assert.isNotNull(adaptable, "adaptable may not be null!"); this.annotationHoover = new BatchEditorAnnotationHoover(); this.contentAssistant = new ContentAssistant(); contentAssistProcessor = new BatchEditorSimpleWordContentAssistProcessor(); contentAssistant.enableColoredLabels(true); contentAssistant.setContentAssistProcessor(contentAssistProcessor, IDocument.DEFAULT_CONTENT_TYPE); for (BatchDocumentIdentifier identifier: BatchDocumentIdentifiers.values()){ contentAssistant.setContentAssistProcessor(contentAssistProcessor, identifier.getId()); } contentAssistant.addCompletionListener(contentAssistProcessor.getCompletionListener()); this.colorManager = adaptable.getAdapter(ColorManager.class); Assert.isNotNull(colorManager, " adaptable must support color manager"); this.defaultTextAttribute = new TextAttribute( colorManager.getColor(getPreferences().getColor(COLOR_NORMAL_TEXT))); this.adaptable=adaptable; }
/** * Creates configuration by given adaptable * * @param adaptable * must provide {@link ColorManager} and {@link IFile} */ public BashSourceViewerConfiguration(IAdaptable adaptable) { IPreferenceStore generalTextStore = EditorsUI.getPreferenceStore(); this.fPreferenceStore = new ChainedPreferenceStore( new IPreferenceStore[] { getPreferences().getPreferenceStore(), generalTextStore }); Assert.isNotNull(adaptable, "adaptable may not be null!"); this.annotationHoover = new BashEditorAnnotationHoover(); this.contentAssistant = new ContentAssistant(); contentAssistProcessor = new BashEditorSimpleWordContentAssistProcessor(); contentAssistant.enableColoredLabels(true); contentAssistant.setContentAssistProcessor(contentAssistProcessor, IDocument.DEFAULT_CONTENT_TYPE); for (BashDocumentIdentifier identifier: BashDocumentIdentifiers.values()){ contentAssistant.setContentAssistProcessor(contentAssistProcessor, identifier.getId()); } contentAssistant.addCompletionListener(contentAssistProcessor.getCompletionListener()); this.colorManager = adaptable.getAdapter(ColorManager.class); Assert.isNotNull(colorManager, " adaptable must support color manager"); this.defaultTextAttribute = new TextAttribute( colorManager.getColor(getPreferences().getColor(COLOR_NORMAL_TEXT))); this.adaptable=adaptable; }
public HydrographCompletionProposal(String replacementString, int replacementOffset, int replacementLength, int cursorPosition, Image image, String displayString, IContextInformation contextInformation, String additionalProposalInfo) { Assert.isNotNull(replacementString); Assert.isTrue(replacementOffset >= 0); Assert.isTrue(replacementLength >= 0); Assert.isTrue(cursorPosition >= 0); fReplacementString = replacementString; fReplacementOffset = replacementOffset; fReplacementLength = replacementLength; fCursorPosition = cursorPosition; fImage = image; fDisplayString = displayString; fContextInformation = contextInformation; fAdditionalProposalInfo = additionalProposalInfo; }
private void addBreakpointToMap(IBreakpoint breakpoint) throws CoreException { Assert.isTrue(supportsBreakpoint(breakpoint) && breakpoint instanceof ILineBreakpoint); if (breakpoint instanceof ILineBreakpoint) { ILineBreakpoint lineBreakpoint = (ILineBreakpoint) breakpoint; IResource resource = lineBreakpoint.getMarker().getResource(); IPath location = resource.getLocation(); String path = location.toOSString(); String name = location.lastSegment(); int lineNumber = lineBreakpoint.getLineNumber(); Source source = new Source().setName(name).setPath(path); List<SourceBreakpoint> sourceBreakpoints = targetBreakpoints.computeIfAbsent(source, s -> new ArrayList<>()); sourceBreakpoints.add(new SourceBreakpoint().setLine(lineNumber)); } }
private void deleteBreakpointFromMap(IBreakpoint breakpoint) throws CoreException { Assert.isTrue(supportsBreakpoint(breakpoint) && breakpoint instanceof ILineBreakpoint); if (breakpoint instanceof ILineBreakpoint) { ILineBreakpoint lineBreakpoint = (ILineBreakpoint) breakpoint; IResource resource = lineBreakpoint.getMarker().getResource(); IPath location = resource.getLocation(); String path = location.toOSString(); String name = location.lastSegment(); int lineNumber = lineBreakpoint.getLineNumber(); for (Entry<Source, List<SourceBreakpoint>> entry : targetBreakpoints.entrySet()) { Source source = entry.getKey(); if (Objects.equals(name, source.name) && Objects.equals(path, source.path)) { List<SourceBreakpoint> bps = entry.getValue(); for (Iterator<SourceBreakpoint> iterator = bps.iterator(); iterator.hasNext();) { SourceBreakpoint sourceBreakpoint = (SourceBreakpoint) iterator.next(); if (Objects.equals(lineNumber, sourceBreakpoint.line)) { iterator.remove(); } } } } } }
/** * Handles a core exception thrown during a testing environment operation */ private void handleCoreException(CoreException e) { e.printStackTrace(); IStatus status = e.getStatus(); String message = e.getMessage(); if (status.isMultiStatus()) { MultiStatus multiStatus = (MultiStatus) status; IStatus[] children = multiStatus.getChildren(); StringBuffer buffer = new StringBuffer(); for (int i = 0, max = children.length; i < max; i++) { IStatus child = children[i]; if (child != null) { buffer.append(child.getMessage()); buffer.append(System.getProperty("line.separator"));//$NON-NLS-1$ Throwable childException = child.getException(); if (childException != null) { childException.printStackTrace(); } } } message = buffer.toString(); } Assert.isTrue(false, "Core exception in testing environment: " + message); //$NON-NLS-1$ }
public static List<Match> perform(ASTNode start, ASTNode[] snippet) { Assert.isTrue(start instanceof AbstractTypeDeclaration || start instanceof AnonymousClassDeclaration); SnippetFinder finder = new SnippetFinder(snippet); start.accept(finder); for (Iterator<Match> iter = finder.fResult.iterator(); iter.hasNext();) { Match match = iter.next(); ASTNode[] nodes = match.getNodes(); // doesn't match if the candidate is the left hand side of an // assignment and the snippet consists of a single node. // Otherwise y= i; i= z; results in y= e(); e()= z; if (nodes.length == 1 && isLeftHandSideOfAssignment(nodes[0])) { iter.remove(); } } return finder.fResult; }
/** * Creates configuration by given adaptable * * @param adaptable * must provide {@link ColorManager} and {@link IFile} */ public GradleSourceViewerConfiguration(IAdaptable adaptable) { super(adaptable, COLOR_NORMAL_TEXT); Assert.isNotNull(adaptable, "adaptable may not be null!"); /* code completion */ this.contentAssistant = new ContentAssistant(); this.gradleContentAssistProcessor = new GradleContentAssistProcessor(adaptable, new RelevantCodeCutter()); contentAssistant.setContentAssistProcessor(gradleContentAssistProcessor, IDocument.DEFAULT_CONTENT_TYPE); contentAssistant.setContentAssistProcessor(gradleContentAssistProcessor, GRADLE_APPLY_KEYWORD.getId()); contentAssistant.setContentAssistProcessor(gradleContentAssistProcessor, GRADLE_KEYWORD.getId()); contentAssistant.setContentAssistProcessor(gradleContentAssistProcessor, GRADLE_TASK_KEYWORD.getId()); contentAssistant.setContentAssistProcessor(gradleContentAssistProcessor, GRADLE_VARIABLE.getId()); contentAssistant.addCompletionListener(gradleContentAssistProcessor.getCompletionListener()); // contentAssistant.enableColoredLabels(true); - when... // ICompletionProposalExtension6 implemented /* enable auto activation */ contentAssistant.enableAutoActivation(true); /* set a propert orientation for proposal */ contentAssistant.setContextInformationPopupOrientation(IContentAssistant.CONTEXT_INFO_ABOVE); }
/** * Finds the first whitespace character position to the right of (and including) * <code>position</code>. * * @param document the document being modified * @param position the first character position in <code>document</code> to be considered * @return the position of a whitespace character greater or equal than <code>position</code> * separated only by whitespace, or -1 if none found */ private static int firstWhitespaceToRight(IDocument document, int position) { int length = document.getLength(); Assert.isTrue(position >= 0); Assert.isTrue(position <= length); try { while (position < length) { char ch = document.getChar(position); if (Character.isWhitespace(ch)) return position; position++; } return position; } catch (BadLocationException e) {} return -1; }
/** * Create a grid layout with the specified number of columns and the * standard spacings. * * @param numColumns * the number of columns * @param converter * the pixel converter * @param margins * One of <code>MARGINS_DEFAULT</code>, * <code>MARGINS_NONE</code> or <code>MARGINS_DIALOG</code>. * @return the grid layout */ public static GridLayout createGridLayout(int numColumns, PixelConverter converter, int margins) { Assert.isTrue(margins == MARGINS_DEFAULT || margins == MARGINS_NONE || margins == MARGINS_DIALOG); final GridLayout layout= new GridLayout(numColumns, false); layout.horizontalSpacing= converter.convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); layout.verticalSpacing= converter.convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING); switch (margins) { case MARGINS_NONE: layout.marginLeft= layout.marginRight= 0; layout.marginTop= layout.marginBottom= 0; break; case MARGINS_DIALOG: layout.marginLeft= layout.marginRight= converter.convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); layout.marginTop= layout.marginBottom= converter.convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); break; case MARGINS_DEFAULT: layout.marginLeft= layout.marginRight= layout.marginWidth; layout.marginTop= layout.marginBottom= layout.marginHeight; } layout.marginWidth= layout.marginHeight= 0; return layout; }
public String suggestNewVariableName(String[] prefixes, String[] suffixes, String oldVariableName, String oldTypeName, String newTypeName) { Assert.isNotNull(prefixes); Assert.isNotNull(suffixes); Assert.isNotNull(oldVariableName); Assert.isNotNull(oldTypeName); Assert.isNotNull(newTypeName); Assert.isTrue(oldVariableName.length() > 0); Assert.isTrue(oldTypeName.length() > 0); Assert.isTrue(newTypeName.length() > 0); final String usedPrefix = findLongestPrefix(oldVariableName, prefixes); final String usedSuffix = findLongestSuffix(oldVariableName, suffixes); final String strippedVariableName = oldVariableName.substring(usedPrefix.length(), oldVariableName.length() - usedSuffix.length()); String newVariableName = match(oldTypeName, newTypeName, strippedVariableName); return (newVariableName != null) ? usedPrefix + newVariableName + usedSuffix : null; }
/** * Registers our auto edit vetoer with the viewer. * * @param viewer * the viewer we want to veto ui-triggered changes within linked * positions */ private void registerAutoEditVetoer(ITextViewer viewer) { try { String[] contentTypes = getContentTypes(viewer.getDocument()); if (viewer instanceof ITextViewerExtension2) { ITextViewerExtension2 vExtension = ((ITextViewerExtension2) viewer); for (int i = 0; i < contentTypes.length; i++) { vExtension.prependAutoEditStrategy(fAutoEditVetoer, contentTypes[i]); } } else { Assert.isTrue(false); } } catch (BadPartitioningException e) { leave(ILinkedModeListener.EXIT_ALL); } }
/** * Processes a modify event that occurred in this text cell editor. This * framework method performs validation and sets the error message accordingly, * and then reports a change via <code>fireEditorValueChanged</code>. Subclasses * should call this method at appropriate times. Subclasses may extend or * reimplement. * * @param e * the SWT modify event */ protected void editOccured(ModifyEvent e) { String value = text.getText(); if (value == null) { value = "";//$NON-NLS-1$ } Object typedValue = value; boolean oldValidState = isValueValid(); boolean newValidState = isCorrect(typedValue); if (typedValue == null && newValidState) { Assert.isTrue(false, "Validator isn't limiting the cell editor's type range");//$NON-NLS-1$ } if (!newValidState) { // try to insert the current value into the error message. setErrorMessage(MessageFormat.format(getErrorMessage(), new Object[] { value })); } valueChanged(oldValidState, newValidState); }
/** * Creates and returns a parameter list of the given method or type proposal suitable for * display. The list does not include parentheses. The lower bound of parameter types is * returned. * <p> * Examples: * * <pre> * "void method(int i, String s)" -> "int i, String s" * "? extends Number method(java.lang.String s, ? super Number n)" -> "String s, Number n" * </pre> * * </p> * * @param proposal the proposal to create the parameter list for * @return the list of comma-separated parameters suitable for display */ public StringBuilder createParameterList(CompletionProposal proposal) { int kind= proposal.getKind(); switch (kind) { case CompletionProposal.METHOD_REF: case CompletionProposal.CONSTRUCTOR_INVOCATION: return appendUnboundedParameterList(new StringBuilder(), proposal); case CompletionProposal.TYPE_REF: case CompletionProposal.JAVADOC_TYPE_REF: return appendTypeParameterList(new StringBuilder(), proposal); case CompletionProposal.ANONYMOUS_CLASS_DECLARATION: case CompletionProposal.ANONYMOUS_CLASS_CONSTRUCTOR_INVOCATION: return appendUnboundedParameterList(new StringBuilder(), proposal); default: Assert.isLegal(false); return null; // dummy } }
/** * The keys to add to the list of overlay keys. * <p> * Note: This method must be called before {@link #load()} is called. * </p> * * @param keys an array with overlay keys * @since 3.0 */ public void addKeys(OverlayKey[] keys) { Assert.isTrue(!fLoaded); Assert.isNotNull(keys); int overlayKeysLength = fOverlayKeys.length; OverlayKey[] result = new OverlayKey[keys.length + overlayKeysLength]; for (int i = 0, length = overlayKeysLength; i < length; i++) result[i] = fOverlayKeys[i]; for (int i = 0, length = keys.length; i < length; i++) result[overlayKeysLength + i] = keys[i]; fOverlayKeys = result; if (fLoaded) load(); }
/** * Finds the lowest position in <code>document</code> such that the position is >= * <code>position</code> and < <code>bound</code> and * <code>document.getChar(position) == ch</code> evaluates to <code>true</code> for at least one * ch in <code>chars</code> and the position is in the default partition. * * @param document the document being modified * @param position the first character position in <code>document</code> to be considered * @param partitioning the document partitioning * @param bound the first position in <code>document</code> to not consider any more, with * <code>scanTo</code> > <code>position</code> * @param chars an array of <code>char</code> to search for * @return the lowest position of one element in <code>chars</code> in [<code>position</code>, * <code>bound</code>) that resides in a Java partition, or <code>-1</code> if none can * be found */ private static int scanForward(IDocument document, int position, String partitioning, int bound, char[] chars) { Assert.isTrue(position >= 0); Assert.isTrue(bound <= document.getLength()); Arrays.sort(chars); try { while (position < bound) { if (Arrays.binarySearch(chars, document.getChar(position)) >= 0 && isDefaultPartition(document, position, partitioning)) return position; position++; } } catch (BadLocationException e) {} return -1; }
/** * Stores root file name in project preferences * @param project * @param rootFilename */ public static void storeRootFilename(IProject project, String rootFilename) { // If this condition does not hold, the subsequent code but also // AddModuleHandler will not work. The claim is that spec files are // always in the parent folder of the IProject. final IPath path = new Path(rootFilename); Assert.isTrue(ResourceHelper.isProjectParent(path.removeLastSegments(1), project), project.getLocation().toOSString() + " is *not* a subdirectory of " + rootFilename + ". This is commonly caused by a symlink contained in the latter path."); // Store the filename *without* any path information, but prepend the // magical PARENT-1-PROJECT-LOC. It indicates that the file can be found // *one* level up (hence the "1") from the project location. // readProjectRootFile can later easily deduce the relative location of // the file. rootFilename = ResourceHelper.PARENT_ONE_PROJECT_LOC + path.lastSegment(); IEclipsePreferences projectPrefs = getProjectPreferences(project); projectPrefs.put(IPreferenceConstants.P_PROJECT_ROOT_FILE, rootFilename); storePreferences(projectPrefs); }
/** * Returns <code>true</code> if the given sequence into the underlying text * represents a delimiter, <code>false</code> otherwise. * * @param offset * the offset * @param exclusiveEnd * the end offset * @return <code>true</code> if the given range is a delimiter */ private boolean isDelimiter(int offset, int exclusiveEnd) { if (exclusiveEnd == DONE || offset == DONE) { return false; } Assert.isTrue(offset >= 0); Assert.isTrue(exclusiveEnd <= getText().getEndIndex()); Assert.isTrue(exclusiveEnd > offset); CharSequence seq = fIterator.fText; while (offset < exclusiveEnd) { char ch = seq.charAt(offset); if (ch != '\n' && ch != '\r') { return false; } offset++; } return true; }
/** * Performs some weird initialization steps needed to run the tests. * * @param bot * to work with, must not be {@code null} */ public static void initializeWorkbench(final SwtWorkbenchBot bot) { Assert.isNotNull(bot, ARGUMENT_BOT); // Move mouse outside client area (to prevent problems with context menus) PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { @Override public void run() { try { final Robot robot = new Robot(); robot.mouseMove(MOUSE_POSITION_X, MOUSE_POSITION_Y); } catch (SWTException | AWTException wte) { throw new WrappedException("Error during initialisation SWT mouse", wte); } } }); // The welcome page must be closed before resetting the workbench to avoid trashing the UI: bot.closeWelcomePage(); bot.resetActivePerspective(); }
/** * Returns the type node for the given declaration. * * @param declaration the declaration * @return the type node or <code>null</code> if the given declaration represents a type * inferred parameter in lambda expression */ public static Type getType(VariableDeclaration declaration) { if (declaration instanceof SingleVariableDeclaration) { return ((SingleVariableDeclaration)declaration).getType(); } else if (declaration instanceof VariableDeclarationFragment) { ASTNode parent= ((VariableDeclarationFragment)declaration).getParent(); if (parent instanceof VariableDeclarationExpression) { return ((VariableDeclarationExpression)parent).getType(); } else if (parent instanceof VariableDeclarationStatement) { return ((VariableDeclarationStatement)parent).getType(); } else if (parent instanceof FieldDeclaration) { return ((FieldDeclaration)parent).getType(); } else if (parent instanceof LambdaExpression) { return null; } } Assert.isTrue(false, "Unknown VariableDeclaration"); //$NON-NLS-1$ return null; }
@SuppressWarnings("unchecked") public <T> T getAdapter(Object adaptableObject, Class<T> adapterType) { if (!Model.class.equals(adapterType)) { return null; } if (adaptableObject instanceof ILaunchConfiguration) { final ILaunchConfiguration launchConfiguration = (ILaunchConfiguration) adaptableObject; // The ILC instances change all the time due to working copies being // created dynamically upon save. Thus, map the various ILC's to one // model by using the canonical IFile that all ILC instances are // technically represented by. final IFile key = launchConfiguration.getFile(); Assert.isNotNull(key); if (!launch2model.containsKey(key)) { launch2model.put(key, new Model(launchConfiguration)); } return (T) launch2model.get(key); } return null; }
/** * Finds the highest position in <code>document</code> such that the position is <= * <code>position</code> and > <code>bound</code> and * <code>document.getChar(position) == ch</code> evaluates to <code>true</code> for at least one * ch in <code>chars</code> and the position is in the default partition. * * @param document the document being modified * @param position the first character position in <code>document</code> to be considered * @param partitioning the document partitioning * @param bound the first position in <code>document</code> to not consider any more, with * <code>scanTo</code> > <code>position</code> * @param chars an array of <code>char</code> to search for * @return the highest position of one element in <code>chars</code> in (<code>bound</code>, * <code>position</code>] that resides in a Java partition, or <code>-1</code> if none * can be found */ private static int scanBackward(IDocument document, int position, String partitioning, int bound, char[] chars) { Assert.isTrue(bound >= -1); Assert.isTrue(position < document.getLength()); Arrays.sort(chars); try { while (position > bound) { if (Arrays.binarySearch(chars, document.getChar(position)) >= 0 && isDefaultPartition(document, position, partitioning)) return position; position--; } } catch (BadLocationException e) {} return -1; }
/** * Returns array of elements from top of the stack with start as the last element (call pop until the start is found) * @param code * @return */ private ITypedRegion[] getFindStart(int code) { Assert.isTrue(!stack.isEmpty(), "Bug. Empty stack, start tag expected"); Vector<ITypedRegion> elements = new Vector<ITypedRegion>(); while (!stack.isEmpty()) { ITypedRegion region = (ITypedRegion) stack.pop(); elements.add(region); if (TagBasedTLCOutputTokenScanner.TAG_OPEN.equals(region.getType())) { TLCRegion startRegion = (TLCRegion) region; Assert.isTrue(startRegion.getMessageCode() == code, "Found a non-matching start. This is a bug."); // found a match break; } else { // not a start tag // but something else, e.G. user partition } } return (ITypedRegion[]) elements.toArray(new ITypedRegion[elements.size()]); }
@Override public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel positionGroups) throws CoreException { final ASTRewrite rewrite = cuRewrite.getASTRewrite(); VariableDeclarationFragment fragment = null; for (int i = 0; i < fNodes.length; i++) { final ASTNode node = fNodes[i]; final AST ast = node.getAST(); fragment = ast.newVariableDeclarationFragment(); fragment.setName(ast.newSimpleName(NAME_FIELD)); final FieldDeclaration declaration = ast.newFieldDeclaration(fragment); declaration.setType(ast.newPrimitiveType(PrimitiveType.LONG)); declaration.modifiers().addAll(ASTNodeFactory.newModifiers(ast, Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL)); if (!addInitializer(fragment, node)) { continue; } if (fragment.getInitializer() != null) { final TextEditGroup editGroup = createTextEditGroup(FixMessages.SerialVersion_group_description, cuRewrite); if (node instanceof AbstractTypeDeclaration) { rewrite.getListRewrite(node, ((AbstractTypeDeclaration) node).getBodyDeclarationsProperty()).insertAt(declaration, 0, editGroup); } else if (node instanceof AnonymousClassDeclaration) { rewrite.getListRewrite(node, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY).insertAt(declaration, 0, editGroup); } else if (node instanceof ParameterizedType) { final ParameterizedType type = (ParameterizedType) node; final ASTNode parent = type.getParent(); if (parent instanceof ClassInstanceCreation) { final ClassInstanceCreation creation = (ClassInstanceCreation) parent; final AnonymousClassDeclaration anonymous = creation.getAnonymousClassDeclaration(); if (anonymous != null) { rewrite.getListRewrite(anonymous, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY).insertAt(declaration, 0, editGroup); } } } else { Assert.isTrue(false); } addLinkedPositions(rewrite, fragment, positionGroups); } final String comment = CodeGeneration.getFieldComment(fUnit, declaration.getType().toString(), NAME_FIELD, "\n" /* StubUtility.getLineDelimiterUsed(fUnit) */); if (comment != null && comment.length() > 0 && !"/**\n *\n */\n".equals(comment)) { final Javadoc doc = (Javadoc) rewrite.createStringPlaceholder(comment, ASTNode.JAVADOC); declaration.setJavadoc(doc); } } if (fragment == null) { return; } positionGroups.setEndPosition(rewrite.track(fragment)); }
@SuppressWarnings("unchecked") @Override public int open() { List<Object[]> selection = getInitialElementSelections(); if (selection == null || selection.size() != fNumberOfPages) { setInitialSelections(new Object[fNumberOfPages]); selection = getInitialElementSelections(); } Assert.isTrue(selection.size() == fNumberOfPages); return super.open(); }
protected void createDependency(Button master, Control slave) { Assert.isNotNull(slave); indent(slave); MasterButtonSlaveSelectionListener listener = new MasterButtonSlaveSelectionListener(master, slave); master.addSelectionListener(listener); this.masterSlaveListeners.add(listener); }
private void editorClosed(IEditorPart part) { if (part instanceof ITextEditor) { ICodeLensController controller = codeLensControllers.remove(part); if (controller != null) { controller.uninstall(); Assert.isTrue(null == codeLensControllers.get(part), "An old ICodeLensController is not un-installed on Text Editor instance"); } } }
/** * @param componentName May not be null. All whitespaces will be replaced by "-". * @param componentVersion May not be null * @param categoryName If null, the component name is used as category name. All whitespaces will be replaced by "-". * @param actionName May not be null. All whitespaces will be replaced by "-". * @param labelDescription Optinal. May be null. * @param valueDescription Optinal. May be null. */ public UsageEventType(String componentName, String componentVersion, String actionName, String valueDescription) { Assert.isLegal(componentName!=null, "Component name may not be null"); Assert.isLegal(componentVersion!=null, "Component version may not be null"); //$NON-NLS-1$ Assert.isLegal(actionName != null, "Action name may not be null"); //$NON-NLS-1$ this.componentName = componentName.replaceAll("\\s", "-"); this.componentVersion = componentVersion; this.actionName = actionName.replaceAll("\\s", "-"); this.valueDescription = valueDescription; }
/** * Returns an RGB that lies between the given foreground and background * colors using the given mixing factor. A <code>factor</code> of 1.0 will produce a * color equal to <code>fg</code>, while a <code>factor</code> of 0.0 will produce one * equal to <code>bg</code>. * @param bg the background color * @param fg the foreground color * @param factor the mixing factor, must be in [0, 1] * * @return the interpolated color */ private static RGB blend(RGB bg, RGB fg, float factor) { // copy of org.eclipse.jface.internal.text.revisions.Colors#blend(..) Assert.isLegal(bg != null); Assert.isLegal(fg != null); Assert.isLegal(factor >= 0f && factor <= 1f); float complement = 1f - factor; return new RGB((int) (complement * bg.red + factor * fg.red), (int) (complement * bg.green + factor * fg.green), (int) (complement * bg.blue + factor * fg.blue)); }
private Image getSWTImage() { Shell shell = getShell(); final Display display; if (shell == null || shell.isDisposed()) { shell = getParentShell(); } if (shell == null || shell.isDisposed()) { display = Display.getCurrent(); // The dialog should be always instantiated in UI thread. // However it was possible to instantiate it in other threads // (the code worked in most cases) so the assertion covers // only the failing scenario. See bug 107082 for details. Assert.isNotNull(display, "The dialog should be created in UI thread"); //$NON-NLS-1$ } else { display = shell.getDisplay(); } final Image[] image = new Image[1]; display.syncExec(new Runnable() { public void run() { image[0] = display.getSystemImage(SWT.ICON_QUESTION); } }); return image[0]; }
void handle(Exception e) { if (e instanceof CoreException) { handleCoreException((CoreException) e); } else { e.printStackTrace(); Assert.isTrue(false); } }
private void editorClosed(IEditorPart part) { if (part instanceof AbstractTextEditor) { ApplyEditorConfig apply = applies.remove(part); if (apply != null) { apply.uninstall(); Assert.isTrue(null == applies.get(part), "An old ApplyEditorConfig is not un-installed on Text Editor instance"); } } }
/** * Gets the valid model. * * @param grammar * the grammar * @return the valid model */ private ValidModel getValidModel(final Grammar grammar) { if (model != null) { return model; } Resource resource = null; final String name = GrammarUtil.getName(grammar) + '.' + XTEXT_EXTENSION; URI uri; for (final Resource res : grammar.eResource().getResourceSet().getResources()) { if (res.getURI() != null && name.equals(EmfResourceUtil.getFileName(res.getURI()))) { resource = res; break; } } if (getValidURI() == null) { Assert.isNotNull(resource, NLS.bind(Messages.RESOURCE_NOT_FOUND, name)); uri = resource.getURI().trimFileExtension().appendFileExtension(VALID_EXTENSION); } else { uri = URI.createURI(getValidURI()); } resource = resource.getResourceSet().getResource(uri, true); final List<Issue> issues = VALIDATOR.validate(resource, LOGGER); for (final Issue issue : issues) { if (issue.isSyntaxError() || issue.getSeverity() == Severity.ERROR) { throw new WorkflowInterruptedException(NLS.bind(Messages.ERROR_FOUND, uri.toString())); } } model = (ValidModel) resource.getContents().get(0); return model; }
@Override public void install(ITextViewer viewer) { Assert.isNotNull(viewer); this.viewer = viewer; viewer.addTextInputListener(internalListener); IDocument document = viewer.getDocument(); if (document != null) { internalListener.inputDocumentChanged(null, document); } themeChangeListener = new ThemeChangeListener(); ThemeManager.getInstance().addPreferenceChangeListener(themeChangeListener); }
/** * Creates a rule for the given starting and ending sequence. When these sequences are detected * the rule will return the specified token. Alternatively, the sequence can also be ended by * the end of the line. Any character which follows the given escapeCharacter will be ignored. * * @param startSequence the pattern's start sequence * @param endSequence the pattern's end sequence, <code>null</code> is a legal value * @param token the token which will be returned on success * @param escapeCharacter any character following this one will be ignored * @param breaksOnEOL indicates whether the end of the line also terminates the pattern */ public MatchRule(String startSequence, String endSequence, IToken token, char escapeCharacter, boolean breaksOnEOL) { Assert.isTrue(startSequence != null && startSequence.length() > 0); Assert.isTrue(endSequence != null || breaksOnEOL); Assert.isNotNull(token); fStartSequence = startSequence.toCharArray(); fEndSequence = (endSequence == null ? new char[0] : endSequence.toCharArray()); fToken = token; fEscapeCharacter = escapeCharacter; fBreaksOnEOL = breaksOnEOL; }
/** * Adds the given {@link AbstractStep}s to this compound step. * * @param steps * the steps to add, must not be {@code null} */ public void addSteps(final List<AbstractStep> steps) { Assert.isNotNull(steps, ARGUMENT_STEPS); for (final AbstractStep step : steps) { if (step != null) { addStep(step); } } }
FoldingStructureComputationContext(IDocument document, ProjectionAnnotationModel model, boolean allowCollapsing) { Assert.isNotNull(document); Assert.isNotNull(model); fDocument = document; fModel = model; fAllowCollapsing = allowCollapsing; }
/** * Creates an expandable section within the parent created previously by calling * <code>createSectionComposite</code>. Controls can be added directly to the returned * composite, which has no layout initially. * * @param label the display name of the section * @return a composite within the expandable section */ public Composite createSection(String label) { Assert.isNotNull(fBody); final ExpandableComposite excomposite = new ExpandableComposite(fBody, SWT.NONE, ExpandableComposite.TWISTIE | ExpandableComposite.CLIENT_INDENT | ExpandableComposite.COMPACT); if (fFirstChild == null) fFirstChild = excomposite; excomposite.setText(label); String last = null; if (fLastOpenKey != null && fDialogSettingsStore != null) last = fDialogSettingsStore.getString(fLastOpenKey); if (fFirstChild == excomposite && !__NONE.equals(last) || label.equals(last)) { excomposite.setExpanded(true); if (fFirstChild != excomposite) fFirstChild.setExpanded(false); } else { excomposite.setExpanded(false); } excomposite.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, true, false)); updateSectionStyle(excomposite); manage(excomposite); Composite contents = new Composite(excomposite, SWT.NONE); excomposite.setClient(contents); return contents; }