Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 35c7316ff8e61a4728933e6ce8f4378ea13aae0d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
/*****************************************************************************
 * Copyright (c) 2009 CEA LIST & LIFL 
 *
 *    
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *  Cedric Dumoulin  Cedric.dumoulin@lifl.fr - Initial API and implementation
 *
 *****************************************************************************/
package org.eclipse.papyrus.infra.core.sasheditor.internal;

import static org.eclipse.papyrus.infra.core.sasheditor.Activator.log;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.util.Geometry;
import org.eclipse.papyrus.infra.core.sasheditor.contentprovider.IComponentModel;
import org.eclipse.papyrus.infra.core.sasheditor.contentprovider.IEditorModel;
import org.eclipse.papyrus.infra.core.sasheditor.contentprovider.IPageModel;
import org.eclipse.papyrus.infra.core.sasheditor.contentprovider.ISashWindowsContentProvider;
import org.eclipse.papyrus.infra.core.sasheditor.contentprovider.ITabFolderModel;
import org.eclipse.papyrus.infra.core.sasheditor.editor.IEditorPage;
import org.eclipse.papyrus.infra.core.sasheditor.editor.IFolder;
import org.eclipse.papyrus.infra.core.sasheditor.editor.IPage;
import org.eclipse.papyrus.infra.core.sasheditor.editor.IPageChangedListener;
import org.eclipse.papyrus.infra.core.sasheditor.editor.IPageLifeCycleEventsListener;
import org.eclipse.papyrus.infra.core.sasheditor.editor.IPageVisitor;
import org.eclipse.papyrus.infra.core.sasheditor.editor.ISashWindowsContainer;
import org.eclipse.papyrus.infra.core.sasheditor.editor.ITabMouseEventsListener;
import org.eclipse.papyrus.infra.core.sasheditor.utils.IObservableList;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.internal.DragCursors;
import org.eclipse.ui.internal.dnd.DragUtil;
import org.eclipse.ui.internal.dnd.IDragOverListener;
import org.eclipse.ui.internal.dnd.IDropTarget;


/**
 * Main entry class of the SashWindows system.
 * This class allows to have a multitab window with sashes.
 * The class require a ContentProvider describing the content to be shown.
 * 
 * @author dumoulin
 */
@SuppressWarnings("restriction")
public class SashWindowsContainer implements ISashWindowsContainer {

	/**
	 * The content provider describing the sashes, folders and tabs.
	 */
	private ISashWindowsContentProvider contentProvider;

	/**
	 * The manager used to get Main editor properties like Site, ActionBars, ...
	 */
	private IMultiEditorManager multiEditorManager;

	/**
	 * Tracker tracking the current active page. The tracker also disconnect last active page and connect
	 * the new one.
	 */
	private ActivePageTracker activePageTracker;

	/**
	 * Event provider firing Pages life cycle events to registered listeners. Inner parts call the fireXxxEvents
	 * when appropriate.
	 */
	private SashContainerEventsProvider lifeCycleEventProvider;

	/**
	 * Event provider firing Folder life cycle events to registered listeners. Inner parts call the fireXxxEvents
	 * when appropriate.
	 */
	private SashContainerFolderEventsProvider folderLifeCycleEventProvider;

	/**
	 * Event provider firing mouse events from tabs.
	 * 
	 */
	private TabMouseEventsProvider tabMouseEventsProvider;

	/**
	 * A manager used to maintain a view list of available {@link TabFolderPart}. This list should 
	 * only be used in a READ way. It should not be modified by something else than its manager.
	 * 
	 */
	private TabFolderListManager folderListManager;
	
	/**
	 * The part used as root. We use an extra class as root in order to separate the code dedicated to
	 * ITilePart.
	 */
	private RootPart rootPart;

	/**
	 * The SWT container associated to this part. This is generally the container of the
	 * parent.
	 */
	private Composite container;

	/**
	 * The drop target.
	 */
	protected DropTarget dropTarget;

	/** A flag that indicates that the model is being synchronized. */
	private AtomicBoolean isRefreshing = new AtomicBoolean(false);

	/**
	 * The cached value of the menu manager, if any.
	 */
	private MenuManager folderTabMenuManager;

	/**
	 * Listener on widget diposed event.
	 */
	private DisposeListener widgetDisposedListener = new DisposeListener() {

		/**
		 * Called when the widget is disposed.
		 * 
		 * @see org.eclipse.swt.events.DisposeListener#widgetDisposed(org.eclipse.swt.events.DisposeEvent)
		 * 
		 * @param e
		 */
		public void widgetDisposed(DisposeEvent e) {
			// We dispose the container.
			dispose();
		}
	};

	/**
	 * Constructor.
	 * Build a Container without IEditor management. Trying to add a EditorPart will result in an Exception.
	 * The ContentProvider should not contain IEditorModel.
	 */
	public SashWindowsContainer() {
		this(null);
	}

