Пример #1
0
 /**
  * Read the command line arguments for the program from the preferences. The input filename is
  * marked with a "%input" and the output file name is marked with a "%output".
  *
  * @return the command line arguments for the program
  */
 public String getProgramArguments() {
   String args = TexlipsePlugin.getPreference(getArgumentsPreferenceName());
   if (args == null || args.length() == 0) {
     return TexlipsePlugin.getPreference(getArgumentsPreferenceNameByClass());
   } else {
     return args;
   }
 }
Пример #2
0
 /** @return the program path and filename from the preferences */
 public String getProgramPath() {
   String path = TexlipsePlugin.getPreference(getCommandPreferenceName());
   if (path == null || path.length() == 0) {
     // Fall back to class-based config
     return TexlipsePlugin.getPreference(getCommandPreferenceNameByClass());
   } else {
     return path;
   }
 }
Пример #3
0
  /**
   * Constructs a new document model.
   *
   * @param editor The editor this model is associated to.
   */
  public TexDocumentModel(TexEditor editor) {
    this.editor = editor;
    this.isDirty = true;

    // initialize jobs
    parseJob = new ParseJob("Parsing");
    postParseJob = new PostParseJob("Updating");
    parseJob.setPriority(Job.DECORATE);
    postParseJob.setPriority(Job.DECORATE);
    // get preferences
    this.parseDelay =
        TexlipsePlugin.getDefault()
            .getPreferenceStore()
            .getInt(TexlipseProperties.AUTO_PARSING_DELAY);
    this.autoParseEnabled =
        TexlipsePlugin.getDefault()
            .getPreferenceStore()
            .getBoolean(TexlipseProperties.AUTO_PARSING);
    this.sectionCheckEnabled =
        TexlipsePlugin.getDefault()
            .getPreferenceStore()
            .getBoolean(TexlipseProperties.SECTION_CHECK);

    // add preference change listener
    TexlipsePlugin.getDefault()
        .getPreferenceStore()
        .addPropertyChangeListener(
            new IPropertyChangeListener() {

              public void propertyChange(PropertyChangeEvent event) {
                String property = event.getProperty();
                if (TexlipseProperties.AUTO_PARSING.equals(property)) {
                  autoParseEnabled =
                      TexlipsePlugin.getDefault()
                          .getPreferenceStore()
                          .getBoolean(TexlipseProperties.AUTO_PARSING);
                } else if (TexlipseProperties.AUTO_PARSING_DELAY.equals(property)) {
                  parseDelay =
                      TexlipsePlugin.getDefault()
                          .getPreferenceStore()
                          .getInt(TexlipseProperties.AUTO_PARSING_DELAY);
                } else if (TexlipseProperties.SECTION_CHECK.equals(property)) {
                  sectionCheckEnabled =
                      TexlipsePlugin.getDefault()
                          .getPreferenceStore()
                          .getBoolean(TexlipseProperties.SECTION_CHECK);
                }
              }
            });
  }
  /**
   * Deletes the contents of the temporary files folder, including subfolders
   *
   * @param monitor progress monitor
   * @throws CoreException if an error occurs
   */
  public void cleanTempFiles(IProgressMonitor monitor) throws CoreException {
    if (tempDir != null && tempDir.exists()) {
      monitor.beginTask(
          TexlipsePlugin.getResourceString("builderSubTaskClean"), tempDir.members().length);
      monitor.subTask(TexlipsePlugin.getResourceString("builderSubTaskCleanTemp"));

      // Retrieve current temp folder content
      final Set<IPath> currentTmpFiles = tracking.getTempFolderNames(monitor);

      // Perform deletion
      deleteFiles(currentTmpFiles, monitor);
    }
    tracking.clearSnapshots();
  }
