Skip to main content
summaryrefslogtreecommitdiffstats
blob: 36463340ba441a2f4b75369a18ccf8b6f4d8c62b (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
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
/*******************************************************************************
 * Copyright (c) 2004, 2007 Composent, Inc. 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:
 *    Composent, Inc. - initial API and implementation
 ******************************************************************************/
package org.eclipse.ecf.internal.ui.deprecated.views;

import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;

import org.eclipse.core.runtime.Assert;
import org.eclipse.ecf.core.IContainerListener;
import org.eclipse.ecf.core.events.IContainerDisconnectedEvent;
import org.eclipse.ecf.core.events.IContainerEvent;
import org.eclipse.ecf.core.identity.ID;
import org.eclipse.ecf.core.identity.IDFactory;
import org.eclipse.ecf.core.security.ConnectContextFactory;
import org.eclipse.ecf.core.user.IUser;
import org.eclipse.ecf.core.util.ECFException;
import org.eclipse.ecf.presence.IIMMessageEvent;
import org.eclipse.ecf.presence.IIMMessageListener;
import org.eclipse.ecf.presence.IPresence;
import org.eclipse.ecf.presence.chatroom.IChatRoomContainer;
import org.eclipse.ecf.presence.chatroom.IChatRoomInfo;
import org.eclipse.ecf.presence.chatroom.IChatRoomInvitationListener;
import org.eclipse.ecf.presence.chatroom.IChatRoomManager;
import org.eclipse.ecf.presence.chatroom.IChatRoomMessage;
import org.eclipse.ecf.presence.chatroom.IChatRoomMessageEvent;
import org.eclipse.ecf.presence.chatroom.IChatRoomMessageSender;
import org.eclipse.ecf.presence.chatroom.IChatRoomParticipantListener;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabFolder2Listener;
import org.eclipse.swt.custom.CTabFolderEvent;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchPreferenceConstants;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.editors.text.EditorsUI;
import org.eclipse.ui.editors.text.TextSourceViewerConfiguration;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.progress.IWorkbenchSiteProgressService;

public class ChatRoomManagerView extends ViewPart implements
		IChatRoomInvitationListener {

	public static final String VIEW_ID = "org.eclipse.ecf.presence.ui.chatroom.ChatRoomManagerView";

	private static final String COMMAND_PREFIX = "/";

	private static final String COMMAND_DELIM = " ";

	private static final String USERNAME_HOST_DELIMETER = "@";

	private static final int RATIO_WRITE_PANE = 1;

	private static final int RATIO_READ_PANE = 7;

	private static final int RATIO_READ_WRITE_PANE = 85;

	private static final int RATIO_PRESENCE_PANE = 15;

	protected static final String DEFAULT_ME_COLOR = "0,255,0";

	protected static final String DEFAULT_OTHER_COLOR = "0,0,0";

	protected static final String DEFAULT_SYSTEM_COLOR = "0,0,255";

	/**
	 * The default color used to highlight the string of text when the user's
	 * name is referred to in the chatroom. The default color is red.
	 */
	protected static final String DEFAULT_HIGHLIGHT_COLOR = "255,0,0";

	protected static final String DEFAULT_DATE_COLOR = "0,0,0";

	protected static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";

	protected static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";

	protected static final int DEFAULT_INPUT_HEIGHT = 25;

	protected static final int DEFAULT_INPUT_SEPARATOR = 5;

	private CTabFolder rootTabFolder = null;

	private ChatRoomTab rootChannelTab = null;

	private IChatRoomViewCloseListener rootCloseListener = null;

	private IChatRoomMessageSender rootMessageSender = null;

	private IChatRoomContainer rootChatRoomContainer = null;

	private IChatRoomManager rootChatRoomManager = null;

	private Color otherColor = null;

	private Color systemColor = null;

	private Color dateColor = null;

	private Color highlightColor = null;

	Action outputClear = null;

	Action outputCopy = null;

	Action outputPaste = null;

	Action outputSelectAll = null;

	boolean rootDisposed = false;

	private ID rootTargetID;

	private String userName = "<user>";

	private String hostName = "<host>";

	private boolean rootEnabled = false;

	private Hashtable chatRooms = new Hashtable();

	class ChatRoomTab {
		private SashForm fullChat;

		private CTabItem tabItem;

		private SashForm rightSash;

		private StyledText outputText;

		private Text inputText;

		private ListViewer listViewer;

		private Action outputSelectAll;
		private Action outputCopy;
		private Action outputClear;

		ChatRoomTab(CTabFolder parent, String name) {
			this(true, parent, name, null);
		}

		ChatRoomTab(boolean withParticipantsList, CTabFolder parent,
				String name, KeyListener keyListener) {
			tabItem = new CTabItem(parent, SWT.NULL);
			tabItem.setText(name);
			if (withParticipantsList) {
				fullChat = new SashForm(parent, SWT.HORIZONTAL);
				fullChat.setLayout(new FillLayout());
				Composite memberComp = new Composite(fullChat, SWT.NONE);
				memberComp.setLayout(new FillLayout());
				listViewer = new ListViewer(memberComp, SWT.BORDER
						| SWT.V_SCROLL | SWT.H_SCROLL);
				listViewer.setSorter(new ViewerSorter());
				Composite rightComp = new Composite(fullChat, SWT.NONE);
				rightComp.setLayout(new FillLayout());
				rightSash = new SashForm(rightComp, SWT.VERTICAL);
			} else
				rightSash = new SashForm(parent, SWT.VERTICAL);
			Composite readInlayComp = new Composite(rightSash, SWT.FILL);
			readInlayComp.setLayout(new GridLayout());
			readInlayComp.setLayoutData(new GridData(GridData.FILL_BOTH));

			SourceViewer result = new SourceViewer(readInlayComp, null, null,
					true, SWT.BORDER | SWT.WRAP | SWT.V_SCROLL | SWT.MULTI
							| SWT.H_SCROLL | SWT.READ_ONLY);
			result.configure(new TextSourceViewerConfiguration(EditorsUI
					.getPreferenceStore()));
			result.setDocument(new Document());

			outputText = result.getTextWidget();
			outputText.setEditable(false);
			outputText.setLayoutData(new GridData(GridData.FILL_BOTH));

			Composite writeComp = new Composite(rightSash, SWT.NONE);
			writeComp.setLayout(new FillLayout());
			inputText = new Text(writeComp, SWT.BORDER | SWT.MULTI | SWT.WRAP
					| SWT.V_SCROLL);
			if (keyListener != null)
				inputText.addKeyListener(keyListener);
			rightSash
					.setWeights(new int[] { RATIO_READ_PANE, RATIO_WRITE_PANE });
			if (withParticipantsList) {
				fullChat.setWeights(new int[] { RATIO_PRESENCE_PANE,
						RATIO_READ_WRITE_PANE });
				tabItem.setControl(fullChat);
			} else
				tabItem.setControl(rightSash);

			parent.setSelection(tabItem);

			makeActions();
			hookContextMenu();
		}

		protected void outputClear() {
			if (MessageDialog.openConfirm(null, "Confirm Clear Text Output",
					"Are you sure you want to clear output?")) {
				outputText.setText(""); //$NON-NLS-1$
			}
		}

		protected void outputCopy() {
			String t = outputText.getSelectionText();
			if (t == null || t.length() == 0) {
				outputText.selectAll();
			}
			outputText.copy();
			outputText.setSelection(outputText.getText().length());
		}

		private void fillContextMenu(IMenuManager manager) {
			manager.add(outputCopy);
			manager.add(outputClear);
			manager.add(new Separator());
			manager.add(outputSelectAll);
			manager.add(new Separator("Additions"));
		}

		private void hookContextMenu() {
			MenuManager menuMgr = new MenuManager("#PopupMenu");
			menuMgr.setRemoveAllWhenShown(true);
			menuMgr.addMenuListener(new IMenuListener() {
				public void menuAboutToShow(IMenuManager manager) {
					fillContextMenu(manager);
				}
			});
			Menu menu = menuMgr.createContextMenu(outputText);
			outputText.setMenu(menu);
			ISelectionProvider selectionProvider = new ISelectionProvider() {

				public void addSelectionChangedListener(
						ISelectionChangedListener listener) {
				}

				public ISelection getSelection() {
					ISelection selection = new TextSelection(outputText
							.getSelectionRange().x, outputText
							.getSelectionRange().y);

					return selection;
				}

				public void removeSelectionChangedListener(
						ISelectionChangedListener listener) {
				}

				public void setSelection(ISelection selection) {
					if (selection instanceof ITextSelection) {
						ITextSelection textSelection = (ITextSelection) selection;
						outputText.setSelection(textSelection.getOffset(),
								textSelection.getOffset()
										+ textSelection.getLength());
					}
				}

			};
			getSite().registerContextMenu(menuMgr, selectionProvider);
		}

		private void makeActions() {
			outputSelectAll = new Action() {
				public void run() {
					outputText.selectAll();
				}
			};
			outputSelectAll.setText("Select All");
			outputSelectAll.setToolTipText("Select All");
			outputSelectAll.setAccelerator(SWT.CTRL | 'A');
			outputCopy = new Action() {
				public void run() {
					outputCopy();
				}
			};
			outputCopy.setText("Copy");
			outputCopy.setToolTipText("Copy Selected");
			outputCopy.setAccelerator(SWT.CTRL | 'C');
			outputCopy.setImageDescriptor(PlatformUI.getWorkbench()
					.getSharedImages().getImageDescriptor(
							ISharedImages.IMG_TOOL_COPY));
			outputClear = new Action() {
				public void run() {
					outputClear();
				}
			};
			outputClear.setText("Clear");
			outputClear.setToolTipText("Clear output window");
			outputPaste = new Action() {
				public void run() {
					getRootTextInput().paste();
				}
			};

		}

		protected Text getInputText() {
			return inputText;
		}

		protected void setKeyListener(KeyListener listener) {
			if (listener != null)
				inputText.addKeyListener(listener);
		}

		protected ListViewer getListViewer() {
			return listViewer;
		}

		/**
		 * @return
		 */
		public StyledText getOutputText() {
			return outputText;
		}
	}

	public void createPartControl(Composite parent) {
		otherColor = colorFromRGBString(DEFAULT_OTHER_COLOR);
		systemColor = colorFromRGBString(DEFAULT_SYSTEM_COLOR);
		highlightColor = colorFromRGBString(DEFAULT_HIGHLIGHT_COLOR);
		dateColor = colorFromRGBString(DEFAULT_DATE_COLOR);
		Composite rootComposite = new Composite(parent, SWT.NONE);
		rootComposite.setLayout(new FillLayout());
		boolean useTraditionalTabFolder = PlatformUI
				.getPreferenceStore()
				.getBoolean(
						IWorkbenchPreferenceConstants.SHOW_TRADITIONAL_STYLE_TABS);
		rootTabFolder = new CTabFolder(rootComposite, SWT.NORMAL | SWT.CLOSE);
		rootTabFolder.setUnselectedCloseVisible(false);
		rootTabFolder.setSimple(useTraditionalTabFolder);
		PlatformUI.getPreferenceStore().addPropertyChangeListener(
				new IPropertyChangeListener() {
					public void propertyChange(PropertyChangeEvent event) {
						if (event
								.getProperty()
								.equals(
										IWorkbenchPreferenceConstants.SHOW_TRADITIONAL_STYLE_TABS)
								&& !rootTabFolder.isDisposed()) {
							rootTabFolder.setSimple(((Boolean) event
									.getNewValue()).booleanValue());
							rootTabFolder.redraw();
						}
					}
				});

		rootTabFolder.addCTabFolder2Listener(new CTabFolder2Listener() {
			public void close(CTabFolderEvent event) {
				event.doit = closeTabItem((CTabItem) event.item);
			}

			public void maximize(CTabFolderEvent event) {
			}

			public void minimize(CTabFolderEvent event) {
			}

			public void restore(CTabFolderEvent event) {
			}

			public void showList(CTabFolderEvent event) {
			}
		});
		rootChannelTab = new ChatRoomTab(false, rootTabFolder, hostName,
				new KeyListener() {
					public void keyPressed(KeyEvent evt) {
						handleKeyPressed(evt);
					}

					public void keyReleased(KeyEvent evt) {
						handleKeyReleased(evt);
					}
				});
		setEnabled(false);
		makeActions();
		hookContextMenu();
	}

	private boolean closeTabItem(CTabItem tabItem) {
		ChatRoom chatRoom = findChatRoomForTabItem(tabItem);
		if (chatRoom == null) {
			return false;
		} else {
			if (MessageDialog.openQuestion(getSite().getShell(),
					"Close Chat Room", NLS
							.bind("Close {0}?", tabItem.getText()))) {
				chatRoom.disconnect();
				return true;
			} else
				return false;
		}
	}

	private ChatRoom findChatRoomForTabItem(CTabItem tabItem) {
		for (Iterator i = chatRooms.values().iterator(); i.hasNext();) {
			ChatRoom cr = (ChatRoom) i.next();
			if (tabItem == cr.chatRoomTab.tabItem)
				return cr;
		}
		return null;
	}

	private Text getRootTextInput() {
		return rootChannelTab.getInputText();
	}

	private StyledText getRootTextOutput() {
		return rootChannelTab.getOutputText();
	}

	public void initialize(final IChatRoomViewCloseListener parent,
			final IChatRoomContainer chatRoomContainer,
			final IChatRoomManager chatRoomManager, final ID targetID) {
		Assert.isNotNull(parent);
		Assert.isNotNull(chatRoomContainer);
		Assert.isNotNull(chatRoomManager);
		Assert.isNotNull(targetID);
		ChatRoomManagerView.this.rootChatRoomManager = chatRoomManager;
		ChatRoomManagerView.this.rootCloseListener = parent;
		ChatRoomManagerView.this.rootChatRoomContainer = chatRoomContainer;
		ChatRoomManagerView.this.rootTargetID = targetID;
		ChatRoomManagerView.this.rootMessageSender = chatRoomContainer
				.getChatRoomMessageSender();
		setUsernameAndHost(ChatRoomManagerView.this.rootTargetID);
		ChatRoomManagerView.this.setPartName(userName + USERNAME_HOST_DELIMETER
				+ hostName);
		ChatRoomManagerView.this.setTitleToolTip("Host: " + hostName);
		ChatRoomManagerView.this.rootChannelTab.tabItem.setText(hostName);
		if (chatRoomContainer.getConnectedID() == null)
			initializeControls(targetID);
		setEnabled(false);
	}

	private void initializeControls(ID targetID) {
		// clear text output area
		StyledText outputText = getRootTextOutput();
		if (!outputText.isDisposed())
			outputText.setText(new SimpleDateFormat(
					"EEE, d MMM yyyy HH:mm:ss Z").format(new Date())
					+ "\nConnecting to " + targetID.getName() + "\n\n");
	}

	public void setEnabled(boolean enabled) {
		this.rootEnabled = enabled;
		Text inputText = getRootTextInput();
		if (!inputText.isDisposed())
			inputText.setEnabled(enabled);
	}

	public boolean isEnabled() {
		return rootEnabled;
	}

	protected void clearInput() {
		getRootTextInput().setText(""); //$NON-NLS-1$
	}

	protected void handleCommands(String line, String[] tokens) {
		// Look at first one and switch
		String command = tokens[0];
		while (command.startsWith(COMMAND_PREFIX))
			command = command.substring(1);
		String[] args = new String[tokens.length - 1];
		System.arraycopy(tokens, 1, args, 0, tokens.length - 1);
		if (command.equalsIgnoreCase("QUIT")) {
			cleanUp();
		} else if (command.equalsIgnoreCase("JOIN")) {
			String arg1 = args[0];
			String arg2 = "";
			if (args.length > 1) {
				arg2 = args[1];
			}
			doJoinRoom(arg1, arg2);
		} else
			sendMessageLine(line);
	}

	protected void sendMessageLine(String line) {
		try {
			rootMessageSender.sendMessage(line);
		} catch (ECFException e) {
			// And cut ourselves off
			removeLocalUser();
		}
	}

	public void disconnected() {
		Display.getDefault().asyncExec(new Runnable() {
			public void run() {
				if (rootDisposed)
					return;
				setEnabled(false);
				setPartName("(" + getPartName() + ")");
			}
		});
	}

	protected CTabItem getTabItem(String targetName) {
		CTabItem[] items = rootTabFolder.getItems();
		for (int i = 0; i < items.length; i++) {
			if (items[i].getText().equals(targetName)) {
				return items[i];
			}
		}
		return null;
	}

	protected void doJoinRoom(final String target, final String key) {
		// first, check to see if we already have it open. If so just activate
		ChatRoom room = (ChatRoom) chatRooms.get(target);

		if (room != null && room.isConnected()) {
			room.setSelected();
			return;
		}

		// With manager, first thing we do is get the IChatRoomInfo for the
		// target
		// channel
		IChatRoomInfo roomInfo = rootChatRoomManager.getChatRoomInfo(target);
		// If it's null, we give up
		if (roomInfo == null)
			// no room info for given target...give error message and skip
			return;
		else {
			// Then we create a new chatRoomContainer from the roomInfo
			try {
				final IChatRoomContainer chatRoomContainer = roomInfo
						.createChatRoomContainer();

				// Setup new user interface (new tab)
				final ChatRoom chatroom = new ChatRoom(chatRoomContainer,
						new ChatRoomTab(rootTabFolder, target));
				// setup message listener
				chatRoomContainer.addMessageListener(new IIMMessageListener() {
					public void handleMessageEvent(IIMMessageEvent messageEvent) {
						if (messageEvent instanceof IChatRoomMessageEvent) {
							IChatRoomMessage m = ((IChatRoomMessageEvent) messageEvent)
									.getChatRoomMessage();
							chatroom.handleMessage(m.getFromID(), m
									.getMessage());
						}
					}
				});
				// setup participant listener
				chatRoomContainer
						.addChatRoomParticipantListener(new IChatRoomParticipantListener() {
							public void handlePresenceUpdated(ID fromID,
									IPresence presence) {
								chatroom.handlePresence(fromID, presence);
							}

							public void handleArrived(IUser participant) {
							}

							public void handleUpdated(IUser updatedParticipant) {
							}

							public void handleDeparted(IUser participant) {
							}
						});
				chatRoomContainer.addListener(new IContainerListener() {
					public void handleEvent(IContainerEvent evt) {
						if (evt instanceof IContainerDisconnectedEvent) {
							chatroom.disconnected();
						}
					}
				});
				// Now connect/join
				Display.getDefault().asyncExec(new Runnable() {
					public void run() {
						try {
							chatRoomContainer.connect(IDFactory.getDefault()
									.createID(
											chatRoomContainer
													.getConnectNamespace(),
											target), ConnectContextFactory
									.createPasswordConnectContext(key));
							chatRooms.put(target, chatroom);
						} catch (Exception e) {
							MessageDialog
									.openError(
											getSite().getShell(),
											"Connect Error",
											NLS
													.bind(
															"Could connect to {0}.\n\nError is {1}.",
															target,
															e
																	.getLocalizedMessage()));
						}
					}
				});
			} catch (Exception e) {
				MessageDialog
						.openError(
								getSite().getShell(),
								"Container Create Error",
								NLS
										.bind(
												"Could not create chatRoomContainer for {0}.\n\nError is {1}.",
												target, e.getLocalizedMessage()));
			}
		}
	}

	class ChatRoom implements IChatRoomInvitationListener, KeyListener {

		private IChatRoomContainer chatRoomContainer;

		private ChatRoomTab chatRoomTab;

		private IChatRoomMessageSender chatRoomMessageSender;

		private IUser localUser;

		private ListViewer chatRoomParticipantViewer = null;

		/**
		 * A list of available nicknames for nickname completion via the 'tab'
		 * key.
		 */
		private ArrayList options;

		/**
		 * Denotes the number of options that should be available for the user
		 * to cycle through when pressing the 'tab' key to perform nickname
		 * completion. The default value is set to 5.
		 */
		private int maximumCyclingOptions = 5;

		/**
		 * The length of a nickname's prefix that has already been typed in by
		 * the user. This is used to remove the beginning part of the available
		 * nickname choices.
		 */
		private int prefixLength;

		/**
		 * The index of the next nickname to select from {@link #options}.
		 */
		private int choice = 0;

		/**
		 * The length of the user's nickname that remains resulting from
		 * subtracting the nickname's length from the prefix that the user has
		 * keyed in already.
		 */
		private int nickRemainder;

		/**
		 * The caret position of {@link #inputText} when the user first started
		 * cycling through nickname completion options.
		 */
		private int caret;

		/**
		 * The character to enter after the user's nickname has been
		 * autocompleted. The default value is a colon (':').
		 */
		private char nickCompletionSuffix = ':';

		/**
		 * Indicates whether the user is currently cycling over the list of
		 * nicknames for nickname completion.
		 */
		private boolean isCycling = false;

		/**
		 * Check to see whether the user is currently starting the line of text
		 * with a nickname at the beginning of the message. This determines
		 * whether {@link #nickCompletionSuffix} should be inserted when
		 * performing autocompletion. If the user is not at the beginning of the
		 * message, it is likely that the user is typing another user's name to
		 * reference that person and not to direct the message to said person,
		 * as such, the <code>nickCompletionSuffix</code> does not need to be
		 * appeneded.
		 */
		private boolean isAtStart = false;

		private CTabItem itemSelected = null;

		private Text getInputText() {
			return chatRoomTab.getInputText();
		}

		private StyledText getOutputText() {
			return chatRoomTab.getOutputText();
		}

		ChatRoom(IChatRoomContainer container, ChatRoomTab tabItem) {
			Assert.isNotNull(container);
			Assert.isNotNull(tabItem);
			this.chatRoomContainer = container;
			this.chatRoomMessageSender = container.getChatRoomMessageSender();
			this.chatRoomTab = tabItem;
			chatRoomParticipantViewer = this.chatRoomTab.getListViewer();
			options = new ArrayList();
			this.chatRoomTab.setKeyListener(this);

			rootTabFolder.setUnselectedCloseVisible(true);

			rootTabFolder.addSelectionListener(new SelectionListener() {

				public void widgetDefaultSelected(SelectionEvent e) {
				}

				public void widgetSelected(SelectionEvent e) {
					itemSelected = (CTabItem) e.item;
					if (itemSelected == chatRoomTab.tabItem)
						makeTabItemNormal();
				}
			});
		}

		protected void makeTabItemBold() {
			changeTabItem(true);
		}

		protected void makeTabItemNormal() {
			changeTabItem(false);
		}

		protected void changeTabItem(boolean bold) {
			CTabItem item = chatRoomTab.tabItem;
			Font oldFont = item.getFont();
			FontData[] fd = oldFont.getFontData();
			item.setFont(new Font(oldFont.getDevice(), fd[0].getName(), fd[0]
					.getHeight(), (bold) ? SWT.BOLD : SWT.NORMAL));
		}

		public void handleMessage(final ID fromID, final String messageBody) {
			Display.getDefault().asyncExec(new Runnable() {
				public void run() {
					if (rootDisposed)
						return;
					appendText(getOutputText(), new ChatLine(messageBody,
							new ChatRoomParticipant(fromID)));
					CTabItem item = rootTabFolder.getSelection();
					if (item != chatRoomTab.tabItem)
						makeTabItemBold();
				}
			});
		}

		public void handleInvitationReceived(ID roomID, ID from,
				String subject, String body) {
			System.out.println("invitation room=" + roomID + ",from=" + from
					+ ",subject=" + subject + ",body=" + body);
		}

		public void keyPressed(KeyEvent e) {
			handleKeyPressed(e);
		}

		public void keyReleased(KeyEvent e) {
			handleKeyReleased(e);
		}

		protected void handleKeyPressed(KeyEvent evt) {
			Text inputText = getInputText();
			if (evt.character == SWT.CR) {
				if (inputText.getText().trim().length() > 0)
					handleTextInput(inputText.getText());
				clearInput();
				evt.doit = false;
				isCycling = false;
			} else if (evt.character == SWT.TAB) {
				// don't propogate the event upwards and insert a tab character
				evt.doit = false;
				int pos = inputText.getCaretPosition();
				// if the user is at the beginning of the line, do nothing
				if (pos == 0)
					return;
				String text = inputText.getText();
				// check to see if the user is currently cycling through the
				// available nicknames
				if (isCycling) {
					// if everything's been cycled over, start over at zero
					if (choice == options.size()) {
						choice = 0;
					}
					// cut of the user's nickname based on what's already
					// entered and at a trailing space
					String append = ((String) options.get(choice++))
							.substring(prefixLength)
							+ (isAtStart ? nickCompletionSuffix + " " : " ");
					// add what's been typed along with the next nickname option
					// and the rest of the message
					inputText.setText(text.substring(0, caret) + append
							+ text.substring(caret + nickRemainder));
					nickRemainder = append.length();
					// set the caret position to be the place where the nickname
					// completion ended
					inputText.setSelection(caret + nickRemainder, caret
							+ nickRemainder);
				} else {
					// the user is not cycling, so we need to identify what the
					// user has typed based on the current caret position
					int count = pos - 1;
					// keep looping until the whitespace has been identified or
					// the beginning of the message has been reached
					while (count > -1
							&& !Character.isWhitespace(text.charAt(count))) {
						count--;
					}
					count++;
					// remove all previous options
					options.clear();
					// get the prefix that the user typed
					String prefix = text.substring(count, pos);
					isAtStart = count == 0;
					// if what's found was actually whitespace, do nothing
					if (prefix.trim().equals("")) { //$NON-NLS-1$
						return;
					}
					// get all of the users in this room and store them if they
					// start with the prefix that the user has typed
					String[] participants = chatRoomParticipantViewer.getList()
							.getItems();
					for (int i = 0; i < participants.length; i++) {
						if (participants[i].startsWith(prefix)) {
							options.add(participants[i]);
						}
					}

					// simply return if no matches have been found
					if (options.isEmpty())
						return;

					prefixLength = prefix.length();
					if (options.size() == 1) {
						String nickname = (String) options.get(0);
						// since only one nickname is available, simply insert
						// it after truncating the prefix
						nickname = nickname.substring(prefixLength);
						inputText
								.insert(nickname
										+ (isAtStart ? nickCompletionSuffix
												+ " " : " "));
					} else if (options.size() <= maximumCyclingOptions) {
						// note that the user is currently cycling through
						// options and also store the current caret position
						isCycling = true;
						caret = pos;
						choice = 0;
						// insert the nickname after removing the prefix
						String nickname = options.get(choice++)
								+ (isAtStart ? nickCompletionSuffix + " " : " ");
						nickname = nickname.substring(prefixLength);
						inputText.insert(nickname);
						// store the length of this truncated nickname so that
						// it can be removed when the user is cycling
						nickRemainder = nickname.length();
					} else {
						// as there are too many choices for the user to pick
						// from, simply display all of the available ones on the
						// chat window so that the user can get a visual
						// indicator of what's available and narrow down the
						// choices by typing a few more additional characters
						StringBuffer choices = new StringBuffer();
						synchronized (choices) {
							for (int i = 0; i < options.size(); i++) {
								choices.append(options.get(i)).append(' ');
							}
							choices.delete(choices.length() - 1, choices
									.length());
						}
						appendText(getOutputText(), new ChatLine(choices
								.toString()));
					}
				}
			} else {
				// remove the cycling marking for any other key pressed
				isCycling = false;
			}
		}

		protected void handleKeyReleased(KeyEvent evt) {
			if (evt.character == SWT.TAB) {
				// don't move to the next widget or try to add tabs
				evt.doit = false;
			}
		}

		protected void handleTextInput(String text) {
			if (chatRoomMessageSender == null) {
				MessageDialog.openError(getViewSite().getShell(),
						"Not connect", "Not connected to channel room");
				return;
			} else
				handleInputLine(text);
		}

		protected void handleInputLine(String line) {
			if ((line != null && line.startsWith(COMMAND_PREFIX))) {
				StringTokenizer st = new StringTokenizer(line, COMMAND_DELIM);
				int countTokens = st.countTokens();
				String toks[] = new String[countTokens];
				for (int i = 0; i < countTokens; i++) {
					toks[i] = st.nextToken();
				}
				String[] tokens = toks;
				handleCommands(line, tokens);
			} else
				sendMessageLine(line);
		}

		protected void handleCommands(String line, String[] tokens) {
			// Look at first one and switch
			String command = tokens[0];
			while (command.startsWith(COMMAND_PREFIX))
				command = command.substring(1);
			String[] args = new String[tokens.length - 1];
			System.arraycopy(tokens, 1, args, 0, tokens.length - 1);
			if (command.equalsIgnoreCase("QUIT")) {
				cleanUp();
			} else if (command.equalsIgnoreCase("PART")) {
				disconnect();
			} else {
				sendMessageLine(line);
			}
		}

		protected void disconnect() {
			if (chatRoomContainer != null)
				chatRoomContainer.disconnect();
		}

		protected void clearInput() {
			getInputText().setText(""); //$NON-NLS-1$
		}

		protected void sendMessageLine(String line) {
			try {
				chatRoomMessageSender.sendMessage(line);
			} catch (ECFException e) {
				disconnected();
			}
		}

		public void handlePresence(final ID fromID, final IPresence presence) {
			Display.getDefault().asyncExec(new Runnable() {
				public void run() {
					if (rootDisposed)
						return;
					boolean isAdd = presence.getType().equals(
							IPresence.Type.AVAILABLE);
					ChatRoomParticipant p = new ChatRoomParticipant(fromID);
					if (isAdd) {
						if (localUser == null)
							localUser = p;
						addParticipant(p);
					} else
						removeParticipant(p);
				}
			});
		}

		public void disconnected() {
			Display.getDefault().asyncExec(new Runnable() {
				public void run() {
					if (rootDisposed)
						return;
					Text inputText = getInputText();
					if (!inputText.isDisposed())
						inputText.setEnabled(false);
				}
			});
		}

		protected boolean isConnected() {
			Text inputText = getInputText();
			return !inputText.isDisposed() && inputText.isEnabled();
		}

		protected void setSelected() {
			rootTabFolder.setSelection(chatRoomTab.tabItem);
		}

		protected void addParticipant(IUser p) {
			if (p != null) {
				ID id = p.getID();
				if (id != null) {
					appendText(getOutputText(), new ChatLine("("
							+ getDateTime() + ") " + trimUserID(id)
							+ " entered", null));
					chatRoomParticipantViewer.add(p);
				}
			}
		}

		protected boolean isLocalUser(ID id) {
			if (localUser == null)
				return false;
			else if (localUser.getID().equals(id))
				return true;
			else
				return false;
		}

		protected void removeLocalUser() {
			// It's us that's gone away... so we're outta here
			String title = getPartName();
			setPartName("(" + title + ")");
			removeAllParticipants();
			cleanUp();
			setEnabled(false);
		}

		protected void removeParticipant(IUser p) {
			if (p != null) {
				ID id = p.getID();
				if (id != null) {
					appendText(getOutputText(), new ChatLine("("
							+ getDateTime() + ") " + trimUserID(id) + " left",
							null));
					chatRoomParticipantViewer.remove(p);
				}
			}
		}

		protected void removeAllParticipants() {
			org.eclipse.swt.widgets.List l = chatRoomParticipantViewer
					.getList();
			for (int i = 0; i < l.getItemCount(); i++) {
				Object o = chatRoomParticipantViewer.getElementAt(i);
				if (o != null)
					chatRoomParticipantViewer.remove(o);
			}
		}
	}

	protected void handleInputLine(String line) {
		if ((line != null && line.startsWith(COMMAND_PREFIX))) {
			StringTokenizer st = new StringTokenizer(line, COMMAND_DELIM);
			int countTokens = st.countTokens();
			String toks[] = new String[countTokens];
			for (int i = 0; i < countTokens; i++) {
				toks[i] = st.nextToken();
			}
			String[] tokens = toks;
			handleCommands(line, tokens);
		} else
			sendMessageLine(line);
	}

	protected void handleTextInput(String text) {
		if (rootMessageSender == null) {
			MessageDialog.openError(getViewSite().getShell(), "Not connect",
					"Not connected to chat room");
			return;
		} else
			handleInputLine(text);
	}

	protected void handleEnter() {
		Text inputText = getRootTextInput();
		if (inputText.getText().trim().length() > 0)
			handleTextInput(inputText.getText());
		clearInput();
	}

	protected void handleKeyPressed(KeyEvent evt) {
		if (evt.character == SWT.CR) {
			handleEnter();
			evt.doit = false;
		}
	}

	protected void handleKeyReleased(KeyEvent evt) {
	}

	public void setFocus() {
		getRootTextInput().setFocus();
	}

	protected void setUsernameAndHost(ID chatHostID) {
		URI uri = null;
		try {
			uri = new URI(chatHostID.getName());
			String tmp = uri.getUserInfo();
			if (tmp != null)
				userName = tmp;
			tmp = uri.getHost();
			if (tmp != null)
				hostName = tmp;
		} catch (URISyntaxException e) {
		}
	}

	public void joinRoom(final String room) {
		if (room != null)
			Display.getDefault().syncExec(new Runnable() {
				public void run() {
					if (rootDisposed)
						return;
					doJoinRoom(room, null);
				}
			});
	}

	public void dispose() {
		rootDisposed = true;
		cleanUp();
		super.dispose();
	}

	protected String getMessageString(ID fromID, String text) {
		return fromID.getName() + ": " + text + "\n";
	}

	public void handleMessage(final ID fromID, final String messageBody) {
		Display.getDefault().asyncExec(new Runnable() {
			public void run() {
				if (rootDisposed)
					return;
				appendText(getRootTextOutput(), new ChatLine(messageBody,
						new ChatRoomParticipant(fromID)));
			}
		});
	}

	private String trimUserID(ID userID) {
		try {
			URI uri = new URI(userID.getName());
			String user = uri.getUserInfo();
			return user == null ? userID.getName() : user;
		} catch (URISyntaxException e) {
			String userAtHost = userID.getName();
			int atIndex = userAtHost.lastIndexOf(USERNAME_HOST_DELIMETER);
			if (atIndex != -1) {
				userAtHost = userAtHost.substring(0, atIndex);
			}
			return userAtHost;
		}
	}

	class ChatRoomParticipant implements IUser {
		private static final long serialVersionUID = 2008114088656711572L;

		ID id;

		public ChatRoomParticipant(ID id) {
			this.id = id;
		}

		public ID getID() {
			return id;
		}

		public String getName() {
			return toString();
		}

		public boolean equals(Object other) {
			if (!(other instanceof ChatRoomParticipant))
				return false;
			ChatRoomParticipant o = (ChatRoomParticipant) other;
			if (id.equals(o.id))
				return true;
			return false;
		}

		public int hashCode() {
			return id.hashCode();
		}

		public String toString() {
			return trimUserID(id);
		}

		public Map getProperties() {
			return null;
		}

		public Object getAdapter(Class adapter) {
			return null;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see org.eclipse.ecf.core.user.IUser#getNickname()
		 */
		public String getNickname() {
			return getName();
		}
	}

	protected String getCurrentDate(String format) {
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		String res = sdf.format(new Date());
		return res;
	}

	protected String getDateTime() {
		StringBuffer buf = new StringBuffer();
		buf.append(getCurrentDate(DEFAULT_DATE_FORMAT)).append(" ").append(
				getCurrentDate(DEFAULT_TIME_FORMAT));
		return buf.toString();
	}

	protected void cleanUp() {
		if (rootCloseListener != null) {
			if (rootTargetID == null)
				rootCloseListener.chatRoomViewClosing(null);
			else
				rootCloseListener.chatRoomViewClosing(rootTargetID.getName());
			rootCloseListener = null;
			rootChatRoomContainer = null;
			rootMessageSender = null;
		}
	}

	protected void removeLocalUser() {
		// It's us that's gone away... so we're outta here
		String title = getPartName();
		setPartName("(" + title + ")");
		cleanUp();
		setEnabled(false);
	}

	public void handleInvitationReceived(ID roomID, ID from, String subject,
			String body) {
		System.out.println("invitation room=" + roomID + ",from=" + from
				+ ",subject=" + subject + ",body=" + body);
	}

	private boolean intelligentAppend(StyledText st, ChatLine text) {
		String line = text.getText();

		int startRange = st.getText().length();
		StringBuffer sb = new StringBuffer();
		// check to see if the message has the user's name contained within
		boolean nickContained = text.getText().indexOf(userName) != -1;
		if (text.getOriginator() != null) {
			// check to make sure that the person referring to the user's name
			// is not the user himself, no highlighting is required in this case
			// as the user is already aware that his name is being referenced
			nickContained = !text.getOriginator().getName().equals(userName)
					&& nickContained;
			sb.append('(').append(getCurrentDate(DEFAULT_TIME_FORMAT)).append(
					") "); //$NON-NLS-1$
			StyleRange dateStyle = new StyleRange();
			dateStyle.start = startRange;
			dateStyle.length = sb.length();
			dateStyle.foreground = dateColor;
			dateStyle.fontStyle = SWT.NORMAL;
			st.append(sb.toString());
			st.setStyleRange(dateStyle);
			sb = new StringBuffer();
			sb.append(text.getOriginator().getName()).append(": "); //$NON-NLS-1$
			StyleRange sr = new StyleRange();
			sr.start = startRange + dateStyle.length;
			sr.length = sb.length();
			sr.fontStyle = SWT.BOLD;
			// check to see which color should be used
			sr.foreground = nickContained ? highlightColor : otherColor;
			st.append(sb.toString());
			st.setStyleRange(sr);
		}

		if (line != null && !line.equals("")) { //$NON-NLS-1$
			int beforeMessageIndex = st.getText().length();
			st.append(line);
			if (text.getOriginator() == null) {
				StyleRange sr = new StyleRange();
				sr.start = beforeMessageIndex;
				sr.length = line.length();
				sr.foreground = systemColor;
				sr.fontStyle = SWT.BOLD;
				st.setStyleRange(sr);
			} else if (nickContained) {
				// highlight the message itself as necessary
				StyleRange sr = new StyleRange();
				sr.start = beforeMessageIndex;
				sr.length = line.length();
				sr.foreground = highlightColor;
				st.setStyleRange(sr);
			}
		}

		if (!text.isNoCRLF()) {
			st.append("\n"); //$NON-NLS-1$
		}

		String t = st.getText();
		if (t == null)
			return true;
		st.setSelection(t.length());

		return true;
	}

	protected void appendText(StyledText readText, ChatLine text) {
		if (readText == null || text == null) {
			return;
		}
		StyledText st = readText;
		if (st == null || intelligentAppend(st, text)) {
			return;
		}
		int startRange = st.getText().length();
		StringBuffer sb = new StringBuffer();
		// check to see if the message has the user's name contained within
		boolean nickContained = text.getText().indexOf(userName) != -1;
		if (text.getOriginator() != null) {
			// check to make sure that the person referring to the user's name
			// is not the user himself, no highlighting is required in this case
			// as the user is already aware that his name is being referenced
			nickContained = !text.getOriginator().getName().equals(userName)
					&& nickContained;
			sb.append("(").append(getCurrentDate(DEFAULT_TIME_FORMAT)).append(
					") ");
			StyleRange dateStyle = new StyleRange();
			dateStyle.start = startRange;
			dateStyle.length = sb.length();
			dateStyle.foreground = dateColor;
			dateStyle.fontStyle = SWT.NORMAL;
			st.append(sb.toString());
			st.setStyleRange(dateStyle);
			sb = new StringBuffer();
			sb.append(text.getOriginator().getName()).append(": ");
			StyleRange sr = new StyleRange();
			sr.start = startRange + dateStyle.length;
			sr.length = sb.length();
			sr.fontStyle = SWT.BOLD;
			// check to see which color should be used
			sr.foreground = nickContained ? highlightColor : otherColor;
			st.append(sb.toString());
			st.setStyleRange(sr);
		}
		int beforeMessageIndex = st.getText().length();
		st.append(text.getText());
		if (text.getOriginator() == null) {
			StyleRange sr = new StyleRange();
			sr.start = beforeMessageIndex;
			sr.length = text.getText().length();
			sr.foreground = systemColor;
			sr.fontStyle = SWT.BOLD;
			st.setStyleRange(sr);
		} else if (nickContained) {
			// highlight the message itself as necessary
			StyleRange sr = new StyleRange();
			sr.start = beforeMessageIndex;
			sr.length = text.getText().length();
			sr.foreground = highlightColor;
			st.setStyleRange(sr);
		}
		if (!text.isNoCRLF()) {
			st.append("\n");
		}
		String t = st.getText();
		if (t == null)
			return;
		st.setSelection(t.length());
		// Bold title if view is not visible.
		IWorkbenchSiteProgressService pservice = (IWorkbenchSiteProgressService) this
				.getSite().getAdapter(IWorkbenchSiteProgressService.class);
		pservice.warnOfContentChange();
	}

	protected void outputClear() {
		if (MessageDialog.openConfirm(null, "Confirm Clear Text Output",
				"Are you sure you want to clear output?")) {
			getRootTextOutput().setText(""); //$NON-NLS-1$
		}
	}

	protected void outputCopy() {
		StyledText outputText = getRootTextOutput();
		String t = outputText.getSelectionText();
		if (t == null || t.length() == 0) {
			outputText.selectAll();
		}
		outputText.copy();
		outputText.setSelection(outputText.getText().length());
	}

	protected void outputSelectAll() {
		getRootTextOutput().selectAll();
	}

	protected void makeActions() {
		outputSelectAll = new Action() {
			public void run() {
				outputSelectAll();
			}
		};
		outputSelectAll.setText("Select All");
		outputSelectAll.setToolTipText("Select All");
		outputSelectAll.setAccelerator(SWT.CTRL | 'A');
		outputCopy = new Action() {
			public void run() {
				outputCopy();
			}
		};
		outputCopy.setText("Copy");
		outputCopy.setToolTipText("Copy Selected");
		outputCopy.setAccelerator(SWT.CTRL | 'C');
		outputCopy.setImageDescriptor(PlatformUI.getWorkbench()
				.getSharedImages().getImageDescriptor(
						ISharedImages.IMG_TOOL_COPY));
		outputClear = new Action() {
			public void run() {
				outputClear();
			}
		};
		outputClear.setText("Clear");
		outputClear.setToolTipText("Clear output window");
		outputPaste = new Action() {
			public void run() {
				getRootTextInput().paste();
			}
		};
		outputPaste.setText("Paste");
		outputPaste.setToolTipText("Paste");
		outputPaste.setAccelerator(SWT.CTRL | 'V');
		outputPaste.setImageDescriptor(PlatformUI.getWorkbench()
				.getSharedImages().getImageDescriptor(
						ISharedImages.IMG_TOOL_PASTE));
	}

	private void fillContextMenu(IMenuManager manager) {
		manager.add(outputCopy);
		manager.add(outputPaste);
		manager.add(outputClear);
		manager.add(new Separator());
		manager.add(outputSelectAll);
		manager.add(new Separator("Additions"));
	}

	private void hookContextMenu() {
		MenuManager menuMgr = new MenuManager("#PopupMenu");
		menuMgr.setRemoveAllWhenShown(true);
		menuMgr.addMenuListener(new IMenuListener() {
			public void menuAboutToShow(IMenuManager manager) {
				fillContextMenu(manager);
			}
		});
		StyledText outputText = getRootTextOutput();
		Menu menu = menuMgr.createContextMenu(outputText);
		outputText.setMenu(menu);
		ISelectionProvider selectionProvider = new ISelectionProvider() {

			public void addSelectionChangedListener(
					ISelectionChangedListener listener) {
			}

			public ISelection getSelection() {
				StyledText outputText = getRootTextOutput();
				ISelection selection = new TextSelection(outputText
						.getSelectionRange().x,
						outputText.getSelectionRange().y);

				return selection;
			}

			public void removeSelectionChangedListener(
					ISelectionChangedListener listener) {
			}

			public void setSelection(ISelection selection) {
				StyledText outputText = getRootTextOutput();
				if (selection instanceof ITextSelection) {
					ITextSelection textSelection = (ITextSelection) selection;
					outputText.setSelection(textSelection.getOffset(),
							textSelection.getOffset()
									+ textSelection.getLength());
				}
			}

		};
		getSite().registerContextMenu(menuMgr, selectionProvider);
	}

	private Color colorFromRGBString(String rgb) {
		Color color = null;
		if (rgb == null || rgb.equals("")) {
			color = new Color(getViewSite().getShell().getDisplay(), 0, 0, 0);
			return color;
		}
		if (color != null) {
			color.dispose();
		}
		StringTokenizer st = new StringTokenizer(rgb,",");
		String [] vals = new String [3];
		for(int i=0; i < 3; i++) {
			vals[i] = st.nextToken();
		}
		color = new Color(getViewSite().getShell().getDisplay(), Integer
				.parseInt(vals[0]), Integer.parseInt(vals[1]), Integer
				.parseInt(vals[2]));
		return color;
	}
}

Back to the top