	/**
	 * Constructor.
	 * Build a container with EditorPart management. The container will allow to add EditorPart
	 * (and thus IEditorModel to the ContentProvider).
	 * 
	 * @param multiEditorManager
	 *        The manager allowing to use {@link IEditorModel} in the model.
	 *        If null, the sash will not render IEditorModel.
	 * 
	 */
	public SashWindowsContainer(IMultiEditorManager multiEditorManager) {
		this.multiEditorManager = multiEditorManager;
		activePageTracker = new ActivePageTracker();

		if(multiEditorManager != null) {
			// Add listener on activePageChange.
			// This listener will take in charge editor services switching.
			activePageTracker.addActiveEditorChangedListener(new ActiveEditorServicesSwitcher(multiEditorManager.getEditorSite()));
		}

		// Life cycle event provider
		lifeCycleEventProvider = new SashContainerEventsProvider();

		// Tab mouve event provider
		tabMouseEventsProvider = new TabMouseEventsProvider();
		
		// Folder list view
		initTabFolderListManager();
	}

	/**
	 * @return the contentProvider
	 */
	protected ISashWindowsContentProvider getContentProvider() {
		// Content provider should have been set.
		assert (contentProvider != null);
		// Double check for development
		if(contentProvider == null) {
			throw new IllegalStateException("ContentProvider should be set before calling any method requiring it.");
		}

		return contentProvider;
	}

	/**
	 * Set the content provider describing the sashes, folders and tabs.
	 * 
	 * @param contentProvider
	 *        the contentProvider to set
	 */
	public void setContentProvider(ISashWindowsContentProvider contentProvider) {
		// Use a delegate
		// The delegate is used as a central point performing calls to the 
		// external implementation.
		this.contentProvider = new DelegateContentProvider(contentProvider);
	}

	/**
	 * Creates control associated to this Container.
	 * This method should be called when the parent is build.
	 * 
	 * @param parent
	 *        The parent in which the editor should be created; must not be <code>null</code>.
	 */
	public void createPartControl(Composite parent) {
		this.container = parent;

		rootPart = createRootPart();
		// Create the tree of tile part.
		rootPart.createPartControl(container);
		// TODO 20130205
		// Read lastActivePart from ContentProvider, and set it 
		// before refresh. Like this, sash will select the last save page

		// Create children
		refreshTabs();
		// Set selection
		// TODO 20130205 remove next, because refresh already do it
		selectPage(lookupFirstValidPage());

		// postCreatePartControl();
		// TODO reactivate next
		initDrag(container);
		// activate();

		// Listen for disposale
		container.addDisposeListener(widgetDisposedListener);
	}

	/**
	 * Create the root part for the model.
	 */
	private RootPart createRootPart() {
		RootPart part = new RootPart(this);
		return part;
	}

	/**
	 * Dispose the Container. All referenced resources will be disposed.
	 * The container should not be used anymore once disposed.
	 * The result of calling a method after a dispose() is unpredictable. <br>
	 * This method can be called several times. <br>
	 * <br>
	 * How the method works:
	 * <ul>
	 * <li>The {@link SashWindowsContainer} has two trees, the SWT tree and a Part tree ({@link #rootPart}).</li>
	 * <li>The SWT tree is disposed first.</li>
	 * <ul>
	 * <li>This prevent events fired from user interaction or from Widget modifiaction</li>
	 * <li>The SWT disposal stop before nested editors SWT (thanks to the DISPOSE event in {@link EditorPart}). At this point, the nested editor
	 * dispose() method is called.</li>
	 * <li>This allow to let the nested editor receive one single dispose call.</li>
	 * <li></li>
	 * </ul>
	 * <li>The Part tree is disposed second (by calling rootPart.disposeThisAndChildren() )</li>
	 * <ul>
	 * <li>properties are cleaned in order to help the GC</li>
	 * <li>swt controls are not disposed again</li>
	 * </ul>
	 * <li></li> <li></li> <li></li> <li></li> <li></li> </ul>
	 * 
	 */
	public void dispose() {
		// Check if already disposed
		if(isDisposed()) {
			return;
		}

		// End disposing children's SWT controls.
		// It is possible to recall the dispose() method on a Widget, even if we are called by the dispose event.
		// Recalling the dispose method will continue disposing SWT children's.
		container.dispose();

		// dispose part children
		if(rootPart!=null) {
			// rootPart can be null if createPartControl has not been called.
			// This can happen in tests.
		    rootPart.disposeThisAndChildren();
		}

		// clean up properties to help GC
		activePageTracker = null;
		container = null;
		contentProvider = null;
		dragOverListener = null;
		folderTabMenuManager = null;
		lifeCycleEventProvider = null;
		multiEditorManager = null;
		rootPart = null;
	}

	/**
	 * Return true if the container is disposed, false otherwise.
	 * 
	 * @return
	 */
	public boolean isDisposed() {
		// Use the activePageTracker as a flag.
		return activePageTracker == null;
	}

