KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > ui > internal > ReopenEditorMenu


1 /*******************************************************************************
2  * Copyright (c) 2000, 2006 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11 package org.eclipse.ui.internal;
12
13 import org.eclipse.core.runtime.IPath;
14 import org.eclipse.core.runtime.Path;
15 import org.eclipse.core.runtime.SafeRunner;
16 import org.eclipse.jface.action.ContributionItem;
17 import org.eclipse.jface.action.IMenuListener;
18 import org.eclipse.jface.action.IMenuManager;
19 import org.eclipse.jface.action.MenuManager;
20 import org.eclipse.jface.dialogs.MessageDialog;
21 import org.eclipse.jface.util.SafeRunnable;
22 import org.eclipse.osgi.util.NLS;
23 import org.eclipse.osgi.util.TextProcessor;
24 import org.eclipse.swt.SWT;
25 import org.eclipse.swt.events.SelectionAdapter;
26 import org.eclipse.swt.events.SelectionEvent;
27 import org.eclipse.swt.widgets.Menu;
28 import org.eclipse.swt.widgets.MenuItem;
29 import org.eclipse.ui.IEditorDescriptor;
30 import org.eclipse.ui.IEditorInput;
31 import org.eclipse.ui.IWorkbenchPage;
32 import org.eclipse.ui.IWorkbenchWindow;
33 import org.eclipse.ui.PartInitException;
34
35 /**
36  * A dynamic menu item which supports to switch to other Windows.
37  */

