Esempio n. 1
0
  private void switchToDebugView(boolean dueToBreakpoint) {
    if (isInPerspective("org.eclipse.debug.ui.DebugPerspective")) return;

    IPreferenceStore prefs = RuntimePlugin.getDefault().getPreferenceStore();
    boolean dontAsk = prefs.getBoolean(RuntimePreferences.DONT_ASK_DEBUG_SWITCH);
    int rtnCode = 2;

    if (!dontAsk) {
      MessageDialogWithToggle mdwt =
          MessageDialogWithToggle.openYesNoQuestion(
              PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
              dueToBreakpoint
                  ? "Switch to jACT-R Run Perspective?"
                  : "Switch to Debug Perspective?",
              dueToBreakpoint
                  ? "Model breakpoint detected! Switch to debug perspective?"
                  : "Debug models start suspended. To resume, use the Debug Perspective. Switch now?",
              "Don't ask again",
              false,
              prefs,
              RuntimePreferences.DONT_ASK_DEBUG_SWITCH);

      rtnCode = mdwt.getReturnCode();

      if (mdwt.getToggleState()) {
        prefs.setValue(RuntimePreferences.SWITCH_TO_DEBUG_PERSPECTIVE, rtnCode == 2);
        prefs.setValue(RuntimePreferences.DONT_ASK_DEBUG_SWITCH, true);
      } else prefs.setValue(RuntimePreferences.DONT_ASK_DEBUG_SWITCH, false);
    } else if (prefs.getBoolean(RuntimePreferences.SWITCH_TO_DEBUG_PERSPECTIVE)) rtnCode = 2;
    else rtnCode = 3;

    if (rtnCode == 2) switchToPerspective("org.eclipse.debug.ui.DebugPerspective");
  }
  @Deprecated
  public void promptToAddQuery(TaskRepository taskRepository) {
    IPreferenceStore preferenceStore = TasksUiPlugin.getDefault().getPreferenceStore();
    if (!preferenceStore.getBoolean(PREF_ADD_QUERY)) {
      Shell shell = PlatformUI.getWorkbench().getDisplay().getActiveShell();
      MessageDialogWithToggle messageDialog =
          MessageDialogWithToggle.openYesNoQuestion(
              shell,
              Messages.AddRepositoryAction_Add_new_query,
              Messages.AddRepositoryAction_Add_a_query_to_the_Task_List,
              Messages.AddRepositoryAction_Do_not_show_again,
              false,
              preferenceStore,
              PREF_ADD_QUERY);
      preferenceStore.setValue(PREF_ADD_QUERY, messageDialog.getToggleState());
      if (messageDialog.getReturnCode() == IDialogConstants.YES_ID) {
        AbstractRepositoryConnectorUi connectorUi =
            TasksUiPlugin.getConnectorUi(taskRepository.getConnectorKind());
        IWizard queryWizard = connectorUi.getQueryWizard(taskRepository, null);
        if (queryWizard instanceof Wizard) {
          ((Wizard) queryWizard).setForcePreviousAndNextButtons(true);
        }

        WizardDialog queryDialog = new WizardDialog(shell, queryWizard);
        queryDialog.create();
        queryDialog.setBlockOnOpen(true);
        queryDialog.open();
      }
    }
  }