	/**
	 * Notifies this page container that the specified page has been activated. This method
	 * is called after the current tabs has been changed, either by refreshing the tabs, or by a user
	 * UI action.
	 * This method just set correctly the active page value in the Container, and fire pageChanged events if needed.
	 * It does not change the selected page in the Part.
	 * 
	 * Propagate the event to activePageTracker.
	 * Removed since 0.10
	 * 
	 * @param childPart
	 */
	//	protected void pageChanged(PagePart childPart) {
	//		activePageTracker.setActiveEditor(childPart);
	//		lifeCycleEventProvider.firePageActivatedEvent(childPart);
	//	}

	/**
	 * Notifies this page container that a pageChanged event has been fired by one swt Control.
	 * This method is usually called after the user selects a different tab.
	 * 
	 * The method notify the ContentProvider, and calls {@link #pageChanged(PagePart)}.
	 * Removed since 0.10
	 * 
	 * @param childPart
	 */
	//	protected void pageChangedEvent(PagePart childPart) {
	//
	//		// Check if it is really a change before changing the model (which can throw change event)
	//		// The folder model change is done before the tracker fires the listeners, like this
	//		// listeners can check the model.
	//		if(getActivePage() == childPart)
	//			return;
	//
	//		pageChanged(childPart);
	//	}

	/**
	 * Set the active page. The current active page will be the specified page. Throw events indicating that
	 * the current ActivePage has changed. <br>
	 * Do not set the activeSelection.
	 * 
	 * 
	 * @param childPart
	 */
	protected void setActivePage(PagePart childPart) {

		// Do nothing if the activePage has not changed
		if(childPart == null || getActivePage() == childPart) {
			return;
		}

		// TODO 20130205 remove next
		contentProvider.setCurrentFolder(childPart.getParent().getRawModel());

		activePageTracker.setActiveEditor(childPart);
		lifeCycleEventProvider.firePageActivatedEvent(childPart);
	}

	/**
	 * This method allow to change current activePage. It set the activePage, and select it in
	 * the folder. <br>
	 * This method fires notifications (activePageChanged).
	 * 
	 * @param newActivePage
	 *        The page that should become the active one.
	 */
	protected void setActivePageAndSelection(PagePart newActivePage) {

		PagePart oldSelection = getActivePage();
		// First, set the selection, like this the observers will see the correct selection.
		synchronizeActiveSelection(newActivePage);
		try {
			// Set the active page
			setActivePage(newActivePage);

		} catch (RuntimeException e) {
			// Restore selection in case of exception
			synchronizeActiveSelection(oldSelection);
			// lets propagate
			throw e;
		}
	}

	/**
	 * Synchronize the active selection to be the page of the activePage.
	 * This should be called when the activePage is set, but the selection is not
	 * yet set. <br>
	 * This should not throw events (neither selctionChanged or pageChanged event).
	 * 
	 */
	protected void synchronizeActiveSelection() {
		PagePart activePage = getActivePage();

		synchronizeActiveSelection(activePage);
	}

	/**
	 * Synchronize the active selection to be the specified page. Do not synchronize with the activePage. <br>
	 * This should not throw events (neither selctionChanged or pageChanged event).
	 * 
	 * @param page
	 */
	private void synchronizeActiveSelection(PagePart page) {
		if(page == null) {
			return;
		}
		TabFolderPart folder = page.getParent();

		// Folder can be null in case of tests
		if(folder != null) {
			folder.setSelection(page);
		}

	}

	/**
	 * A change has happen in one of the inner parts. Relay the event.
	 * This method is called by inner parts whenever the event happen in one of the part.
	 * It collects and relay the firePropertyChange(int propertyId) calls from the inner IEditor.
	 * 
	 * @param propertyId
	 */
	protected void firePropertyChange(int propertyId) {
		// For now, we do nothing with this event.
	}

	/**
	 * Create the part for the specified newModel.
	 * 
	 * @param parent
	 *        The parent of the created part.
	 * @param partModel
	 *        The model for which a part should be created.
	 * @return
	 */
	protected PagePart createPagePart(TabFolderPart parent, IPageModel partModel, Object rawModel) {


		if(partModel instanceof IEditorModel) {
			// Check if we can use IEditorModel
			if(multiEditorManager == null) {
				throw new IllegalArgumentException("Container can't accept IEditorModel as no IMultiEditorManager is set. Please set a IMultiEditorManager.");
			}

			return new EditorPart(parent, (IEditorModel)partModel, rawModel, multiEditorManager);
		} else if(partModel instanceof IComponentModel) {
			return new ComponentPart(parent, (IComponentModel)partModel, rawModel);
		} else {
			// Return a default part
		}

		// TODO return a default part showing an error instead.
		throw new IllegalArgumentException("No Part found for the model '" + rawModel + "'");
	}

	/**
	 * Get the {@link ITabFolderModel} of the currently selected folder.
	 * 
	 * @return
	 */
	public ITabFolderModel getSelectedTabFolderModel() {

		// Get the activePage. The seleted folder is its parent.
		PagePart activePage = activePageTracker.getActiveEditor();
		if(activePage != null && activePage.getParent() != null) {
			return activePage.getParent().getPartModel();
		}
		// No active page exist, but their should be a folder
		TabFolderPart folder = lookupFirstValidFolder();
		return folder.getPartModel();
	}

