Search in sources :

Example 11 with IJsTranslation

use of org.eclipse.wst.jsdt.web.core.javascript.IJsTranslation in project webtools.sourceediting by eclipse.

the class JsValidator method performValidation.

void performValidation(IFile f, IReporter reporter, IStructuredModel model, boolean inBatch) {
    if (model instanceof IDOMModel) {
        IDOMModel domModel = (IDOMModel) model;
        JsTranslationAdapterFactory.setupAdapterFactory(domModel);
        IDOMDocument xmlDoc = domModel.getDocument();
        JsTranslationAdapter translationAdapter = (JsTranslationAdapter) xmlDoc.getAdapterFor(IJsTranslation.class);
        // translationAdapter.resourceChanged();
        IJsTranslation translation = translationAdapter.getJsTranslation(false);
        if (!reporter.isCancelled()) {
            translation.setProblemCollectingActive(true);
            translation.reconcileCompilationUnit();
            List problems = translation.getProblems();
            // only update task markers if the model is the same as what's on disk
            boolean updateTasks = !domModel.isDirty() && f != null && f.isAccessible();
            if (updateTasks) {
                // remove old JavaScript task markers
                try {
                    IMarker[] foundMarkers = f.findMarkers(JAVASCRIPT_TASK_MARKER_TYPE, true, IResource.DEPTH_ONE);
                    for (int i = 0; i < foundMarkers.length; i++) {
                        foundMarkers[i].delete();
                    }
                } catch (CoreException e) {
                    Logger.logException(e);
                }
            }
            // add new messages
            for (int i = 0; i < problems.size() && !reporter.isCancelled(); i++) {
                IProblem problem = (IProblem) problems.get(i);
                IMessage m = createMessageFromProblem(problem, f, translation, domModel.getStructuredDocument());
                if (m != null) {
                    if (problem.getID() == IProblem.Task) {
                        if (updateTasks) {
                            // add new JavaScript task marker
                            try {
                                IMarker task = f.createMarker(JAVASCRIPT_TASK_MARKER_TYPE);
                                task.setAttribute(IMarker.LINE_NUMBER, new Integer(m.getLineNumber()));
                                task.setAttribute(IMarker.CHAR_START, new Integer(m.getOffset()));
                                task.setAttribute(IMarker.CHAR_END, new Integer(m.getOffset() + m.getLength()));
                                task.setAttribute(IMarker.MESSAGE, m.getText());
                                task.setAttribute(IMarker.USER_EDITABLE, Boolean.FALSE);
                                switch(m.getSeverity()) {
                                    case IMessage.HIGH_SEVERITY:
                                        {
                                            task.setAttribute(IMarker.PRIORITY, new Integer(IMarker.PRIORITY_HIGH));
                                            task.setAttribute(IMarker.SEVERITY, new Integer(IMarker.SEVERITY_ERROR));
                                        }
                                        break;
                                    case IMessage.LOW_SEVERITY:
                                        {
                                            task.setAttribute(IMarker.PRIORITY, new Integer(IMarker.PRIORITY_LOW));
                                            task.setAttribute(IMarker.SEVERITY, new Integer(IMarker.SEVERITY_INFO));
                                        }
                                        break;
                                    default:
                                        {
                                            task.setAttribute(IMarker.PRIORITY, new Integer(IMarker.PRIORITY_NORMAL));
                                            task.setAttribute(IMarker.SEVERITY, new Integer(IMarker.SEVERITY_WARNING));
                                        }
                                }
                            } catch (CoreException e) {
                                Logger.logException(e);
                            }
                        }
                    } else {
                        reporter.addMessage(fMessageOriginator, m);
                    }
                }
            }
        }
    }
}
Also used : IJsTranslation(org.eclipse.wst.jsdt.web.core.javascript.IJsTranslation) IDOMModel(org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel) IMessage(org.eclipse.wst.validation.internal.provisional.core.IMessage) IDOMDocument(org.eclipse.wst.xml.core.internal.provisional.document.IDOMDocument) JsTranslationAdapter(org.eclipse.wst.jsdt.web.core.javascript.JsTranslationAdapter) IProblem(org.eclipse.wst.jsdt.core.compiler.IProblem) CoreException(org.eclipse.core.runtime.CoreException) ArrayList(java.util.ArrayList) List(java.util.List) IMarker(org.eclipse.core.resources.IMarker)