Esempio n. 3
0
  private void switchToRuntimeView() {
    if (isInPerspective(ACTRRuntimePerspective.ID)) return;
    /*
     * query
     */
    IPreferenceStore prefs = RuntimePlugin.getDefault().getPreferenceStore();
    boolean dontAsk = prefs.getBoolean(RuntimePreferences.DONT_ASK_RUN_SWITCH);
    int rtnCode = 2; // yes

    if (!dontAsk) {
      MessageDialogWithToggle mdwt =
          MessageDialogWithToggle.openYesNoQuestion(
              PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
              "Switch to jACT-R Run Perspective?",
              "Models are best inspected using the jACT-R Run perspective. Switch now?",
              "Don't ask again",
              false,
              prefs,
              RuntimePreferences.DONT_ASK_RUN_SWITCH);

      rtnCode = mdwt.getReturnCode();

      if (mdwt.getToggleState()) {
        prefs.setValue(RuntimePreferences.SWITCH_TO_RUN_PERSPECTIVE, rtnCode == 2);
        prefs.setValue(RuntimePreferences.DONT_ASK_RUN_SWITCH, true);
      } else prefs.setValue(RuntimePreferences.DONT_ASK_RUN_SWITCH, false);
    } else if (prefs.getBoolean(RuntimePreferences.SWITCH_TO_RUN_PERSPECTIVE)) rtnCode = 2;
    else rtnCode = 3;

    if (rtnCode == 2) switchToPerspective(ACTRRuntimePerspective.ID);
  }
 private void ok() {
   if (Const.isEmpty(wStepname.getText())) {
     return;
   }
   getMeta(joinMeta);
   // Show a warning (optional)
   if ("Y".equalsIgnoreCase(props.getCustomParameter(STRING_SORT_WARNING_PARAMETER, "Y"))) {
     MessageDialogWithToggle md =
         new MessageDialogWithToggle(
             shell,
             BaseMessages.getString(PKG, "MultiMergeJoinDialog.InputNeedSort.DialogTitle"),
             null,
             BaseMessages.getString(
                     PKG, "MultiMergeJoinDialog.InputNeedSort.DialogMessage", Const.CR)
                 + Const.CR,
             MessageDialog.WARNING,
             new String[] {
               BaseMessages.getString(PKG, "MultiMergeJoinDialog.InputNeedSort.Option1")
             },
             0,
             BaseMessages.getString(PKG, "MultiMergeJoinDialog.InputNeedSort.Option2"),
             "N".equalsIgnoreCase(props.getCustomParameter(STRING_SORT_WARNING_PARAMETER, "Y")));
     MessageDialogWithToggle.setDefaultImage(GUIResource.getInstance().getImageSpoon());
     md.open();
     props.setCustomParameter(STRING_SORT_WARNING_PARAMETER, md.getToggleState() ? "N" : "Y");
     props.saveProps();
   }
   stepname = wStepname.getText(); // return value
   dispose();
 }
  @Override
  protected void okPressed() {
    if (textFile.getText().length() == 0 || scopeCombo.getSelectionIndex() < 0) {
      MessageDialog.openWarning(
          getShell(), Messages.GenerateReportDialog_5, Messages.GenerateReportDialog_6);
      return;
    }
    List<Integer> rootElements = new ArrayList<Integer>(0);
    rootElements.add(getRootElement());
    if (getRootElements() != null) rootElements.addAll(Arrays.asList(getRootElements()));
    IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore();
    boolean dontShow =
        preferenceStore.getBoolean(PreferenceConstants.SHOW_REPORT_VALIDATION_WARNING);
    IValidationService vService = ServiceFactory.lookupValidationService();
    boolean validationsExistant = false;
    for (Integer scopeId : rootElements) {
      if (vService.getValidations(scopeId, (Integer) null).size() > 0) {
        validationsExistant = true;
        break;
      }
    }

    if (!dontShow && validationsExistant) {
      MessageDialogWithToggle dialog =
          MessageDialogWithToggle.openYesNoQuestion(
              getParentShell(),
              Messages.GenerateReportDialog_5,
              Messages.GenerateReportDialog_21,
              Messages.GenerateReportDialog_23,
              dontShow,
              preferenceStore,
              PreferenceConstants.SHOW_REPORT_VALIDATION_WARNING);
      preferenceStore.setValue(
          PreferenceConstants.SHOW_REPORT_VALIDATION_WARNING, dialog.getToggleState());

      if (!(dialog.getReturnCode() == IDialogConstants.OK_ID
          || dialog.getReturnCode() == IDialogConstants.YES_ID)) {
        return;
      }
    }

    String f = textFile.getText();
    chosenReportType = reportTypes[comboReportType.getSelectionIndex()];
    chosenOutputFormat = chosenReportType.getOutputFormats()[comboOutputFormat.getSelectionIndex()];

    chosenReportType.setReportFile(textReportTemplateFile.getText());

    // This just appends the chosen report's extension if the existing
    // suffix does not match. Could be enhanced.
    if (!f.endsWith(chosenOutputFormat.getFileSuffix())) {
      f += "." + chosenOutputFormat.getFileSuffix(); // $NON-NLS-1$
    }

    outputFile = new File(f);
    resetScopeCombo();
    super.okPressed();
  }