	/**
	 * Lookup the first valid folder in this sash system.
	 * There is always a valid folder.
	 * 
	 * @return The first valid folder.
	 */
	private TabFolderPart lookupFirstValidFolder() {

		LookupFirstFolderVisitor visitor = new LookupFirstFolderVisitor();
		rootPart.visit(visitor);
		return visitor.result();
	}

	/**
	 * Get the active page.
	 * 
	 * @return
	 */
	private PagePart getActivePage() {
		return activePageTracker.getActiveEditor();
	}

	/**
	 * @see org.eclipse.papyrus.infra.core.sasheditor.editor.ISashWindowsContainer#getActiveEditor()
	 * @return
	 * 
	 */
	public IEditorPart getActiveEditor() {
		PagePart pagePart = getActivePage();
		if(pagePart instanceof EditorPart) {
			return ((EditorPart)pagePart).getIEditorPart();
		} else {
			return null;
		}
	}

	/**
	 * Get the active page public API.
	 * 
	 * @return
	 */
	public IPage getActiveSashWindowsPage() {
		return getActivePage();
	}

	/**
	 * Get the list of visible IPages. The visible IPages are the one that have there diagram area
	 * visible.
	 * 
	 * @return
	 */
	public List<IPage> getVisiblePages() {
		CollectVisiblePageVisitor visitor = new CollectVisiblePageVisitor();

		rootPart.visit(visitor);

		return visitor.getVisiblePages();
	}

	/**
	 * Get the list of visible IPages. The visible IPages are the one that have there diagram area
	 * visible.
	 * 
	 * @return
	 */
	//	public List<IEditorPage> getVisibleIEditorPages() {
	//		CollectVisiblePageVisitor visitor = new CollectVisiblePageVisitor( IEditorPage.class);
	//		
	//		rootPart.visit(visitor);
	//		
	//		return visitor.getVisiblePages();
	//	}

	/**
	 * Get the list of visible IPages. The visible IPages are the one that have there diagram area
	 * visible.
	 * 
	 * @return
	 */
	public List<IEditorPart> getVisibleIEditorParts() {
		CollectVisibleIEditorPart visitor = new CollectVisibleIEditorPart();
		rootPart.visit(visitor);

		return visitor.getVisiblePages();
	}


	/**
	 * @see org.eclipse.papyrus.infra.core.sasheditor.editor.ISashWindowsContainer#setFocus()
	 * 
	 */
	public void setFocus() {
		setFocus(getActivePage());
	}

	/**
	 * Sets focus to the control for the given page. If the page has an editor,
	 * this calls its <code>setFocus()</code> method. Otherwise, this calls <code>setFocus</code> on the control for the page.
	 * 
	 * @param pageIndex
	 *        the index of the page
	 */
	private void setFocus(PagePart part) {
		if(part != null) {
			part.setFocus();
		}
	}


	/**
	 * Refresh the tabs.
	 * Is we are already currently refreshing, simply return.
	 * 
	 * @see org.eclipse.papyrus.infra.core.sasheditor.editor.ISashWindowsContainer#refreshTabs()
	 * 
	 */
	public void refreshTabs() {

		// Check if we arent already refreshing
		if(isRefreshing.compareAndSet(false, true)) {
			try {
				refreshTabsInternal();
			} finally {
				isRefreshing.set(false);
			}
		} else {
			log.warn("refresh inside refresh !");
		}

	}

	/**
	 * Refresh the tab of the page, (i.e the name and icon in the page's tab).
	 * 
	 * @param page
	 *        The page for which the name and icon should be refreshed.
	 */
	public void refreshPageTab(IPage page) {
		if(page instanceof PagePart) {
			((PagePart)page).refreshTab();
		} else {
			// TODO : lookup for the corresponding PagePart, and call refresh.

		}
	}

	/**
	 * Real implementation of refreshTab.
	 * 
	 * @see org.eclipse.papyrus.infra.core.sasheditor.editor.ISashWindowsContainer#refreshTabs()
	 * 
	 */
	private void refreshTabsInternal() {
		//		System.out.println("start synchronize2() ------------------------");
		//		showTilesStatus();

		// Get the currently selected folder
		PagePart oldActivePage = getActivePage();

		// Do refresh
		container.setRedraw(false);
		// Create map of parts
		// PartMap<T> partMap = new PartMap<T>();
		PartLists garbageMaps = new PartLists();
		rootPart.fillPartMap(garbageMaps);

		// Synchronize parts
		rootPart.synchronize2(garbageMaps);


		// Remove orphaned parts (no more used)
		garbageMaps.garbage();

		// set active page if needed
		setActivePageAndSelection(checkAndGetActivePage(oldActivePage, garbageMaps));

		// Reenable SWT and force layout
		container.setRedraw(true);
		container.layout(true, true);
		//		System.out.println("end synchronize2() ------------------------");
		//		showTilesStatus();
	}