Example 12 with IJsTranslation

use of org.eclipse.wst.jsdt.web.core.javascript.IJsTranslation in project webtools.sourceediting by eclipse.

the class FormattingStrategyJSDT method format.

/*
	 * @see org.eclipse.jface.text.formatter.ContextBasedFormattingStrategy#format()
	 */
public void format() {
    super.format();
    final IStructuredDocument document = (IStructuredDocument) fDocuments.removeFirst();
    final TypedPosition partition = (TypedPosition) fPartitions.removeFirst();
    if (document != null) {
        // calculate the indent of the leading <script> tag because we need to add that indent level to the JS indent level
        IStructuredDocumentRegion scriptTagStartRegion = document.getRegionAtCharacterOffset(partition.offset - 1);
        // $NON-NLS-1$
        String scriptRegionIndent = "";
        if (scriptTagStartRegion != null) {
            try {
                int scriptRegionIndentLevel = getIndentOfLine(document, document.getLineOfOffset(scriptTagStartRegion.getStartOffset())).length();
                scriptRegionIndent = getIndentationString(getPreferences(), scriptRegionIndentLevel);
                this.startIndentLevel += scriptRegionIndentLevel;
            } catch (BadLocationException e) {
                // $NON-NLS-1$
                Logger.logException("Could not calculate starting indent of the script region, using 0", e);
            }
        }
        String lineDelim = TextUtilities.getDefaultLineDelimiter(document);
        try {
            // get the JS text from the document (not translated)
            String jsTextNotTranslated = document.get(partition.getOffset(), partition.getLength());
            String originalText = jsTextNotTranslated;
            // deal with getting the JS text and unwrapping it from any <!-- //--> statements
            String preText = "";
            String postText = lineDelim + scriptRegionIndent;
            // find and remove start comment tag if it's there
            // $NON-NLS-1$
            Pattern startPattern = Pattern.compile("(\\A(\\s*<!--.*(" + lineDelim + ")?))");
            Matcher matcher = startPattern.matcher(jsTextNotTranslated);
            if (matcher.find()) {
                preText = lineDelim + scriptRegionIndent + matcher.group().trim();
                // $NON-NLS-1$
                jsTextNotTranslated = matcher.replaceFirst("");
            }
            // find and remove end comment tag if it's there
            matcher = END_PATTERN.matcher(jsTextNotTranslated);
            if (matcher.find()) {
                // $NON-NLS-1$
                jsTextNotTranslated = matcher.replaceFirst("");
                postText = lineDelim + scriptRegionIndent + matcher.group().trim() + postText;
            }
            /*
				 * replace the text in the document with the non-translated JS
				 * text but without HTML leading and trailing comments
				 */
            int scriptLength = jsTextNotTranslated.length();
            TextEdit replaceEdit = null;
            if (scriptLength != originalText.length()) {
                replaceEdit = new ReplaceEdit(partition.getOffset(), partition.getLength(), jsTextNotTranslated);
                replaceEdit.apply(document);
            }
            // translate the web page without the script "wrapping"
            IJsTranslation translation = getTranslation(document);
            String jsTextTranslated = translation.getJsText();
            /*
				 * Set a default replace text that is the original contents
				 * with a new line and proper indentation in front
				 */
            String replaceText = lineDelim + getIndentationString(getPreferences(), startIndentLevel) + jsTextNotTranslated;
            int javaScriptOffset = ((JsTranslation) translation).getJavaScriptOffset(partition.getOffset());
            // known range, proceed
            if (javaScriptOffset >= 0) {
                // format the translated text
                TextEdit edit = CodeFormatterUtil.format2(CodeFormatter.K_JAVASCRIPT_UNIT, jsTextTranslated, javaScriptOffset, scriptLength, startIndentLevel, lineDelim, getPreferences());
                IDocument jsDoc = new Document(jsTextTranslated);
                if (edit != null) {
                    /*
						 * Put the original (possibly not JS) text back into the doc
						 * to which we're applying the edit
						 */
                    if (translation instanceof JsTranslation) {
                        IJsTranslator translator = ((JsTranslation) translation).getTranslator();
                        if (translator instanceof JsTranslator) {
                            Region[] regions = ((JsTranslator) translator).getGeneratedRanges();
                            Arrays.sort(regions, new Comparator() {

                                public int compare(Object o1, Object o2) {
                                    return ((IRegion) o1).getOffset() - ((IRegion) o2).getOffset();
                                }
                            });
                            /*
								 * for each web page range representing content needing replacements, replace it with the
								 * original web page's text
								 */
                            for (int r = 0; r < regions.length; ++r) {
                                int javascriptOffset = ((JsTranslation) translation).getJavaScriptOffset(regions[r].getOffset());
                                if (javascriptOffset > 0) {
                                    jsDoc.replace(javascriptOffset, regions[r].getLength(), document.get(regions[r].getOffset(), regions[r].getLength()));
                                }
                            }
                        }
                    }
                    edit.apply(jsDoc);
                    replaceText = lineDelim + getIndentationString(getPreferences(), startIndentLevel) + (jsDoc.get(edit.getOffset(), edit.getLength())).trim();
                } else {
                    /*
						 * Revert changes (it may still appear dirty, though,
						 * because of the above edits having been applied)
						 */
                    replaceEdit = new ReplaceEdit(partition.getOffset(), scriptLength, originalText);
                    replaceEdit.apply(document);
                    return;
                }
            }
            // apply edit to html doc using the formated translated text and the possible leading and trailing html comments
            replaceText = preText + replaceText + postText;
            replaceEdit = new ReplaceEdit(partition.getOffset(), scriptLength, replaceText);
            replaceEdit.apply(document);
        } catch (BadLocationException e) {
            Logger.logException(e);
        }
    }
}
Also used : IJsTranslation(org.eclipse.wst.jsdt.web.core.javascript.IJsTranslation) Pattern(java.util.regex.Pattern) IStructuredDocumentRegion(org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion) Matcher(java.util.regex.Matcher) JsTranslator(org.eclipse.wst.jsdt.web.core.javascript.JsTranslator) IJsTranslator(org.eclipse.wst.jsdt.web.core.javascript.IJsTranslator) JsTranslation(org.eclipse.wst.jsdt.web.core.javascript.JsTranslation) IJsTranslation(org.eclipse.wst.jsdt.web.core.javascript.IJsTranslation) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) IDOMDocument(org.eclipse.wst.xml.core.internal.provisional.document.IDOMDocument) BasicStructuredDocument(org.eclipse.wst.sse.core.internal.text.BasicStructuredDocument) IStructuredDocument(org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument) IJsTranslator(org.eclipse.wst.jsdt.web.core.javascript.IJsTranslator) IRegion(org.eclipse.jface.text.IRegion) Comparator(java.util.Comparator) TypedPosition(org.eclipse.jface.text.TypedPosition) TextEdit(org.eclipse.text.edits.TextEdit) ReplaceEdit(org.eclipse.text.edits.ReplaceEdit) Region(org.eclipse.jface.text.Region) IRegion(org.eclipse.jface.text.IRegion) IStructuredDocumentRegion(org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion) IStructuredDocument(org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument) BadLocationException(org.eclipse.jface.text.BadLocationException) IDocument(org.eclipse.jface.text.IDocument)

