1 /*******************************************************************************
2  * Copyright (c) 2019 Red Hat and others.
3  *
4  * This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License 2.0
6  * which accompanies this distribution, and is available at
7  * https://www.eclipse.org/legal/epl-2.0/
8  *
9  * SPDX-License-Identifier: EPL-2.0
10  *
11  * Contributors:
12  *     Red Hat - initial API and implementation
13  *******************************************************************************/
14 package org.eclipse.swt.tests.gtk.snippets;
15 
16 import org.eclipse.swt.SWT;
17 import org.eclipse.swt.layout.FillLayout;
18 import org.eclipse.swt.widgets.Display;
19 import org.eclipse.swt.widgets.Shell;
20 import org.eclipse.swt.widgets.Tree;
21 import org.eclipse.swt.widgets.TreeItem;
22 
23 public class Bug489751_TreeItemDisposeSelect {
24 
25 	private static final boolean DISPOSE_DIRECTLY = true;
26 
main(String[] args)27 	public static void main(String[] args) {
28 		final Display display = new Display ();
29 		final Shell shell = new Shell (display);
30 		shell.setLayout(new FillLayout());
31 		final Tree tree = new Tree (shell, SWT.BORDER);
32 		for (int i=0; i<4; i++) {
33 			TreeItem iItem = new TreeItem (tree, 0);
34 			iItem.setText ("TreeItem (0) -" + i);
35 			for (int j=0; j<4; j++) {
36 				TreeItem jItem = new TreeItem (iItem, 0);
37 				jItem.setText ("TreeItem (1) -" + j);
38 				for (int k=0; k<4; k++) {
39 					TreeItem kItem = new TreeItem (jItem, 0);
40 					kItem.setText ("TreeItem (2) -" + k);
41 					for (int l=0; l<4; l++) {
42 						TreeItem lItem = new TreeItem(kItem, 0);
43 						lItem.setText ("TreeItem (3) -" + l);
44 					}
45 				}
46 			}
47 		}
48 
49 		final TreeItem firstNode = tree.getItem(0);
50 		firstNode.setExpanded(true);
51 		tree.setSelection(firstNode.getItem(3));
52 
53 		shell.setSize(200, 200);
54 		shell.open();
55 
56 		display.timerExec(1000, () -> {
57 			if (shell.isDisposed()) {
58 				return;
59 			}
60 
61 			// replace selected node
62 			final TreeItem[] selection = tree.getSelection();
63 			if (selection.length != 1) {
64 				return;
65 			}
66 
67 			final TreeItem item = selection[0];
68 			final TreeItem parentItem = item.getParentItem();
69 			if (parentItem == null) {
70 				return;
71 			}
72 
73 			tree.deselectAll();
74 
75 			if (DISPOSE_DIRECTLY) {
76 				item.dispose();
77 			}
78 			else {
79 				display.asyncExec(() -> {
80 					if (!item.isDisposed()) {
81 						return;
82 					}
83 
84 					item.dispose();
85 				});
86 			}
87 		});
88 
89 		while (!shell.isDisposed()) {
90 			if (!display.readAndDispatch ()) display.sleep ();
91 		}
92 		display.dispose();
93 	}
94 }