1 /*******************************************************************************
2 * Copyright (c) 2007, 2010 Association for Decentralized Information Management
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
15 package org.simantics.utils.ui.gfx.rasterize;
17 import java.util.LinkedList;
19 import org.eclipse.core.runtime.IProgressMonitor;
20 import org.eclipse.core.runtime.IStatus;
21 import org.eclipse.core.runtime.Status;
22 import org.eclipse.core.runtime.jobs.Job;
23 import org.eclipse.swt.graphics.ImageData;
28 * @author Toni Kalajainen
30 public class LazyRasterizer {
32 public static void addJob(RasterJob job) {
36 public static void addAsFirstJob(RasterJob job) {
37 getJob().addAsFirstJob(job);
40 public static void removeJob(RasterJob job) {
41 getJob().removeJob(job);
44 static RasterizeJob job;
46 synchronized static RasterizeJob getJob() {
48 job = new RasterizeJob();
52 static class RasterizeJob extends Job {
53 LinkedList<RasterJob> queue = new LinkedList<RasterJob>();
55 @SuppressWarnings("unused")
56 private boolean isRunning;
58 public RasterizeJob() {
59 super("Rasterize Job");
63 protected IStatus run(IProgressMonitor monitor) {
64 //System.out.println(Thread.currentThread());
65 setThread(Thread.currentThread());
68 monitor.beginTask("Rasterizing", taskLeft);
71 RasterJob job = pullNextJob();
73 // 2. Check if canceled
74 if (monitor.isCanceled()) {
76 return Status.CANCEL_STATUS;
81 monitor.subTask(job.raster.toString());
82 ImageData id = job.raster.rasterize(job.width, job.height);
83 job.listener.rasterizationComplete(job, id);
84 } catch (Exception e) {
85 job.listener.rasterizationFailed(job, e);
88 int jobsLeft = jobsLeft();
93 workLeft = ((double) taskLeft) / ((double) jobsLeft());
95 int worked = (int) workLeft;
96 monitor.worked(worked);
102 } while (job != null);
108 return Status.OK_STATUS;
111 protected synchronized int jobsLeft() {
115 protected synchronized RasterJob pullNextJob() {
118 return queue.removeFirst();
121 public synchronized void clear() {
122 RasterJob jobs[] = queue.toArray(new RasterJob[0]);
123 for (RasterJob j : jobs)
127 public synchronized void addJob(RasterJob job) {
129 job.status = RasterJobStatus.QUEUED;
130 //if (!isRunning && queue.size()==1)
134 public synchronized void addAsFirstJob(RasterJob job) {
136 job.status = RasterJobStatus.QUEUED;
137 //if (!isRunning && queue.size()==1)
141 public synchronized boolean removeJob(RasterJob job) {
142 if (queue.remove(job)) {
143 job.status = RasterJobStatus.COMPLETE;
144 job.listener.rasterizationCanceled(job);