Esempio n. 6
0
  private static boolean confirmPerspectiveSwitch(
      IWorkbenchWindow window, IPerspectiveDescriptor finalPersp) {
    IPreferenceStore store = IDEWorkbenchPlugin.getDefault().getPreferenceStore();

    String pspm = store.getString(IDEInternalPreferences.PROJECT_SWITCH_PERSP_MODE);

    if (!IDEInternalPreferences.PSPM_PROMPT.equals(pspm)) {
      // Return whether or not we should always switch
      return IDEInternalPreferences.PSPM_ALWAYS.equals(pspm);
    }

    String desc = finalPersp.getDescription();
    String message;

    if (desc == null || desc.length() == 0) {
      message = NLS.bind(ResourceMessages.NewProject_perspSwitchMessage, finalPersp.getLabel());
    } else {
      message =
          NLS.bind(
              ResourceMessages.NewProject_perspSwitchMessageWithDesc,
              new String[] {finalPersp.getLabel(), desc});
    }

    MessageDialogWithToggle dialog =
        MessageDialogWithToggle.openYesNoQuestion(
            window.getShell(),
            ResourceMessages.NewProject_perspSwitchTitle,
            message,
            null,
            false,
            store,
            IDEInternalPreferences.PROJECT_SWITCH_PERSP_MODE);

    int result = dialog.getReturnCode();

    // If we are not going to prompt anymore propogate the choice.
    if (dialog.getToggleState()) {
      String preferenceValue;

      if (result == IDialogConstants.YES_ID) {
        // Doesn't matter if it is replace or new window
        // as we are going to use the open perspective setting
        preferenceValue = IWorkbenchPreferenceConstants.OPEN_PERSPECTIVE_REPLACE;
      } else {
        preferenceValue = IWorkbenchPreferenceConstants.NO_NEW_PERSPECTIVE;
      }

      // update PROJECT_OPEN_NEW_PERSPECTIVE to correspond
      PrefUtil.getAPIPreferenceStore()
          .setValue(IDE.Preferences.PROJECT_OPEN_NEW_PERSPECTIVE, preferenceValue);
    }

    return result == IDialogConstants.YES_ID;
  }
 /*
  * @see AbstractInfoView#internalCreatePartControl(Composite)
  */
 protected void internalCreatePartControl(Composite parent) {
   try {
     fBrowser = new Browser(parent, SWT.NONE);
     fIsUsingBrowserWidget = true;
   } catch (SWTError er) {
     /*
      * The Browser widget throws an SWTError if it fails to instantiate
      * properly. Application code should catch this SWTError and disable
      * any feature requiring the Browser widget. Platform requirements
      * for the SWT Browser widget are available from the SWT FAQ web
      * site.
      */
     IPreferenceStore store =
         this.getPreferenceStore(); // JavaPlugin.getDefault().getPreferenceStore();
     boolean doNotWarn = store.getBoolean(DO_NOT_WARN_PREFERENCE_KEY);
     if (WARNING_DIALOG_ENABLED && !doNotWarn) {
       String title = InfoViewMessages.ScriptdocView_error_noBrowser_title;
       String message = InfoViewMessages.ScriptdocView_error_noBrowser_message;
       String toggleMessage = InfoViewMessages.ScriptdocView_error_noBrowser_doNotWarn;
       MessageDialogWithToggle dialog =
           MessageDialogWithToggle.openError(
               parent.getShell(), title, message, toggleMessage, false, null, null);
       if (dialog.getReturnCode() == Window.OK)
         store.setValue(DO_NOT_WARN_PREFERENCE_KEY, dialog.getToggleState());
     }
     fIsUsingBrowserWidget = false;
   }
   if (!fIsUsingBrowserWidget) {
     fText = new StyledText(parent, SWT.V_SCROLL | SWT.H_SCROLL);
     fText.setEditable(false);
     fPresenter = new HTMLTextPresenter(false);
     fText.addControlListener(
         new ControlAdapter() {
           /*
            * @see org.eclipse.swt.events.ControlAdapter#controlResized(org.eclipse.swt.events.ControlEvent)
            */
           public void controlResized(ControlEvent e) {
             setInput(fText.getText());
           }
         });
   }
   initStyleSheet();
   getViewSite().setSelectionProvider(new SelectionProvider(getControl()));
 }
 /**
  * Opens a yes/no question box with a toggle checkbox, stored in the given preference.
  *
  * @param parent the parent shell of the dialog, or null if none
  * @param title the dialog's title, or null if none
  * @param message the message
  * @param toggleMessage the message for the toggle control, or null for the default message
  * @param toggleState the initial state for the toggle
  * @param store the IPreference store in which the user's preference should be persisted; null if
  *     you don't want it persisted automatically.
  * @param key the key to use when persisting the user's preference; null if you don't want it
  *     persisted.
  * @return MessageDialogWithToggle
  */
 public static MessageDialogWithToggle openToggleYesNoQuestion(
     String title,
     String message,
     String toggleMessage,
     boolean initToggle,
     IPreferenceStore store,
     String key) {
   return MessageDialogWithToggle.openYesNoQuestion(
       getActiveShell(), title, message, toggleMessage, initToggle, store, key);
 }
