Search code examples
javaeclipseeclipse-plugineclipse-rcpprogressmonitor

How to set worked precisely in IProgressMonitor in Eclipse plugin?


The method org.eclipse.core.runtime.IProgressMonitor.worked(int) receives integer which means increment. This means, that the only units available are natural units. It can't be percents, for example.

So, if I process some files in the job, I can't report the counting stage, because the first method I should call is org.eclipse.core.runtime.IProgressMonitor.beginTask(String, int) which requires me to know the total amount.

How to accomplish?

UPDATE

I wrote a wrapper below, but this looks absurd one need to do so:

public class ProgressMonitorDoubleWrapper implements IProgressMonitor {

    private IProgressMonitor delegate;
    private int currentWork, totalWork;
    private double currentWorkDouble;

    public ProgressMonitorDoubleWrapper(IProgressMonitor monitor) {
        this.delegate = monitor;
    }

    @Override
    public void beginTask(String name, int totalWork) {
        beginTask(name, (double) totalWork); 
    }

    public void beginTask(String name, double totalWork) {
        this.totalWork = (int) totalWork;
        currentWork = 0;
        currentWorkDouble = 0;
        delegate.beginTask(name, this.totalWork);
    }

    @Override
    public void done() {
        delegate.done();
    }

    @Override
    public void internalWorked(double work) {
        delegate.internalWorked(work);
    }

    @Override
    public boolean isCanceled() {
        return delegate.isCanceled();
    }

    @Override
    public void setCanceled(boolean value) {
        delegate.setCanceled(value);
    }

    @Override
    public void setTaskName(String name) {
        delegate.setTaskName(name);
    }

    @Override
    public void subTask(String name) {
        delegate.subTask(name);
    }

    @Override
    public void worked(int work) {
        worked((double)work);
    }

    public void worked(double work) {
        currentWorkDouble += work;
        int increment = (int)(currentWorkDouble - (double)currentWork);
        currentWork += increment;
        delegate.worked(increment);
    }

}

Solution

  • I haven't seen a good solution for this, what you can do one of the following:

    Do some sort of quick scan to work out the total if possible.

    You can specify IProgressMonitor.UNKNOWN as the value on beginTask, this gives you a different progress bar which just shows something is happening.

    Just guess a value! Probably something that is bigger than the total worked value is likely to get.

    If the work can be split in to several pieces use SubProgressMonitor for each piece and specify a reasonable work count for each part:

     monitor.beginTask("task", 2 * 1000);
    
     work1(new SubProgressMonitor(monitor, 1000));
    
     work2(new SubProgressMonitor(monitor, 1000));