public OutputStream getOutputStream(Shell shell) {
    FileDialog dialog = new FileDialog(shell, SWT.SAVE);

    String filterPath;
    String relativeFileName;

    int lastIndexOfFileSeparator = defaultFileName.lastIndexOf(File.separator);
    if (lastIndexOfFileSeparator >= 0) {
      filterPath = defaultFileName.substring(0, lastIndexOfFileSeparator);
      relativeFileName = defaultFileName.substring(lastIndexOfFileSeparator + 1);
    } else {
      filterPath = "/"; // $NON-NLS-1$
      relativeFileName = defaultFileName;
    }

    dialog.setFilterPath(filterPath);
    dialog.setOverwrite(true);

    dialog.setFileName(relativeFileName);
    dialog.setFilterNames(defaultFilterNames);
    dialog.setFilterExtensions(defaultFilterExtensions);
    String fileName = dialog.open();
    if (fileName == null) {
      return null;
    }

    try {
      return new PrintStream(fileName);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      return null;
    }
  }
  public void get() {
    try {

      // As the user for a file to use as a reference
      //
      FileDialog dialog = new FileDialog(shell, SWT.OPEN);
      dialog.setFilterExtensions(new String[] {"*.sas7bdat;*.SAS7BDAT", "*.*"});
      dialog.setFilterNames(
          new String[] {
            BaseMessages.getString(PKG, "SASInputDialog.FileType.SAS7BAT")
                + ", "
                + BaseMessages.getString(PKG, "System.FileType.TextFiles"),
            BaseMessages.getString(PKG, "System.FileType.CSVFiles"),
            BaseMessages.getString(PKG, "System.FileType.TextFiles"),
            BaseMessages.getString(PKG, "System.FileType.AllFiles")
          });
      if (dialog.open() != null) {
        String filename =
            dialog.getFilterPath() + System.getProperty("file.separator") + dialog.getFileName();
        SasInputHelper helper = new SasInputHelper(filename);
        BaseStepDialog.getFieldsFromPrevious(
            helper.getRowMeta(), wFields, 1, new int[] {1}, new int[] {3}, 4, 5, null);
      }

    } catch (Exception e) {
      new ErrorDialog(shell, "Error", "Error reading information from file", e);
    }
  }
  public void run(IAction action) {

    FileDialog fileDialog = new FileDialog(Display.getDefault().getActiveShell(), SWT.SAVE);
    fileDialog.setFilterPath(fileDirectory);
    fileDialog.setFilterNames(filterName);
    fileDialog.setFilterExtensions(filterExtension);

    if (action.isChecked()) {
      String filename = fileDialog.open();
      // check if file Exists. Gaelle 16/03/2009

      if (filename != null && recordInThisFile(filename)) {

        FableJep.record(true);
        try {
          FableJep.getFableJep().setScriptFileName(filename);
        } catch (Throwable e) {
          e.printStackTrace();
        }
        // action.setText("Stop Recording Script");
        action.setToolTipText("Stop recording python actions.");
      } else {
        action.setChecked(false);
        FableJep.record(false);
        // action.setText("Record Script");
        action.setToolTipText("Record python actions in a script.");
      }
    } else {
      FableJep.record(false);
      // action.setText("Record Script");
      action.setToolTipText("Record python actions in a script.");
    }
  }
Example #4
0
  private boolean saveAs() {

    FileDialog saveDialog = new FileDialog(shell, SWT.SAVE);
    saveDialog.setFilterExtensions(new String[] {"*.adr;", "*.*"});
    saveDialog.setFilterNames(new String[] {"Address Books (*.adr)", "All Files "});

    saveDialog.open();
    String name = saveDialog.getFileName();

    if (name.equals("")) return false;

    if (name.indexOf(".adr") != name.length() - 4) {
      name += ".adr";
    }

    File file = new File(saveDialog.getFilterPath(), name);
    if (file.exists()) {
      MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.YES | SWT.NO);
      box.setText(resAddressBook.getString("Save_as_title"));
      box.setMessage(
          resAddressBook.getString("File")
              + file.getName()
              + " "
              + resAddressBook.getString("Query_overwrite"));
      if (box.open() != SWT.YES) {
        return false;
      }
    }
    this.file = file;
    return save();
  }