Esempio n. 9
0
  public Object execute(ExecutionEvent event) throws ExecutionException {

    DBSelection dbSel = new DBSelection(HandlerUtil.getCurrentSelection(event));

    ElementDBNode sel = dbSel.getSel();
    if (sel == null) {
      Logger.warn("nothing selected in the design browser, nothing to report");
      return null;
    }
    String selName = (sel instanceof ModelDBNode) ? "/" : ((InstanceDBNode) sel).getInstPath();

    MessageDialogWithToggle dialog =
        new MessageDialogWithToggle(
            HandlerUtil.getActiveShell(event),
            "Report type",
            null,
            "After clicking OK, the states of the current model are applied successively; "
                + "the currents found in each state are stored in a PowerPoint document ",
            MessageDialog.INFORMATION,
            new String[] {IDialogConstants.OK_LABEL, IDialogConstants.CANCEL_LABEL},
            0,
            "generate a power report instead",
            false);

    if (dialog.open() == Window.OK) {

      IScriptService interpreter = ScriptRegistry.instance.interpreter(SCRIPT_LANGAGE.TCL);

      try {
        interpreter.eval(
            "package require ms_report; ms_report::ppa_report "
                + selName
                + " "
                + (dialog.getToggleState() ? "power" : "current"),
            SCR_LOG_TYPE.PRINT_TRANSCRIPT);
      } catch (ScriptServiceException e) {
        ViewUtils.setErrorMessage("report generation failed", true);
      }
    }

    return null;
  }
Esempio n. 10
0
 /**
  * Opens a perspective with the given ID.
  *
  * @param perspectiveID The ID of the perspective to open.
  * @return True, if the user wants to change the perspective, false otherwise.
  */
 public static boolean openPerspective(String perspectiveID) {
   IWorkbench worbench = PlatformUI.getWorkbench();
   IWorkbenchWindow activeWindow = worbench.getActiveWorkbenchWindow();
   try {
     IPerspectiveDescriptor activePerspective = getActivePerspective(activeWindow.getActivePage());
     if (activePerspective != null && activePerspective.getId().equals(perspectiveID)) {
       return true;
     }
     final IPreferenceStore preferenceStore = Plugin.getDefault().getPreferenceStore();
     int value = preferenceStore.getInt(Constants.PERSP_CHANGE_KEY);
     if (value == Constants.PERSPECTIVE_CHANGE_YES) {
       worbench.showPerspective(perspectiveID, activeWindow);
       return true;
     } else if (value == Constants.PERSPECTIVE_CHANGE_NO) {
       return true;
     }
     // if --> value = Constants.PERSPECTIVE_CHANGE_PROMPT:
     String perspectiveName = StringConstants.EMPTY;
     if (perspectiveID.equals(Constants.SPEC_PERSPECTIVE)) {
       perspectiveName = Messages.UtilsSpecPerspective;
     } else {
       perspectiveName = Messages.UtilsExecPerspective;
     }
     final int returnCodeYES = 256; // since Eclipse3.2 (not 0)
     final int returnCodeNO = 257; // since Eclipse3.2 (not 1)
     final int returnCodeCANCEL = -1;
     MessageDialogWithToggle dialog =
         new MessageDialogWithToggle(
             activeWindow.getShell(),
             Messages.UtilsTitle,
             null,
             NLS.bind(Messages.UtilsQuestion, perspectiveName),
             MessageDialog.QUESTION,
             new String[] {Messages.UtilsYes, Messages.UtilsNo},
             0,
             Messages.UtilsRemember,
             false) {
           /** {@inheritDoc} */
           protected void buttonPressed(int buttonId) {
             super.buttonPressed(buttonId);
             preferenceStore.setValue(Constants.REMEMBER_KEY, getToggleState());
             int val = Constants.PERSPECTIVE_CHANGE_PROMPT;
             if (getToggleState() && getReturnCode() == returnCodeNO) {
               val = Constants.PERSPECTIVE_CHANGE_NO;
             } else if (getToggleState() && getReturnCode() == returnCodeYES) {
               val = Constants.PERSPECTIVE_CHANGE_YES;
             }
             preferenceStore.setValue(Constants.PERSP_CHANGE_KEY, val);
           }
         };
     dialog.create();
     DialogUtils.setWidgetNameForModalDialog(dialog);
     dialog.open();
     if (dialog.getReturnCode() == returnCodeNO) {
       return true;
     } else if (dialog.getReturnCode() == returnCodeCANCEL) {
       return false;
     }
     worbench.showPerspective(perspectiveID, activeWindow);
   } catch (WorkbenchException e) {
     StringBuilder msg = new StringBuilder();
     msg.append(Messages.CannotOpenThePerspective)
         .append(StringConstants.COLON)
         .append(StringConstants.SPACE)
         .append(perspectiveID)
         .append(StringConstants.LEFT_PARENTHESES)
         .append(e)
         .append(StringConstants.RIGHT_PARENTHESES)
         .append(StringConstants.DOT);
     log.error(msg.toString());
     ErrorHandlingUtil.createMessageDialog(MessageIDs.E_NO_PERSPECTIVE);
     return false;
   }
   return true;
 }