Пример #5
0
 /**
  * Checks whether all includes exists, if they are outside of the project, add a link to the file
  * to the project
  *
  * @param includes
  */
 private void processIncludes(List<OutlineNode> includes, IEditorInput input) {
   IProject project = getCurrentProject();
   if (project == null) return;
   IFile referFile = (IFile) input.getAdapter(IFile.class);
   if (referFile == null) return;
   for (OutlineNode node : includes) {
     IFile f = null;
     IFile mainTexFile = TexlipseProperties.getProjectSourceFile(project);
     if (mainTexFile != null) {
       // Includes are always relative to the main file
       f = TexProjectParser.findIFile(node.getName(), mainTexFile, project);
     }
     if (f == null) {
       // Try finding it relative to refering file
       f = TexProjectParser.findIFile(node.getName(), referFile, project);
     }
     if (f == null) {
       MarkerHandler marker = MarkerHandler.getInstance();
       String errorMsg =
           MessageFormat.format(
               TexlipsePlugin.getResourceString("parseErrorIncludeNotFound"),
               new Object[] {node.getName()});
       marker.createErrorMarker(referFile, errorMsg, node.getBeginLine());
     }
   }
 }
  /**
   * Performs actions after the LaTeX builder has finished building a document for the current
   * source; namely:
   *
   * <ul>
   *   <li>renaming and/or moving output (and other derived) files out of the build directory into
   *       the output folder
   *   <li>moving old and new temporary files out of the build directory into the temporary files
   *       folder
   * </ul>
   *
   * @param inputFile name of the input file; this can be <code>null</code>, if the current main
   *     document has just been built, but should be set after partial builds
   * @param monitor progress monitor
   * @throws CoreException if an error occurs
   */
  public void performAfterBuild(IProgressMonitor monitor) throws CoreException {
    // keeping first exception, which occurs when moving files; however, attempts
    // to still perform following steps
    CoreException ex = null;

    // make sure this has access to all files (if this fails, it means trouble to
    // all following steps)
    refreshView(monitor);

    Set<IPath> outputFiles = null;
    try { // possibly move output files away from the source dir and mark as derived
      outputFiles = moveOutputFiles(monitor);
    } catch (CoreException e) {
      // store exception for throwing it later
      ex =
          new BuilderCoreException(
              TexlipsePlugin.stat(TexlipsePlugin.getResourceString("builderCoreErrorOutputBlock")));
    }

    try { // move temp files out of this folder and mark as derived
      moveTempFiles(outputFiles, monitor);
    } catch (CoreException e) {
      // we only worry about this one, if the build was okay
      if (ex == null) {
        ex =
            new BuilderCoreException(
                TexlipsePlugin.stat(TexlipsePlugin.getResourceString("builderCoreErrorTempBlock")));
      }
    }

    try {
      refreshView(monitor);
    } catch (CoreException e) {
      // this is not irrelevant, but not as severe as the others
      if (ex == null) {
        ex = e;
      }
    }

    tracking.clearSnapshots();
    // now throw any pending exception, after cleaning up
    if (ex != null) {
      throw ex;
    }
  }
  /**
   * Deletes the output file.
   *
   * @param monitor progress monitor
   * @throws CoreException if an error occurs
   */
  public void cleanOutputFile(IProgressMonitor monitor) throws CoreException {
    monitor.subTask(TexlipsePlugin.getResourceString("builderSubTaskCleanOutput"));

    IFile outputFile = getSelectedOutputFile();
    if (outputFile != null && outputFile.exists()) {
      outputFile.delete(true, monitor);
    }

    monitor.worked(1);
  }
  /**
   * Moves temporary files out of the build directory, if applicable. A file is considered a
   * temporary file, if
   *
   * <ul>
   *   <li>it had been in the temporary files folder before the build process
   *       <p><b>or</b>
   *   <li>it was created or modified during the build process, and has a temporary file extension
   *       as specified in the preferences
   * </ul>
   *
   * @param excludes set of paths to exclude from moving, e.g. because they are the main output
   *     files
   * @param monitor progress monitor
   * @throws CoreException if an error occurs
   */
  private void moveTempFiles(final Set<IPath> excludes, IProgressMonitor monitor)
      throws CoreException {
    final IContainer aSourceContainer = getActualSourceContainer();
    if (tracking.isInitial() || aSourceContainer == null || !aSourceContainer.exists()) {
      return;
    }

    final boolean markAsDerived =
        "true"
            .equals(
                TexlipseProperties.getProjectProperty(
                    project, TexlipseProperties.MARK_TEMP_DERIVED_PROPERTY));
    final String[] tempExts = TexlipsePlugin.getPreferenceArray(TexlipseProperties.TEMP_FILE_EXTS);

    // Check if there is anything to do
    if (markAsDerived || tempDir != null) {
      // First move temporary files, which had been placed into the source folder
      // just prior to the build;
      // then check for new temporary files, which need to be moved
      project
          .getWorkspace()
          .run(
              new IWorkspaceRunnable() {
                public void run(IProgressMonitor monitor) throws CoreException {
                  if (movedFiles != null) {
                    if (excludes != null) {
                      movedFiles.removeAll(excludes);
                    }
                    moveFiles(sourceDir, tempDir, movedFiles, markAsDerived, true, monitor);
                  }
                  final Set<IPath> newTempNames =
                      tracking.getNewTempNames(aSourceContainer, tempExts, format, monitor);
                  if (excludes != null) {
                    newTempNames.removeAll(excludes);
                  }
                  moveFiles(sourceDir, tempDir, newTempNames, markAsDerived, true, monitor);
                }
              },
              monitor);
    }
  }