Example #5
0
  /** Export the selected values from the table to a csv file */
  private void export() {

    FileDialog dialog = new FileDialog(shell, SWT.SAVE);
    String[] filterNames = new String[] {"CSV Files", "All Files (*)"};
    String[] filterExtensions = new String[] {"*.csv;", "*"};
    String filterPath = "/";
    String platform = SWT.getPlatform();
    if (platform.equals("win32") || platform.equals("wpf")) {
      filterNames = new String[] {"CSV Files", "All Files (*.*)"};
      filterExtensions = new String[] {"*.csv", "*.*"};
      filterPath = "c:\\";
    }
    dialog.setFilterNames(filterNames);
    dialog.setFilterExtensions(filterExtensions);
    dialog.setFilterPath(filterPath);
    try {
      dialog.setFileName(this.getCurrentKey() + ".csv");
    } catch (Exception e) {
      dialog.setFileName("export.csv");
    }
    String fileName = dialog.open();

    FileOutputStream fos;
    OutputStreamWriter out;
    try {
      fos = new FileOutputStream(fileName);
      out = new OutputStreamWriter(fos, "UTF-8");
    } catch (Exception e) {
      MessageBox messageBox = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR);
      messageBox.setMessage("Error creating export file " + fileName + " : " + e.getMessage());
      messageBox.open();
      return;
    }

    Vector<TableItem> sel = new Vector<TableItem>(this.dataTable.getSelection().length);

    sel.addAll(Arrays.asList(this.dataTable.getSelection()));
    Collections.reverse(sel);

    for (TableItem item : sel) {
      String date = item.getText(0);
      String value = item.getText(1);
      try {
        out.write(date + ";" + value + "\n");
      } catch (IOException e) {
        continue;
      }
    }

    try {
      out.close();
      fos.close();
    } catch (IOException e) {
      MessageBox messageBox = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR);
      messageBox.setMessage("Error writing export file " + fileName + " : " + e.getMessage());
      messageBox.open();
      e.printStackTrace();
    }
  }
 public void addManifestation() {
   final FileDialog fileDialog = new FileDialog(getSite().getShell(), SWT.OPEN);
   fileDialog.setFilterExtensions(new String[] {"*.xml;*.raid", "*.raid"});
   fileDialog.setFilterNames(
       new String[] {"Fichiers chronosRAID (*.xml,*.raid)", "Projet ChronosRAID (*.raid)"});
   final String fileName = fileDialog.open();
   if (fileName != null) {
     ProjectManager.openProject(fileName);
   }
 }
  private void openAddressBook() {
    FileDialog fileDialog = new FileDialog(shell, SWT.OPEN);

    fileDialog.setFilterExtensions(new String[] {"*.messages;", "*.*"});
    fileDialog.setFilterNames(
        new String[] {
          resMessages.getString("Book_filter_name") + " (*.messages)",
          resMessages.getString("All_filter_name") + " (*.*)"
        });
    String name = fileDialog.open();
    openAddressBook(name);
  }
 private void selectFile() {
   FileDialog fileDialog = new FileDialog(getShell(), SWT.OPEN);
   fileDialog.setText("Select JSHint library file");
   File file = new File(preferences.getCustomLibPath());
   fileDialog.setFileName(file.getName());
   fileDialog.setFilterPath(file.getParent());
   fileDialog.setFilterNames(new String[] {"JavaScript files"});
   fileDialog.setFilterExtensions(new String[] {"*.js", ""});
   String selectedPath = fileDialog.open();
   if (selectedPath != null) {
     customLibPathText.setText(selectedPath);
   }
 }
Example #9
0
 /** Open a resource chooser to select a PDA program */
 protected void browseLispExeFiles() {
   FileDialog fd = new FileDialog(getShell());
   fd.setFileName(fProgramText.getText());
   if (exename != null && exename != "") {
     fd.setFilterNames(new String[] {exename});
   } else if (System.getProperty("os.name").toLowerCase().contains("windows")) {
     fd.setFilterExtensions(new String[] {"*.exe"});
   }
   String fileName = fd.open();
   if (fileName != null) {
     fProgramText.setText(fileName);
   }
 }