Example 13 with IJsTranslation

use of org.eclipse.wst.jsdt.web.core.javascript.IJsTranslation in project webtools.sourceediting by eclipse.

the class JSDTHyperlinkDetector method getJsTranslation.

/**
 * Get JSP translation object
 *
 * @return JSPTranslation if one exists, null otherwise
 */
private IJsTranslation getJsTranslation(IDocument document) {
    IJsTranslation translation = null;
    IDOMModel xmlModel = null;
    try {
        xmlModel = (IDOMModel) StructuredModelManager.getModelManager().getExistingModelForRead(document);
        if (xmlModel != null) {
            IDOMDocument xmlDoc = xmlModel.getDocument();
            JsTranslationAdapter adapter = (JsTranslationAdapter) xmlDoc.getAdapterFor(IJsTranslation.class);
            if (adapter != null) {
                translation = adapter.getJsTranslation(true);
            }
        }
    } finally {
        if (xmlModel != null) {
            xmlModel.releaseFromRead();
        }
    }
    return translation;
}
Also used : IJsTranslation(org.eclipse.wst.jsdt.web.core.javascript.IJsTranslation) IDOMModel(org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel) IDOMDocument(org.eclipse.wst.xml.core.internal.provisional.document.IDOMDocument) JsTranslationAdapter(org.eclipse.wst.jsdt.web.core.javascript.JsTranslationAdapter)