Пример #9
0
  /**
   * Does the same as super.createDocument(Object), except this also adds latex nature to the
   * project containing the given document.
   */
  public IDocument getDocument(Object element) {
    IDocument doc = super.getDocument(element);

    // add latex nature to project holding this latex file
    // this way we also get latex builder to any project that has latex files
    if (element instanceof FileEditorInput) {
      IFile file = (IFile) ((FileEditorInput) element).getAdapter(IFile.class);
      if (file != null) {

        IProject project = file.getProject();
        try {
          if (!project.hasNature(TexlipseNature.NATURE_ID)) {
            return doc;
            //                        TexlipseProjectCreationOperation.addProjectNature(project, new
            // NullProgressMonitor());
          } else if (TexlipseProperties.getProjectProperty(
                  project, TexlipseProperties.OUTPUT_FORMAT)
              == null) {
            // this is needed for imported projects
            TexlipseNature n = new TexlipseNature();
            // the nature is not added, just configured
            n.setProject(project);
            // this will cause the builder to be added, if not already there
            n.configure();
          }
        } catch (CoreException e) {
          return doc;
        }

        // output format might not yet be set
        String format =
            TexlipseProperties.getProjectProperty(project, TexlipseProperties.OUTPUT_FORMAT);
        if (format == null || format.length() == 0) {
          TexlipseProperties.setProjectProperty(
              project,
              TexlipseProperties.OUTPUT_FORMAT,
              TexlipsePlugin.getPreference(TexlipseProperties.OUTPUT_FORMAT));
          TexlipseProperties.setProjectProperty(
              project,
              TexlipseProperties.BUILDER_NUMBER,
              TexlipsePlugin.getPreference(TexlipseProperties.BUILDER_NUMBER));
          TexlipseProperties.setProjectProperty(
              project, TexlipseProperties.MARK_TEMP_DERIVED_PROPERTY, "true");
          TexlipseProperties.setProjectProperty(
              project, TexlipseProperties.MARK_OUTPUT_DERIVED_PROPERTY, "true");

          String name = file.getName();
          TexlipseProperties.setProjectProperty(
              project, TexlipseProperties.MAINFILE_PROPERTY, name);
          String output =
              name.substring(0, name.lastIndexOf('.') + 1)
                  + TexlipsePlugin.getPreference(TexlipseProperties.OUTPUT_FORMAT);
          TexlipseProperties.setProjectProperty(
              project, TexlipseProperties.OUTPUTFILE_PROPERTY, output);

          IPath path = file.getFullPath();
          String dir = path.removeFirstSegments(1).removeLastSegments(1).toString();
          if (dir.length() > 0) {
            TexlipseProperties.setProjectProperty(
                project, TexlipseProperties.SOURCE_DIR_PROPERTY, dir);
            TexlipseProperties.setProjectProperty(
                project, TexlipseProperties.OUTPUT_DIR_PROPERTY, dir);
            TexlipseProperties.setProjectProperty(
                project, TexlipseProperties.TEMP_DIR_PROPERTY, dir);
          }
        }
      }
    }

    return doc;
  }