Example #10
0
 @Override
 public void run() {
   final FileDialog fileChooser = new FileDialog(imageCanvas.getShell(), SWT.SAVE);
   fileChooser.setText("Save .dot file");
   fileChooser.setFilterPath("");
   fileChooser.setFilterExtensions(new String[] {"*.dot"});
   fileChooser.setFilterNames(new String[] {"Graphviz file " + " (dot)"});
   final String filename = fileChooser.open();
   if (filename != null) {
     try {
       FileUtils.copyFile(dotFile, new File(filename));
     } catch (final IOException e) {
       MessageDialog.openError(imageCanvas.getShell(), "Saving error", e.getMessage());
     }
   }
 }
  private String browse(final String path) {
    final FileDialog dialog = new FileDialog(getShell(), SWT.SAVE);
    dialog.setFilterExtensions(m_filenameExtensions);
    dialog.setFilterNames(m_fileTypes);
    if (path != "") // $NON-NLS-1$
    dialog.setFileName(path);
    final String fileName = dialog.open();

    if (fileName == null) return ""; // $NON-NLS-1$

    final String[] filterExtensions = dialog.getFilterExtensions();
    boolean regularExtension = false;
    for (final String filterExtension : filterExtensions)
      if (fileName.endsWith(filterExtension.substring(1))) {
        regularExtension = true;
        break;
      }
    if (!regularExtension && filterExtensions.length == 1)
      return fileName + filterExtensions[0].substring(1);
    return fileName;
  }
  private void handleCellData(final Object cellData) {

    if (cellData instanceof SqlJetMemoryPointer) {
      // save as file
      final Shell shell = new Shell(Display.getDefault());

      final FileDialog dialog = new FileDialog(shell, SWT.SAVE);
      dialog.setFilterNames(new String[] {"All Files (*.*)"});
      dialog.setFilterExtensions(new String[] {"*.*"}); // Windows
      dialog.setFilterPath(System.getProperty("user.home"));

      final String fileName = dialog.open();
      if (fileName != null) {

        final SqlJetMemoryPointer p = (SqlJetMemoryPointer) cellData;
        final int count = p.remaining();
        RandomAccessFile file = null;
        try {
          file = new RandomAccessFile(fileName, "rw");
          p.writeToFile(file, 0, count);
          file.close();
        } catch (final IOException e) {
          e.printStackTrace();
        } finally {
          if (file != null) {
            try {
              file.close();
            } catch (final IOException e) {
            }
          }
        }
      }
    } else if (cellData != null) {
      // copy clipboard
      final Clipboard cb = new Clipboard(Display.getDefault());
      final TextTransfer textTransfer = TextTransfer.getInstance();
      cb.setContents(new Object[] {cellData.toString()}, new Transfer[] {textTransfer});
    }
  }
  private String getFilePathByFileDialog(String modelElementName) {
    FileDialog dialog =
        new FileDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), SWT.SAVE);
    dialog.setFilterNames(FILTER_NAMES);
    dialog.setFilterExtensions(FILTER_EXTS);
    String initialPath =
        PreferenceHelper.getPreference(EXPORT_MODEL_PATH, System.getProperty("user.home"));
    dialog.setFilterPath(initialPath);
    dialog.setOverwrite(true);

    try {
      // String initialFileName = projectSpace.getProjectName() + "@"
      // + projectSpace.getBaseVersion().getIdentifier() + ".ucp";
      String initialFileName = "ModelElement_" + modelElementName + "." + FILE_EXTENSION;
      dialog.setFileName(initialFileName);

    } catch (NullPointerException e) {
      // do nothing
    }

    String filePath = dialog.open();

    return filePath;
  }
