protected void setEditorTextPreservingCarret(String newContents) throws CommonException {
    if (areEqual(newContents, doc.get())) {
      return;
    }

    LangSourceViewer sourceViewer = getEditorSourceViewer();

    ISelection sel = sourceViewer.getSelectionProvider().getSelection();

    int line = -1;
    int col = -1;
    if (sel instanceof ITextSelection) {
      ITextSelection textSelection = (ITextSelection) sel;

      try {
        line = doc.getLineOfOffset(textSelection.getOffset());
        col = textSelection.getOffset() - doc.getLineOffset(line);
      } catch (BadLocationException e) {
        // Ignore
      }
    }

    IDocument document = sourceViewer.getDocument();

    if (document instanceof IDocumentExtension4) {
      IDocumentExtension4 doc_4 = (IDocumentExtension4) document;
      // We use the DocumentRewriteSession to prevent the caret from jumping around
      DocumentRewriteSession rewriteSession =
          doc_4.startRewriteSession(DocumentRewriteSessionType.SEQUENTIAL);
      document.set(newContents);
      doc_4.stopRewriteSession(rewriteSession);
    } else {
      int topIndex = sourceViewer.getTopIndex();
      document.set(newContents);
      sourceViewer.setTopIndex(topIndex);
    }

    int newOffset = -1;
    if (line != -1 && col != -1) {
      try {
        newOffset = getOffsetFor(line, col);
      } catch (BadLocationException e) {
        // ignore
      }
    }

    if (newOffset != -1) {
      sourceViewer.getSelectionProvider().setSelection(new TextSelection(newOffset, 0));
    } else {
      sourceViewer.getSelectionProvider().setSelection(sel);
    }
  }
  /**
   * Evaluates a 'java' template in the context of a compilation unit
   *
   * @param template the template to be evaluated
   * @param compilationUnit the compilation unit in which to evaluate the template
   * @param position the position inside the compilation unit for which to evaluate the template
   * @return the evaluated template
   * @throws CoreException in case the template is of an unknown context type
   * @throws BadLocationException in case the position is invalid in the compilation unit
   * @throws TemplateException in case the evaluation fails
   */
  public static String evaluateTemplate(
      Template template, ICompilationUnit compilationUnit, int position)
      throws CoreException, BadLocationException, TemplateException {

    TemplateContextType contextType =
        JavaPlugin.getDefault()
            .getTemplateContextRegistry()
            .getContextType(template.getContextTypeId());
    if (!(contextType instanceof CompilationUnitContextType))
      throw new CoreException(
          new Status(
              IStatus.ERROR,
              JavaUI.ID_PLUGIN,
              IStatus.ERROR,
              JavaTemplateMessages.JavaContext_error_message,
              null));

    IDocument document = new Document();
    if (compilationUnit != null && compilationUnit.exists())
      document.set(compilationUnit.getSource());

    CompilationUnitContext context =
        ((CompilationUnitContextType) contextType)
            .createContext(document, position, 0, compilationUnit);
    context.setForceEvaluation(true);

    TemplateBuffer buffer = context.evaluate(template);
    if (buffer == null) return null;
    return buffer.getString();
  }
  protected void setDocumentContent(IDocument document, InputStream contentStream, String encoding)
      throws IOException {
    Reader in = null;

    try {
      if (encoding == null) {
        encoding = GeneralUtils.DEFAULT_FILE_CHARSET_NAME;
      }

      in = new BufferedReader(new InputStreamReader(contentStream, encoding), DEFAULT_BUFFER_SIZE);
      StringBuilder buffer = new StringBuilder(DEFAULT_BUFFER_SIZE);
      char[] readBuffer = new char[2048];
      int n = in.read(readBuffer);
      while (n > 0) {
        buffer.append(readBuffer, 0, n);
        n = in.read(readBuffer);
      }

      document.set(buffer.toString());

    } finally {
      if (in != null) {
        ContentUtils.close(in);
      } else {
        ContentUtils.close(contentStream);
      }
    }
  }
 /**
  * Line endings can be an issue when running tests on different OSs. This function standardizes
  * the line endings to use <code>\n</code>
  *
  * <p>It will get the text from the given editor, change the line endings, and then save the
  * editor
  *
  * @param editor standardize the line endings of the text presented in this editor.
  */
 private static void standardizeLineEndings(ITextEditor editor) {
   IDocument doc = editor.getDocumentProvider().getDocument(editor.getEditorInput());
   String contents = doc.get();
   contents = StringUtils.replace(contents, "\r\n", "\n");
   contents = StringUtils.replace(contents, "\r", "\n");
   doc.set(contents);
 }
  /*
   * (non-Javadoc)
   *
   * @see com.cea.accordcpp.core.ui.panels.AccordAbstractPanel#refreshPanel()
   */
  @Override
  protected void refreshPanel() {
    if (selectedParameter != null) {
      // Const

      isConst.setSelection(StereotypeUtil.isApplied(selectedParameter, Const.class));
      // TODO: examine effect;
      // isConst.setSelection(selectedParameter.getEffect?);

      docPtr.set(StereotypeUtil.isApplied(selectedParameter, Ptr.class) ? "*" : "");
      docRef.set(StereotypeUtil.isApplied(selectedParameter, Ref.class) ? "&" : "");
      docDefault.set(selectedParameter.getDefault());
      docArray.set(StereotypeUtil.isApplied(selectedParameter, Array.class) ? "[]" : "");
      // need definition?
    }
  }
 /**
  * Line endings can be an issue when running tests on different OSs. This function standardizes
  * the line endings to use <code>\n</code>
  *
  * <p>It will get the text from the given editor, change the line endings, and then save the
  * editor
  *
  * @param editor standardize the line endings of the text presented in this editor.
  */
 private static void standardizeLineEndings(StructuredTextEditor editor) {
   IDocument doc = editor.getTextViewer().getDocument();
   String contents = doc.get();
   contents = StringUtils.replace(contents, "\r\n", "\n");
   contents = StringUtils.replace(contents, "\r", "\n");
   doc.set(contents);
 }
  @Test
  public void testBacketHandling() {

    IDocument document = new Document();
    document.set(input.replace(CURSOR, ""));
    DocumentCommand command = new DocumentCommandStub();
    command.text = textToInsert;
    // insert text at cursor position
    command.offset = input.indexOf(CURSOR);
    // position cursor at correct position in input text
    command.caretOffset = input.indexOf(CURSOR);
    command.shiftsCaret = true;
    stategy.customizeDocumentCommand(document, command);
    System.out.println("text = '" + command.text + "'");
    String expectedDocumentAfter = expected.replace(CURSOR, "");

    System.out.println("Cursor before " + command.caretOffset);
    executeCommand(document, command);
    System.out.println("Cursor after " + command.caretOffset);
    String documentAfter = document.get();
    System.out.println("Document after: '" + documentAfter + "'");
    assertEquals(expectedDocumentAfter, documentAfter);
    int expectedCursorOffset = expected.indexOf(CURSOR);
    assertEquals("Cursor at unexpected position", expectedCursorOffset, command.caretOffset);
  }
  /** Test that modifications to the editor's content will notify reconciling listeners */
  public void testModificationReconciling() throws Exception {
    IFile file = getOrCreateFile(PROJECT_NAME + "/" + "reconcilingmodificationtest.xml");
    IWorkbenchPage activePage =
        PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
    final int[] state = new int[2];
    Arrays.fill(state, -1);
    ISourceReconcilingListener listener =
        new ISourceReconcilingListener() {
          int mod = 0;

          public void reconciled(
              IDocument document,
              IAnnotationModel model,
              boolean forced,
              IProgressMonitor progressMonitor) {
            state[1] = mod++;
          }

          public void aboutToBeReconciled() {
            state[0] = mod++;
          }
        };
    IEditorPart editor =
        IDE.openEditor(activePage, file, "org.eclipse.wst.sse.ui.StructuredTextEditor.test");
    try {
      assertTrue("Not a StructuredTextEditor", editor instanceof StructuredTextEditor);
      addReconcilingListener((StructuredTextEditor) editor, listener);
      waitForReconcile(state);
      assertTrue(
          "Initial: Reconciling did not complete in a timely fashion",
          state[0] != -1 && state[1] != -1);
      assertTrue(
          "Initial: aboutToBeReconciled not invoked first (" + state[0] + ")", state[0] == 0);
      assertTrue(
          "Initial: reconciled not invoked after aboutToBeReconciled (" + state[1] + ")",
          state[1] == 1);
      IDocument document =
          ((StructuredTextEditor) editor)
              .getDocumentProvider()
              .getDocument(editor.getEditorInput());
      assertTrue("Editor doesn't have a document", document != null);
      document.set("<?xml version=\"1.0\" ?>");
      Arrays.fill(state, -1);
      waitForReconcile(state);
      assertTrue(
          "Modified: Reconciling did not complete in a timely fashion",
          state[0] != -1 && state[1] != -1);
      assertTrue(
          "Modified: aboutToBeReconciled not invoked first (" + state[0] + ")", state[0] == 2);
      assertTrue(
          "Modified: reconciled not invoked after aboutToBeReconciled (" + state[1] + ")",
          state[1] == 3);
    } finally {
      if (editor != null && activePage != null) {
        activePage.closeEditor(editor, false);
      }
    }
  }
  public String format(String text, int startOffset, int endOffset, int kJavascriptUnit)
      throws FileDoesNotExistsException {
    IDocument doc = new Document();
    try {
      // format the file (the meat and potatoes)
      doc.set(text);
      /**
       * Format <code>source</code>, and returns a text edit that correspond to the difference
       * between the given string and the formatted string.
       *
       * <p>It returns null if the given string cannot be formatted.
       *
       * <p>If the offset position is matching a whitespace, the result can include whitespaces. It
       * would be up to the caller to get rid of preceeding whitespaces.
       *
       * @param kind Use to specify the kind of the code snippet to format. It can be any of these:
       *     K_EXPRESSION, K_STATEMENTS, K_CLASS_BODY_DECLARATIONS, K_JAVASCRIPT_UNIT, K_UNKNOWN,
       *     K_SINGLE_LINE_COMMENT, K_MULTI_LINE_COMMENT, K_JAVA_DOC
       * @param source the source to format
       * @param offset the given offset to start recording the edits (inclusive).
       * @param length the given length to stop recording the edits (exclusive).
       * @param indentationLevel the initial indentation level, used to shift left/right the entire
       *     source fragment. An initial indentation level of zero or below has no effect.
       * @param lineSeparator the line separator to use in formatted source, if set to <code>null
       *     </code>, then the platform default one will be used.
       * @return the text edit
       * @throws IllegalArgumentException if offset is lower than 0, length is lower than 0 or
       *     length is greater than source length.
       */
      TextEdit edit =
          getCodeFormatter()
              .format(
                  kJavascriptUnit,
                  text,
                  startOffset,
                  endOffset - startOffset,
                  0,
                  Settings.LINE_SEPARATOR);
      if (edit != null) {
        edit.apply(doc);
      } else {
        throw new FormattingFailedException();
      }

      return doc.get();
    } catch (BadLocationException e) {
      throw new RuntimeException(e);
    }
  }
