RCP:如何保存TaskList及如何获取TaskList

如果我们在Eclipse RCP程序中添加TaskList View,用来管理Task或者TODO项,如下代码:

PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
	.showView("org.eclipse.ui.views.TaskList");

 

我们发现,创建的Task,在重启之后无法保存,而在Eclipse IDE中却不会有这个问题. 在阅读org.eclipse.ui.internal.views.markers.TasksView的代码后,我发现TasksView在程序退出时,只负责保存TasksView的布局信息。那么,需要怎么保存添加的Task呢?

如何保存TaskList

原来Task的本质是Marker,并不是保存在TasksView中,而是和Resource相关联,保存在IResource对象中。在RCP程序中,保存Marker需要调用IWorkspace的save方法,可以在preShutdown中调用,如下代码:

	@Override
	public boolean preShutdown() {

		/* Save workspace before closing the application */
		final MultiStatus status = new MultiStatus(
				"com.voxana.vuidesigner.diagram", 0, "Saving Workspace....",
				null);
		IRunnableWithProgress runnable = new IRunnableWithProgress() {

			@Override
			public void run(final IProgressMonitor monitor) {
				try {
					IWorkspace ws = ResourcesPlugin.getWorkspace();
					status.merge(ws.save(true, monitor));
				} catch (CoreException e) {
					status.merge(e.getStatus());
				}
			}
		};
		try {
			new ProgressMonitorDialog(null).run(false, false, runnable);
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		if (!status.isOK()) {
			ErrorDialog.openError(Display.getDefault().getActiveShell(),
					"Error...", "Error while saving workspace", status);
			return true;
		}
		return true;
	}

获取TaskList

如前面所说,Task(Marker的其中一种类型)是和Resource关联,保存在IResource中的。我们可以通过以下代码来获取所有Task:

IResource root =  ResourcesPlugin.getWorkspace().getRoot();
String TypeId = "org.eclipse.core.resources.taskmarker";
IMarker[] markers = resource.findMarkers(TypeId, true, IResource.DEPTH_INFINITE);

 

其中,第一个参数TypeId指定要获取的Marker类型;第二个参数指定是否搜索子节点的Marker;第三个参数指定搜索的深度。

在获取了IMarker后,即可通过getAttribute或者getAttributes方法来获取参数

 

参考

https://gama-platform.googlecode.com/svn-history/r4005/branches/GAMA_CURRENT/msi.gama.application/src/msi/gama/gui/swt/ApplicationWorkbenchAdvisor.java

http://www.eclipse.org/forums/index.php/t/106705/

http://wiki.eclipse.org/FAQ_How_and_when_do_I_save_the_workspace%3F

org.eclipse.ui.internal.views.markers.MarkerContentGenerator class internalGatherMarkers method

原文地址:https://www.cnblogs.com/Binhua-Liu/p/3318950.html