Example 14 with IJsTranslation

use of org.eclipse.wst.jsdt.web.core.javascript.IJsTranslation in project webtools.sourceediting by eclipse.

the class JSPJavaSelectionProvider method getSelection.

static IJavaScriptElement[] getSelection(ITextEditor textEditor) {
    IJavaScriptElement[] elements = null;
    IDocument document = textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput());
    ISelection selection = textEditor.getSelectionProvider().getSelection();
    if (selection instanceof ITextSelection) {
        ITextSelection textSelection = (ITextSelection) selection;
        // get the JSP translation object for this editor's document
        IStructuredModel model = null;
        try {
            model = StructuredModelManager.getModelManager().getExistingModelForRead(document);
            if (model instanceof IDOMModel) {
                IDOMModel xmlModel = (IDOMModel) model;
                IDOMDocument xmlDoc = xmlModel.getDocument();
                JsTranslationAdapter adapter = (JsTranslationAdapter) xmlDoc.getAdapterFor(IJsTranslation.class);
                if (adapter != null) {
                    IJsTranslation translation = adapter.getJsTranslation(true);
                    elements = translation.getElementsFromJsRange(translation.getJavaScriptOffset(textSelection.getOffset()), translation.getJavaScriptOffset(textSelection.getOffset() + textSelection.getLength()));
                }
            }
        } finally {
            if (model != null) {
                model.releaseFromRead();
            }
        }
    }
    if (elements == null) {
        elements = new IJavaScriptElement[0];
    }
    return elements;
}
Also used : IJsTranslation(org.eclipse.wst.jsdt.web.core.javascript.IJsTranslation) IDOMModel(org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel) IJavaScriptElement(org.eclipse.wst.jsdt.core.IJavaScriptElement) ISelection(org.eclipse.jface.viewers.ISelection) IDOMDocument(org.eclipse.wst.xml.core.internal.provisional.document.IDOMDocument) IStructuredModel(org.eclipse.wst.sse.core.internal.provisional.IStructuredModel) JsTranslationAdapter(org.eclipse.wst.jsdt.web.core.javascript.JsTranslationAdapter) IDocument(org.eclipse.jface.text.IDocument) ITextSelection(org.eclipse.jface.text.ITextSelection)

Example 15 with IJsTranslation

use of org.eclipse.wst.jsdt.web.core.javascript.IJsTranslation in project webtools.sourceediting by eclipse.

the class JSDTContentAssistantProcessor method computeCompletionProposals.

/**
 * Returns a list of completion proposals based on the specified location
 * within the document that corresponds to the current cursor position
 * within the text viewer.
 *
 * @param viewer
 *            the viewer whose document is used to compute the proposals
 * @param documentPosition
 *            an offset within the document for which completions should be
 *            computed
 * @return an array of completion proposals or <code>null</code> if no
 *         proposals are possible
 */