	/**
	 * Select the specified page in the Parts. The specified page will becomes the active one.
	 * Appropriate events are fired.
	 * This is the programatic counterpart of selecting a page in the UI.
	 * If the provided page is null, do nothing.
	 * Removed since 0.10
	 * 
	 * @param page
	 *        The page to select or null.
	 */
	//	protected void selectPage(PagePart page) {
	//		if(page == null)
	//			return;
	//		TabFolderPart folder = page.getParent();
	//		folder.setActiveEditor(page);
	//	}

	/**
	 * Select the specified page in the Parts. The specified page will becomes the active one.
	 * Appropriate events are fired if needed.
	 * This is the programmatic counterpart of selecting a page in the UI.
	 * If the provided page is null, do nothing.
	 * 
	 * @param page
	 *        The page to select or null. The IPage should
	 *        be an instance previously returned by the SashContainer.
	 * 
	 */
	public void selectPage(IPage page) {
		if(page == null) {
			return;
		}

		// check if we are a correct instance.
		if(!(page instanceof PagePart)) {
			return;
		}

		setActivePageAndSelection((PagePart)page);
	}

	/**
	 * Lookup the {@link IPage} used to render the specified rawModel.
	 * 
	 * @param rawModel
	 *        The model for which the IPage is requested.
	 *        If the model is not rendered, return null;
	 * 
	 * @return The corresponding IPage or null if not found.
	 */
	public IPage lookupModelPage(Object rawModel) {
		// Use a visitor to lookup the first IPage
		LookupModelPageVisitor visitor = new LookupModelPageVisitor(rawModel);
		rootPart.visit(visitor);
		return visitor.result();
	}

	/**
	 * Lookup the {@link IPage} used to render the specified IEditorPart.
	 * 
	 * @param editor
	 *        The IEditorPart for which the IPage is requested.
	 *        If the IEditorPart is not rendered, return null;
	 * 
	 * @return The corresponding IPage or null if not found.
	 */
	public IPage lookupIPageByIEditorPart(IEditorPart editor) {
		// Use a visitor to lookup the first IPage
		LookupIPageByIEditorPartVisitor visitor = new LookupIPageByIEditorPartVisitor(editor);
		rootPart.visit(visitor);
		return visitor.result();
	}

	/**
	 * Check if the oldActivePage still alive, and set it if needed.
	 * If the oldActivePage is null, set an active page if one exist.
	 * If the oldActivePage still alive, let it as the active one. If it is
	 * disposed, get arbitrarily an active page if one exist.
	 * 
	 * @param oldActivePage
	 * @param partLists
	 * @param garbageMaps
	 * @return A valid active page or null if none exists.
	 */
	private PagePart checkAndGetActivePage(PagePart oldActivePage, PartLists partLists) {

		// Check if there is a created page
		PagePart activePage = partLists.getFirstCreatedPage();
		if(activePage != null) {
			// There is a created page. Set it as the selected and active one
			return activePage;
		}

		// Check oldActivePage validity (in case it has been deleted)
		if(oldActivePage != null && !(oldActivePage.isOrphaned() || oldActivePage.isUnchecked())) {
			return oldActivePage;
		}

		// Get an active page if any
		return lookupFirstValidPage();
	}

	/**
	 * Lookup for a valid active Page. Return null if none is found.
	 * TODO Use a visitor to implements this method.
	 * 
	 * @return
	 */
	private PagePart lookupFirstValidPage() {
		// First get a list of active editors
		PartLists garbageMaps = new PartLists();
		rootPart.fillPartMap(garbageMaps);
		return garbageMaps.getFirstValidPage();
	}

	/**
	 * Set a {@link MenuManager} used to manage a contextual menu that is shown on the tabs area of the folders.
	 * 
	 * @param menuManager
	 *        The {@link MenuManager} used to create the menu on the tab area.
	 */
	public void setFolderTabMenuManager(MenuManager menuManager) {
		this.folderTabMenuManager = menuManager;
		// Set the MenuManager in each existing folder.
		// Use a visitor.
		SetFolderTabMenuVisitor visitor = new SetFolderTabMenuVisitor(menuManager);
		rootPart.visit(visitor);
	}

	/**
	 * @return the menuManager
	 */
	protected MenuManager getFolderTabMenuManager() {
		return folderTabMenuManager;
	}

	/**
	 * Show the status of the different Tiles composing the sash system.
	 * Used for debug purpose.
	 */
	public void showTilesStatus() {
		ShowPartStatusVisitor visitor = new ShowPartStatusVisitor();
		rootPart.visit(visitor);
	}


	/**
	 * Visit all the Pages (IEditorPage and IComponentPage), allowing to access to the public interface.
	 */
	public void visit(IPageVisitor pageVisitor) {
		PageVisitorWrapper visitor = new PageVisitorWrapper(pageVisitor);
		rootPart.visit(visitor);
	}

	/**
	 * Visit the Part associated to the container. This method visibility is protected in order to be able to access it
	 * from junit tests.
	 * It is not intended to be used by public API or from outside.
	 */
	protected void visit(IPartVisitor visitor) {
		rootPart.visit(visitor);
	}