Example #14
0
  /**
   * Importiert die Daten.
   *
   * @throws ApplicationException
   */
  private void doImport() throws ApplicationException {
    Imp imp = null;

    try {
      imp = (Imp) getImporterList().getValue();
    } catch (Exception e) {
      Logger.error("error while saving import file", e);
      throw new ApplicationException(i18n.tr("Fehler beim Starten des Imports"), e);
    }

    if (imp == null || imp.importer == null)
      throw new ApplicationException(i18n.tr("Bitte wählen Sie ein Import-Format aus"));

    Settings settings = new Settings(this.getClass());
    settings.setStoreWhenRead(true);

    FileDialog fd = new FileDialog(GUI.getShell(), SWT.OPEN);
    fd.setText(
        i18n.tr("Bitte wählen Sie die Datei aus, welche für den Import verwendet werden soll."));
    fd.setFilterNames(imp.format.getFileExtensions());

    String path = settings.getString("lastdir", System.getProperty("user.home"));
    if (path != null && path.length() > 0) fd.setFilterPath(path);

    final String s = fd.open();

    if (s == null || s.length() == 0) {
      close();
      return;
    }

    final File file = new File(s);
    if (!file.exists() || !file.isFile())
      throw new ApplicationException(i18n.tr("Datei existiert nicht oder ist nicht lesbar"));

    // Wir merken uns noch das Verzeichnis vom letzten mal
    settings.setAttribute("lastdir", file.getParent());

    // Dialog schliessen
    close();

    final Importer importer = imp.importer;
    final IOFormat format = imp.format;

    BackgroundTask t =
        new BackgroundTask() {
          public void run(ProgressMonitor monitor) throws ApplicationException {
            try {
              InputStream is = new BufferedInputStream(new FileInputStream(file));
              importer.doImport(context, format, is, monitor);
              monitor.setPercentComplete(100);
              monitor.setStatus(ProgressMonitor.STATUS_DONE);
              GUI.getStatusBar().setSuccessText(i18n.tr("Daten importiert aus {0}", s));
              GUI.getCurrentView().reload();
            } catch (ApplicationException ae) {
              monitor.setStatus(ProgressMonitor.STATUS_ERROR);
              monitor.setStatusText(ae.getMessage());
              GUI.getStatusBar().setErrorText(ae.getMessage());
              throw ae;
            } catch (Exception e) {
              monitor.setStatus(ProgressMonitor.STATUS_ERROR);
              Logger.error("error while reading objects from " + s, e);
              ApplicationException ae =
                  new ApplicationException(
                      i18n.tr("Fehler beim Importieren der Daten aus {0}", s), e);
              monitor.setStatusText(ae.getMessage());
              GUI.getStatusBar().setErrorText(ae.getMessage());
              throw ae;
            }
          }

          public void interrupt() {}

          public boolean isInterrupted() {
            return false;
          }
        };

    Application.getController().start(t);
  }
  protected void pickFileVFS() {

    FileDialog dialog = new FileDialog(shell, SWT.OPEN);
    dialog.setFilterExtensions(Const.STRING_TRANS_FILTER_EXT);
    dialog.setFilterNames(Const.getTransformationFilterNames());
    String prevName = jobMeta.environmentSubstitute(wPath.getText());
    String parentFolder = null;
    try {
      parentFolder =
          KettleVFS.getFilename(
              KettleVFS.getFileObject(jobMeta.environmentSubstitute(jobMeta.getFilename()))
                  .getParent());
    } catch (Exception e) {
      // not that important
    }
    if (!Utils.isEmpty(prevName)) {
      try {
        if (KettleVFS.fileExists(prevName)) {
          dialog.setFilterPath(
              KettleVFS.getFilename(KettleVFS.getFileObject(prevName).getParent()));
        } else {

          if (!prevName.endsWith(".ktr")) {
            prevName = getEntryName(Const.trim(wPath.getText()) + ".ktr");
          }
          if (KettleVFS.fileExists(prevName)) {
            specificationMethod = ObjectLocationSpecificationMethod.FILENAME;
            wPath.setText(prevName);
            return;
          } else {
            // File specified doesn't exist. Ask if we should create the file...
            //
            MessageBox mb = new MessageBox(shell, SWT.YES | SWT.NO | SWT.ICON_QUESTION);
            mb.setMessage(
                BaseMessages.getString(
                    PKG, "JobTrans.Dialog.CreateTransformationQuestion.Message"));
            mb.setText(
                BaseMessages.getString(
                    PKG, "JobTrans.Dialog.CreateTransformationQuestion.Title")); // Sorry!
            int answer = mb.open();
            if (answer == SWT.YES) {

              Spoon spoon = Spoon.getInstance();
              spoon.newTransFile();
              TransMeta transMeta = spoon.getActiveTransformation();
              transMeta.initializeVariablesFrom(jobEntry);
              transMeta.setFilename(jobMeta.environmentSubstitute(prevName));
              wPath.setText(prevName);
              specificationMethod = ObjectLocationSpecificationMethod.FILENAME;
              spoon.saveFile();
              return;
            }
          }
        }
      } catch (Exception e) {
        dialog.setFilterPath(parentFolder);
      }
    } else if (!Utils.isEmpty(parentFolder)) {
      dialog.setFilterPath(parentFolder);
    }

    String fname = dialog.open();
    if (fname != null) {
      File file = new File(fname);
      String name = file.getName();
      String parentFolderSelection = file.getParentFile().toString();

      if (!Utils.isEmpty(parentFolder) && parentFolder.equals(parentFolderSelection)) {
        wPath.setText(getEntryName(name));
      } else {
        wPath.setText(fname);
      }
    }
  }
  @Override
  public void run() {
    // Get the last-used directory for polygon region models from the preferences.
    final String directory =
        _preferencesStore.get(_preferencesString, Utilities.getWorkingDirectory());

    // Create the file selection dialog.
    Shell shell = new Shell(Display.getCurrent());
    FileDialog dialog = new FileDialog(shell, SWT.OPEN);
    dialog.setFilterPath(directory);
    dialog.setFilterNames(
        new String[] {
          "ABAVO Polygon Model (*." + PolygonRegionsModel.FILE_EXTENSION + ")",
          "Old ABAVO Polygon Model (*." + PolygonRegionsModel.FILE_EXTENSION_OLD + ")"
        });
    dialog.setFilterExtensions(
        new String[] {
          "*." + PolygonRegionsModel.FILE_EXTENSION, "*." + PolygonRegionsModel.FILE_EXTENSION_OLD
        });
    dialog.setText("Load Polygon Model");
    shell.setLocation(_parent.getLocation());

    // Open the file selection dialog and get the result.
    String result = dialog.open();
    if (result != null && result.length() > 0) {

      File file = new File(result);

      // Check the file extension.
      boolean validFile = file.getAbsolutePath().endsWith("." + PolygonRegionsModel.FILE_EXTENSION);
      boolean validFileOld =
          file.getAbsolutePath().endsWith("." + PolygonRegionsModel.FILE_EXTENSION_OLD);

      if (!validFile && !validFileOld) {
        // Show the user an error message.
        UserAssistMessageBuilder message = new UserAssistMessageBuilder();
        message.setDescription("Unable to read polygon model file.");
        message.addReason("Invalid file type.");
        message.addSolution(
            "Select a valid polygon model file (*." + PolygonRegionsModel.FILE_EXTENSION + ").");
        MessageDialog.openError(shell, "File I/O Error", message.toString());
      } else {
        boolean rescalePolygons =
            MessageDialog.openQuestion(
                shell, "Rescale Polygons", "Rescale polygons to plot maximum?");
        try {
          // Store the directory location in the preferences.
          _preferencesStore.put(_preferencesString, file.getParent());
          PreferencesUtil.saveInstanceScopePreferences(ServiceComponent.PLUGIN_ID);

          // Read the model from the file.
          if (validFile) {
            _model.readSession(file, rescalePolygons);
          } else if (validFileOld) {
            _model.readSessionOld(file, rescalePolygons);
          }
          String message = "Polygon regions model loaded:\n\'" + file.getAbsolutePath() + "\'";
          MessageDialog.openInformation(shell, "File I/O", message);
        } catch (Exception ex) {
          // Show the user an error message.
          UserAssistMessageBuilder message = new UserAssistMessageBuilder();
          message.setDescription("Unable to read polygon model file.");
          message.addReason(ex.toString());
          MessageDialog.openError(shell, "File I/O Error", message.toString());
        }
      }
    }
    shell.dispose();
  }
  /**
   * The function called whenever the Action is selected from the drop-down. It will grab the set of
   * silo files and create a .visit file from them which just sequentially lists the files,
   * separated by a newline character.
   */
  @Override
  public void run() {

    // Local Declarations
    String separator = System.getProperty("file.separator");
    String[] fileNames;
    String visitFileName = null;
    ArrayList<String> siloFilesToAdd;
    VizResource vizResource = null, child = null;
    ArrayList<VizResource> children = new ArrayList<VizResource>();

    // Filter files by images (*.silo) or all files.
    String[] filterNames = new String[] {"All Files (*)", ".silo Files", "VisIt Files"};
    String[] filterExtensions = new String[] {"*.silo"};

    // Set this as the default action for the parent Action
    parentAction.setDefaultAction(this);

    // Get the Shell of the workbench
    Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();

    // Open the file system exploration dialog. Use SWT.OPEN for an open
    // file dialog and SWT.MULTI to allow multi-selection of files.
    FileDialog dialog = new FileDialog(shell, SWT.OPEN | SWT.MULTI);

    // Check the OS and adjust if on Windows.
    String platform = SWT.getPlatform();
    if ("win32".equals(platform) || "wpf".equals(platform)) {
      filterNames[0] = "All Files (*.*)";
      filterExtensions[0] = "*.*";
    }

    // Set the dialog's file filters.
    dialog.setFilterNames(filterNames);
    dialog.setFilterExtensions(filterExtensions);

    // If a file was selected in the dialog, create an VizResource for it
    // and add it to the viewer.
    if (dialog.open() != null) {
      // Get a reference to the VizFileViewer.
      VizFileViewer vizViewer = (VizFileViewer) viewer;
      // The file names selected
      fileNames = dialog.getFileNames();
      visitFileName = dialog.getFilterPath() + separator + "visit_time_dependent.visit";
      siloFilesToAdd = new ArrayList<String>(Arrays.asList(fileNames));

      // Write the .visit file
      try {
        Files.write(
            Paths.get(visitFileName),
            siloFilesToAdd,
            Charset.defaultCharset(),
            StandardOpenOption.CREATE,
            StandardOpenOption.TRUNCATE_EXISTING);

        for (String name : fileNames) {
          child = new VizResource(new File(dialog.getFilterPath() + separator + name));
          child.setHost("localhost");
          children.add(child);
        }

        // Create the VizResource from it
        vizResource = new VizResource(new File(visitFileName)); // ,
        // children);

        // Set the host, this should just be local
        vizResource.setHost("localhost");

        // Add the File names so they show up in the tree
        vizResource.setFileSet(fileNames);

        // Give the .visit file to the FileViewer
        vizViewer.addFile(vizResource);

      } catch (IOException e) {
        logger.error(getClass().getName() + " Exception!", e);
      }

    } else {
      logger.info("AddFileSetAction message: No file selected.");
    }

    return;
  }
  /** @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite) */
  public void createControl(Composite parent) {

    dialog = new FileDialog(this.getShell(), SWT.SAVE);
    dialog.setText(Messages.SVGFilePickerPage_WindowMessage);
    dialog.setFilterExtensions(
        new String[] {"*." + Messages.SVGFilePickerPage_Extension}); // $NON-NLS-1$
    dialog.setFilterNames(new String[] {Messages.SVGFilePickerPage_ExtensionName});

    Group group = new Group(parent, SWT.NONE);
    GridLayout layout = new GridLayout();
    layout.numColumns = 2;
    layout.makeColumnsEqualWidth = false;
    group.setLayout(layout);

    GridData data;

    Label label = new Label(group, SWT.NONE);
    label.setText(Messages.SVGFilePickerPage_ChooseWindowMessage);
    data = new GridData(SWT.FILL, SWT.CENTER, true, false);
    data.horizontalSpan = 2;
    data.verticalSpan = 1;
    label.setLayoutData(data);

    filePathText = new Text(group, SWT.NONE);
    filePathText.addModifyListener(
        new ModifyListener() {

          public void modifyText(ModifyEvent e) {

            Text text = (Text) e.widget;
            fileModel.setFilePath(text.getText());
            setPageComplete(getWizard().canFinish());
          }
        });
    data = new GridData(SWT.FILL, SWT.CENTER, true, false);
    data.horizontalSpan = 1;
    data.verticalSpan = 1;
    filePathText.setLayoutData(data);

    Button browse = new Button(group, SWT.PUSH);
    browse.setText(Messages.SVGFilePickerPage_BrowseButtonText);
    browse.setToolTipText(Messages.SVGFilePickerPage_BrowseButtonTooltip);
    browse.setAlignment(SWT.CENTER);
    browse.setEnabled(true);
    browse.setVisible(true);
    data = new GridData(SWT.RIGHT, SWT.CENTER, false, false);
    data.horizontalSpan = 1;
    data.verticalSpan = 1;
    browse.setLayoutData(data);

    browse.addSelectionListener(
        new SelectionListener() {

          public void widgetDefaultSelected(SelectionEvent e) {

            widgetSelected(e);
          }

          public void widgetSelected(SelectionEvent e) {

            dialog.setFilterPath(filePathText.getText());
            String filePath = dialog.open();
            filePathText.setText(filePath);
          }
        });

    setControl(group);
  }