Esempio n. 11
0
  /**
   * Do the "Run Analysis" on a resource (project, folder, or file). Descends to all child nodes,
   * collecting artifacts on each.
   */
  public void run() {
    if (traceOn) {
      System.out.println("RunAnalyseHandlerBase.run()..."); // $NON-NLS-1$
    }

    cancelledByUser = false;
    err = false;
    cumulativeArtifacts = 0;
    readPreferences();

    final int indent = 0;

    if ((selection == null) || selection.isEmpty()) {
      MessageDialog.openWarning(
          null,
          Messages.RunAnalyseHandlerBase_no_files_selected,
          Messages.RunAnalyseHandlerBase_please_select);

      return;
    } else {
      // get preference for include paths
      final List<String> includes = getIncludePath();
      if (areIncludePathsNeeded() && includes.isEmpty()) {
        // System.out.println("RunAnalyseHandlerBase.run(), no include paths found.");
        MessageDialog.openWarning(
            shell,
            name + Messages.RunAnalyseHandlerBase_include_paths_not_found,
            Messages.RunAnalyseHandlerBase_please_first_specify
                + name
                + Messages.RunAnalyseHandlerBase_incl_paths_in_pref_page);

      } else {

        // batch ws modifications *and* report progress
        WorkspaceModifyOperation wmo =
            new WorkspaceModifyOperation() {
              @Override
              protected void execute(IProgressMonitor monitor)
                  throws CoreException, InvocationTargetException, InterruptedException {
                err = runResources(monitor, indent, includes);
              }
            };
        ProgressMonitorDialog pmdialog = new ProgressMonitorDialog(shell);
        try {
          pmdialog.run(true, true, wmo); // fork=true; if false, not
          // cancelable

        } catch (InvocationTargetException e) {
          err = true;
          Throwable cause = e.getCause();
          System.out.println(
              "Error running analysis: ITE: " //$NON-NLS-1$
                  + e.getMessage());
          System.out.println(
              "  cause: "
                  + cause
                  + " - " //$NON-NLS-1$ //$NON-NLS-2$
                  + cause.getMessage());

          cause.printStackTrace();
        } catch (InterruptedException e) {
          cancelledByUser = true;
        }
      } // end else
    }
    if (traceOn) {
      System.out.println(
          "RunAnalyseBase: retd from run iterator, err=" //$NON-NLS-1$
              + err);
    }
    String artsFound =
        "\nNumber of "
            + name
            + " Artifacts found: " //$NON-NLS-1$ //$NON-NLS-2$
            + cumulativeArtifacts;
    if (cancelledByUser) {
      MessageDialog.openInformation(
          null,
          Messages.RunAnalyseHandlerBase_partial_analysis_complete,
          Messages.RunAnalyseHandlerBase_15 + artsFound);
    } else {
      String msg = Messages.RunAnalyseHandlerBase_cancelled_by_user;
      if (!err) {
        String key = IDs.SHOW_ANALYSIS_CONFIRMATION;
        IPreferenceStore pf = CommonPlugin.getDefault().getPreferenceStore();
        boolean showDialog = pf.getBoolean(IDs.SHOW_ANALYSIS_CONFIRMATION);
        if (showDialog) {
          String title = Messages.RunAnalyseHandlerBase_analysis_complete;
          StringBuffer sMsg =
              new StringBuffer(
                  cumulativeArtifacts
                      + " "
                      + name //$NON-NLS-1$
                      + Messages.RunAnalyseHandlerBase_artifacts_found);
          // provide some explanation of why perhaps no artifacts were
          // found.
          // Note: should this perhaps be in a "Details" section of
          // the dialog?
          if (cumulativeArtifacts == 0) {
            // Unless "Recognize artifacts by prefix alone" is set in the preferences (this is the
            // default),
            // this could be a problem with the include file for this API.
            sMsg.append(Messages.RunAnalyseHandlerBase_notfound_0)
                .append(name)
                .append(Messages.RunAnalyseHandlerBase_notfound_1);
            sMsg.append(name).append(Messages.RunAnalyseHandlerBase_notfound_2);
            sMsg.append(Messages.RunAnalyseHandlerBase_notfound_3);
          }
          String togMsg = Messages.RunAnalyseHandlerBase_dont_show_this_again;
          MessageDialogWithToggle.openInformation(
              shell, title, sMsg.toString(), togMsg, false, pf, key);
          showStatusMessage(sMsg.toString(), "RunAnalyseBase.run()"); // $NON-NLS-1$
        }
        activateProblemsView();
        activateArtifactView();
      } else { // error occurred
        showStatusMessage(msg, "RunAnalyseBase.run() error"); // $NON-NLS-1$
        msg = Messages.RunAnalyseHandlerBase_27;
        MessageDialog.openError(null, Messages.RunAnalyseHandlerBase_28, msg + artsFound);
      }
    }
  }