Example #10
0
 public String format(final String input) throws BadLocationException {
   final IDocument doc = new Document();
   doc.set(input);
   final TextEdit edit =
       formatter.format(
           CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS,
           input,
           0,
           input.length(),
           0,
           "\n");
   if (edit == null) throw new RuntimeException("formatting failed");
   edit.apply(doc);
   return doc.get();
 }
  /**
   *
   *
   * <pre>
   * - We create a file with a function
   * - open the JS editor on it
   * - make some unsaved changes
   * - let it reconcile
   * - invoke CA to see that the unsaved contents are reflected in the CA
   * - close the editor without saving those changes
   * - wait for re-index of the underlying file to occur
   * - verify that the index now reflects underlying file's contents and not the unsaved changes.
   * </pre>
   *
   * @throws Exception
   */
  @Test
  public void testAPSTUD2944() throws Exception {
    // Create a test project and file
    project = createTestProject();
    IFile file = project.createFile("apstud2944.js", "function delete_me() {}\n");

    // open JS editor on file
    editor = (ITextEditor) EditorTestHelper.openInEditor(file, "com.aptana.editor.js", true);
    ISourceViewer viewer = ((AbstractThemeableEditor) editor).getISourceViewer();

    EditorTestHelper.joinReconciler((SourceViewer) viewer, 100L, 2000L, 100L);

    // Verify initial contents
    Index index = getIndexManager().getIndex(project.getURI());

    JSIndexQueryHelper _indexHelper = new JSIndexQueryHelper(project.getInnerProject());
    Collection<PropertyElement> projectGlobals = _indexHelper.getGlobals("apstud2944.js");
    assertContainsFunctions(projectGlobals, "delete_me");
    assertDoesntContainFunctions(projectGlobals, "foo");

    // Set the working copy contents to some new valid JS
    IDocument document = EditorTestHelper.getDocument(editor);
    document.set("function foo() { var eight = 8; }");

    // Wait for reconcile
    EditorTestHelper.joinReconciler((SourceViewer) viewer, 100L, 2000L, 100L);

    // get proposals at end of document
    this.processor = new JSContentAssistProcessor((AbstractThemeableEditor) editor);
    ICompletionProposal[] proposals = processor.computeCompletionProposals(viewer, 33, '\0', false);

    // verify that CA contains elements from unsaved JS in document!
    assertContains(proposals, "foo");
    assertDoesntContain(proposals, "delete_me");

    // TODO Verify "eight" is in CA inside foo?

    // Close the editor without saving, make sure we end up indexing underlying content again!
    EditorTestHelper.closeEditor(editor);

    Thread.sleep(1000); // FIXME Is there anyway to tell when indexing happens and is finished?

    // Now verify that our index reflects the file's contents and not the unsaved contents of the
    // editor.
    assertContainsFunctions(projectGlobals, "delete_me");
    assertDoesntContainFunctions(projectGlobals, "foo");
  }
  /**
   * Clear the document and show the initial prompt.
   *
   * @param addInitialCommands indicates if the initial commands should be appended to the document.
   */
  public void clear(boolean addInitialCommands) {
    startDisconnected();
    try {
      doc.set(""); // $NON-NLS-1$
      appendInvitation(true);
    } finally {
      stopDisconnected();
    }

    if (addInitialCommands) {
      try {
        doc.replace(doc.getLength(), 0, this.initialCommands);
      } catch (BadLocationException e) {
        Log.log(e);
      }
    }
  }