	/* ***************************************************** */
	/* Drag and Drop methods */
	/* ***************************************************** */

	/**
	 * 
	 */
	private void initDrag(Composite container) {
		DragUtil.addDragTarget(container, dragOverListener);

	}

	IDragOverListener dragOverListener = new IDragOverListener() {

		/**
		 * 
		 * @see org.eclipse.ui.internal.dnd.IDragOverListener#drag(org.eclipse.swt.widgets.Control, java.lang.Object, org.eclipse.swt.graphics.Point,
		 *      org.eclipse.swt.graphics.Rectangle)
		 */
		public IDropTarget drag(Control currentControl, Object draggedObject, Point position, Rectangle dragRectangle) {
			// TODO remove the cast by changing the method. Only folder can be source and target
			final TabFolderPart sourcePart = (TabFolderPart)rootPart.findPart(draggedObject); // (ITilePart) draggedObject;
			// Compute src tab index
			// TODO move that and previous in the sender of drag event. Use a class containing both as draggedObject.
			final int srcTabIndex = PTabFolder.getDraggedObjectTabIndex(draggedObject);

			//			System.out.println("drag to position=" + position);
			Rectangle containerDisplayBounds = DragUtil.getDisplayBounds(container);
			AbstractPanelPart targetPart = null;

			// Check if the cursor is inside the container
			if(containerDisplayBounds.contains(position)) {

				if(rootPart != null) {
					targetPart = (AbstractPanelPart)rootPart.findPart(position);
					// System.out.println("targetPart=" + targetPart
					// + ", position=" + position
					// + "container.toControl(position)=" + container.toControl(position));
				}

				if(targetPart != null) {
					final Control targetControl = targetPart.getControl();

					final Rectangle targetBounds = DragUtil.getDisplayBounds(targetControl);

					int side = Geometry.getClosestSide(targetBounds, position);
					int distance = Geometry.getDistanceFromEdge(targetBounds, position, side);

					// Reserve the 5 pixels around the edge of the part for the drop-on-edge cursor
					// Check if the target can handle the drop.
					if(distance >= 5) {
						// Otherwise, ask the part if it has any special meaning for this drop location
						// TODO remove cast; change return type of findPart()
						IDropTarget target = targetPart.getDropTarget(draggedObject, sourcePart, position);
						if(target != null) {
							return target;
						}
					} else {
						// We are on the boarder, try to drop on the parent 
						// Warning : the parent could be the rootPart
						//						System.out.println("DropTarget near the border");
					}
					//                     
					if(distance > 30) {
						side = SWT.CENTER;
					}
					//                     
					// // If the part doesn't want to override this drop location then drop on the edge
					//                     
					// // A "pointless drop" would be one that will put the dragged object back where it started.
					// // Note that it should be perfectly valid to drag an object back to where it came from -- however,
					// // the drop should be ignored.
					//
					@SuppressWarnings("unused")
					boolean pointlessDrop = false;

					if(sourcePart == targetPart) {
						pointlessDrop = true;
					}

					return createDropTarget(sourcePart, srcTabIndex, side, side, targetPart);
				}
			} else {
				// Cursor is outside the container
				//				System.out.println("Outside container bounds");
				// This will be used to create a new Window.
				// We only allow dropping into a stack, not creating one
				// if (differentWindows)
				// return null;

				int side = Geometry.getClosestSide(containerDisplayBounds, position);

				boolean pointlessDrop = false;
				int cursor = Geometry.getOppositeSide(side);

				if(pointlessDrop) {
					side = SWT.NONE;
				}

				return createDropTarget(sourcePart, srcTabIndex, side, cursor, null);
			}
			return null;
		}

	};


	/**
	 * Create the drop target
	 */
	private DropTarget createDropTarget(final TabFolderPart sourcePart, int srcTabIndex, int side, int cursor, AbstractPart targetPart) {
		if(dropTarget == null) {
			dropTarget = new DropTarget(sourcePart, srcTabIndex, side, cursor, targetPart);
		} else {
			dropTarget.setTarget(sourcePart, srcTabIndex, side, cursor, targetPart);
		}
		return dropTarget;
	}

	/**
	 * Class implementing methods required by drop targets.
	 */
	protected class DropTarget implements IDropTarget {

		int count = 0;

		int cursor = SWT.TOP;

		private int side;

		private AbstractPanelPart targetPart;

		private int srcTabIndex;

		private TabFolderPart sourcePart;

		/**
		 * Constructor.
		 */
		public DropTarget(TabFolderPart sourcePart, int srcTabIndex, int cursor, int side, AbstractPart targetPart) {
			this.cursor = cursor;
			this.side = side;
			this.sourcePart = sourcePart;
			this.srcTabIndex = srcTabIndex;
			this.targetPart = (AbstractPanelPart)targetPart;
		}

		public void setTarget(TabFolderPart sourcePart, int srcTabIndex, int cursor, int side, AbstractPart targetPart) {
			this.cursor = cursor;
			this.side = side;
			this.sourcePart = sourcePart;
			this.srcTabIndex = srcTabIndex;
			this.targetPart = (AbstractPanelPart)targetPart;
		}