Esempio n. 12
0
  @Override
  protected void okPressed() {
    try {
      if (textFile.getText().length() == 0 || scopeCombo.getSelectionIndex() < 0) {
        MessageDialog.openWarning(
            getShell(), Messages.GenerateReportDialog_5, Messages.GenerateReportDialog_6);
        return;
      }
      List<Integer> scopeIds = new ArrayList<Integer>(0);
      if (getRootElement() != null) {
        scopeIds.add(getRootElement());
      }
      if (getRootElements() != null) {
        for (Integer scopeId : getRootElements()) {
          if (scopeId != null) {
            scopeIds.add(scopeId);
          }
        }
      }
      IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore();
      boolean dontShow =
          preferenceStore.getBoolean(PreferenceConstants.SHOW_REPORT_VALIDATION_WARNING);
      IValidationService vService = ServiceFactory.lookupValidationService();
      boolean validationsExistant = false;
      for (Integer scopeId : scopeIds) {
        if (vService.getValidations(scopeId, (Integer) null).size() > 0) {
          validationsExistant = true;
          break;
        }
      }

      if (!dontShow && validationsExistant) {
        MessageDialogWithToggle dialog =
            MessageDialogWithToggle.openYesNoQuestion(
                getParentShell(),
                Messages.GenerateReportDialog_5,
                Messages.GenerateReportDialog_21,
                Messages.GenerateReportDialog_23,
                dontShow,
                preferenceStore,
                PreferenceConstants.SHOW_REPORT_VALIDATION_WARNING);
        preferenceStore.setValue(
            PreferenceConstants.SHOW_REPORT_VALIDATION_WARNING, dialog.getToggleState());

        if (!(dialog.getReturnCode() == IDialogConstants.OK_ID
            || dialog.getReturnCode() == IDialogConstants.YES_ID)) {
          return;
        }
      }

      String f = textFile.getText();
      if (reportTemplates.length > 0) {
        chosenReportMetaData = reportTemplates[comboReportType.getSelectionIndex()];
      } else {
        showNoReportsExistant();
        return;
      }
      chosenOutputFormat =
          getDepositService()
              .getOutputFormat(
                  chosenReportMetaData.getOutputFormats()[comboOutputFormat.getSelectionIndex()]);

      // This just appends the chosen report's extension if the existing
      // suffix does not match. Could be enhanced.
      if (!f.endsWith(chosenOutputFormat.getFileSuffix())) {
        f += "." + chosenOutputFormat.getFileSuffix(); // $NON-NLS-1$
      }

      String currentPath = setupDirPath();
      if (useDefaultFolder) {
        Activator.getDefault()
            .getPreferenceStore()
            .setValue(PreferenceConstants.DEFAULT_FOLDER_REPORT, currentPath);
      }
      currentPath = getOldTemplateFolderPath();
      outputFile = new File(f);
    } catch (Exception e) {
      LOG.error("Error while creating report.", e);
      MessageDialog.openError(getShell(), "Error", "An error occurred while creating report.");
      return;
    }
    super.okPressed();
  }