Пример #10
0
 /** @param args the program arguments for the preferences */
 public void setProgramArguments(String args) {
   TexlipsePlugin.getDefault().getPreferenceStore().setValue(getArgumentsPreferenceName(), args);
 }
Пример #11
0
 /** Shows user a message */
 private void showMessage(String message) {
   MessageDialog.openInformation(
       viewer.getControl().getShell(),
       TexlipsePlugin.getResourceString("tableviewTableTitle"),
       message);
 }
Пример #12
0
 /** @param path the program path and filename for the preferences */
 public void setProgramPath(String path) {
   TexlipsePlugin.getDefault().getPreferenceStore().setValue(getCommandPreferenceName(), path);
 }
Пример #13
0
  /**
   * Creates all the project data structures. These include the reference completions (BibTeX and
   * label), command completions, the preamble, the BibTeX style.
   *
   * @param project The current project
   */
  private void createProjectDatastructs(IProject project) {
    // IResource resource = ((FileEditorInput)editor.getEditorInput()).getFile();

    IResource[] files = TexlipseProperties.getAllProjectFiles(project);

    if (files != null) {
      IFile mainFile = TexlipseProperties.getProjectSourceFile(project);

      for (int i = 0; i < files.length; i++) {
        // IPath path = files[i].getFullPath();
        String ext = files[i].getFileExtension();
        // here are the file types we want to parse
        if ("tex".equals(ext) || "ltx".equals(ext) || "sty".equals(ext)) {
          try {
            String input = TexlipseProperties.getFileContents(files[i]);
            LatexRefExtractingParser lrep = new LatexRefExtractingParser();
            lrep.parse(input);
            if (lrep.isFatalErrors()) {
              MarkerHandler marker = MarkerHandler.getInstance();
              marker.addFatalError(
                  editor,
                  "The file "
                      + files[i].getFullPath()
                      + " contains fatal errors, parsing aborted.");
              continue;
            }
            List<ReferenceEntry> labels = lrep.getLabels();
            if (labels.size() > 0) {
              labelContainer.addRefSource(files[i].getProjectRelativePath().toString(), labels);
            }
            List<TexCommandEntry> commands = lrep.getCommands();
            if (commands.size() > 0) {
              commandContainer.addRefSource(files[i].getProjectRelativePath().toString(), commands);
            }
            // Only update Preamble, Bibstyle if main Document
            if (files[i].equals(mainFile)) {
              String[] bibs = lrep.getBibs();
              boolean biblatexMode = lrep.isBiblatexMode();
              String biblatexBackend = lrep.getBiblatexBackend();
              this.updateBiblatex(project, biblatexMode, biblatexBackend, true);
              this.updateBibs(bibs, biblatexMode, files[i]);

              String preamble = lrep.getPreamble();
              if (preamble != null) {
                TexlipseProperties.setSessionProperty(
                    project, TexlipseProperties.PREAMBLE_PROPERTY, preamble);
              }

              String bibstyle = lrep.getBibstyle();
              if (bibstyle != null)
                TexlipseProperties.setSessionProperty(
                    project, TexlipseProperties.BIBSTYLE_PROPERTY, bibstyle);
            }
          } catch (IOException ioe) {
            TexlipsePlugin.log(
                "Unable to open file " + files[i].getFullPath() + " for parsing", ioe);
          }
        }
      }
      // save time by doing this last
      labelContainer.organize();
      commandContainer.organize();
    }
  }