		/**
		 * A folder is dropped.
		 * 
		 * @see org.eclipse.ui.internal.dnd.IDropTarget#drop()
		 */
		public void drop() {
			// @TODO remove next cast
			if(side == SWT.CENTER) { // Add to target folder
				contentProvider.movePage(sourcePart.getPartModel(), srcTabIndex, ((TabFolderPart)targetPart).getPartModel(), -1);
			} else { // Create a new folder
				contentProvider.createFolder(sourcePart.getPartModel(), srcTabIndex, ((TabFolderPart)targetPart).getPartModel(), side);
			}
		}

		/**
		 * Return the cursor used during drag.
		 * 
		 * @see org.eclipse.ui.internal.dnd.IDropTarget#getCursor()
		 */
		public Cursor getCursor() {
			//			System.out.println(SashWindowsContainer.this.getClass().getSimpleName() + ".getCursor()-" + count++);
			return DragCursors.getCursor(DragCursors.positionToDragCursor(cursor));

		}

		public Rectangle getSnapRectangle() {
			//			System.out.println(SashWindowsContainer.this.getClass().getSimpleName() + ".getSnapRectangle(" + "sourcePart=" + sourcePart + ", targetPart=" + targetPart + ", side=" + side);
			Rectangle targetDisplayBounds;

			if(targetPart != null) {
				targetDisplayBounds = DragUtil.getDisplayBounds(targetPart.getControl());
			} else {
				// targetBounds = DragUtil.getDisplayBounds(getParent());
				targetDisplayBounds = DragUtil.getDisplayBounds(container);
			}

			if(side == SWT.CENTER || side == SWT.NONE) {
				return targetDisplayBounds;
			}

			int distance = Geometry.getDimension(targetDisplayBounds, !Geometry.isHorizontal(side));

			return Geometry.getExtrudedEdge(targetDisplayBounds, (int)(distance * getDockingRatio(sourcePart, targetPart)), side);
		}

		protected float getDockingRatio(AbstractPart dragged, AbstractPart target) {
			return 0.5f;
		}

	}


	/**
	 * @return the lifeCycleEventProvider
	 */
	protected SashContainerEventsProvider getLifeCycleEventProvider() {
		return lifeCycleEventProvider;
	}

	/**
	 * @return the folderLifeCycleEventProvider
	 */
	protected SashContainerFolderEventsProvider getFolderLifeCycleEventProvider() {
		return folderLifeCycleEventProvider;
	}

	/**
	 * Get the event provider used to throw TabMouseEvents.
	 * @return the TabMouseEventsProvider
	 */
	public TabMouseEventsProvider getFolderTabMouseEventProvider() {
		return tabMouseEventsProvider;
	}

	/**
	 * Return a list of all folders opened in this SashContainer. The list should only
	 * be used as a 'view' list. It should not be modified or written. The list
	 * is observable.
	 * <br>
	 * Actually, the folders are never removed from the list. This is because
	 * TabFolderPart.dispose() is never called.
	 * TODO Let TabFolderPart.dispose() be called.
	 * 
	 * @return a read only and observable list of {@link IFolder}.
	 */
	public IObservableList<IFolder> getIFolderList() {
		return folderListManager.getFolderList();
	}
	
	/**
	 * Init the folderListManager and let it listen to folder events.
	 */
	private void initTabFolderListManager() {
		folderLifeCycleEventProvider = new SashContainerFolderEventsProvider();
		folderListManager = new TabFolderListManager();
		// Listen to folder events.
		folderLifeCycleEventProvider.addListener(folderListManager);
	}
	
	/**
	 * Add a listener on pageChanged event.
	 * This implementation delegates to the internal PageTracker.
	 * 
	 * @see org.eclipse.papyrus.infra.core.sasheditor.editor.ISashWindowsContainer#addPageChangedListener(org.eclipse.papyrus.infra.core.sasheditor.editor.IPageChangedListener)
	 * @param pageChangedListener
	 * 
	 */
	public void addPageChangedListener(IPageChangedListener pageChangedListener) {
		activePageTracker.addPageChangedListener(pageChangedListener);
	}

	/**
	 * Remove a listener on pageChanged event.
	 * 
	 * @see org.eclipse.papyrus.infra.core.sasheditor.editor.ISashWindowsContainer#removePageChangedListener(org.eclipse.papyrus.infra.core.sasheditor.editor.IPageChangedListener)
	 * @param pageChangedListener
	 * 
	 */
	public void removePageChangedListener(IPageChangedListener pageChangedListener) {
		activePageTracker.removePageChangedListener(pageChangedListener);
	}

