1   package com.stateofflow.eclipse.metrics.util;
2   
3   import java.io.IOException;
4   
5   import org.eclipse.core.runtime.CoreException;
6   import org.eclipse.core.runtime.IProgressMonitor;
7   import org.eclipse.core.runtime.OperationCanceledException;
8   import org.eclipse.core.runtime.SubMonitor;
9   
10  public class ProgressMonitor {
11      public interface Runnable {
12          Runnable NULL = new Runnable() {
13              public void run(final ProgressMonitor monitor) throws CoreException, IOException {
14              }
15          };
16  
17          void run(ProgressMonitor monitor) throws Exception;
18      }
19  
20      private final SubMonitor monitor;
21  
22      public ProgressMonitor(final IProgressMonitor monitor, final String task, final int work) {
23          this.monitor = SubMonitor.convert(monitor, task, work);
24      }
25  
26      private ProgressMonitor(final SubMonitor toWrap) {
27          this.monitor = toWrap;
28      }
29  
30      public ProgressMonitor newChild(final int work) {
31          checkCancelation();
32          monitor.subTask("");
33          return new ProgressMonitor(monitor.newChild(work, SubMonitor.SUPPRESS_NONE));
34      }
35  
36      public void beginTask(final String name, final int totalWork) {
37          checkCancelation();
38          monitor.subTask("");
39          monitor.beginTask(name, totalWork);
40      }
41  
42      public void subTask(final String subTask) {
43          checkCancelation();
44          monitor.subTask(subTask);
45      }
46  
47      public void worked(final int work) {
48          checkCancelation();
49          monitor.worked(work);
50      }
51  
52      private void checkCancelation() {
53          if (monitor.isCanceled()) {
54              throw new OperationCanceledException();
55          }
56      }
57  
58      public void run(final Runnable runnable) throws Exception {
59          try {
60              runnable.run(this);
61          } catch (final OperationCanceledException opcex) {
62              monitor.done();
63          } finally {
64              monitor.done();
65          }
66      }
67  }
68