Пример #14
0
  /**
   * Updates completions for the BibTeX -data
   *
   * @param bibNames Names of the BibTeX -files that the document uses
   * @param resource The resource of the document
   */
  private void updateBibs(String[] bibNames, boolean biblatexMode, IResource resource) {
    IProject project = getCurrentProject();
    if (project == null) return;

    if (!biblatexMode) {
      for (int i = 0; i < bibNames.length; i++) {
        if (!bibNames[i].endsWith(".bib")) {
          bibNames[i] += ".bib";
        }
      }
    }

    if (bibContainer.checkFreshness(bibNames)) {
      return;
    }

    TexlipseProperties.setSessionProperty(project, TexlipseProperties.BIBFILE_PROPERTY, bibNames);

    List<String> newBibs = bibContainer.updateBibHash(bibNames);

    IPath path = resource.getFullPath().removeFirstSegments(1).removeLastSegments(1);
    if (!path.isEmpty()) path = path.addTrailingSeparator();

    KpsewhichRunner filesearch = new KpsewhichRunner();

    for (Iterator<String> iter = newBibs.iterator(); iter.hasNext(); ) {
      String name = iter.next();
      try {
        String filepath = "";
        // First try local search
        IResource res = project.findMember(path + name);
        // Try searching relative to main file
        if (res == null) {
          IContainer sourceDir = TexlipseProperties.getProjectSourceDir(project);
          res = sourceDir.findMember(name);
        }

        if (res != null) {
          filepath = res.getLocation().toOSString();
        }
        if (res == null) {
          // Try Kpsewhich
          filepath = filesearch.getFile(resource, name, "bibtex");
          if (filepath.length() > 0 && !(new File(filepath).isAbsolute())) {
            // filepath is a local path
            res = project.findMember(path + filepath);
            if (res != null) {
              filepath = res.getLocation().toOSString();
            } else {
              filepath = "";
            }
          } else if (filepath.length() > 0) {
            // Create a link to resource
            IPath p = new Path(filepath);
            if (name.indexOf('/') >= 0) {
              // Remove path from name
              name = name.substring(name.lastIndexOf('/') + 1);
            }
            IFile f = project.getFile(path + name);
            if (f != null && !f.exists()) {
              f.createLink(p, IResource.NONE, null);
            }
          }
        }

        if (filepath.length() > 0) {
          BibParser parser = new BibParser(filepath);
          try {
            List<ReferenceEntry> bibEntriesList = parser.getEntries();
            if (bibEntriesList != null && bibEntriesList.size() > 0) {
              bibContainer.addRefSource(path + name, bibEntriesList);
            } else if (bibEntriesList == null) {
              MarkerHandler marker = MarkerHandler.getInstance();
              marker.addFatalError(
                  editor,
                  "The BibTeX file " + filepath + " contains fatal errors, parsing aborted.");
              continue;
            }
          } catch (IOException ioe) {
            TexlipsePlugin.log("Can't read BibTeX file " + filepath, ioe);
          }
        } else {
          MarkerHandler marker = MarkerHandler.getInstance();
          marker.addFatalError(editor, "The BibTeX file " + name + " not found.");
        }

      } catch (CoreException ce) {
        TexlipsePlugin.log("Can't run Kpathsea", ce);
      }
    }
    bibContainer.organize();
  }
