/**
   * Selects specified text in specified opened editor, shows open on options via selecting Navigate
   * -> Open Hyperlink and select one of them specified by openOnOption
   *
   * @param bot
   * @param editorTitle
   * @param textToSelect
   * @param selectionOffset
   * @param selectionLength
   * @param textToSelectIndex
   * @param openOnOption
   */
  public static SWTBotEditor selectOpenOnOption(
      SWTBotExt bot,
      String editorTitle,
      String textToSelect,
      int selectionOffset,
      int selectionLength,
      int textToSelectIndex,
      String openOnOption) {
    showOpenOnOptions(
        bot, editorTitle, textToSelect, selectionOffset, selectionLength, textToSelectIndex);

    SWTBotTable table = bot.activeShell().bot().table(0);

    boolean optionFound = false;
    String foundOptions = "";

    for (int i = 0; i < table.rowCount(); i++) {
      String foundOption = table.getTableItem(i).getText();
      foundOptions = foundOptions + foundOption + ", ";
      if (foundOption.contains(openOnOption)) {
        optionFound = true;
        table.click(i, 0);
        break;
      }
    }
    foundOptions = foundOptions.substring(0, foundOptions.length() - 3);
    assertTrue(
        openOnOption
            + " was not found in open on options of "
            + textToSelect
            + " Found: "
            + foundOptions,
        optionFound);
    return bot.activeEditor();
  }
  /**
   * Selects specified text in specified opened editor and shows open on options via selecting
   * Navigate -> Open Hyperlink
   *
   * @param bot
   * @param editorTitle
   * @param textToSelect
   * @param selectionOffset
   * @param selectionLength
   * @param textToSelectIndex
   */
  public static void showOpenOnOptions(
      SWTBotExt bot,
      String editorTitle,
      String textToSelect,
      int selectionOffset,
      int selectionLength,
      int textToSelectIndex) {

    SWTJBTExt.selectTextInSourcePane(
        bot, editorTitle, textToSelect, selectionOffset, selectionLength, textToSelectIndex);
    bot.editorByTitle(editorTitle).show();
    bot.editorByTitle(editorTitle).setFocus();
    bot.menu(IDELabel.Menu.NAVIGATE).menu(IDELabel.Menu.OPEN_HYPERLINK).click();

    bot.waitUntil(new ActiveShellContainsWidget(bot, Table.class));
  }
  /**
   * Checks Content Assist content on specified position within editor with editorTitle and checks
   * if expectedProposalList is equal to current Proposal List
   *
   * @param editorTitle
   * @param textToSelect
   * @param selectionOffset
   * @param selectionLength
   * @param textToSelectIndex
   * @param expectedProposalList
   * @param mustEquals
   */
  public static SWTBotEditor checkContentAssistContent(
      SWTBotExt bot,
      String editorTitle,
      String textToSelect,
      int selectionOffset,
      int selectionLength,
      int textToSelectIndex,
      List<String> expectedProposalList,
      boolean mustEquals) {

    SWTJBTExt.selectTextInSourcePane(
        bot, editorTitle, textToSelect, selectionOffset, selectionLength, textToSelectIndex);

    bot.sleep(Timing.time1S());

    SWTBotEditorExt editor = SWTTestExt.bot.swtBotEditorExtByTitle(editorTitle);
    ContentAssistBot contentAssist = editor.contentAssist();
    List<String> currentProposalList = contentAssist.getProposalList();
    assertTrue(
        "Code Assist menu has incorrect menu items.\n"
            + "Expected Proposal Menu Labels vs. Current Proposal Menu Labels :\n"
            + FormatUtils.getListsDiffFormatted(expectedProposalList, currentProposalList),
        mustEquals
            ? expectedProposalList.equals(currentProposalList)
            : currentProposalList.containsAll(expectedProposalList));

    return editor;
  }
  /**
   * Checks Content Assist auto proposal. It's case when there is only one content assist item and
   * that item is automatically inserted into editor and checks if expectedProposalList is equal to
   * current Proposal List
   *
   * @param editorTitle
   * @param textToSelect
   * @param selectionOffset
   * @param selectionLength
   * @param textToSelectIndex
   * @param expectedInsertedText
   */
  public static SWTBotEditor checkContentAssistAutoProposal(
      SWTBotExt bot,
      String editorTitle,
      String textToSelect,
      int selectionOffset,
      int selectionLength,
      int textToSelectIndex,
      String expectedInsertedText) {

    SWTJBTExt.selectTextInSourcePane(
        bot, editorTitle, textToSelect, selectionOffset, selectionLength, textToSelectIndex);

    bot.sleep(Timing.time1S());

    SWTBotEditorExt editor = SWTTestExt.bot.swtBotEditorExtByTitle(editorTitle);
    String editorLineBeforeInsert = editor.getTextOnCurrentLine();
    int xPos = editor.cursorPosition().column;
    String expectedEditorLineAfterInsert =
        editorLineBeforeInsert.substring(0, xPos)
            + expectedInsertedText
            + editorLineBeforeInsert.substring(xPos);
    ContentAssistBot contentAssist = editor.contentAssist();
    contentAssist.invokeContentAssist();
    String editorLineAfterInsert = editor.getTextOnCurrentLine();
    assertTrue(
        "Text on current line should be:\n"
            + expectedEditorLineAfterInsert
            + "\nbut is:\n"
            + editorLineAfterInsert,
        editorLineAfterInsert.equals(expectedEditorLineAfterInsert));

    return editor;
  }
  private static SWTBotEditor checkActiveEditorTitle(SWTBotExt bot, String expectedOpenedFileName) {

    SWTBotEditor activeEditor = null;
    try {
      bot.waitUntil(
          new ActiveEditorHasTitleCondition(bot, expectedOpenedFileName), Timing.time10S());
      activeEditor = bot.activeEditor();
    } catch (TimeoutException toe) {
      activeEditor = bot.activeEditor();
      fail(
          "Opened file has to have title "
              + expectedOpenedFileName
              + " but has "
              + activeEditor.getTitle());
    }

    return activeEditor;
  }
 private void findSelectEnterpriseRuntimeLibrary(SWTBotExt bot) throws Exception {
   SWTBotTree libraryTree = bot.tree(1);
   boolean libraryFound = false;
   for (SWTBotTreeItem libraryItem : libraryTree.getAllItems()) {
     if (libraryItem.getText().contains("JBoss Enterprise Application Platform")) {
       libraryTree.select(libraryItem);
       libraryFound = true;
       break;
     }
   }
   if (!libraryFound) throw new RuntimeException("No runtime library has been found");
 }
  /**
   * Applies Open On (F3) on textToSelect within editor with editorTitle and checks if
   * expectedOpenedFileName was opened
   *
   * @param editorTitle
   * @param textToSelect
   * @param selectionOffset
   * @param selectionLength
   * @param textToSelectIndex
   * @param expectedOpenedFileName
   */
  public static SWTBotEditor checkOpenOnFileIsOpened(
      SWTBotExt bot,
      String editorTitle,
      String textToSelect,
      int selectionOffset,
      int selectionLength,
      int textToSelectIndex,
      String expectedOpenedFileName) {

    SWTBotEclipseEditor sourceEditor =
        SWTJBTExt.selectTextInSourcePane(
            bot, editorTitle, textToSelect, selectionOffset, selectionLength, textToSelectIndex);

    bot.sleep(Timing.time3S());

    sourceEditor.setFocus();
    // process UI Events
    UIThreadRunnable.syncExec(
        new VoidResult() {
          @Override
          public void run() {}
        });
    bot.sleep(Timing.time3S());
    new SWTUtilExt(bot).waitForNonIgnoredJobs();

    KeyboardHelper.typeKeyCodeUsingAWT(KeyEvent.VK_F3);
    // process UI Events
    UIThreadRunnable.syncExec(
        new VoidResult() {
          @Override
          public void run() {}
        });
    bot.sleep(Timing.time3S());
    new SWTUtilExt(bot).waitForNonIgnoredJobs();

    return checkActiveEditorTitle(bot, expectedOpenedFileName);
  }
 private void removeRuntimeLibrary(
     final SWTBotTree tree, SWTBotTreeItem item, SWTBotExt bot, SWTUtilExt util) {
   nodeContextMenu(tree, item, "Build Path", "Configure Build Path...").click();
   bot.activeShell().activate();
   bot.tabItem("Libraries").activate();
   assertTrue(!bot.button("Remove").isEnabled());
   try {
     findSelectEnterpriseRuntimeLibrary(bot);
     assertTrue(bot.button("Remove").isEnabled());
     bot.button("Remove").click();
     bot.button("OK").click();
     util.waitForNonIgnoredJobs();
   } catch (Exception e) {
     e.printStackTrace();
     bot.button("Cancel").click();
   }
 }
  /**
   * Applies Content Assist auto proposal. It's case when there is only one content assist item and
   * that item is automatically inserted into editor
   *
   * @param editorTitle
   * @param textToSelect
   * @param selectionOffset
   * @param selectionLength
   * @param textToSelectIndex
   */
  public static SWTBotEditor applyContentAssistAutoProposal(
      SWTBotExt bot,
      String editorTitle,
      String textToSelect,
      int selectionOffset,
      int selectionLength,
      int textToSelectIndex) {

    SWTJBTExt.selectTextInSourcePane(
        bot, editorTitle, textToSelect, selectionOffset, selectionLength, textToSelectIndex);

    bot.sleep(Timing.time1S());

    SWTBotEditorExt editor = SWTTestExt.bot.swtBotEditorExtByTitle(editorTitle);
    ContentAssistBot contentAssist = editor.contentAssist();
    contentAssist.invokeContentAssist();

    return editor;
  }
  public void testScrollingSynchronization() throws Throwable {
    /*
     * Copy big file
     */
    try {
      FileHelper.copyFilesBinary(
          new File(
              getPathToRootResources(
                  IDELabel.JsfProjectTree.WEB_CONTENT + "/" + FACELETS_JSP)), // $NON-NLS-1$
          new File(
              FileHelper.getProjectLocation(JBT_TEST_PROJECT_NAME, bot),
              IDELabel.JsfProjectTree.WEB_CONTENT
                  + "/"
                  + IDELabel.JsfProjectTree.PAGES)); // $NON-NLS-1$
    } catch (IOException ioe) {
      throw new RuntimeException(
          "Unable to copy necessary files from plugin's resources directory: ", //$NON-NLS-1$
          ioe);
    }
    bot.menu(IDELabel.Menu.FILE).menu(IDELabel.Menu.REFRESH).click();
    util.waitForAll();
    eclipse.maximizeActiveShell();
    util.sleep(TIME_1S);
    /*
     * Open big file
     */
    openPage(FACELETS_JSP);
    util.waitForAll();
    jspEditor = botExt.swtBotEditorExtByTitle(FACELETS_JSP);
    setEditor(jspEditor);
    setEditorText(jspEditor.getText());
    webBrowser = new SWTBotWebBrowser(FACELETS_JSP, botExt);
    /*
     * Synchronize scrolling button
     */
    SWTBotToolbarToggleButton button = botExt.toolbarToggleButtonWithTooltip(TOOL_TIP);
    if (!button.isEnabled()) {
      button.click();
      util.sleep(TIME_1S);
    }
    assertTrue("Toolbar button should be enabled", button.isEnabled()); // $NON-NLS-1$
    Display d = bot.getDisplay();

    /*
     * Test initial position
     */
    jspEditor.deselectAndSetCursorPosition(0, 0);
    util.sleep(TIME_1S);
    Position cursorPosition = jspEditor.cursorPosition();
    assertEquals("Source line position is wrong", 0, cursorPosition.line); // $NON-NLS-1$

    nsIDOMWindow domWindow = webBrowser.getContentDOMWindow();
    nsIDOMWindowInternal windowInternal =
        org.jboss.tools.vpe.xulrunner.util.XPCOM.queryInterface(
            domWindow, nsIDOMWindowInternal.class);
    /*
     * Set source position -- visual part should be scrolled.
     */
    int scrollY = windowInternal.getScrollY();
    int halfHeight = windowInternal.getScrollMaxY() / 2;
    assertEquals("Step 1. Initital visual position is wrong", 0, scrollY); // $NON-NLS-1$
    /*
     * Test the bottom position.
     * Press CTRL+END to get to the end of the page.
     */
    jspEditor.setFocus();
    KeyboardHelper.typeKeyCodeUsingSWT(d, SWT.END, SWT.CTRL);
    util.sleep(TIME_1S);
    cursorPosition = jspEditor.cursorPosition();
    assertEquals("Source line position is wrong", 1307, cursorPosition.line); // $NON-NLS-1$
    /*
     * Press ARROW_UP several times to select element at the bottom
     */
    for (int i = 0; i < 5; i++) {
      KeyboardHelper.pressKeyCode(d, SWT.ARROW_UP);
      util.sleep(TIME_1S);
    }
    cursorPosition = jspEditor.cursorPosition();
    assertEquals("Source line position is wrong", 1302, cursorPosition.line); // $NON-NLS-1$
    scrollY = windowInternal.getScrollY();
    assertTrue(
        "Step 2. Visual scrolling should be at the bottom of the page,\ncurrent scrolling opstion is " //$NON-NLS-1$
            + scrollY
            + ", but should be more than "
            + halfHeight,
        scrollY > halfHeight); // $NON-NLS-1$
    /*
     * Test custom scroll position in Visual Part
     */
    jspEditor.navigateTo(1260, 20);
    KeyboardHelper.selectTextUsingSWTEvents(d, true, 3);
    util.sleep(TIME_1S);
    cursorPosition = jspEditor.cursorPosition();
    assertEquals("Step 3. Source line position is wrong", 1260, cursorPosition.line); // $NON-NLS-1$

    webBrowser.setFocus();
    util.sleep(TIME_1S);
    for (int i = 0; i < 14; i++) {
      KeyboardHelper.pressKeyCode(d, SWT.ARROW_UP);
      util.sleep(TIME_1S);
    }
    KeyboardHelper.pressKeyCode(d, SWT.ARROW_LEFT);
    util.sleep(TIME_1S);
    cursorPosition = jspEditor.cursorPosition();
    assertEquals("Step 4. Source line position is wrong", 996, cursorPosition.line); // $NON-NLS-1$
  }
 /**
  * Adds External Jar File to Project Build Path. If External Jar File already exists and
  * 'overwriteIfExists' parameter is set to true, it is overwritten
  *
  * @param externalJarLocation
  * @param projectName
  * @return
  */
 public static String addExternalJar(
     final String externalJarLocation, final String projectName, boolean overwriteIfExists) {
   assertTrue(
       "External Jar Location cannot be empty but is " + externalJarLocation,
       externalJarLocation != null && externalJarLocation.length() > 0);
   SWTBotExt bot = new SWTEclipseExt().openPropertiesOfProject(projectName);
   bot.shell(IDELabel.Shell.PROPERTIES_FOR + " " + projectName).activate().bot();
   bot.tree()
       .expandNode(IDELabel.JavaBuildPathPropertiesEditor.JAVA_BUILD_PATH_TREE_ITEM_LABEL)
       .select();
   bot.sleep(Timing.time3S());
   bot.tabItem(IDELabel.JavaBuildPathPropertiesEditor.LIBRARIES_TAB_LABEL).activate();
   final SWTBotButton btn = bot.button(IDELabel.Button.ADD_VARIABLE);
   btn.click();
   bot.sleep(Timing.time2S());
   // workaround because first click is not working when test is run via maven
   try {
     bot.shell(IDELabel.Shell.NEW_VARIABLE_CLASS_PATH_ENTRY).activate();
   } catch (WidgetNotFoundException wnfe) {
     btn.click();
     bot.sleep(Timing.time2S());
     bot.shell(IDELabel.Shell.NEW_VARIABLE_CLASS_PATH_ENTRY).activate();
   }
   String jarFileName = new File(externalJarLocation).getName();
   String variableEntryName = jarFileName.toUpperCase() + "_LOCATION";
   boolean externalJarExists = false;
   for (int i = 0; i < bot.table().rowCount(); i++) {
     if (bot.table().getTableItem(i).getText().split(" - ")[0].equals(variableEntryName)) {
       bot.table().getTableItem(i).select();
       externalJarExists = true;
       break;
     }
   }
   bot.button(IDELabel.Button.CONFIGURE_VARIABLES).click();
   bot.shell(IDELabel.Shell.PREFERENCES_FILTERED).activate();
   if (externalJarExists && overwriteIfExists) {
     bot.button(IDELabel.Button.EDIT).click();
     bot.shell(IDELabel.Shell.EDIT_VARIABLE_ENTRY).activate();
     bot.textWithLabel(IDELabel.NewVariableEntryDialog.PATH_TEXT_LABEL)
         .setText(externalJarLocation);
   } else {
     bot.button(IDELabel.Button.NEW).click();
     bot.shell(IDELabel.Shell.NEW_VARIABLE_ENTRY).activate();
     bot.textWithLabel(IDELabel.NewVariableEntryDialog.NAME_TEXT_LABEL).setText(variableEntryName);
     bot.textWithLabel(IDELabel.NewVariableEntryDialog.PATH_TEXT_LABEL)
         .setText(externalJarLocation);
   }
   bot.clickButton(IDELabel.Button.OK).click();
   String result = TableHelper.getSelectionText(bot.table());
   bot.waitUntil(new ActiveShellTitleMatches(bot, "Preferences \\(Filtered\\)"), Timing.time3S());
   bot.clickButton(IDELabel.Button.OK).click();
   bot.waitUntil(
       new ActiveShellTitleMatches(bot, IDELabel.Shell.NEW_VARIABLE_CLASS_PATH_ENTRY),
       Timing.time3S());
   bot.clickButton(IDELabel.Button.OK).click();
   bot.waitUntil(
       new ActiveShellTitleMatches(bot, IDELabel.Shell.PROPERTIES_FOR + " " + projectName),
       Timing.time3S());
   bot.clickButton(IDELabel.Button.OK).click();
   new SWTUtilExt(bot).waitForNonIgnoredJobs();
   return result;
 }
 /**
  * Removes variable from project classpath
  *
  * @param variableLabel
  * @param removeGlobaly
  */
 public static void removeVariable(
     String projectName, String variableLabel, boolean removeGlobaly) {
   SWTBotExt bot = new SWTEclipseExt().openPropertiesOfProject(projectName);
   bot.tree()
       .expandNode(IDELabel.JavaBuildPathPropertiesEditor.JAVA_BUILD_PATH_TREE_ITEM_LABEL)
       .select();
   bot.tabItem(IDELabel.JavaBuildPathPropertiesEditor.LIBRARIES_TAB_LABEL).activate();
   bot.tree(1).select(variableLabel);
   bot.button(IDELabel.Button.REMOVE).click();
   if (removeGlobaly) {
     bot.button(IDELabel.Button.ADD_VARIABLE).click();
     bot.shell(IDELabel.Shell.NEW_VARIABLE_CLASS_PATH_ENTRY).activate();
     bot.table().select(variableLabel);
     bot.button(IDELabel.Button.CONFIGURE_VARIABLES).click();
     bot.shell(IDELabel.Shell.PREFERENCES_FILTERED).activate();
     bot.button(IDELabel.Button.REMOVE).click();
     bot.button(IDELabel.Button.OK).click();
     bot.shell(IDELabel.Shell.CLASSPATH_VARIABLES_CHANGED).activate();
     bot.button(IDELabel.Button.YES).click();
     new SWTUtilExt(bot).waitForNonIgnoredJobs();
     bot.clickButton(IDELabel.Button.CANCEL).click();
   }
   bot.button(IDELabel.Button.OK).click();
   new SWTUtilExt(bot).waitForNonIgnoredJobs();
 }