38 public class ReopenEditorMenu extends ContributionItem {
39     private IWorkbenchWindow window;
40
41     private EditorHistory history;
42
43     private boolean showSeparator;
44
45     private boolean dirty = true;
46
47     private IMenuListener menuListener = new IMenuListener() {
48         public void menuAboutToShow(IMenuManager manager) {
49             manager.markDirty();
50             dirty = true;
51         }
52     };
53
54     // the maximum length for a file name; must be >= 4
55
private static final int MAX_TEXT_LENGTH = 40;
56
57     // only assign mnemonic to the first nine items
58
private static final int MAX_MNEMONIC_SIZE = 9;
59
60     /**
61      * Create a new instance.
62      * @param window the window on which the menu is to be created
63      * @param id menu's id
64      * @param showSeparator whether or not to show a separator
65      */

66     public ReopenEditorMenu(IWorkbenchWindow window, String JavaDoc id,
67             boolean showSeparator) {
68         super(id);
69         this.window = window;
70         this.showSeparator = showSeparator;
71         history = ((Workbench) window.getWorkbench()).getEditorHistory();
72     }
73
74     /**
75      * Returns the text for a history item. This may be truncated to fit
76      * within the MAX_TEXT_LENGTH.
77      */

78     private String JavaDoc calcText(int index, EditorHistoryItem item) {
79         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
80
81         int mnemonic = index + 1;
82         sb.append(mnemonic);
83         if (mnemonic <= MAX_MNEMONIC_SIZE) {
84             sb.insert(sb.length() - (mnemonic + "").length(), '&'); //$NON-NLS-1$
85
}
86         sb.append(" "); //$NON-NLS-1$
87

88         // IMPORTANT: avoid accessing the item's input since
89
// this can require activating plugins.
90
// Instead, ask the item for the info, which can
91
// consult its memento if it is not restored yet.
92
String JavaDoc fileName = item.getName();
93         String JavaDoc pathName = item.getToolTipText();
94         if (pathName.equals(fileName)) {
95             // tool tip text isn't necessarily a path;
96
// sometimes it's the same as name, so it shouldn't be treated as a path then
97
pathName = ""; //$NON-NLS-1$
98
}
99         IPath path = new Path(pathName);
100         // if last segment in path is the fileName, remove it
101
if (path.segmentCount() > 1
102                 && path.segment(path.segmentCount() - 1).equals(fileName)) {
103             path = path.removeLastSegments(1);
104             pathName = path.toString();
105         }
106
107         if ((fileName.length() + pathName.length()) <= (MAX_TEXT_LENGTH - 4)) {
108             // entire item name fits within maximum length
109
sb.append(fileName);
110             if (pathName.length() > 0) {
111                 sb.append(" ["); //$NON-NLS-1$
112
sb.append(pathName);
113                 sb.append("]"); //$NON-NLS-1$
114
}
115         } else {
116             // need to shorten the item name
117
int length = fileName.length();
118             if (length > MAX_TEXT_LENGTH) {
119                 // file name does not fit within length, truncate it
120
sb.append(fileName.substring(0, MAX_TEXT_LENGTH - 3));
121                 sb.append("..."); //$NON-NLS-1$
122
} else if (length > MAX_TEXT_LENGTH - 7) {
123                 sb.append(fileName);
124             } else {
125                 sb.append(fileName);
126                 int segmentCount = path.segmentCount();
127                 if (segmentCount > 0) {
128                     length += 7; // 7 chars are taken for " [...]"
129

130                     sb.append(" ["); //$NON-NLS-1$
131

132                     // Add first n segments that fit
133
int i = 0;
134                     while (i < segmentCount && length < MAX_TEXT_LENGTH) {
135                         String JavaDoc segment = path.segment(i);
136                         if (length + segment.length() < MAX_TEXT_LENGTH) {
137                             sb.append(segment);
138                             sb.append(IPath.SEPARATOR);
139                             length += segment.length() + 1;
140                             i++;
141                         } else if (i == 0) {
142                             // append at least part of the first segment
143
sb.append(segment.substring(0, MAX_TEXT_LENGTH
144                                     - length));
145                             length = MAX_TEXT_LENGTH;
146                             break;
147                         } else {
148                             break;
149                         }
150                     }
151
152                     sb.append("..."); //$NON-NLS-1$
153

154                     i = segmentCount - 1;
155                     // Add last n segments that fit
156
while (i > 0 && length < MAX_TEXT_LENGTH) {
157                         String JavaDoc segment = path.segment(i);
158                         if (length + segment.length() < MAX_TEXT_LENGTH) {
159                             sb.append(IPath.SEPARATOR);
160                             sb.append(segment);
161                             length += segment.length() + 1;
162                             i--;
163                         } else {
164                             break;
165                         }
166                     }
167
168                     sb.append("]"); //$NON-NLS-1$
169
}
170             }
171         }
172         return TextProcessor.process(sb.toString(), TextProcessor.getDefaultDelimiters() + "[]");//$NON-NLS-1$
173
}
174
175     /**
176      * Fills the given menu with
177      * menu items for all windows.
178      */

179     public void fill(final Menu menu, int index) {
180         if (window.getActivePage() == null
181                 || window.getActivePage().getPerspective() == null) {
182             return;
183         }
184
185         if (getParent() instanceof MenuManager) {
186             ((MenuManager) getParent()).addMenuListener(menuListener);
187         }
188
189         int itemsToShow = WorkbenchPlugin.getDefault().getPreferenceStore()
190                 .getInt(IPreferenceConstants.RECENT_FILES);
191         if (itemsToShow == 0) {
192             return;
193         }
194
195         // Get items.
196
EditorHistoryItem[] historyItems = history.getItems();
197
198         int n = Math.min(itemsToShow, historyItems.length);
199         if (n <= 0) {
200             return;
201         }
202
203         if (showSeparator) {
204             new MenuItem(menu, SWT.SEPARATOR, index);
205             ++index;
206         }
207
208         final int menuIndex[] = new int[] { index };
209
210         for (int i = 0; i < n; i++) {
211             final EditorHistoryItem item = historyItems[i];
212             final int historyIndex = i;
213             SafeRunner.run(new SafeRunnable() {
214                 public void run() throws Exception JavaDoc {
215                     String JavaDoc text = calcText(historyIndex, item);
216                     MenuItem mi = new MenuItem(menu, SWT.PUSH, menuIndex[0]);
217                     ++menuIndex[0];
218                     mi.setText(text);
219                     mi.addSelectionListener(new SelectionAdapter() {
220                         public void widgetSelected(SelectionEvent e) {
221                             open(item);
222                         }
223                     });
224                 }
225
226                 public void handleException(Throwable JavaDoc e) {
227                     // just skip the item if there's an error,
228
// e.g. in the calculation of the shortened name
229
WorkbenchPlugin.log(getClass(), "fill", e); //$NON-NLS-1$
230
}
231             });
232         }
233         dirty = false;
234     }
235
236     /**
237      * Overridden to always return true and force dynamic menu building.
238      */

239     public boolean isDirty() {
240         return dirty;
241     }
242
243     /**
244      * Overridden to always return true and force dynamic menu building.
245      */

246     public boolean isDynamic() {
247         return true;
248     }
249
250     /**
251      * Reopens the editor for the given history item.
252      */

253     private void open(EditorHistoryItem item) {
254         IWorkbenchPage page = window.getActivePage();
255         if (page != null) {
256             try {
257                 String JavaDoc itemName = item.getName();
258                 if (!item.isRestored()) {
259                     item.restoreState();
260                 }
261                 IEditorInput input = item.getInput();
262                 IEditorDescriptor desc = item.getDescriptor();
263                 if (input == null || desc == null) {
264                     String JavaDoc title = WorkbenchMessages.OpenRecent_errorTitle;
265                     String JavaDoc msg = NLS.bind(WorkbenchMessages.OpenRecent_unableToOpen, itemName );
266                     MessageDialog.openWarning(window.getShell(), title, msg);
267                     history.remove(item);
268                 } else {
269                     page.openEditor(input, desc.getId());
270                 }
271             } catch (PartInitException e2) {
272                 String JavaDoc title = WorkbenchMessages.OpenRecent_errorTitle;
273                 MessageDialog.openWarning(window.getShell(), title, e2
274                         .getMessage());
275                 history.remove(item);
276             }
277         }
278     }
279
280 }
281
Popular Tags