Пример #15
0
  /**
   * Parses the LaTeX-document and adds error markers if there were any errors. Throws <code>
   * TexDocumentParseException</code> if there were fatal parse errors that prohibit building an
   * outline.
   *
   * @param monitor
   * @throws TexDocumentParseException
   */
  private ArrayList<OutlineNode> doParse(IProgressMonitor monitor)
      throws TexDocumentParseException {

    if (this.parser == null) {
      this.parser =
          new TexParser(editor.getDocumentProvider().getDocument(editor.getEditorInput()));
    }
    if (projectOutline == null) {
      createProjectOutline();
    }

    try {
      parser.parseDocument(sectionCheckEnabled);
    } catch (IOException e) {
      TexlipsePlugin.log("Can't read file.", e);
      throw new TexDocumentParseException(e);
    }
    pollCancel(monitor);

    List<ParseErrorMessage> errors = parser.getErrors();
    List<ParseErrorMessage> tasks = parser.getTasks();
    MarkerHandler marker = MarkerHandler.getInstance();

    // somewhat inelegantly ensures that errors marked in createProjectDatastructs()
    // aren't removed immediately
    if (!firstRun) {
      marker.clearErrorMarkers(editor);
      marker.clearTaskMarkers(editor);
    } else {
      firstRun = false;
    }

    if (editor.getProject() != null && editor.getFullOutline() != null) {
      IResource res = (IResource) editor.getEditorInput().getAdapter(IResource.class);
      String fileName = res.getProjectRelativePath().toString();
      projectOutline.addOutline(parser.getOutlineTree(), fileName);

      List<OutlineNode> fo = projectOutline.getFullOutline();
      postParseJob.setFONodes(fo);
    } else {
      postParseJob.setFONodes(null);
    }
    pollCancel(monitor);

    processIncludes(parser.getInputs(), editor.getEditorInput());

    if (errors.size() > 0) {
      marker.createErrorMarkers(editor, errors);
    }
    if (tasks.size() > 0) {
      marker.createTaskMarkers(editor, tasks);
    }
    if (parser.isFatalErrors()) {
      throw new TexDocumentParseException("Fatal errors in file, parsing aborted.");
    }

    updateReferences(monitor);

    List<DocumentReference> cites = parser.getCites();
    List<DocumentReference> bibErrors = null;
    for (DocumentReference cite : cites) {
      if (!bibContainer.binTest(cite.getKey())) {
        if (bibErrors == null) bibErrors = new ArrayList<DocumentReference>();
        bibErrors.add(cite);
      }
    }
    if (bibErrors != null) {
      marker.createReferencingErrorMarkers(editor, bibErrors);
    }

    List<DocumentReference> refs = parser.getRefs();
    List<DocumentReference> refErrors = null;
    for (DocumentReference ref : refs) {
      if (!labelContainer.binTest(ref.getKey())) {
        if (refErrors == null) refErrors = new ArrayList<DocumentReference>();
        refErrors.add(ref);
      }
    }
    if (refErrors != null) {
      marker.createReferencingErrorMarkers(editor, refErrors);
    }

    return this.parser.getOutlineTree();
  }