Esempio n. 13
0
  /**
   * Overwrite Make Target dialog.
   *
   * @param name - name of make target to display to a user.
   * @param shell - shell where to display the dialog.
   * @return user's answer.
   */
  private static int overwriteMakeTargetDialog(String name, Shell shell) {

    if (lastUserAnswer == IDialogConstants.YES_TO_ALL_ID
        || lastUserAnswer == IDialogConstants.NO_TO_ALL_ID
        || lastUserAnswer == RENAME_TO_ALL_ID) {

      return lastUserAnswer;
    }

    String labels[] =
        new String[] {
          IDialogConstants.YES_LABEL,
          IDialogConstants.NO_LABEL,
          MakeUIPlugin.getResourceString("MakeTargetDnD.button.rename"), // $NON-NLS-1$
          IDialogConstants.CANCEL_LABEL,
        };

    String title =
        MakeUIPlugin.getResourceString("MakeTargetDnD.title.overwriteTargetConfirm"); // $NON-NLS-1$
    String question =
        MessageFormat.format(
            MakeUIPlugin.getResourceString(
                "MakeTargetDnD.message.overwriteTargetConfirm"), //$NON-NLS-1$
            new Object[] {name});
    String toggleApplyToAll =
        MakeUIPlugin.getResourceString("MakeTargetDnD.toggle.applyToAll"); // $NON-NLS-1$

    MessageDialogWithToggle dialog =
        new MessageDialogWithToggle(
            shell,
            title,
            null,
            question,
            MessageDialog.QUESTION,
            labels,
            0,
            toggleApplyToAll,
            false);

    try {
      dialog.open();
      lastUserAnswer = dialog.getReturnCode();
      boolean toAll = dialog.getToggleState();
      if (toAll && lastUserAnswer == IDialogConstants.YES_ID) {
        lastUserAnswer = IDialogConstants.YES_TO_ALL_ID;
      } else if (toAll && lastUserAnswer == IDialogConstants.NO_ID) {
        lastUserAnswer = IDialogConstants.NO_TO_ALL_ID;
      } else if (toAll && lastUserAnswer == RENAME_ID) {
        lastUserAnswer = RENAME_TO_ALL_ID;
      }
    } catch (SWTException e) {
      MakeUIPlugin.log(e);
      lastUserAnswer = IDialogConstants.CANCEL_ID;
    }

    if (lastUserAnswer == SWT.DEFAULT) {
      // A window close returns SWT.DEFAULT, which has to be
      // mapped to a cancel
      lastUserAnswer = IDialogConstants.CANCEL_ID;
    }
    return lastUserAnswer;
  }
    /**
     * @see
     *     org.eclipse.swt.events.SelectionListener#widgetSelected(org.eclipse.swt.events.SelectionEvent)
     */
    public void widgetSelected(SelectionEvent e) {

      Object source = e.getSource();
      // edit filter
      if (source == mBtnEditFilter) {

        ISelection selection = mFilterList.getSelection();
        openFilterEditor(selection);
        getContainer().updateButtons();
      }
      if (source == mMainTab) {
        mFileSetsEditor.refresh();
        getContainer().updateButtons();

      } else if (source == mChkSyncFormatter) {
        mProjectConfig.setSyncFormatter(mChkSyncFormatter.getSelection());
      } else if (source == mChkSimpleConfig) {
        try {

          mProjectConfig.setUseSimpleConfig(mChkSimpleConfig.getSelection());

          boolean showWarning =
              CheckstyleUIPluginPrefs.getBoolean(CheckstyleUIPluginPrefs.PREF_FILESET_WARNING);
          if (mProjectConfig.isUseSimpleConfig() && showWarning) {
            MessageDialogWithToggle dialog =
                new MessageDialogWithToggle(
                    getShell(),
                    Messages.CheckstylePropertyPage_titleWarnFilesets,
                    null,
                    Messages.CheckstylePropertyPage_msgWarnFilesets,
                    MessageDialogWithToggle.WARNING,
                    new String[] {IDialogConstants.OK_LABEL},
                    0,
                    Messages.CheckstylePropertyPage_mgsWarnFileSetNagOption,
                    showWarning) {
                  /**
                   * Overwritten because we don't want to store which button the user pressed but
                   * the state of the toggle.
                   *
                   * @see MessageDialogWithToggle#buttonPressed(int)
                   */
                  protected void buttonPressed(int buttonId) {
                    getPrefStore().setValue(getPrefKey(), getToggleState());
                    setReturnCode(buttonId);
                    close();
                  }
                };
            dialog.setPrefStore(CheckstyleUIPlugin.getDefault().getPreferenceStore());
            dialog.setPrefKey(CheckstyleUIPluginPrefs.PREF_FILESET_WARNING);
            dialog.open();
          }

          createFileSetsArea(mFileSetsContainer);
          mFileSetsContainer.redraw();
          mFileSetsContainer.update();
          mFileSetsContainer.layout();
        } catch (CheckstylePluginException ex) {
          CheckstyleUIPlugin.errorDialog(getShell(), Messages.errorChangingFilesetEditor, ex, true);
        }
      }
    }
  /**
   * @return the result of the ok action
   * @see org.eclipse.jface.preference.IPreferencePage#performOk()
   */
  public boolean performOk() {

    try {

      IProject project = mProjectConfig.getProject();

      // save the edited project configuration
      if (mProjectConfig.isDirty()) {
        mProjectConfig.store();
      }

      boolean checkstyleEnabled = mChkEnable.getSelection();
      boolean needRebuild = mProjectConfig.isRebuildNeeded();

      // check if checkstyle nature has to be configured/deconfigured
      if (checkstyleEnabled != mCheckstyleInitiallyActivated) {

        ConfigureDeconfigureNatureJob configOperation =
            new ConfigureDeconfigureNatureJob(project, CheckstyleNature.NATURE_ID);
        configOperation.setRule(ResourcesPlugin.getWorkspace().getRoot());
        configOperation.schedule();

        needRebuild = needRebuild || !mCheckstyleInitiallyActivated;
      }

      if (checkstyleEnabled && mProjectConfig.isSyncFormatter()) {

        TransformCheckstyleRulesJob transFormJob = new TransformCheckstyleRulesJob(project);
        transFormJob.schedule();
      }

      // if a rebuild is advised, check/prompt if the rebuild should
      // really be done.
      if (checkstyleEnabled && needRebuild) {

        String promptRebuildPref =
            CheckstyleUIPluginPrefs.getString(CheckstyleUIPluginPrefs.PREF_ASK_BEFORE_REBUILD);

        boolean doRebuild = MessageDialogWithToggle.ALWAYS.equals(promptRebuildPref) && needRebuild;

        //
        // Prompt for rebuild
        //
        if (MessageDialogWithToggle.PROMPT.equals(promptRebuildPref) && needRebuild) {
          MessageDialogWithToggle dialog =
              MessageDialogWithToggle.openYesNoQuestion(
                  getShell(),
                  Messages.CheckstylePropertyPage_titleRebuild,
                  Messages.CheckstylePropertyPage_msgRebuild,
                  Messages.CheckstylePropertyPage_nagRebuild,
                  false,
                  CheckstyleUIPlugin.getDefault().getPreferenceStore(),
                  CheckstyleUIPluginPrefs.PREF_ASK_BEFORE_REBUILD);

          doRebuild = dialog.getReturnCode() == IDialogConstants.YES_ID;
        }

        // check if a rebuild is necessary
        if (checkstyleEnabled && doRebuild) {

          BuildProjectJob rebuildOperation =
              new BuildProjectJob(project, IncrementalProjectBuilder.FULL_BUILD);
          rebuildOperation.setRule(ResourcesPlugin.getWorkspace().getRoot());
          rebuildOperation.schedule();
        }
      }
    } catch (CheckstylePluginException e) {
      CheckstyleUIPlugin.errorDialog(getShell(), e, true);
    }
    return true;
  }