Example #19
0
  /**
   * Handle the create button selection event.
   *
   * @param event org.eclipse.swt.events.SelectionEvent
   */
  void createButtonSelected(SelectionEvent event) {

    /* Compute the appropriate dialog style */
    int style = getDefaultStyle();
    if (okButton.getEnabled() && okButton.getSelection()) style |= SWT.OK;
    if (cancelButton.getEnabled() && cancelButton.getSelection()) style |= SWT.CANCEL;
    if (yesButton.getEnabled() && yesButton.getSelection()) style |= SWT.YES;
    if (noButton.getEnabled() && noButton.getSelection()) style |= SWT.NO;
    if (retryButton.getEnabled() && retryButton.getSelection()) style |= SWT.RETRY;
    if (abortButton.getEnabled() && abortButton.getSelection()) style |= SWT.ABORT;
    if (ignoreButton.getEnabled() && ignoreButton.getSelection()) style |= SWT.IGNORE;
    if (iconErrorButton.getEnabled() && iconErrorButton.getSelection()) style |= SWT.ICON_ERROR;
    if (iconInformationButton.getEnabled() && iconInformationButton.getSelection())
      style |= SWT.ICON_INFORMATION;
    if (iconQuestionButton.getEnabled() && iconQuestionButton.getSelection())
      style |= SWT.ICON_QUESTION;
    if (iconWarningButton.getEnabled() && iconWarningButton.getSelection())
      style |= SWT.ICON_WARNING;
    if (iconWorkingButton.getEnabled() && iconWorkingButton.getSelection())
      style |= SWT.ICON_WORKING;
    if (primaryModalButton.getEnabled() && primaryModalButton.getSelection())
      style |= SWT.PRIMARY_MODAL;
    if (applicationModalButton.getEnabled() && applicationModalButton.getSelection())
      style |= SWT.APPLICATION_MODAL;
    if (systemModalButton.getEnabled() && systemModalButton.getSelection())
      style |= SWT.SYSTEM_MODAL;
    if (saveButton.getEnabled() && saveButton.getSelection()) style |= SWT.SAVE;
    if (openButton.getEnabled() && openButton.getSelection()) style |= SWT.OPEN;
    if (multiButton.getEnabled() && multiButton.getSelection()) style |= SWT.MULTI;

    /* Open the appropriate dialog type */
    String name = dialogCombo.getText();

    if (name.equals(ControlExample.getResourceString("ColorDialog"))) {
      ColorDialog dialog = new ColorDialog(shell, style);
      dialog.setRGB(new RGB(100, 100, 100));
      dialog.setText(ControlExample.getResourceString("Title"));
      RGB result = dialog.open();
      textWidget.append(ControlExample.getResourceString("ColorDialog") + Text.DELIMITER);
      textWidget.append(
          ControlExample.getResourceString("Result", new String[] {"" + result}) + Text.DELIMITER);
      textWidget.append("getRGB() = " + dialog.getRGB() + Text.DELIMITER + Text.DELIMITER);
      return;
    }

    if (name.equals(ControlExample.getResourceString("DirectoryDialog"))) {
      DirectoryDialog dialog = new DirectoryDialog(shell, style);
      dialog.setMessage(ControlExample.getResourceString("Example_string"));
      dialog.setText(ControlExample.getResourceString("Title"));
      String result = dialog.open();
      textWidget.append(ControlExample.getResourceString("DirectoryDialog") + Text.DELIMITER);
      textWidget.append(
          ControlExample.getResourceString("Result", new String[] {"" + result})
              + Text.DELIMITER
              + Text.DELIMITER);
      return;
    }

    if (name.equals(ControlExample.getResourceString("FileDialog"))) {
      FileDialog dialog = new FileDialog(shell, style);
      dialog.setFileName(ControlExample.getResourceString("readme_txt"));
      dialog.setFilterNames(FilterNames);
      dialog.setFilterExtensions(FilterExtensions);
      dialog.setText(ControlExample.getResourceString("Title"));
      String result = dialog.open();
      textWidget.append(ControlExample.getResourceString("FileDialog") + Text.DELIMITER);
      textWidget.append(
          ControlExample.getResourceString("Result", new String[] {"" + result}) + Text.DELIMITER);
      textWidget.append("getFileNames() =" + Text.DELIMITER);
      if ((dialog.getStyle() & SWT.MULTI) != 0) {
        String[] files = dialog.getFileNames();
        for (int i = 0; i < files.length; i++) {
          textWidget.append("\t" + files[i] + Text.DELIMITER);
        }
      }
      textWidget.append(
          "getFilterIndex() = " + dialog.getFilterIndex() + Text.DELIMITER + Text.DELIMITER);
      return;
    }

    if (name.equals(ControlExample.getResourceString("FontDialog"))) {
      FontDialog dialog = new FontDialog(shell, style);
      dialog.setText(ControlExample.getResourceString("Title"));
      FontData result = dialog.open();
      textWidget.append(ControlExample.getResourceString("FontDialog") + Text.DELIMITER);
      textWidget.append(
          ControlExample.getResourceString("Result", new String[] {"" + result}) + Text.DELIMITER);
      textWidget.append("getFontList() =" + Text.DELIMITER);
      FontData[] fonts = dialog.getFontList();
      if (fonts != null) {
        for (int i = 0; i < fonts.length; i++) {
          textWidget.append("\t" + fonts[i] + Text.DELIMITER);
        }
      }
      textWidget.append("getRGB() = " + dialog.getRGB() + Text.DELIMITER + Text.DELIMITER);
      return;
    }

    if (name.equals(ControlExample.getResourceString("PrintDialog"))) {
      PrintDialog dialog = new PrintDialog(shell, style);
      dialog.setText(ControlExample.getResourceString("Title"));
      PrinterData result = dialog.open();
      textWidget.append(ControlExample.getResourceString("PrintDialog") + Text.DELIMITER);
      textWidget.append(
          ControlExample.getResourceString("Result", new String[] {"" + result}) + Text.DELIMITER);
      textWidget.append("getScope() = " + dialog.getScope() + Text.DELIMITER);
      textWidget.append("getStartPage() = " + dialog.getStartPage() + Text.DELIMITER);
      textWidget.append("getEndPage() = " + dialog.getEndPage() + Text.DELIMITER);
      textWidget.append(
          "getPrintToFile() = " + dialog.getPrintToFile() + Text.DELIMITER + Text.DELIMITER);
      return;
    }

    if (name.equals(ControlExample.getResourceString("MessageBox"))) {
      MessageBox dialog = new MessageBox(shell, style);
      dialog.setMessage(ControlExample.getResourceString("Example_string"));
      dialog.setText(ControlExample.getResourceString("Title"));
      int result = dialog.open();
      textWidget.append(ControlExample.getResourceString("MessageBox") + Text.DELIMITER);
      /*
       * The resulting integer depends on the original
       * dialog style.  Decode the result and display it.
       */
      switch (result) {
        case SWT.OK:
          textWidget.append(ControlExample.getResourceString("Result", new String[] {"SWT.OK"}));
          break;
        case SWT.YES:
          textWidget.append(ControlExample.getResourceString("Result", new String[] {"SWT.YES"}));
          break;
        case SWT.NO:
          textWidget.append(ControlExample.getResourceString("Result", new String[] {"SWT.NO"}));
          break;
        case SWT.CANCEL:
          textWidget.append(
              ControlExample.getResourceString("Result", new String[] {"SWT.CANCEL"}));
          break;
        case SWT.ABORT:
          textWidget.append(ControlExample.getResourceString("Result", new String[] {"SWT.ABORT"}));
          break;
        case SWT.RETRY:
          textWidget.append(ControlExample.getResourceString("Result", new String[] {"SWT.RETRY"}));
          break;
        case SWT.IGNORE:
          textWidget.append(
              ControlExample.getResourceString("Result", new String[] {"SWT.IGNORE"}));
          break;
        default:
          textWidget.append(ControlExample.getResourceString("Result", new String[] {"" + result}));
          break;
      }
      textWidget.append(Text.DELIMITER + Text.DELIMITER);
    }
  }