Пример #16
0
  /**
   * Creates the table component attaching it to the given composite object
   *
   * @param parent composite object
   * @return The created table component
   */
  public Table createTable(Composite parent) {
    int style =
        SWT.SINGLE
            | SWT.BORDER
            | SWT.H_SCROLL
            | SWT.V_SCROLL
            | SWT.HIDE_SELECTION
            | SWT.FULL_SELECTION;

    Table table = new Table(parent, style);

    GridData gridData = new GridData(GridData.FILL_BOTH);
    gridData.grabExcessVerticalSpace = true;
    gridData.horizontalSpan = 3;
    table.setLayoutData(gridData);

    table.setLinesVisible(true);
    table.setHeaderVisible(true);
    table.setToolTipText(TexlipsePlugin.getResourceString("tableviewTableTooltip"));

    TableColumn column;
    for (int i = 0; i < TexRow.COLUMNS; i++) {
      column = new TableColumn(table, SWT.LEFT, 0);
      column.setText(columnNames[i]);
      column.setWidth(50);
    }

    // The way to add listener to column, so that rows are sorted when header is clicked
    /*
    column.addSelectionListener(new SelectionAdapter() {
    public void widgetSelected(SelectionEvent e) {
    tableViewer.setSorter(new TexRowSorter());
    }
    });
    */

    menu = new Menu(parent);
    MenuItem mi;
    mi = new MenuItem(menu, SWT.SINGLE);
    mi.setText(TexlipsePlugin.getResourceString("tableviewInsertRow"));
    mi.setEnabled(true);
    mi.addSelectionListener(
        new SelectionAdapter() {
          public void widgetSelected(SelectionEvent e) {
            TexRow row = (TexRow) ((IStructuredSelection) viewer.getSelection()).getFirstElement();
            int index = -1;
            if (row != null) index = rowList.indexOf(row);
            if (index != -1) rowList.insertRow(index);
            else rowList.addRow(); // FIXME this is probably never executed
          }
        });
    mi = new MenuItem(menu, SWT.SINGLE);
    mi.setText(TexlipsePlugin.getResourceString("tableviewDeleteRow"));
    mi.setEnabled(true);
    mi.addSelectionListener(
        new SelectionAdapter() {
          public void widgetSelected(SelectionEvent e) {
            TexRow row = (TexRow) ((IStructuredSelection) viewer.getSelection()).getFirstElement();
            if (row != null) {
              rowList.removeRow(row);
            }
          }
        });
    mi = new MenuItem(menu, SWT.SINGLE);
    mi.setText(TexlipsePlugin.getResourceString("tableviewClearAll"));
    mi.setEnabled(true);
    mi.addSelectionListener(
        new SelectionAdapter() {
          public void widgetSelected(SelectionEvent e) {
            rowList.clearAll();
          }
        });

    new MenuItem(menu, SWT.SEPARATOR);

    mi = new MenuItem(menu, SWT.SINGLE);
    mi.setText(TexlipsePlugin.getResourceString("tableviewRowUp"));
    mi.setEnabled(true);
    mi.addSelectionListener(
        new SelectionAdapter() {
          public void widgetSelected(SelectionEvent e) {
            TexRow row = (TexRow) ((IStructuredSelection) viewer.getSelection()).getFirstElement();
            if (row != null) {
              rowList.move(row, rowList.indexOf(row) - 1);
            }
          }
        });
    mi = new MenuItem(menu, SWT.SINGLE);
    mi.setText(TexlipsePlugin.getResourceString("tableviewRowDown"));
    mi.setEnabled(true);
    mi.addSelectionListener(
        new SelectionAdapter() {
          public void widgetSelected(SelectionEvent e) {
            TexRow row = (TexRow) ((IStructuredSelection) viewer.getSelection()).getFirstElement();
            if (row != null) {
              rowList.move(row, rowList.indexOf(row) + 2);
            }
          }
        });
    mi = new MenuItem(menu, SWT.SINGLE);
    mi.setText(TexlipsePlugin.getResourceString("tableviewDuplicateRow"));
    mi.setEnabled(true);
    mi.addSelectionListener(
        new SelectionAdapter() {
          public void widgetSelected(SelectionEvent e) {
            TexRow row = (TexRow) ((IStructuredSelection) viewer.getSelection()).getFirstElement();
            if (row != null) {
              rowList.copy(row, rowList.indexOf(row));
            }
          }
        });

    new MenuItem(menu, SWT.SEPARATOR);

    mi = new MenuItem(menu, SWT.SINGLE);
    mi.setText(TexlipsePlugin.getResourceString("tableviewEditorImport"));
    mi.setEnabled(true);
    mi.addSelectionListener(
        new SelectionAdapter() {
          public void widgetSelected(SelectionEvent e) {
            // Get selection from texteditor
            IEditorPart targetEditor = TexlipsePlugin.getCurrentWorkbenchPage().getActiveEditor();

            if (!(targetEditor instanceof ITextEditor)) {
              return;
            }
            TexSelections selection = new TexSelections((ITextEditor) targetEditor);
            TexRow row = (TexRow) ((IStructuredSelection) viewer.getSelection()).getFirstElement();
            int index = 0;
            if (row != null) index = rowList.indexOf(row);
            rowList.importSelection(selection, index);
          }
        });

    mi = new MenuItem(menu, SWT.SINGLE);
    mi.setText(TexlipsePlugin.getResourceString("tableviewEditorExport"));
    mi.setEnabled(true);
    mi.addSelectionListener(
        new SelectionAdapter() {
          public void widgetSelected(SelectionEvent e) {
            String value = rowList.export();

            // transfer string to clipboard
            Clipboard cb = new Clipboard(null);
            TextTransfer textTransfer = TextTransfer.getInstance();
            cb.setContents(new Object[] {value}, new Transfer[] {textTransfer});
          }
        });

    mi = new MenuItem(menu, SWT.SINGLE);
    mi.setText(TexlipsePlugin.getResourceString("tableviewRawExport"));
    mi.setEnabled(true);
    mi.addSelectionListener(
        new SelectionAdapter() {
          public void widgetSelected(SelectionEvent e) {
            String value = rowList.exportRaw();

            // transfer string to clipboard
            Clipboard cb = new Clipboard(null);
            TextTransfer textTransfer = TextTransfer.getInstance();
            cb.setContents(new Object[] {value}, new Transfer[] {textTransfer});
          }
        });

    new MenuItem(menu, SWT.SEPARATOR);

    mi = new MenuItem(menu, SWT.SINGLE);
    mi.setText(TexlipsePlugin.getResourceString("tableviewFlipRows"));
    mi.setEnabled(true);
    mi.addSelectionListener(
        new SelectionAdapter() {
          public void widgetSelected(SelectionEvent e) {
            rowList.flipRowsAndColumns();
          }
        });
    mi = new MenuItem(menu, SWT.SINGLE);
    mi.setText(TexlipsePlugin.getResourceString("tableviewMirrorColumns"));
    mi.setEnabled(true);
    mi.addSelectionListener(
        new SelectionAdapter() {
          public void widgetSelected(SelectionEvent e) {
            rowList.mirrorColumns();
          }
        });
    mi = new MenuItem(menu, SWT.SINGLE);
    mi.setText(TexlipsePlugin.getResourceString("tableviewMirrorRows"));
    mi.setEnabled(true);
    mi.addSelectionListener(
        new SelectionAdapter() {
          public void widgetSelected(SelectionEvent e) {
            rowList.mirrorRows();
          }
        });

    table.setMenu(menu);

    return (table);
  }