Example #13
0
  public void formatAll(
      IDocument doc,
      IPyEdit edit,
      boolean isOpenedFile,
      FormatStd formatStd,
      boolean throwSyntaxError)
      throws SyntaxErrorException {
    String d = doc.get();
    String delimiter = PySelection.getDelimiter(doc);
    String formatted = formatStr(d, formatStd, delimiter, throwSyntaxError);

    String contents = doc.get();
    if (contents.equals(formatted)) {
      return; // it's the same: nothing to do.
    }
    if (!isOpenedFile) {
      doc.set(formatted);
    } else {
      // let's try to apply only the differences
      int minorLen;
      int contentsLen = contents.length();
      if (contentsLen > formatted.length()) {
        minorLen = formatted.length();
      } else {
        minorLen = contentsLen;
      }
      int applyFrom = 0;
      for (; applyFrom < minorLen; applyFrom++) {
        if (contents.charAt(applyFrom) == formatted.charAt(applyFrom)) {
          continue;
        } else {
          // different
          break;
        }
      }

      try {
        doc.replace(applyFrom, contentsLen - applyFrom, formatted.substring(applyFrom));
      } catch (BadLocationException e) {
        Log.log(e);
      }
    }
  }
Example #14
0
  @Override
  public void run(IAction action) {
    if (!(editor instanceof WurstEditor)) {
      return;
    }
    WurstEditor editor = (WurstEditor) this.editor;

    // Pretty print CU
    StringBuilder prettyBuilder = new StringBuilder();
    editor.doWithCompilationUnitR(
        cu -> {
          if (cu != null) {
            PrettyPrinter.prettyPrint(cu, new MaxOneSpacer(), prettyBuilder, 0);
          }
          return null;
        });

    IDocument doc = editor.getDocumentProvider().getDocument(editor.getEditorInput());
    doc.set(prettyBuilder.toString());
  }
