Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 164c0eaf3c4acbd0b0c8ee67b4f62cd6291abe67 (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
/*******************************************************************************
 * Copyright (c) 2012 Tilera Corporation and others.
 * 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:
 *     William R. Swanson (Tilera Corporation) - initial API and implementation
 *     Marc Dumais (Ericsson) - Bug 396076 
 *     Marc Dumais (Ericsson) - Bug 396184
 *     Marc Dumais (Ericsson) - Bug 396200
 *     Marc Dumais (Ericsson) - Bug 396293
 *     Marc Dumais (Ericsson) - Bug 399281
 *     Marc Dumais (Ericsson) - Add CPU/core load information to the multicore visualizer (Bug 396268)
 *     Marc Dumais (Ericsson) - Bug 399419
 *     Marc Dumais (Ericsson) - Bug 404894
 *******************************************************************************/

package org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.view;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;

import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.MulticoreVisualizerUIPlugin;
import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.model.VisualizerCPU;
import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.model.VisualizerCore;
import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.model.VisualizerModel;
import org.eclipse.cdt.dsf.gdb.multicorevisualizer.internal.ui.model.VisualizerThread;
import org.eclipse.cdt.visualizer.ui.canvas.GraphicCanvas;
import org.eclipse.cdt.visualizer.ui.plugin.CDTVisualizerUIPlugin;
import org.eclipse.cdt.visualizer.ui.util.GUIUtils;
import org.eclipse.cdt.visualizer.ui.util.MouseMonitor;
import org.eclipse.cdt.visualizer.ui.util.SelectionManager;
import org.eclipse.cdt.visualizer.ui.util.SelectionUtils;
import org.eclipse.cdt.visualizer.ui.util.Timer;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Composite;


/**
 * MulticoreVisualizer's display canvas.
 */
public class MulticoreVisualizerCanvas extends GraphicCanvas
	implements ISelectionProvider
{
	// --- constants ---

	/** Canvas update interval in milliseconds. */
	protected static final int CANVAS_UPDATE_INTERVAL = 100;
	
	/** Spacing to allow between threads, when many are displayed on same tile. */
	protected static final int THREAD_SPACING = 8;
	
	protected static final int SELECTION_SLOP = 20;
	

	// --- members ---
	
	/** Update timer */
	protected Timer m_updateTimer = null;
	
	/** Whether we need to recache graphic objects. */
	protected boolean m_recache = true;
	
	/**
	 * Whether we need to recache objects that depend on target state.
	 */
	protected boolean m_recacheState = true;
	
	/**
	 * Whether view size has changed, requiring us to recalculate object sizes.
	 */
	protected boolean m_recacheSizes = true;
	
	/**
	 * Whether the load information has changed and we need to update the load meters
	 * @since 1.1
	 */
	protected boolean m_recacheLoadMeters = true;
		
	/** Whether we need to repaint the canvas */
	protected boolean m_update = true;


	// --- UI members ---
	
	/** Text font */
	protected Font m_textFont = null;
	
	/** Externally visible selection manager. */
	protected SelectionManager m_selectionManager;

    /** Mouse-drag marquee graphic element */
    protected MulticoreVisualizerMarquee m_marquee = null;
    
    /** Last mouse down/up point, for shift-click selections. */
    protected Point m_lastSelectionClick = new Point(0,0);
    
	/** Mouse click/drag monitor */
    protected MouseMonitor m_mouseMonitor = null;
	

	// --- cached repaint state ---
	
	/** Current visualizer model we're displaying. */
	protected VisualizerModel m_model = null;
	
	/** Number of CPUs to display. */
	protected int m_cpu_count = 15;
	
	/** Number of Cores per CPU to display. */
	protected int m_cores_per_cpu = 3;
	
	/** List of CPUs we're displaying. */
	protected ArrayList<MulticoreVisualizerCPU> m_cpus = null;
	/** Mapping from model to view objects. */
	protected Hashtable<VisualizerCPU, MulticoreVisualizerCPU> m_cpuMap = null;

	/** List of CPU cores we're displaying. */
	protected ArrayList<MulticoreVisualizerCore> m_cores = null;
	/** Mapping from model to view objects. */
	protected Hashtable<VisualizerCore, MulticoreVisualizerCore> m_coreMap = null;
	
	/** Graphic objects representing threads */
	protected ArrayList<MulticoreVisualizerThread> m_threads = null;
	/** Mapping from model to view objects. */
	protected Hashtable<VisualizerThread, MulticoreVisualizerThread> m_threadMap = null;
	
	/** Selected PIDs. */
	protected HashSet<Integer> m_selectedPIDs = null;
	

	// --- constructors/destructors ---
	
	/** Constructor. */
	public MulticoreVisualizerCanvas(Composite parent) {
		super(parent);
		initMulticoreVisualizerCanvas(parent);
	}
	
	/** Dispose method. */
	@Override
	public void dispose() {
		cleanupMulticoreVisualizerCanvas();
		super.dispose();
	}

	
	// --- init methods ---
	
	/** Initializes control */
	protected void initMulticoreVisualizerCanvas(Composite parent) {
		// perform any initialization here
		
		// text font
		m_textFont = CDTVisualizerUIPlugin.getResources().getFont("Luxi Sans", 6); //$NON-NLS-1$
		setFont(m_textFont);
		
		// initialize cached state storage
		m_cpus        = new ArrayList<MulticoreVisualizerCPU>();
		m_cpuMap      = new Hashtable<VisualizerCPU, MulticoreVisualizerCPU>();
		
		m_cores       = new ArrayList<MulticoreVisualizerCore>();
		m_coreMap     = new Hashtable<VisualizerCore, MulticoreVisualizerCore>();
		
		m_threads     = new ArrayList<MulticoreVisualizerThread>();
		m_threadMap   = new Hashtable<VisualizerThread, MulticoreVisualizerThread>();
		
		m_selectedPIDs = new HashSet<Integer>();
		
		// mouse-drag monitor
		m_mouseMonitor = new MouseMonitor(this) {
			/** Invoked for a selection click at the specified point. */
			@Override
			public void select(int x, int y, int keys) {
				MulticoreVisualizerCanvas.this.select(x, y, keys);
			}

			/** Invoked for a double click at the specified point. */
			@Override
			public void mouseDoubleClick(int button, int x, int y, int keys) {
				MulticoreVisualizerCanvas.this.select(x, y, keys);
			}

			/** Invoked for a menu mouse down at the specified point. */
			@Override
			public void mouseDown(int button, int x, int y, int keys) {
				if (button == RIGHT_BUTTON) {
					if (! hasSelection()) {
						// If there isn't a selection currently, try to
						// select item(s) under the mouse before popping up the context menu.
						MulticoreVisualizerCanvas.this.select(x, y, keys);
					}
				}
			}

			/** Invoked when mouse is dragged. */
			@Override
			public void drag(int button, int x, int y, int keys, int dragState) {
				if (button == LEFT_BUTTON) {
					MulticoreVisualizerCanvas.this.drag(x, y, keys, dragState);
				}
			}
		};
		
		// selection marquee
		m_marquee = new MulticoreVisualizerMarquee();

		// selection manager
		m_selectionManager = new SelectionManager(this, "MulticoreVisualizerCanvas selection manager"); //$NON-NLS-1$
		
		// add update timer
		m_updateTimer = new Timer(CANVAS_UPDATE_INTERVAL) {
			@Override
			public void run() {
				update();
			}
		};
		m_updateTimer.setRepeating(false); // one-shot timer
		m_updateTimer.start();
	}
	
	/** Cleans up control */
	protected void cleanupMulticoreVisualizerCanvas() {
		if (m_updateTimer != null) {
			m_updateTimer.dispose();
			m_updateTimer = null;
		}
	    if (m_marquee != null) {
	    	m_marquee.dispose();
	    	m_marquee = null;
	    }
        if (m_mouseMonitor != null) {
            m_mouseMonitor.dispose();
            m_mouseMonitor = null;
	    }
	    if (m_selectionManager != null) {
	    	m_selectionManager.dispose();
	    	m_selectionManager = null;
	    }
        if (m_cpus != null) {
        	m_cpus.clear();
        	m_cpus = null;
        }
        if (m_cpuMap != null) {
        	m_cpuMap.clear();
        	m_cpuMap = null;
        }
        if (m_cores != null) {
        	m_cores.clear();
        	m_cores = null;
        }
        if (m_coreMap != null) {
        	m_coreMap.clear();
        	m_coreMap = null;
        }
        if (m_threads != null) {
        	m_threads.clear();
        	m_threads = null;
        }
        if (m_threadMap != null) {
        	m_threadMap.clear();
        	m_threadMap = null;
        }
        if (m_selectedPIDs != null) {
        	m_selectedPIDs.clear();
        	m_selectedPIDs = null;
        }
	}
	

	// --- accessors ---
	
	/** Gets currently displayed model. */
	public VisualizerModel getModel()
	{
		return m_model;
	}
	
	/** Sets model to display, and requests canvas update. */
	public void setModel(VisualizerModel model)
	{
		m_model = model;
		requestRecache();
		requestUpdate();
	}
	
	/**
	 * only update the load meters
	 * @since 1.1
	 */
	public void refreshLoadMeters() {
		requestRecache(false, false, true);
	}
	
	
	// --- resize methods ---
	
	/** Invoked when control is resized. */
	@Override
	public void resized(Rectangle bounds) {
		requestRecache(false, true);
		// note: resize itself will trigger an update, so we don't have to request one
	}

	
	// --- update methods ---
	
	/**
	 * Requests an update on next timer tick.
	 * NOTE: use this method instead of normal update(),
	 * multiple update requests on same tick are batched.
	 */
	public void requestUpdate() {
		GUIUtils.exec(new Runnable() { @Override public void run() {
			if (m_updateTimer != null) {
				m_updateTimer.start();
			}
		}});
	}
	

	// --- paint methods ---
	
	/** Requests that next paint call should recache state and/or size information */
	// synchronized so we don't change recache flags while doing a recache
	public synchronized void requestRecache() {
		requestRecache(true, true, true);
	}

	/** Requests that next paint call should recache state and/or size information */
	// synchronized so we don't change recache flags while doing a recache
	public synchronized void requestRecache(boolean state, boolean sizes) {
		requestRecache(state, sizes, true);
	}
	
	/**
	 * Requests that the next paing call should recache state and/or size and/or load information
	 * @since 1.1
	 */
	// synchronized so we don't change recache flags while doing a recache
	public synchronized void requestRecache(boolean state, boolean sizes, boolean load) {
		m_recache = true;
		// NOTE: we intentionally OR these flags with any pending request(s)
		m_recacheState |= state;
		m_recacheSizes |= sizes;
		m_recacheLoadMeters |= load;
	}
	
	/** Fits n square items into a rectangle of the specified size.
	 *  Returns largest edge of one of the square items that allows
	 *  them all to pack neatly in rows/columns in the specified area. */
	public int fitSquareItems(int nitems, int width, int height) {
		int max_edge = 0;
		if (width > height) {
			for (int items_per_row = nitems; items_per_row > 0; --items_per_row) {
				int rows = (int) Math.ceil(1.0 * nitems / items_per_row);
				int w = width / items_per_row;
				int h = height / rows;
				int edge = (w < h) ? w : h;
				if (edge * rows > height || edge * items_per_row > width) continue;
				if (edge > max_edge) max_edge = edge;
			}
		}
		else {
			for (int items_per_col = nitems; items_per_col > 0; --items_per_col) {
				int cols = (int) Math.ceil(1.0 * nitems / items_per_col);
				int w = width / cols;
				int h = height / items_per_col;
				int edge = (w < h) ? w : h;
				if (edge * cols > width || edge * items_per_col > height) continue;
				if (edge > max_edge) max_edge = edge;
			}
		}
		return max_edge;
	}
	
	/** Recache persistent objects (tiles, etc.) for new monitor */
	// synchronized so we don't change recache flags while doing a recache
	public synchronized void recache() {
		if (! m_recache) return; // nothing to do, free the lock quickly

		if (m_recacheState) {

			// clear all grid view objects
			clear();
			
			// clear cached state
			m_cpus.clear();
			m_cores.clear();
			m_threads.clear();
			m_cpuMap.clear();
			m_coreMap.clear();
			m_threadMap.clear();

			// For debugging purposes only, allows us to force a CPU count.
			//int cpu_count = 0;
			//int force_cpu_count = 2;
			
			if (m_model != null) {
				for (VisualizerCPU cpu : m_model.getCPUs()) {
					//if (force_cpu_count >= cpu_count) break;
					//cpu_count++;
					MulticoreVisualizerCPU mcpu = new MulticoreVisualizerCPU(cpu.getID());
					m_cpus.add(mcpu);
					m_cpuMap.put(cpu, mcpu);
					for (VisualizerCore core : cpu.getCores()) {
						MulticoreVisualizerCore mcore = new MulticoreVisualizerCore(mcpu, core.getID());
						m_cores.add(mcore);
						m_coreMap.put(core, mcore);
					}
				}
			}
			/*
			while (cpu_count < force_cpu_count) {
				MulticoreVisualizerCPU mcpu = new MulticoreVisualizerCPU(cpu_count);
				m_cpus.add(mcpu);
				cpu_count++;
			}
			*/
			
			// we've recached state, which implies recacheing sizes and load meters
			m_recacheState = false;
			m_recacheLoadMeters = true;
			m_recacheSizes = true;
		}
		
		if (m_recacheLoadMeters) {
			// refresh the visualizer CPU and core load meters
			if (m_model != null) {
				Enumeration<VisualizerCPU> modelCpus = m_cpuMap.keys();
				while (modelCpus.hasMoreElements()) {
					VisualizerCPU modelCpu = modelCpus.nextElement();
					MulticoreVisualizerCPU visualizerCpu = m_cpuMap.get(modelCpu);
					// update CPUs load meter 
					MulticoreVisualizerLoadMeter meter = visualizerCpu.getLoadMeter();
					meter.setEnabled(m_model.getLoadMetersEnabled());
					meter.setLoad(modelCpu.getLoad());
					meter.setHighLoadWatermark(modelCpu.getHighLoadWatermark());
					
					for (VisualizerCore modelCore : modelCpu.getCores()) {
						MulticoreVisualizerCore visualizerCore = m_coreMap.get(modelCore);
						// update cores load meter
						meter = visualizerCore.getLoadMeter();
						meter.setEnabled(m_model.getLoadMetersEnabled());
						meter.setLoad(modelCore.getLoad());
						meter.setHighLoadWatermark(modelCore.getHighLoadWatermark());
					}
				}
			}
			
			m_recacheSizes = true;
			m_recacheLoadMeters = false;
		}

		if (m_recacheSizes) {
			// avoid doing resize calculations if the model is not ready
			if (m_model == null ) {
				m_recacheSizes = false;
				return;
			}
			// update cached size information
			
			// General margin/spacing constants.
			int cpu_margin = 8;       // margin around edges of CPU grid
			int cpu_separation = 6;   // spacing between CPUS
			
			// make room when load meters are present, else use a more compact layout
			int core_margin = m_model.getLoadMetersEnabled() ? 20 : 12;      // margin around cores in a CPU 
			int core_separation = 4;  // spacing between cores

			int loadMeterWidth = core_margin*3/5;
			int loadMeterHMargin = core_margin/5;
			int loadMeterHCoreMargin = loadMeterHMargin + 5;
			
			// Get overall area we have for laying out content.
			Rectangle bounds = getClientArea();
			GUIUtils.inset(bounds, cpu_margin);

			// Figure out area to allocate to each CPU box.
			int ncpus  = m_cpus.size();
			int width  = bounds.width  + cpu_separation;
			int height = bounds.height + cpu_separation;
			int cpu_edge = fitSquareItems(ncpus, width, height);
			int cpu_size = cpu_edge - cpu_separation;
			if (cpu_size < 0) cpu_size = 0;
			
			// Calculate area on each CPU for placing cores.
			int ncores = m_cores.size() / ((ncpus == 0) ? 1 : ncpus);
			int cpu_width  = cpu_size - core_margin * 2 + core_separation;
			int cpu_height = cpu_size - core_margin * 2 + core_separation;
			int core_edge  = fitSquareItems(ncores, cpu_width, cpu_height);
			int core_size  = core_edge - core_separation;
			if (core_size < 0) core_size = 0;
			
			int x = bounds.x, y = bounds.y;
			for (MulticoreVisualizerCPU cpu : m_cpus) {
				cpu.setBounds(x, y, cpu_size-1, cpu_size-1);
				// put cpu meter in the right margin of the CPU
				cpu.getLoadMeter().setBounds(x + cpu_size - 2*cpu_margin, y + 2*core_margin, loadMeterWidth, cpu_size-3*core_margin);
				
				int left = x + core_margin;
				int cx = left, cy = y + core_margin;
				for (MulticoreVisualizerCore core : cpu.getCores())
				{
					core.setBounds(cx, cy, core_size, core_size);
					
					core.getLoadMeter().setBounds(
							cx + core_size - loadMeterHCoreMargin - loadMeterWidth, 
							cy + core_size * 1 / 3,
							loadMeterWidth, 
							core_size * 2 / 3 - loadMeterHCoreMargin
							);

					cx += core_size + core_separation;
					if (cx + core_size + core_margin > x + cpu_size) {
						cx = left;
						cy += core_size + core_separation;
					}
				}
				
				x += cpu_size + cpu_separation;
				if (x + cpu_size > bounds.x + width) {
					x = bounds.x;
					y += cpu_size + cpu_separation;
				}
			}

			m_recacheSizes = false;
		}
		m_recache = false;
	}
	
	/** Invoked when canvas repaint event is raised.
	 *  Default implementation clears canvas to background color.
	 */
	@Override
	public void paintCanvas(GC gc) {
		// NOTE: We have a little setup to do first,
		// so we delay clearing/redrawing the canvas until needed,
		// to minimize any potential visual flickering.
		
		// recache/resize tiles & shims if needed
		recache();

		// do any "per frame" updating/replacement of graphic objects
		
		// recalculate process/thread graphic objects on the fly
		// TODO: can we cache/pool these and just move them around?
		for (MulticoreVisualizerCore core : m_cores) {
			core.removeAllThreads();
		}
		m_threads.clear();
		m_threadMap.clear();
		
		// update based on current processes/threads
		if (m_model != null) {
			
			// NOTE: we assume that we've already created and sized the graphic
			// objects for cpus/cores in recache() above,
			// so we can use these to determine the size/location of more dynamic elements
			// like processes and threads
			
			for (VisualizerThread thread : m_model.getThreads()) {
				VisualizerCore core = thread.getCore();
				MulticoreVisualizerCore mcore = m_coreMap.get(core);
				if (mcore != null) {
					MulticoreVisualizerThread mthread =
						new MulticoreVisualizerThread(mcore, thread);
					mcore.addThread(mthread);
					m_threads.add(mthread);
					m_threadMap.put(thread, mthread);
				}
			}

			// now set sizes of processes/threads for each tile
			for (MulticoreVisualizerCore core : m_cores) {
				Rectangle bounds = core.getBounds();
				
				// how we lay out threads depends on how many there are
				List<MulticoreVisualizerThread> threads = core.getThreads();
				int threadspotsize = MulticoreVisualizerThread.THREAD_SPOT_SIZE;
				int threadheight = threadspotsize + THREAD_SPACING;
				int count = threads.size();
				int tileheight = bounds.height - 4;
				int tx = bounds.x + 2;
				int ty = bounds.y + 2;
				int dty = (count < 1) ? 0 : tileheight / count;
				if (dty > threadheight) dty = threadheight;
				if (count > 0 && dty * count <= tileheight) {
					ty = bounds.y + 2 + (tileheight - (dty * count)) / 2;
					if (ty < bounds.y + 2) ty = bounds.y + 2;
				}
				else if (count > 0) {
					dty = tileheight / count;
					if (dty > threadheight) dty = threadheight;
				}
				int t = 0;
				for (MulticoreVisualizerThread threadobj : threads) {
					int y = ty + dty * (t++);
					threadobj.setBounds(tx, y, threadspotsize, threadspotsize);
				}
			}
		}
		
		// restore canvas object highlighting from model object selection
		restoreSelection();

		// FIXME: enable secondary highlight for threads that are
		// part of a selected process.
		m_selectedPIDs.clear();
		for (MulticoreVisualizerThread mthread : m_threads) {
			if (mthread.isSelected()) {
				m_selectedPIDs.add(mthread.getPID());
			}
		}
		for (MulticoreVisualizerThread mthread : m_threads) {
			mthread.setProcessSelected(m_selectedPIDs.contains(mthread.getPID()));
		}
		
		// NOW we can clear the background
		clearCanvas(gc);

		// Make sure color/font resources are properly initialized.
		MulticoreVisualizerUIPlugin.getResources();
		
		// paint cpus
		for (MulticoreVisualizerCPU cpu : m_cpus) {
			cpu.paintContent(gc);
			cpu.getLoadMeter().paintContent(gc);
			cpu.getLoadMeter().paintDecorations(gc);
		}

		// paint cores
		for (MulticoreVisualizerCore core : m_cores) {
			core.paintContent(gc);
			core.getLoadMeter().paintContent(gc);
			core.getLoadMeter().paintDecorations(gc);
		}
		
		// paint cpus IDs on top of cores
		for (MulticoreVisualizerCPU cpu : m_cpus) {
			cpu.paintDecorations(gc);
		}

		// paint threads on top of cores
		for (MulticoreVisualizerThread thread : m_threads) {
			thread.paintContent(gc);
		}
		
		// paint drag-selection marquee last, so it's on top.
		m_marquee.paintContent(gc);
	}
	
	
	// --- mouse event handlers ---

	/** Invoked when mouse is dragged. */
	public void drag(int x, int y, int keys, int dragState)
	{
		Rectangle region = m_mouseMonitor.getDragRegion();
		switch (dragState) {
		case MouseMonitor.MOUSE_DRAG_BEGIN:
			m_marquee.setBounds(region);
			m_marquee.setVisible(true);
			update();
			break;
		case MouseMonitor.MOUSE_DRAG:
			m_marquee.setBounds(region);
			update();
			break;
		case MouseMonitor.MOUSE_DRAG_END:
		default:
			m_marquee.setBounds(region);
			m_marquee.setVisible(false);

			boolean addToSelection = MouseMonitor.isShiftDown(keys);
			boolean toggleSelection = MouseMonitor.isControlDown(keys);
			
			selectRegion(m_marquee.getBounds(), addToSelection, toggleSelection);

			// remember last mouse-up point for shift-click selection
			m_lastSelectionClick.x = x;
			m_lastSelectionClick.y = y;
			
			update();
			break;
		}
	}

	/** Invoked for a selection click at the specified point. */
	public void select(int x, int y, int keys)
	{
		boolean addToSelection = MouseMonitor.isShiftDown(keys);
		boolean toggleSelection = MouseMonitor.isControlDown(keys);
		
		selectPoint(x,y, addToSelection, toggleSelection);
	}
	

	// --- selection methods ---

	/**
	 * Selects item(s), if any, in specified region
	 * 
	 * If addToSelection is true, appends item(s) to current selection
	 * without changing selection state of other items.
	 *  
	 * If toggleSelection is true, toggles selection of item(s)
	 * without changing selection state of other items.
	 * 
	 * If both are true, deselects item(s)
	 * without changing selection state of other items.
	 *  
	 * Otherwise, selects item(s) and deselects other items.
	 */
	public void selectRegion(Rectangle region,
							 boolean addToSelection, boolean toggleSelection)
	{
		boolean changed = false;

		List<MulticoreVisualizerGraphicObject> selectableObjects = getSelectableObjects();

		for (MulticoreVisualizerGraphicObject gobj : selectableObjects) {
			boolean within = gobj.isWithin(region);

			if (addToSelection && toggleSelection) {
				if (within) {
					gobj.setSelected(false);
					changed = true;
				}
			}
			else if (addToSelection) {
				if (within) {
					gobj.setSelected(true);
					changed = true;
				}
			}
			else if (toggleSelection) {
				if (within) {
					gobj.setSelected(! gobj.isSelected());
					changed = true;
				}
			}
			else {
				gobj.setSelected(within);
				changed = true;
			}
		}

		if (changed)
			selectionChanged();
	}
	
	/**
	 * Selects item(s), if any, at specified point.
	 * 
	 * If addToSelection is true, appends item(s) to current selection
	 * without changing selection state of other items.
	 *  
	 * If toggleSelection is true, toggles selection of item(s)
	 * without changing selection state of other items.
	 * 
	 * If both are true, deselects item(s)
	 * without changing selection state of other items.
	 *  
	 * Otherwise, selects item(s) and deselects other items.
	 */
	public void selectPoint(int x, int y,
			boolean addToSelection, boolean toggleSelection)
	{
		List<MulticoreVisualizerGraphicObject> selectedObjects = new ArrayList<MulticoreVisualizerGraphicObject>();
		List<MulticoreVisualizerGraphicObject> selectableObjects = getSelectableObjects();

		// the list of selectable objects is ordered to have contained objects 
		// before container objects, so the first match we find is the specific 
		// one we want.
		for (MulticoreVisualizerGraphicObject gobj : selectableObjects) {
			if (gobj.contains(x,y)) {
				selectedObjects.add(gobj);
				break;
			}
		}
		
		// else we assume it landed outside any CPU; de-select everything
		if (selectedObjects.isEmpty()) {
			clearSelection();
		}

		// in addToSelection case, include any object in region
		// bracketed by last selection click and current click
		// (with some extra slop added so we pick up objects that
		// overlap the edge of this region)
		if (addToSelection) {
			int slop = SELECTION_SLOP;
			Rectangle r1 = new Rectangle(m_lastSelectionClick.x - slop/2,
					m_lastSelectionClick.y - slop/2,
					slop, slop);
			Rectangle r2 = new Rectangle(x - slop/2, y - slop/2, slop, slop);
			Rectangle region = r1.union(r2);

			for (MulticoreVisualizerGraphicObject gobj : selectableObjects) {
				if (gobj.isWithin(region)) {
					selectedObjects.add(gobj);
				}
			}
		}

		boolean changed = false;

		for (MulticoreVisualizerGraphicObject gobj : selectableObjects) {
			boolean within = selectedObjects.contains(gobj);

			if (addToSelection && toggleSelection) {
				if (within) {
					gobj.setSelected(false);
					changed = true;
				}
			}
			else if (addToSelection) {
				if (within) {
					gobj.setSelected(true);
					changed = true;
				}
			}
			else if (toggleSelection) {
				if (within) {
					gobj.setSelected(! gobj.isSelected());
					changed = true;
				}
			}
			else {
				gobj.setSelected(within);
				changed = true;
			}
		}

		if (changed)
			selectionChanged();

		// remember last mouse-up point for shift-click selection
		m_lastSelectionClick.x = x;
		m_lastSelectionClick.y = y;
	}
		
	
	
	// --- selection management methods ---
		
	/** Selects all items in the canvas. */
	public void selectAll()
	{
		List<MulticoreVisualizerGraphicObject> selectableObjects = getSelectableObjects();

		for (MulticoreVisualizerGraphicObject gobj : selectableObjects) {
			gobj.setSelected(true);
		}

		selectionChanged();
	}

	/** Clears selection. */
	public void clearSelection() {

		List<MulticoreVisualizerGraphicObject> selectableObjects = getSelectableObjects();

		for (MulticoreVisualizerGraphicObject gobj : selectableObjects) {
			gobj.setSelected(false);
		}

		selectionChanged();
	}
	
	/** Things to do whenever the selection changes. */
	protected void selectionChanged() {
		selectionChanged(true);
	}

	/** Things to do whenever the selection changes. */
	protected void selectionChanged(boolean raiseEvent) {
		// Note: we save selection (and raise event) now,
		// and let canvas "catch up" on its next update tick.
		updateSelection(raiseEvent);
		requestUpdate();
	}

	/** Saves current canvas selection as list of model objects. */
	protected void updateSelection(boolean raiseEvent) {
		// get model objects (if any) corresponding to canvas selection
		HashSet<Object> selectedObjects = new HashSet<Object>();
		
		// threads
		if (m_threads != null) {
			for (MulticoreVisualizerThread tobj : m_threads) {
				if (tobj.isSelected()) {
					selectedObjects.add(tobj.getThread());
				}
			}
		}
		
		// cpus and cores
		if (m_model != null) {
			for (VisualizerCPU modelCpu : m_model.getCPUs()) {
				MulticoreVisualizerCPU cpu = m_cpuMap.get(modelCpu);
				if (cpu != null && cpu.isSelected()) {
					selectedObjects.add(modelCpu);
				}
				for (VisualizerCore modelCore : modelCpu.getCores()) {
					MulticoreVisualizerCore core = m_coreMap.get(modelCore);
					if (core != null && core.isSelected()) {
						selectedObjects.add(modelCore);
					}
				}
			}
		}
		
		// update model object selection
		ISelection selection = SelectionUtils.toSelection(selectedObjects);
		setSelection(selection, raiseEvent);
	}
	
	/** Restores current selection from saved list of model objects. */
	protected void restoreSelection() {
		ISelection selection = getSelection();
		List<Object> selectedObjects = SelectionUtils.getSelectedObjects(selection);
		
		for (Object modelObj : selectedObjects) {
			if (modelObj instanceof VisualizerThread) {
				MulticoreVisualizerThread thread = m_threadMap.get(modelObj);
				if (thread != null) {
					thread.setSelected(true);
				}
			}
			else if (modelObj instanceof VisualizerCore) {
				MulticoreVisualizerCore core = m_coreMap.get(modelObj);
				if (core != null) {
					core.setSelected(true);
				}
			}
			else if (modelObj instanceof VisualizerCPU) {
				MulticoreVisualizerCPU cpu = m_cpuMap.get(modelObj);
				if (cpu != null) {
					cpu.setSelected(true);
				}
			}
		}
	}
	
	/** 
	 * Gets the current list of selectable objects.  The list is ordered by object type,
	 * so that more specific objects will appear first, followed by enclosing objects.
	 * For instance, threads are before cores and cores before CPUs. 
	 */
    protected List<MulticoreVisualizerGraphicObject> getSelectableObjects () {
    	List<MulticoreVisualizerGraphicObject> selectableObjects = new ArrayList<MulticoreVisualizerGraphicObject>();
		selectableObjects.addAll(m_threads);
		selectableObjects.addAll(m_cores);
		selectableObjects.addAll(m_cpus);
		
		return selectableObjects;
    }
	
	
	// --- ISelectionProvider implementation ---
	
	// Delegate to selection manager.
	
	/** Adds external listener for selection change events. */
	@Override
	public void addSelectionChangedListener(ISelectionChangedListener listener) {
		m_selectionManager.addSelectionChangedListener(listener);
	}

	/** Removes external listener for selection change events. */
	@Override
	public void removeSelectionChangedListener(ISelectionChangedListener listener) {
		if (m_selectionManager != null) {
			m_selectionManager.removeSelectionChangedListener(listener);
		}
	}
	
	/** Raises selection changed event. */
	public void raiseSelectionChangedEvent() {
		m_selectionManager.raiseSelectionChangedEvent();
	}
	
	/** Returns true if we have a selection. */
	public boolean hasSelection()
	{
		return m_selectionManager.hasSelection();
	}
	
	/** Gets current externally-visible selection. */
	@Override
	public ISelection getSelection()
	{
		return m_selectionManager.getSelection();
	}
	
	/** Sets externally-visible selection. */
	@Override
	public void setSelection(ISelection selection)
	{
		setSelection(selection, true);
	}
	
	/** Sets externally-visible selection. */
	public void setSelection(ISelection selection, boolean raiseEvent)
	{
		m_selectionManager.setSelection(selection, raiseEvent);
		requestUpdate();
	}
	
    /** Sets whether selection events are enabled. */
    public void setSelectionEventsEnabled(boolean enabled) {
        m_selectionManager.setSelectionEventsEnabled(enabled);
    }
}

Back to the top