Пример #17
0
  /**
   * Renames output files and/or moves them if necessary. A file is considered an output file, if
   *
   * <ul>
   *   <li>it is the current output file (which can also be from a temporary build)
   *       <p><b>or</b>
   *   <li>it has the same file name as the current input file, apart from its file extension, and
   *       one of the derived file extensions as specified in the preferences
   * </ul>
   *
   * @param monitor progress monitor
   * @return set of paths to the (possibly moved) files
   * @throws CoreException if an error occurs
   */
  private Set<IPath> moveOutputFiles(IProgressMonitor monitor) throws CoreException {
    final boolean markAsDerived =
        "true"
            .equals(
                TexlipseProperties.getProjectProperty(
                    project, TexlipseProperties.MARK_OUTPUT_DERIVED_PROPERTY));
    final String[] derivedExts =
        TexlipsePlugin.getPreferenceArray(TexlipseProperties.DERIVED_FILES);

    final IFile aSourceFile = getActualSourceFile();
    final IContainer aSourceContainer = getActualSourceContainer();
    final IFile sOutputFile = getSelectedOutputFile();
    final IContainer sOutputContainer = getSelectedOutputContainer(markAsDerived, monitor);
    if (aSourceFile == null
        || aSourceContainer == null
        || sOutputFile == null
        || sOutputContainer == null) {
      // Something is wrong with the settings
      return null;
    }

    // Get name without extension from main files for renaming
    final String dotFormat = '.' + format;
    final String sourceBaseName = stripFileExt(aSourceFile.getName(), null);
    final String outputBaseName = stripFileExt(sOutputFile.getName(), dotFormat);

    // Check if files are to be moved or renamed
    final boolean moveFiles =
        !sourceBaseName.equals(outputBaseName) || !sOutputContainer.equals(aSourceContainer);
    // Retrieve output and other derived files along with their extensions
    final Map<IPath, String> outputFiles =
        ProjectFileTracking.getOutputNames(
            aSourceContainer, sourceBaseName, derivedExts, format, monitor);

    // Check if there is anything to do
    if ((moveFiles || markAsDerived) && !outputFiles.isEmpty()) {
      final Set<IPath> movedFiles = new HashSet<IPath>(outputFiles.size());

      project
          .getWorkspace()
          .run(
              new IWorkspaceRunnable() {
                public void run(IProgressMonitor monitor) throws CoreException {
                  // Move files to destination folder and rename
                  for (Entry<IPath, String> entry : outputFiles.entrySet()) {
                    IFile currentFile = project.getFile(entry.getKey());
                    if (moveFiles) {
                      // Determine new file name
                      String destName = outputBaseName + entry.getValue();
                      // Move file
                      IFile dest =
                          moveFile(project, currentFile, sOutputContainer, destName, monitor);
                      if (dest != null && markAsDerived) {
                        dest.setDerived(true);
                      }
                      movedFiles.add(dest.getProjectRelativePath());
                    } else {
                      // Possibly mark as derived
                      if (markAsDerived) {
                        currentFile.setDerived(true);
                      }
                      movedFiles.add(entry.getKey());
                    }
                  }
                }
              },
              monitor);

      return movedFiles;
    } else {
      return outputFiles.keySet();
    }
  }