Example #15
0
  public void formatAll(
      IDocument doc,
      IPyEdit edit,
      boolean isOpenedFile,
      FormatStd formatStd,
      boolean throwSyntaxError)
      throws SyntaxErrorException {
    String d = doc.get();
    String delimiter = PySelection.getDelimiter(doc);
    String formatted = formatAll(formatStd, throwSyntaxError, d, delimiter);

    String contents = doc.get();
    if (contents.equals(formatted)) {
      return; // it's the same: nothing to do.
    }
    if (!isOpenedFile) {
      doc.set(formatted);
    } else {
      // let's try to apply only the differences
      TextSelectionUtils.setOnlyDifferentCode(doc, contents, formatted);
    }
  }
Example #16
0
  public void dumpInfoToConfigSection() throws BadLocationException {
    StringBuilder sb = new StringBuilder();

    if (!hasConfigSection) {
      sb.append(MyContentOutlinePage.CONFIG_MARKER).append("\n\n");
      createdConfigSection = true;
    }

    boolean change = appendOidInfos(sb);
    if (!configuration.skipThreadProcessing) {
      if (appendThreads(sb)) {
        change = true;
      }
    }

    if (!hasConfigSection) {
      ConfigurationTemplateHelp.writeTo(sb);
    }

    if (change) {
      String s = sb.toString();
      document.set(document.get() + "\n" + s);
    }
  }
 public void setText(String s) {
   if (readOnly) {
     throw new IllegalStateException("The model is read-only!");
   }
   document.set(s);
 }
