1 /*******************************************************************************
2 * Copyright (c) 2017 Association for Decentralized Information Management in
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 * Semantum Oy - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.ui.workspace.tracker.internal.contributions;
14 import java.io.IOException;
15 import java.nio.file.FileStore;
16 import java.nio.file.Files;
17 import java.nio.file.Path;
19 import org.eclipse.e4.ui.model.application.ui.menu.MToolControl;
20 import org.eclipse.jface.action.Action;
21 import org.eclipse.jface.action.IMenuManager;
22 import org.eclipse.jface.action.MenuManager;
23 import org.eclipse.jface.preference.IPreferenceStore;
24 import org.eclipse.jface.util.IPropertyChangeListener;
25 import org.eclipse.osgi.util.NLS;
26 import org.eclipse.swt.SWT;
27 import org.eclipse.swt.graphics.Color;
28 import org.eclipse.swt.graphics.GC;
29 import org.eclipse.swt.graphics.Point;
30 import org.eclipse.swt.graphics.Rectangle;
31 import org.eclipse.swt.widgets.Composite;
32 import org.eclipse.swt.widgets.Control;
33 import org.eclipse.swt.widgets.Display;
34 import org.eclipse.swt.widgets.Listener;
35 import org.eclipse.swt.widgets.Menu;
36 import org.eclipse.swt.widgets.Shell;
37 import org.simantics.filesystem.services.sizetracker.SizeTracker;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
42 * The Heap Status control, which shows the heap usage statistics in the window trim.
46 public class WorkspaceSizeTrackerTrim extends Composite {
48 private Logger logger = LoggerFactory.getLogger(WorkspaceSizeTrackerTrim.class);
50 private MToolControl toolControl;
51 private SizeTracker sizeTracker;
52 private IPreferenceStore prefStore;
54 private Color bgCol, usedSpaceCol, lowSpaceCol, topLeftCol, bottomRightCol, sepCol, textCol;
55 @SuppressWarnings("unused")
56 private Color markCol;
58 private int updateInterval;
60 private String storeName;
61 private long totalSpace;
62 private long availableSpace;
63 private long usedSpace;
64 private long prevTotalSpace = -1L;
65 private long prevAvailableSpace = -1L;
66 private long prevUsedSpace = -1L;
68 private boolean hasChanged;
69 private long mark = -1;
72 * How many MB of free disk space means we are low on disk space?
74 private long lowSpaceThreshold = 500;
75 private boolean highlightLowSpace = true;
77 private boolean updateTooltip = false;
79 private final Runnable timer = new Runnable() {
91 getDisplay().timerExec(updateInterval, this);
96 private final IPropertyChangeListener prefListener = event -> {
97 if (IWorkspaceSizeTrackerConstants.PREF_UPDATE_INTERVAL.equals(event.getProperty())) {
98 setUpdateIntervalInMS(prefStore.getInt(IWorkspaceSizeTrackerConstants.PREF_UPDATE_INTERVAL));
99 } else if (IWorkspaceSizeTrackerConstants.PREF_HIGHLIGHT_LOW_SPACE.equals(event.getProperty())) {
100 highlightLowSpace = prefStore.getBoolean(IWorkspaceSizeTrackerConstants.PREF_HIGHLIGHT_LOW_SPACE);
102 } else if (IWorkspaceSizeTrackerConstants.PREF_LOW_SPACE_THRESHOLD.equals(event.getProperty())) {
103 lowSpaceThreshold = prefStore.getLong(IWorkspaceSizeTrackerConstants.PREF_LOW_SPACE_THRESHOLD);
105 } else if (IWorkspaceSizeTrackerConstants.PREF_SHOW_MONITOR.equals(event.getProperty())) {
106 boolean show = prefStore.getBoolean(IWorkspaceSizeTrackerConstants.PREF_SHOW_MONITOR);
113 * Creates a new heap status control with the given parent, and using
114 * the given preference store to obtain settings such as the refresh
118 * @param parent the parent composite
119 * @param sizeTracker the workspace sizeTracker service
120 * @param prefStore the preference store
122 public WorkspaceSizeTrackerTrim(Composite parent, MToolControl toolControl, SizeTracker sizeTracker, IPreferenceStore prefStore) {
123 super(parent, SWT.NONE);
124 this.toolControl = toolControl;
125 this.sizeTracker = sizeTracker;
127 this.prefStore = prefStore;
128 prefStore.addPropertyChangeListener(prefListener);
130 setUpdateIntervalInMS(prefStore.getInt(IWorkspaceSizeTrackerConstants.PREF_UPDATE_INTERVAL));
132 Display display = getDisplay();
133 usedSpaceCol = display.getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW);
134 lowSpaceCol = new Color(display, 255, 70, 70); // medium red
135 bgCol = display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND);
136 sepCol = topLeftCol = display.getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW);
137 bottomRightCol = display.getSystemColor(SWT.COLOR_WIDGET_HIGHLIGHT_SHADOW);
138 markCol = textCol = display.getSystemColor(SWT.COLOR_WIDGET_FOREGROUND);
142 Listener listener = event -> {
143 switch (event.type) {
148 if (event.widget == WorkspaceSizeTrackerTrim.this) {
149 paintComposite(event.gc);
153 if (event.button == 1) {
154 if (event.widget == WorkspaceSizeTrackerTrim.this) {
160 WorkspaceSizeTrackerTrim.this.updateTooltip = true;
164 if (event.widget == WorkspaceSizeTrackerTrim.this) {
165 WorkspaceSizeTrackerTrim.this.updateTooltip = false;
170 addListener(SWT.Dispose, listener);
171 addListener(SWT.MouseDown, listener);
172 addListener(SWT.Paint, listener);
173 addListener(SWT.MouseEnter, listener);
174 addListener(SWT.MouseExit, listener);
176 // make sure stats are updated before first paint
179 getDisplay().asyncExec(() -> {
181 getDisplay().timerExec(updateInterval, timer);
187 public void setBackground(Color color) {
192 public void setForeground(Color color) {
194 markCol = textCol = getDisplay().getSystemColor(SWT.COLOR_INFO_BACKGROUND);
196 markCol = textCol = color;
201 public Color getForeground() {
202 if (usedSpaceCol != null) {
205 return getDisplay().getSystemColor(SWT.COLOR_INFO_BACKGROUND);
208 private void setUpdateIntervalInMS(int interval) {
209 updateInterval = Math.max(100, interval);
212 private void doDispose() {
213 prefStore.removePropertyChangeListener(prefListener);
214 if (lowSpaceCol != null) {
215 lowSpaceCol.dispose();
220 public Point computeSize(int wHint, int hHint, boolean changed) {
221 GC gc = new GC(this);
222 Point p = gc.textExtent(Messages.WorkspaceSizeTrackerTrim_widthStr);
223 int height = p.y + 4;
225 return new Point(p.x, height);
229 * Creates the context menu
231 private void createContextMenu() {
232 MenuManager menuMgr = new MenuManager();
233 menuMgr.setRemoveAllWhenShown(true);
234 menuMgr.addMenuListener(menuMgr1 -> fillMenu(menuMgr1));
235 Menu menu = menuMgr.createContextMenu(this);
239 private void fillMenu(IMenuManager menuMgr) {
240 menuMgr.add(new SetMarkAction());
241 menuMgr.add(new ClearMarkAction());
242 menuMgr.add(new CloseSizeTrackerTrimAction());
246 * Sets the mark to the current usedMem level.
248 private void setMark() {
249 safeUpdateStats(); // get up-to-date stats before taking the mark
258 private void clearMark() {
264 private void paintComposite(GC gc) {
265 paintCompositeMaxUnknown(gc);
268 private void paintCompositeMaxUnknown(GC gc) {
269 Rectangle rect = getClientArea();
274 int sw = w - 1; // status width
275 long storeUsedSpace = totalSpace - availableSpace;
276 int uw = (int) (sw * storeUsedSpace / totalSpace); // used space width
277 int ux = x + 1 + uw; // used space right edge
279 gc.setBackground(bgCol);
281 gc.fillRectangle(rect);
283 boolean lowOnSpace = false;
284 if (highlightLowSpace) {
285 lowOnSpace = (1024L*1024L*lowSpaceThreshold) >= availableSpace;
288 gc.setForeground(sepCol);
289 gc.drawLine(ux, y, ux, y + h);
290 gc.setForeground(topLeftCol);
291 gc.drawLine(x, y, x+w, y);
292 gc.drawLine(x, y, x, y+h);
293 gc.setForeground(bottomRightCol);
294 gc.drawLine(x+w-1, y, x+w-1, y+h);
295 gc.drawLine(x, y+h-1, x+w, y+h-1);
297 gc.setBackground(lowOnSpace ? lowSpaceCol : usedSpaceCol);
298 gc.fillRectangle(x + 1, y + 1, uw, h - 2);
300 String s = NLS.bind(Messages.WorkspaceSizeTrackerTrim_status, convertToSizeString(usedSpace), convertToSizeString(availableSpace));
301 Point p = gc.textExtent(s);
302 int sx = (rect.width - 15 - p.x) / 2 + rect.x + 1;
303 int sy = (rect.height - 2 - p.y) / 2 + rect.y + 1;
304 gc.setForeground(textCol);
305 gc.drawString(s, sx, sy, true);
308 private void safeUpdateStats() {
311 } catch (IOException e) {
312 logger.error("Failed to update workspace size statistics.", e);
316 private void updateStats() throws IOException {
317 Path path = sizeTracker.path();
318 FileStore store = Files.getFileStore(path);
320 storeName = store.toString();
321 totalSpace = store.getTotalSpace();
322 availableSpace = store.getUsableSpace();
323 usedSpace = sizeTracker.size();
325 if (convertToMeg(prevTotalSpace) != convertToMeg(totalSpace)) {
326 prevTotalSpace = totalSpace;
327 this.hasChanged = true;
329 if (prevAvailableSpace != availableSpace) {
330 prevAvailableSpace = availableSpace;
331 this.hasChanged = true;
333 if (convertToMeg(prevUsedSpace) != convertToMeg(usedSpace)) {
334 prevUsedSpace = usedSpace;
335 this.hasChanged = true;
339 private void updateToolTip() {
340 String usedStr = convertToSizeString(usedSpace);
341 String availableStr = convertToSizeString(availableSpace);
342 String totalStr = convertToSizeString(totalSpace);
343 String markStr = mark == -1 ? Messages.WorkspaceSizeTrackerTrim_noMark : convertToSizeString(mark);
344 String toolTip = NLS.bind(Messages.WorkspaceSizeTrackerTrim_memoryToolTip, new Object[] { usedStr, storeName, availableStr, totalStr, markStr });
345 if (!toolTip.equals(getToolTipText())) {
346 setToolTipText(toolTip);
351 * Converts the given number of bytes to a printable number of megabytes (rounded up).
353 private String convertToSizeString(long numBytes) {
354 long megs = convertToMeg(numBytes);
356 double megsd = (double) megs;
357 long gigs = (long) Math.floor(megsd / 1024.0);
358 long decimals = (long) (megsd - gigs*1024);
359 decimals = (decimals + 5) / 10;
360 return NLS.bind(Messages.WorkspaceSizeTrackerTrim_gig, new Long(gigs), new Long(decimals));
362 return NLS.bind(Messages.WorkspaceSizeTrackerTrim_meg, new Long(megs));
367 * Converts the given number of bytes to the corresponding number of megabytes (rounded up).
369 private long convertToMeg(long numBytes) {
370 return (numBytes + (512 * 1024)) / (1024 * 1024);
373 class SetMarkAction extends Action {
375 super(Messages.SetMarkAction_text);
384 class ClearMarkAction extends Action {
386 super(Messages.ClearMarkAction_text);
395 class CloseSizeTrackerTrimAction extends Action{
396 CloseSizeTrackerTrimAction(){
397 super(Messages.WorkspaceSizeTrackerTrim_close);
406 private void showTracker(boolean show) {
407 if (toolControl.isToBeRendered() != show) {
408 Object widget = toolControl.getWidget();
409 Shell shell = widget instanceof Control ? ((Control) widget).getShell() : null;
410 toolControl.setToBeRendered(show);
412 shell.layout(null, SWT.ALL | SWT.CHANGED | SWT.DEFER);
413 prefStore.setValue(IWorkspaceSizeTrackerConstants.PREF_SHOW_MONITOR, show);