	/**
	 * Add a listener on Page LifeCycle events.
	 * This implementation delegates to the internal PageTracker.
	 * 
	 * @see org.eclipse.papyrus.infra.core.sasheditor.editor.ISashWindowsContainer#addPageChangedListener(org.eclipse.papyrus.infra.core.sasheditor.editor.IPageChangedListener)
	 * @param listener
	 * 
	 */
	public void addPageLifeCycleListener(IPageLifeCycleEventsListener listener) {
		lifeCycleEventProvider.addListener(listener);
	}

	
	/**
	 * Remove a listener on Page LifeCycle events.
	 * 
	 * @see org.eclipse.papyrus.infra.core.sasheditor.editor.ISashWindowsContainer#removePageChangedListener(org.eclipse.papyrus.infra.core.sasheditor.editor.IPageChangedListener)
	 * @param listener
	 * 
	 */
	public void removePageLifeCycleListener(IPageLifeCycleEventsListener listener) {
		lifeCycleEventProvider.removeListener(listener);
	}

	/**
	 * Add a listener {@link ITabMouseEventsListener} on folder's tabs events.
	 * 
	 * @param listener
	 */
	public void addFolderTabMouseEventListener(ITabMouseEventsListener listener) {
		tabMouseEventsProvider.addListener(listener);
	}
	
	/**
	 * Add a listener {@link ITabMouseEventsListener} on folder's tabs events.
	 * 
	 * @param listener
	 */
	public void removeFolderTabMouseEventListener(ITabMouseEventsListener listener) {
		tabMouseEventsProvider.removeListener(listener);
	}
	
	/* ***************************************************** */
	/* Internal Visitors */
	/* ***************************************************** */


	/**
	 * Inner class.
	 * A visitor setting the {@link MenuManager} on each folder.
	 */
	private class SetFolderTabMenuVisitor extends PartVisitor {


		private MenuManager menuManager;

		/**
		 * Constructor.
		 * 
		 * @param menuManager
		 */
		public SetFolderTabMenuVisitor(MenuManager menuManager) {
			this.menuManager = menuManager;
		}

		/**
		 * Set the menu if the visited node is a folder.
		 */
		@Override
		public boolean accept(TabFolderPart part) {
			part.setFolderTabMenuManager(menuManager);
			return true;
		}

	}

	/**
	 * Inner class.
	 * A visitor used to collect all visible page in the sashcontainer.
	 * A visible page is a page whose the diagram area is visible.
	 */
	private class CollectVisiblePageVisitor extends PartVisitor {

		private List<IPage> visiblePages = new ArrayList<IPage>();

		private Class<? extends IPage> expectedClass;

		/**
		 * Constructor.
		 * 
		 * @param menuManager
		 */
		public CollectVisiblePageVisitor() {

		}

		/**
		 * Constructor.
		 * 
		 * @param menuManager
		 */
		@SuppressWarnings("unused")
		public CollectVisiblePageVisitor(Class<? extends IPage> expectedClass) {
			this.expectedClass = expectedClass;
		}

		/**
		 * Get the result list.
		 * 
		 * @param <T>
		 * @return
		 */
		@SuppressWarnings("unchecked")
		public <T> List<T> getVisiblePages() {
			return (List<T>)visiblePages;
		}

		/**
		 * Set the menu if the visited node is a folder.
		 */
		@Override
		public boolean accept(TabFolderPart part) {

			IPage page = part.getVisiblePagePart();
			if(part != null) {
				if(expectedClass != null && expectedClass.isInstance(page)) {
					visiblePages.add(page);
				} else {
					visiblePages.add(page);
				}

			}

			return true;
		}

	}

	/**
	 * Inner class.
	 * A visitor used to collect all visible page in the sashcontainer.
	 * A visible page is a page whose the diagram area is visible.
	 */
	private class AbstractCollectIEditorPart extends PartVisitor {

		protected List<IEditorPart> editorParts = new ArrayList<IEditorPart>();

		/**
		 * Constructor.
		 * 
		 * @param menuManager
		 */
		public AbstractCollectIEditorPart() {

		}

		/**
		 * Get the result list.
		 * 
		 * @param <T>
		 * @return
		 */
		public List<IEditorPart> getVisiblePages() {
			return editorParts;
		}

	}

	/**
	 * Inner class.
	 * A visitor used to collect all visible page in the sashcontainer.
	 * A visible page is a page whose the diagram area is visible.
	 */
	private class CollectVisibleIEditorPart extends AbstractCollectIEditorPart {

		/**
		 * Set the menu if the visited node is a folder.
		 */
		@Override
		public boolean accept(TabFolderPart part) {

			IPage page = part.getVisiblePagePart();
			if(page != null && page instanceof IEditorPage) {
				IEditorPage editorPage = (IEditorPage)page;
				editorParts.add(editorPage.getIEditorPart());

			}
			// continue searching
			return true;
		}

	}

	/**
	 * Inner class.
	 * A visitor used to collect all parts in the sashcontainer.
	 * A visible page is a page whose the diagram area is visible.
	 */
	@SuppressWarnings("unused")
	private class CollectIEditorParts extends AbstractCollectIEditorPart {

		/**
		 * Add the part to thecollection.
		 */
		@Override
		public boolean accept(EditorPart part) {

			IEditorPart editorPart = part.getIEditorPart();
			if(editorPart != null) {
				editorParts.add(editorPart);
			}

			// continue searching
			return true;
		}

	}



}

Back to the top