Example #18
0
  /*
   * @see ITextOperationTarget#doOperation(int)
   */
  public void doOperation(int operation) {

    if (getTextWidget() == null || (!redraws() && operation != FORMAT)) return;

    switch (operation) {
      case CONTENTASSIST_PROPOSALS:
        fContentAssistant.showPossibleCompletions();
        return;
      case CONTENTASSIST_CONTEXT_INFORMATION:
        fContentAssistant.showContextInformation();
        return;
      case QUICK_ASSIST:
        // FIXME: must find a way to post to the status line
        /* String msg= */ fQuickAssistAssistant.showPossibleQuickAssists();
        // setStatusLineErrorMessage(msg);
        return;
      case INFORMATION:
        fInformationPresenter.showInformation();
        return;
      case FORMAT:
        {
          final Point selection = rememberSelection();
          final IRewriteTarget target = getRewriteTarget();
          final IDocument document = getDocument();
          IFormattingContext context = null;
          DocumentRewriteSession rewriteSession = null;

          if (document instanceof IDocumentExtension4) {
            IDocumentExtension4 extension = (IDocumentExtension4) document;
            DocumentRewriteSessionType type =
                (selection.y == 0 && document.getLength() > 1000) || selection.y > 1000
                    ? DocumentRewriteSessionType.SEQUENTIAL
                    : DocumentRewriteSessionType.UNRESTRICTED_SMALL;
            rewriteSession = extension.startRewriteSession(type);
          } else {
            setRedraw(false);
            target.beginCompoundChange();
          }

          try {

            final String rememberedContents = document.get();

            try {

              if (fContentFormatter instanceof IContentFormatterExtension) {
                final IContentFormatterExtension extension =
                    (IContentFormatterExtension) fContentFormatter;
                context = createFormattingContext();
                if (selection.y == 0) {
                  context.setProperty(FormattingContextProperties.CONTEXT_DOCUMENT, Boolean.TRUE);
                } else {
                  context.setProperty(FormattingContextProperties.CONTEXT_DOCUMENT, Boolean.FALSE);
                  context.setProperty(
                      FormattingContextProperties.CONTEXT_REGION,
                      new Region(selection.x, selection.y));
                }
                extension.format(document, context);
              } else {
                IRegion r;
                if (selection.y == 0) {
                  IRegion coverage = getModelCoverage();
                  r = coverage == null ? new Region(0, 0) : coverage;
                } else {
                  r = new Region(selection.x, selection.y);
                }
                fContentFormatter.format(document, r);
              }

              updateSlaveDocuments(document);

            } catch (RuntimeException x) {
              // fire wall for https://bugs.eclipse.org/bugs/show_bug.cgi?id=47472
              // if something went wrong we undo the changes we just did
              // TODO to be removed after 3.0 M8
              document.set(rememberedContents);
              throw x;
            }

          } finally {

            if (document instanceof IDocumentExtension4) {
              IDocumentExtension4 extension = (IDocumentExtension4) document;
              extension.stopRewriteSession(rewriteSession);
            } else {
              target.endCompoundChange();
              setRedraw(true);
            }

            restoreSelection();
            if (context != null) context.dispose();
          }
          return;
        }
      default:
        super.doOperation(operation);
    }
  }