Example #20
0
  private void openAddressBook() {
    FileDialog fileDialog = new FileDialog(shell, SWT.OPEN);

    fileDialog.setFilterExtensions(new String[] {"*.adr;", "*.*"});
    fileDialog.setFilterNames(
        new String[] {
          resAddressBook.getString("Book_filter_name") + " (*.adr)",
          resAddressBook.getString("All_filter_name") + " (*.*)"
        });
    String name = fileDialog.open();

    if (name == null) return;
    File file = new File(name);
    if (!file.exists()) {
      displayError(
          resAddressBook.getString("File")
              + file.getName()
              + " "
              + resAddressBook.getString("Does_not_exist"));
      return;
    }

    Cursor waitCursor = shell.getDisplay().getSystemCursor(SWT.CURSOR_WAIT);
    shell.setCursor(waitCursor);

    FileReader fileReader = null;
    BufferedReader bufferedReader = null;
    String[] data = new String[0];
    try {
      fileReader = new FileReader(file.getAbsolutePath());
      bufferedReader = new BufferedReader(fileReader);
      String nextLine = bufferedReader.readLine();
      while (nextLine != null) {
        String[] newData = new String[data.length + 1];
        System.arraycopy(data, 0, newData, 0, data.length);
        newData[data.length] = nextLine;
        data = newData;
        nextLine = bufferedReader.readLine();
      }
    } catch (FileNotFoundException e) {
      displayError(resAddressBook.getString("File_not_found") + "\n" + file.getName());
      return;
    } catch (IOException e) {
      displayError(resAddressBook.getString("IO_error_read") + "\n" + file.getName());
      return;
    } finally {

      shell.setCursor(null);

      if (fileReader != null) {
        try {
          fileReader.close();
        } catch (IOException e) {
          displayError(resAddressBook.getString("IO_error_close") + "\n" + file.getName());
          return;
        }
      }
    }

    String[][] tableInfo = new String[data.length][table.getColumnCount()];
    int writeIndex = 0;
    for (int i = 0; i < data.length; i++) {
      String[] line = decodeLine(data[i]);
      if (line != null) tableInfo[writeIndex++] = line;
    }
    if (writeIndex != data.length) {
      String[][] result = new String[writeIndex][table.getColumnCount()];
      System.arraycopy(tableInfo, 0, result, 0, writeIndex);
      tableInfo = result;
    }
    Arrays.sort(tableInfo, new RowComparator(0));

    for (int i = 0; i < tableInfo.length; i++) {
      TableItem item = new TableItem(table, SWT.NONE);
      item.setText(tableInfo[i]);
    }
    shell.setText(resAddressBook.getString("Title_bar") + fileDialog.getFileName());
    isModified = false;
    this.file = file;
  }