Eclipse RCP 預設將工作台狀態(視圖位置、大小、可見性)儲存於 workbench.xml,多用戶環境下會互相覆蓋。本文提供一種「山寨但有效」的方案:在 Application.start() 階段根據登入用戶動態切換配置檔,實現用戶級界面狀態隔離。
Application.start() 執行登入邏輯,取得用戶名{username}_workbench.xmlworkbench.xmlworkbench.xml 寫回用戶配置檔,刪除預設檔public class Application implements IApplication {
public Object start(IApplicationContext context) throws Exception {
Display display = PlatformUI.createDisplay();
try {
String defaultName = "workbench.xml";
String workBenchPath = "D:/runtime-rcptest.application/.metadata/.plugins/org.eclipse.ui.workbench/";
String absolutePath = workBenchPath + defaultName;
String loginUser = "SystemManager"; // 實際從登入對話框獲取
String userCfgPath = workBenchPath + loginUser + "_" + defaultName;
File userFile = new File(userCfgPath);
// 啟動前:載入用戶配置
if (userFile.isFile()) {
copyFile(userFile, new File(absolutePath));
}
int returnCode = PlatformUI.createAndRunWorkbench(display, new ApplicationWorkbenchAdvisor());
// 關閉後:持久化用戶配置
File defaultFile = new File(absolutePath);
if (defaultFile.isFile()) {
copyFile(defaultFile, new File(userCfgPath));
defaultFile.deleteOnExit(); // 避免新用戶看到舊配置
}
return returnCode == PlatformUI.RETURN_RESTART ? IApplication.EXIT_RESTART : IApplication.EXIT_OK;
} finally {
display.dispose();
}
}
private void copyFile(File src, File dest) throws IOException {
try (FileInputStream fis = new FileInputStream(src);
FileOutputStream fos = new FileOutputStream(dest)) {
byte[] buf = new byte[fis.available()];
fis.read(buf);
fos.write(buf);
}
}
// stop()...
}
在 ApplicationWorkbenchAdvisor.initialize() 啟用儲存/恢復:
@Override
public void initialize(IWorkbenchConfigurer configurer) {
super.initialize(configurer);
configurer.setSaveAndRestore(true);
}
Platform.getStateLocation() 動態獲取IPerspectiveFactory + IWorkbenchPreferenceConstants 或使用 Eclipse 4 的 MWindow 模型此方案適合快速原型、舊版 RCP 維護專案,生產環境建議遷移至標準持久化機制。