Example #19
0
  public void createPartControl(Composite parent) {
    SashForm sash = new SashForm(parent, SWT.VERTICAL | SWT.SMOOTH);

    queryViewer = new SourceViewer(sash, null, SWT.MULTI | SWT.WRAP);
    queryString = queryViewer.getTextWidget();
    queryString.setFont(JFaceResources.getFont(JFaceResources.TEXT_FONT));
    Color background = queryString.getBackground();
    IThemeManager themeManager = PlatformUI.getWorkbench().getThemeManager();
    ITheme current = themeManager.getCurrentTheme();
    ColorRegistry colorRegistry = current.getColorRegistry();
    commentCol = colorRegistry.get(ColorProvider.COMMENT_COLOR_PREF);
    keywordCol = colorRegistry.get(ColorProvider.KEYWORD_COLOR_PREF);
    IDocument d = createDocument();
    d.set(Messages.OQLPane_F1ForHelp);

    queryViewer.addSelectionChangedListener(
        new ISelectionChangedListener() {
          public void selectionChanged(SelectionChangedEvent event) {
            updateActions();
          }
        });

    queryViewer.setDocument(d);
    queryViewer.configure(new OQLTextViewerConfiguration(getSnapshot(), commentCol, keywordCol));
    // Eclipse 4 seems to need this otherwise in high contrast mode the background is white
    queryString.setBackground(background);
    queryString.selectAll();

    PlatformUI.getWorkbench()
        .getHelpSystem()
        .setHelp(queryString, "org.eclipse.mat.ui.help.oql"); // $NON-NLS-1$
    queryString.addKeyListener(
        new KeyAdapter() {
          public void keyPressed(KeyEvent e) {
            if (e.keyCode == '\r' && (e.stateMask & SWT.MOD1) != 0) {
              executeAction.run();
              e.doit = false;
            } else if (e.keyCode == ' ' && (e.stateMask & SWT.CTRL) != 0) {
              // ctrl space combination for content assist
              contentAssistAction.run();
            } else if (e.keyCode == SWT.F5) {
              executeAction.run();
              e.doit = false;
            }
          }
        });

    queryString.addFocusListener(
        new FocusListener() {

          public void focusGained(FocusEvent e) {
            IActionBars actionBars = getEditor().getEditorSite().getActionBars();
            actionBars.setGlobalActionHandler(ActionFactory.COPY.getId(), copyQueryStringAction);
            actionBars.updateActionBars();
          }

          public void focusLost(FocusEvent e) {}
        });
    queryString.setFocus();

    createContainer(sash);

    sash.setWeights(new int[] {1, 4});

    makeActions();
    hookContextMenu();
  }