public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int pos) {
    initialize(pos);
    JSDTProposalCollector collector = null;
    IDOMModel xmlModel = null;
    try {
        fViewer = viewer;
        xmlModel = (IDOMModel) StructuredModelManager.getModelManager().getExistingModelForRead(fViewer.getDocument());
        IDOMDocument xmlDoc = xmlModel.getDocument();
        JsTranslationAdapterFactory.setupAdapterFactory(xmlModel);
        JsTranslationAdapter translationAdapter = (JsTranslationAdapter) xmlDoc.getAdapterFor(IJsTranslation.class);
        if (translationAdapter != null) {
            IJsTranslation translation = translationAdapter.getJsTranslation(true);
            fJavaPosition = translation.getJavaScriptOffset(getDocumentPosition());
            try {
                IJavaScriptUnit cu = translation.getCompilationUnit();
                // or without a valid position
                if (cu == null || -1 == fJavaPosition) {
                    return new ICompletionProposal[0];
                }
                collector = getProposalCollector();
                synchronized (cu) {
                    cu.codeComplete(fJavaPosition, collector, null);
                }
            } catch (CoreException coreEx) {
                // a possible Java Model Exception due to not being a Web
                // (Java) Project
                coreEx.printStackTrace();
            }
        }
    } catch (Exception exc) {
        exc.printStackTrace();
    // throw out exceptions on code assist.
    } finally {
        if (xmlModel != null) {
            xmlModel.releaseFromRead();
        }
    }
    ICompletionProposal[] results = new ICompletionProposal[0];
    if (collector != null) {
        results = collector.getJSPCompletionProposals();
        if (results == null || results.length < 1) {
            fErrorMessage = JsUIMessages.Java_Content_Assist_is_not_UI_;
        }
    }
    return results;
}
Also used : IJsTranslation(org.eclipse.wst.jsdt.web.core.javascript.IJsTranslation) CoreException(org.eclipse.core.runtime.CoreException) IDOMModel(org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel) ICompletionProposal(org.eclipse.jface.text.contentassist.ICompletionProposal) IDOMDocument(org.eclipse.wst.xml.core.internal.provisional.document.IDOMDocument) JsTranslationAdapter(org.eclipse.wst.jsdt.web.core.javascript.JsTranslationAdapter) IJavaScriptUnit(org.eclipse.wst.jsdt.core.IJavaScriptUnit) CoreException(org.eclipse.core.runtime.CoreException)

Aggregations

IJsTranslation (org.eclipse.wst.jsdt.web.core.javascript.IJsTranslation)51 JsTranslationAdapter (org.eclipse.wst.jsdt.web.core.javascript.JsTranslationAdapter)41 IDOMModel (org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel)41 IStructuredModel (org.eclipse.wst.sse.core.internal.provisional.IStructuredModel)32 IDOMDocument (org.eclipse.wst.xml.core.internal.provisional.document.IDOMDocument)15 List (java.util.List)6 IJavaScriptElement (org.eclipse.wst.jsdt.core.IJavaScriptElement)6 IDocument (org.eclipse.jface.text.IDocument)5 IStructuredDocument (org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument)5 IModelManager (org.eclipse.wst.sse.core.internal.provisional.IModelManager)4 CoreException (org.eclipse.core.runtime.CoreException)3 BadLocationException (org.eclipse.jface.text.BadLocationException)3 Document (org.eclipse.jface.text.Document)3 JavaScriptModelException (org.eclipse.wst.jsdt.core.JavaScriptModelException)3 ArrayList (java.util.ArrayList)2 IRegion (org.eclipse.jface.text.IRegion)2 ITypedRegion (org.eclipse.jface.text.ITypedRegion)2 ISelection (org.eclipse.jface.viewers.ISelection)2 IProblem (org.eclipse.wst.jsdt.core.compiler.IProblem)2 NodeImpl (org.eclipse.wst.xml.core.internal.document.NodeImpl)2