Example #20
0
  private void checkResourceFix(String name, String caretLocation, String expectedNewPath)
      throws Exception {
    IProject project = getProject();
    IFile file = getTestDataFile(project, name, FD_RES + "/" + FD_RES_LAYOUT + "/" + name);

    // Determine the offset
    final int offset = getCaretOffset(file, caretLocation);

    String osRoot = project.getLocation().toOSString();
    List<String> errors = new ArrayList<String>();
    String fileRelativePath = file.getProjectRelativePath().toPortableString();
    String filePath = osRoot + File.separator + fileRelativePath;
    // Run AaptParser such that markers are added...
    // When debugging these tests, the project gets a chance to build itself
    // so
    // the real aapt errors are there. But when the test is run directly,
    // aapt has
    // not yet run. I tried waiting for the build (using the code in
    // SampleProjectTest)
    // but this had various adverse effects (exception popups from the
    // Eclipse debugger
    // etc) so instead this test just hardcodes the aapt errors that should
    // be
    // observed on quickfix1.xml.
    assertEquals("Unit test is hardcoded to errors for quickfix1.xml", "quickfix1.xml", name);
    errors.add(
        filePath
            + ":7: error: Error: No resource found that matches the given name"
            + " (at 'text' with value '@string/firststring').");
    errors.add(
        filePath
            + ":7: error: Error: No resource found that matches the given name"
            + " (at 'layout_width' with value '@dimen/testdimen').");
    errors.add(
        filePath
            + ":13: error: Error: No resource found that matches the given name"
            + " (at 'layout' with value '@layout/testlayout').");
    AaptParser.parseOutput(errors, project);

    AaptQuickFix aaptQuickFix = new AaptQuickFix();

    // Open file
    IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
    assertNotNull(page);
    IEditorPart editor = IDE.openEditor(page, file);
    assertTrue(editor instanceof AndroidXmlEditor);
    AndroidXmlEditor layoutEditor = (AndroidXmlEditor) editor;
    final ISourceViewer viewer = layoutEditor.getStructuredSourceViewer();

    // Test marker resolution.
    IMarker[] markers =
        file.findMarkers(AndmoreAndroidConstants.MARKER_AAPT_COMPILE, true, IResource.DEPTH_ZERO);
    for (IMarker marker : markers) {
      int start = marker.getAttribute(IMarker.CHAR_START, 0);
      int end = marker.getAttribute(IMarker.CHAR_END, 0);
      if (offset >= start && offset <= end) {
        // Found the target marker. Now check the marker resolution of
        // it.
        assertTrue(aaptQuickFix.hasResolutions(marker));
        IMarkerResolution[] resolutions = aaptQuickFix.getResolutions(marker);
        assertNotNull(resolutions);
        assertEquals(1, resolutions.length);
        IMarkerResolution resolution = resolutions[0];
        assertNotNull(resolution);
        assertTrue(resolution.getLabel().contains("Create resource"));

        // Not running marker yet -- if we create the files here they
        // already
        // exist when the quick assist code runs. (The quick fix and the
        // quick assist
        // mostly share code for the implementation anyway.)
        // resolution.run(marker);
        break;
      }
    }

    // Next test quick assist.

    IQuickAssistInvocationContext invocationContext =
        new IQuickAssistInvocationContext() {
          @Override
          public int getLength() {
            return 0;
          }

          @Override
          public int getOffset() {
            return offset;
          }

          @Override
          public ISourceViewer getSourceViewer() {
            return viewer;
          }
        };
    ICompletionProposal[] proposals = aaptQuickFix.computeQuickAssistProposals(invocationContext);
    assertNotNull(proposals);
    assertTrue(proposals.length == 1);
    ICompletionProposal proposal = proposals[0];

    assertNotNull(proposal.getAdditionalProposalInfo());
    assertNotNull(proposal.getImage());
    assertTrue(proposal.getDisplayString().contains("Create resource"));

    IDocument document = new Document();
    String fileContent = AndmoreAndroidPlugin.readFile(file);
    document.set(fileContent);

    // Apply quick fix
    proposal.apply(document);

    IPath path = new Path(expectedNewPath);
    IFile newFile = project.getFile(path);
    assertNotNull(path.toPortableString(), newFile);

    // Ensure that the newly created file was opened
    IEditorPart currentFile = AdtUtils.getActiveEditor();
    assertEquals(
        newFile.getProjectRelativePath(),
        ((FileEditorInput) currentFile.getEditorInput()).getFile().getProjectRelativePath());

    // Look up caret offset
    assertTrue(
        currentFile != null ? currentFile.getClass().getName() : "null",
        currentFile instanceof AndroidXmlEditor);
    AndroidXmlEditor newEditor = (AndroidXmlEditor) currentFile;
    ISourceViewer newViewer = newEditor.getStructuredSourceViewer();
    Point selectedRange = newViewer.getSelectedRange();

    String newFileContents = AndmoreAndroidPlugin.readFile(newFile);

    // Insert selection markers -- [ ] for the selection range, ^ for the
    // caret
    String newFileWithCaret = addSelection(newFileContents, selectedRange);
    newFileWithCaret = removeSessionData(newFileWithCaret);

    assertEqualsGolden(name, newFileWithCaret);
  }