Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: fd137420ff74404639ba67aca47936c16a8fe6dd (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
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
/*******************************************************************************
 * Copyright (C) 2008, Marek Zawirski <marek.zawirski@gmail.com>
 *
 * 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
 *******************************************************************************/
package org.eclipse.egit.ui.internal.components;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Pattern;

import org.eclipse.egit.ui.Activator;
import org.eclipse.egit.ui.UIIcons;
import org.eclipse.egit.ui.UIText;
import org.eclipse.jface.fieldassist.ComboContentAdapter;
import org.eclipse.jface.fieldassist.ContentProposalAdapter;
import org.eclipse.jface.fieldassist.ControlDecoration;
import org.eclipse.jface.fieldassist.FieldDecorationRegistry;
import org.eclipse.jface.fieldassist.IContentProposal;
import org.eclipse.jface.fieldassist.IContentProposalListener;
import org.eclipse.jface.fieldassist.IContentProposalProvider;
import org.eclipse.jface.fieldassist.TextContentAdapter;
import org.eclipse.jface.layout.TableColumnLayout;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.CheckboxCellEditor;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.ColumnViewerToolTipSupport;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.EditingSupport;
import org.eclipse.jface.viewers.IElementComparer;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.transport.FetchConnection;
import org.eclipse.jgit.transport.RefSpec;
import org.eclipse.jgit.transport.RemoteConfig;
import org.eclipse.jgit.transport.Transport;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.TraverseEvent;
import org.eclipse.swt.events.TraverseListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.fieldassist.ContentAssistCommandAdapter;

/**
 * This class provides universal panel for editing list of {@link RefSpec} -
 * specifications for both push or fetch, depending on panel configuration.
 * <p>
 * It is intended to allow user easily edit specifications, supporting user with
 * content assistant and giving feedback with error information as soon as
 * possible. Component uses editable specifications table and panels for easy
 * creation of new specifications basing on typical push/fetch schemes (like
 * branch update, deletion, all branches update, saved configuration etc.).
 * <p>
 * The model of specifications list behind panel is accessible by public methods
 * - giving both read and write access. Listener interface for handling changes
 * in model is provided by {@link SelectionChangeListener}.
 * <p>
 * Typical class usage:
 *
 * <pre>
 * // create panel for editing push-specifications
 * RefSpecPanel panel = new RefSpecPanel(parent, true);
 * // register model listener
 * panel.addRefSpecPanelListener(listener);
 *
 * // provide information about local and remote refs
 * panel.setRefsData(localRepo, remoteRefs, remoteName);
 *
 * // get result data
 * List&lt;RefSpec&gt; result = panel.getRefSpecs();
 * // further processing: push or save configuration...
 * </pre>
 *
 * @see SelectionChangeListener
 */
public class RefSpecPanel {
	private static final String IMAGE_ADD = "ADD"; //$NON-NLS-1$

	private static final String IMAGE_DELETE = "DELETE"; //$NON-NLS-1$

	private static final String IMAGE_TRASH = "TRASH"; //$NON-NLS-1$

	private static final String IMAGE_CLEAR = "CLEAR"; //$NON-NLS-1$

	private static final int TABLE_PREFERRED_HEIGHT = 165;

	private static final int TABLE_PREFERRED_WIDTH = 560;

	private static final int COLUMN_MODE_WEIGHT = 23;

	private static final int COLUMN_SRC_WEIGHT = 40;

	private static final int COLUMN_DST_WEIGHT = 40;

	private static final int COLUMN_FORCE_WEIGHT = 30;

	private static final int COLUMN_REMOVE_WEIGHT = 20;

	private static boolean isDeleteRefSpec(final Object element) {
		return ((RefSpec) element).getSource() == null;
	}

	private static boolean isValidRefExpression(final String s) {
		if (RefSpec.isWildcard(s)) {
			// replace wildcard with some legal name just for checking
			return Repository
					.isValidRefName(s.substring(0, s.length() - 1) + 'X');
		} else
			return Repository.isValidRefName(s);
	}

	private static RefSpec setRefSpecSource(final RefSpec spec, final String src) {
		final String dst;
		if (RefSpec.isWildcard(src))
			dst = wildcardSpecComponent(spec.getDestination());
		else
			dst = unwildcardSpecComponent(spec.getDestination(), src);
		return spec.setSourceDestination(src, dst);
	}

	private static RefSpec setRefSpecDestination(final RefSpec spec,
			final String dst) {
		final String src;
		if (RefSpec.isWildcard(dst))
			src = wildcardSpecComponent(spec.getSource());
		else
			src = unwildcardSpecComponent(spec.getSource(), dst);
		return spec.setSourceDestination(src, dst);
	}

	private static String wildcardSpecComponent(final String comp) {
		final int i;
		if (RefSpec.isWildcard(comp))
			return comp;
		if (comp == null || (i = comp.lastIndexOf('/')) == -1) {
			// That's somewhat ugly. What better can we do here?
			return UIText.RefSpecPanel_refChooseSomeWildcard;
		}
		return comp.substring(0, i + 1) + '*';
	}

	private static String unwildcardSpecComponent(final String comp,
			final String other) {
		if (!RefSpec.isWildcard(comp))
			return comp;
		if (other == null || other.length() == 0)
			return ""; //$NON-NLS-1$
		final int i = other.lastIndexOf('/');
		return comp.substring(0, comp.length() - 1) + other.substring(i + 1);
	}

	private static List<RefContentProposal> createProposalsFilteredRemote(
			final List<RefContentProposal> proposals) {
		final List<RefContentProposal> result = new ArrayList<RefContentProposal>();
		for (final RefContentProposal p : proposals) {
			final String content = p.getContent();
			if (content.equals(Constants.HEAD)
					|| content.startsWith(Constants.R_HEADS))
				result.add(p);
		}
		return result;
	}

	private static Image getDecorationImage(final String key) {
		return FieldDecorationRegistry.getDefault().getFieldDecoration(key)
				.getImage();
	}

	private static void setControlDecoration(final ControlDecoration control,
			final String imageKey, final String description) {
		control.setImage(getDecorationImage(imageKey));
		control.setDescriptionText(description);
		control.show();
	}

	private final List<RefSpec> specs = new ArrayList<RefSpec>();

	private final Composite panel;

	private TableViewer tableViewer;

	private CellEditor modeCellEditor;

	private CellEditor localRefCellEditor;

	private CellEditor remoteRefCellEditor;

	private CellEditor forceUpdateCellEditor;

	private CellEditor removeSpecCellEditor;

	private int srcColumnIndex;

	private Button removeAllSpecButton;

	private Button forceUpdateAllButton;

	private Button creationButton;

	private Button addConfiguredButton;

	private Button addTagsButton;

	private Button addBranchesButton;

	private ControlDecoration creationSrcDecoration;

	private ControlDecoration creationDstDecoration;

	private ControlDecoration deleteRefDecoration;

	private Combo creationSrcCombo;

	private Combo creationDstCombo;

	private Combo deleteRefCombo;

	private Button deleteButton;

	private Repository localDb;

	private RemoteConfig remoteConfig;

	private Set<String> localRefNames = Collections.emptySet();

	private Set<String> remoteRefNames = Collections.emptySet();

	private List<RefSpec> predefinedConfigured = Collections.emptyList();

	private RefSpec predefinedBranches = null;

	private final RefContentProposalProvider remoteProposalProvider;

	private final RefContentProposalProvider localProposalProvider;

	private ComboLabelingSupport creationSrcComboSupport;

	private ComboLabelingSupport creationDstComboSupport;

	private ComboLabelingSupport deleteRefComboSupport;

	private final boolean pushSpecs;

	private final List<SelectionChangeListener> listeners = new LinkedList<SelectionChangeListener>();

	private final ImageRegistry imageRegistry;

	private boolean matchingAnyRefs;

	private RefSpec invalidSpec;

	private RefSpec invalidSpecSameDst;

	private String errorMessage;

	private Color errorBackgroundColor;

	private Color errorTextColor;

	/**
	 * Create a new panel and install it on a provided composite. Panel is
	 * created either for editing push or fetch specifications - this setting
	 * can't be changed later, after constructing object.
	 * <p>
	 * Panel is created with an empty model, with no provided assistant. It
	 * can't be used by user until
	 * {@link #setAssistanceData(Repository, Collection, RemoteConfig)} method is
	 * called, and to this time is disabled.
	 *
	 * @param parent
	 *            parent control for panel.
	 * @param pushSpecs
	 *            true if panel is used for editing push specifications, false
	 *            if panel is used for editing fetch specifications.
	 */
	public RefSpecPanel(final Composite parent, final boolean pushSpecs) {
		this.pushSpecs = pushSpecs;
		this.localProposalProvider = new RefContentProposalProvider(pushSpecs);
		this.remoteProposalProvider = new RefContentProposalProvider(false);
		this.imageRegistry = new ImageRegistry(parent.getDisplay());

		panel = new Composite(parent, SWT.NONE);
		panel.setLayout(new GridLayout());

		safeCreateResources();

		createCreationPanel();
		if (pushSpecs)
			createDeleteCreationPanel();
		createPredefinedCreationPanel();
		createTableGroup();

		addRefSpecTableListener(new SelectionChangeListener() {
			public void selectionChanged() {
				validateSpecs();
			}
		});
		setEnable(false);
	}

	/**
	 * Enable or disable panel controls.
	 *
	 * @param enable
	 *            true to enable panel, false to disable.
	 */
	public void setEnable(final boolean enable) {
		getControl().setEnabled(enable);
	}

	/**
	 * Set information needed for assisting user with entering data and
	 * validating user input. This method automatically enables the panel.
	 *
	 * @param localRepo
	 *            local repository where specifications will be applied.
	 * @param remoteRefs
	 *            collection of remote refs as advertised by remote repository.
	 *            Typically they are collected by {@link FetchConnection}
	 *            implementation.
	 * @param config
	 */
	public void setAssistanceData(final Repository localRepo,
			final Collection<Ref> remoteRefs, RemoteConfig config) {
		this.localDb = localRepo;
        this.remoteConfig = config;
		final List<RefContentProposal> remoteProposals = createContentProposals(
				remoteRefs, null);
		remoteProposalProvider.setProposals(remoteProposals);
		remoteRefNames = new HashSet<String>();
		for (final RefContentProposal p : remoteProposals)
			remoteRefNames.add(p.getContent());

		Ref HEAD = null;
		try {
			HEAD = localDb.getRef(Constants.HEAD);
		} catch (IOException e) {
			Activator.logError("Couldn't read HEAD from local repository", e); //$NON-NLS-1$
		}
		final List<RefContentProposal> localProposals = createContentProposals(
				localDb.getAllRefs().values(), HEAD);
		localProposalProvider.setProposals(localProposals);
		localRefNames = new HashSet<String>();
		for (final RefContentProposal ref : localProposals)
			localRefNames.add(ref.getContent());

		final List<RefContentProposal> localFilteredProposals = createProposalsFilteredLocal(localProposals);
		final List<RefContentProposal> remoteFilteredProposals = createProposalsFilteredRemote(remoteProposals);

		if (pushSpecs) {
			creationSrcComboSupport.setProposals(localFilteredProposals);
			creationDstComboSupport.setProposals(remoteFilteredProposals);
		} else {
			creationSrcComboSupport.setProposals(remoteFilteredProposals);
			creationDstComboSupport.setProposals(localFilteredProposals);
		}
		validateCreationPanel();

		if (pushSpecs) {
			deleteRefComboSupport.setProposals(remoteFilteredProposals);
			validateDeleteCreationPanel();
		}

		if (remoteConfig == null)
			predefinedConfigured = Collections.emptyList();
		else {
			if (pushSpecs)
				predefinedConfigured = remoteConfig.getPushRefSpecs();
			else
				predefinedConfigured = remoteConfig.getFetchRefSpecs();
			for (final RefSpec spec : predefinedConfigured)
				addRefSpec(spec);
		}

		updateAddPredefinedButton(addConfiguredButton, predefinedConfigured);
		if (pushSpecs)
			predefinedBranches = Transport.REFSPEC_PUSH_ALL;
		else {
			final String r;
			if (remoteConfig == null)
				r = UIText.RefSpecPanel_refChooseRemoteName;
			else
				r = remoteConfig.getName();
			predefinedBranches = new RefSpec("refs/heads/*:refs/remotes/" //$NON-NLS-1$
					+ r + "/*"); //$NON-NLS-1$
		}
		updateAddPredefinedButton(addBranchesButton, predefinedBranches);
		setEnable(true);
	}

	/**
	 * @return underlying control for this panel.
	 */
	public Control getControl() {
		return panel;
	}

	/**
	 * Return current list of specifications of this panel.
	 * <p>
	 * This method should be called only from the UI thread.
	 *
	 * @return unmodifiable view of specifications list as edited by user in
	 *         this panel. Note that this view underlying model may change -
	 *         create a copy if needed.
	 */
	public List<RefSpec> getRefSpecs() {
		return Collections.unmodifiableList(specs);
	}

	/**
	 * @return true if specifications list is empty, false otherwise.
	 */
	public boolean isEmpty() {
		return getRefSpecs().isEmpty();
	}

	/**
	 * @return true if specifications match any ref(s) in source repository -
	 *         resolve to concrete ref updates, false otherwise. For non empty
	 *         specifications list, false value is possible only in case of
	 *         specifications with wildcards.
	 */
	public boolean isMatchingAnyRefs() {
		return matchingAnyRefs;
	}

	/**
	 * Add provided specification to this panel. Panel view is automatically
	 * refreshed, model is revalidated.
	 * <p>
	 * Note that the same reference can't be added twice to the panel, while two
	 * or more equals RefSpec (in terms of equals method) can be - likely
	 * causing validation error.
	 * <p>
	 * This method should be called only from the UI thread.
	 *
	 * @param spec
	 *            specification to add.
	 * @throws IllegalArgumentException
	 *             if specification with same reference already exists in panel.
	 */
	public void addRefSpec(final RefSpec spec) {
		final int i = indexOfSpec(spec);
		if (i != -1)
			throw new IllegalArgumentException("RefSpec " + spec //$NON-NLS-1$
					+ " already exists."); //$NON-NLS-1$
		specs.add(spec);
		tableViewer.add(spec);
		notifySpecsChanged();
	}

	/**
	 * Remove provided specification from this panel. Panel view is
	 * automatically refreshed, model is revalidated.
	 * <p>
	 * Provided specification must be equals with existing one in terms of
	 * reference equality, not an equals method.
	 * <p>
	 * This method should be called only from the UI thread.
	 *
	 * @param spec
	 *            specification to remove.
	 * @throws IllegalArgumentException
	 *             if specification with this reference doesn't exist in this
	 *             panel.
	 */
	public void removeRefSpec(final RefSpec spec) {
		final int i = indexOfSpec(spec);
		if (i == -1)
			throw new IllegalArgumentException("RefSpec " + spec //$NON-NLS-1$
					+ " not found."); //$NON-NLS-1$
		specs.remove(i);
		tableViewer.remove(spec);
		notifySpecsChanged();
	}

	/**
	 * Change some specification to the new one.
	 * <p>
	 * Old specification must exist in the panel, while new specification can't
	 * exist before (both in terms of reference equality).
	 * <p>
	 * This method should be called only from the UI thread.
	 *
	 * @param oldSpec
	 *            specification to change. Can't be null.
	 * @param newSpec
	 *            new specification to override existing one. Can't be null.
	 */
	public void setRefSpec(final RefSpec oldSpec, final RefSpec newSpec) {
		final int oldI = indexOfSpec(oldSpec);
		if (oldI == -1)
			throw new IllegalArgumentException("RefSpec " + oldSpec //$NON-NLS-1$
					+ " not found."); //$NON-NLS-1$
		final int newI = indexOfSpec(newSpec);
		if (newI != -1)
			throw new IllegalArgumentException("RefSpec " + newSpec //$NON-NLS-1$
					+ " already exists."); //$NON-NLS-1$
		specs.set(oldI, newSpec);

		// have to refresh whole table as we are operating on immutable objects
		// (this shouldn't be an issue)
		tableViewer.refresh();
		notifySpecsChanged();
	}

	/**
	 * Clear all specifications from this panel.
	 * <p>
	 * This method should be called only from the UI thread.
	 */
	public void clearRefSpecs() {
		final RefSpec toRemove[] = specs.toArray(new RefSpec[0]);
		specs.clear();
		tableViewer.remove(toRemove);
		notifySpecsChanged();
	}

	/**
	 * Add listener of changes in panel model.
	 * <p>
	 * Listeners are notified on events caused by both operations invoked by
	 * external calls and user interaction. Listener method(s) is always called
	 * from UI thread and shouldn't perform long computations.
	 * <p>
	 * Order of adding listeners is significant. This method is not thread-safe.
	 * Listeners should be set up before panel usage.
	 *
	 * @param listener
	 *            listener to add.
	 */
	public void addRefSpecTableListener(final SelectionChangeListener listener) {
		listeners.add(listener);
	}

	/**
	 * Get user-friendly error message regarding invalid specification.
	 *
	 * @return user-readable information about invalid specification.
	 */
	public String getErrorMessage() {
		return errorMessage;
	}

	/**
	 * Return information about validity of specifications.
	 * <p>
	 * Specifications are considered valid if pushing/fetching (depending on
	 * panel configuration) shouldn't cause any error except for
	 * non-fast-forward or server-related errors complaint. I.e. specifications
	 * destinations don't overlap and every specification is correctly
	 * formulated, preferably none is referring to non-existing ref etc.
	 *
	 * @return true if all specifications in panel are valid, false if at least
	 *         one specification is invalid (in this case
	 *         {@link #getErrorMessage()} gives detailed information for user).
	 */
	public boolean isValid() {
		return errorMessage == null;
	}

	private int indexOfSpec(final RefSpec spec) {
		int i;
		for (i = 0; i < specs.size(); i++) {
			// we have to compare references, not use List#indexOf,
			// as equals is implemented in RefSpec
			if (specs.get(i) == spec)
				break;
		}
		if (i == specs.size())
			return -1;
		return i;
	}

	private void notifySpecsChanged() {
		for (final SelectionChangeListener listener : listeners)
			listener.selectionChanged();
	}

	private void safeCreateResources() {
		imageRegistry.put(IMAGE_ADD, UIIcons.ELCL16_ADD);
		imageRegistry.put(IMAGE_DELETE, UIIcons.ELCL16_DELETE);
		imageRegistry.put(IMAGE_TRASH, UIIcons.ELCL16_TRASH);
		imageRegistry.put(IMAGE_CLEAR, UIIcons.ELCL16_CLEAR);
		errorBackgroundColor = new Color(panel.getDisplay(), 255, 150, 150);
		errorTextColor = new Color(panel.getDisplay(), 255, 0, 0);

		panel.addDisposeListener(new DisposeListener() {
			public void widgetDisposed(DisposeEvent e) {
				imageRegistry.dispose();
				errorBackgroundColor.dispose();
				errorTextColor.dispose();
			}
		});
	}

	private RefContentProposalProvider getRefsProposalProvider(
			final boolean local) {
		return (local ? localProposalProvider : remoteProposalProvider);
	}

	private void createCreationPanel() {
		final Group creationPanel = new Group(panel, SWT.NONE);
		creationPanel.setText(UIText.RefSpecPanel_creationGroup);
		creationPanel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
				false));
		final GridLayout layout = new GridLayout();
		layout.numColumns = 3;
		layout.horizontalSpacing = 10;
		layout.verticalSpacing = 2;
		creationPanel.setLayout(layout);

		new Label(creationPanel, SWT.NONE)
				.setText(UIText.RefSpecPanel_creationSrc);
		new Label(creationPanel, SWT.NONE)
				.setText(UIText.RefSpecPanel_creationDst);
		creationButton = new Button(creationPanel, SWT.PUSH);
		creationButton.setLayoutData(new GridData(SWT.RIGHT, SWT.BOTTOM, false,
				false, 1, 2));
		creationButton.setImage(imageRegistry.get(IMAGE_ADD));
		creationButton.setText(UIText.RefSpecPanel_creationButton);
		creationButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				final String src = creationSrcCombo.getText();
				final String dst = creationDstCombo.getText();
				RefSpec spec = new RefSpec(src + ':' + dst);
				addRefSpec(spec);
				creationSrcCombo.setText(""); //$NON-NLS-1$
				creationDstCombo.setText(""); //$NON-NLS-1$
			}
		});
		creationButton.setToolTipText(NLS.bind(
				UIText.RefSpecPanel_creationButtonDescription, typeString()));

		creationSrcDecoration = createAssistedDecoratedCombo(creationPanel,
				getRefsProposalProvider(pushSpecs),
				new IContentProposalListener() {
					public void proposalAccepted(IContentProposal proposal) {
						tryAutoCompleteSrcToDst();
					}
				});
		creationSrcCombo = (Combo) creationSrcDecoration.getControl();
		creationSrcCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
				false));
		creationSrcCombo.addTraverseListener(new TraverseListener() {
			public void keyTraversed(TraverseEvent e) {
				// SWT.TRAVERSE_RETURN may be also reasonable here, but
				// it can be confused with RETURN for content proposal
				if (e.detail == SWT.TRAVERSE_TAB_NEXT)
					tryAutoCompleteSrcToDst();
			}
		});
		if (pushSpecs)
			creationSrcCombo
					.setToolTipText(UIText.RefSpecPanel_srcPushDescription);
		else
			creationSrcCombo
					.setToolTipText(UIText.RefSpecPanel_srcFetchDescription);
		creationSrcComboSupport = new ComboLabelingSupport(creationSrcCombo,
				new SelectionAdapter() {
					@Override
					public void widgetSelected(SelectionEvent e) {
						tryAutoCompleteSrcToDst();
					}
				});

		creationDstDecoration = createAssistedDecoratedCombo(creationPanel,
				getRefsProposalProvider(!pushSpecs),
				new IContentProposalListener() {
					public void proposalAccepted(IContentProposal proposal) {
						tryAutoCompleteDstToSrc();
					}
				});
		creationDstCombo = (Combo) creationDstDecoration.getControl();
		creationDstCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
				false));
		creationDstCombo.addTraverseListener(new TraverseListener() {
			public void keyTraversed(TraverseEvent e) {
				// SWT.TRAVERSE_RETURN may be also reasonable here, but
				// it can be confused with RETURN for content proposal
				if (e.detail == SWT.TRAVERSE_TAB_NEXT)
					tryAutoCompleteDstToSrc();
			}
		});
		if (pushSpecs)
			creationDstCombo
					.setToolTipText(UIText.RefSpecPanel_dstPushDescription);
		else
			creationDstCombo
					.setToolTipText(UIText.RefSpecPanel_dstFetchDescription);
		creationDstComboSupport = new ComboLabelingSupport(creationDstCombo,
				new SelectionAdapter() {
					@Override
					public void widgetSelected(SelectionEvent e) {
						tryAutoCompleteDstToSrc();
					}
				});

		validateCreationPanel();
		final ModifyListener validator = new ModifyListener() {
			public void modifyText(final ModifyEvent e) {
				validateCreationPanel();
			}
		};
		creationSrcCombo.addModifyListener(validator);
		creationDstCombo.addModifyListener(validator);
	}

	private void createDeleteCreationPanel() {
		final Group deletePanel = new Group(panel, SWT.NONE);
		deletePanel.setText(UIText.RefSpecPanel_deletionGroup);
		deletePanel
				.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
		final GridLayout layout = new GridLayout();
		layout.numColumns = 3;
		layout.horizontalSpacing = 10;
		deletePanel.setLayout(layout);

		final Label label = new Label(deletePanel, SWT.NONE);
		label.setText(UIText.RefSpecPanel_deletionRef);
		label.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));

		deleteRefDecoration = createAssistedDecoratedCombo(deletePanel,
				getRefsProposalProvider(false), null);
		deleteRefCombo = (Combo) deleteRefDecoration.getControl();
		deleteRefCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
				false));
		deleteRefCombo
				.setToolTipText(UIText.RefSpecPanel_dstDeletionDescription);
		deleteRefComboSupport = new ComboLabelingSupport(deleteRefCombo, null);

		deleteButton = new Button(deletePanel, SWT.PUSH);
		deleteButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
				false));
		deleteButton.setImage(imageRegistry.get(IMAGE_DELETE));
		deleteButton.setText(UIText.RefSpecPanel_deletionButton);
		deleteButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				RefSpec spec = new RefSpec(':' + deleteRefCombo.getText());
				addRefSpec(spec);
				deleteRefCombo.setText(""); //$NON-NLS-1$
			}
		});
		deleteButton
				.setToolTipText(UIText.RefSpecPanel_deletionButtonDescription);
		validateDeleteCreationPanel();

		deleteRefCombo.addModifyListener(new ModifyListener() {
			public void modifyText(final ModifyEvent e) {
				validateDeleteCreationPanel();
			}
		});
	}

	private void createPredefinedCreationPanel() {
		final Group predefinedPanel = new Group(panel, SWT.NONE);
		predefinedPanel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
				false));
		predefinedPanel.setText(UIText.RefSpecPanel_predefinedGroup);
		final GridLayout layout = new GridLayout();
		layout.numColumns = 3;
		predefinedPanel.setLayout(layout);

		addConfiguredButton = new Button(predefinedPanel, SWT.PUSH);
		addConfiguredButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER,
				true, false));
		addConfiguredButton.setText(NLS.bind(
				UIText.RefSpecPanel_predefinedConfigured, typeString()));
		addConfiguredButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				addPredefinedRefSpecs(predefinedConfigured);
			}
		});
		addConfiguredButton
				.setToolTipText(UIText.RefSpecPanel_predefinedConfiguredDescription);
		updateAddPredefinedButton(addConfiguredButton, predefinedConfigured);

		addBranchesButton = new Button(predefinedPanel, SWT.PUSH);
		addBranchesButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER,
				true, false));
		addBranchesButton.setText(UIText.RefSpecPanel_predefinedAll);
		addBranchesButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				addPredefinedRefSpecs(predefinedBranches);
			}
		});
		addBranchesButton
				.setToolTipText(UIText.RefSpecPanel_predefinedAllDescription);
		updateAddPredefinedButton(addBranchesButton, predefinedBranches);

		addTagsButton = new Button(predefinedPanel, SWT.PUSH);
		addTagsButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
				false));
		addTagsButton.setText(UIText.RefSpecPanel_predefinedTags);
		addTagsButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				addPredefinedRefSpecs(Transport.REFSPEC_TAGS);
			}
		});
		addTagsButton
				.setToolTipText(UIText.RefSpecPanel_predefinedTagsDescription);
		updateAddPredefinedButton(addTagsButton, Transport.REFSPEC_TAGS);

		addRefSpecTableListener(new SelectionChangeListener() {
			public void selectionChanged() {
				updateAddPredefinedButton(addConfiguredButton,
						predefinedConfigured);
				updateAddPredefinedButton(addBranchesButton, predefinedBranches);
				updateAddPredefinedButton(addTagsButton, Transport.REFSPEC_TAGS);
			}
		});
	}

	private ControlDecoration createAssistedDecoratedCombo(
			final Composite parent,
			final IContentProposalProvider proposalProvider,
			final IContentProposalListener listener) {
		// FIXME: VERY ANNOYING! reported as 243991 in eclipse bugzilla
		// when typing, pressing arrow-down key opens combo box drop-down
		// instead of moving within autocompletion list (Mac 10.4&10.5, Eclipse
		// 3.4)
		final Combo combo = new Combo(parent, SWT.DROP_DOWN);
		final ControlDecoration decoration = new ControlDecoration(combo,
				SWT.BOTTOM | SWT.LEFT);
		final ContentAssistCommandAdapter proposal = new ContentAssistCommandAdapter(
				combo, new ComboContentAdapter(), proposalProvider, null, null,
				true);
		proposal
				.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE);
		if (listener != null)
			proposal.addContentProposalListener(listener);
		return decoration;
	}

	private void createTableGroup() {
		final Group tableGroup = new Group(panel, SWT.NONE);
		tableGroup.setText(NLS.bind(UIText.RefSpecPanel_specifications,
				typeString()));
		tableGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
		tableGroup.setLayout(new GridLayout());

		createTable(tableGroup);
		createSpecsButtonsPanel(tableGroup);
	}

	private void createTable(final Group tableGroup) {
		final Composite tablePanel = new Composite(tableGroup, SWT.NONE);
		final GridData layoutData = new GridData(SWT.FILL, SWT.FILL, true, true);
		layoutData.heightHint = TABLE_PREFERRED_HEIGHT;
		layoutData.widthHint = TABLE_PREFERRED_WIDTH;
		tablePanel.setLayoutData(layoutData);

		tableViewer = new TableViewer(tablePanel, SWT.FULL_SELECTION
				| SWT.MULTI | SWT.BORDER | SWT.V_SCROLL);
		ColumnViewerToolTipSupport.enableFor(tableViewer);
		final Table table = tableViewer.getTable();
		table.setLinesVisible(true);
		table.setHeaderVisible(true);

		createTableColumns(tablePanel);
		createCellEditors(table);

		tableViewer.setContentProvider(new ArrayContentProvider());
		tableViewer.setInput(specs);

		tableViewer.setComparer(new IElementComparer() {
			public boolean equals(Object a, Object b) {
				// need that as viewers are not designed to support 2 equals
				// object, while we have RefSpec#equals implemented
				return a == b;
			}

			public int hashCode(Object element) {
				return element.hashCode();
			}
		});
	}

	private void createTableColumns(final Composite tablePanel) {
		final TableColumnLayout columnLayout = new TableColumnLayout();
		tablePanel.setLayout(columnLayout);

		createDummyColumn(columnLayout);
		if (pushSpecs)
			createModeColumn(columnLayout);
		createSrcColumn(columnLayout);
		createDstColumn(columnLayout);
		createForceColumn(columnLayout);
		createRemoveColumn(columnLayout);
	}

	private void createDummyColumn(final TableColumnLayout columnLayout) {
		final TableViewerColumn viewerColumn = new TableViewerColumn(
				tableViewer, SWT.LEFT);
		final TableColumn column = viewerColumn.getColumn();
		columnLayout.setColumnData(column, new ColumnWeightData(0, 0, false));
		viewerColumn.setLabelProvider(new ColumnLabelProvider());
		// FIXME: first cell is left aligned on Mac OS X 10.4, Eclipse 3.4
	}

	private void createModeColumn(final TableColumnLayout columnLayout) {
		final TableViewerColumn column = createColumn(columnLayout,
				UIText.RefSpecPanel_columnMode, COLUMN_MODE_WEIGHT, SWT.CENTER);
		column.setLabelProvider(new ColumnLabelProvider() {
			@Override
			public String getText(final Object element) {
				return (isDeleteRefSpec(element) ? UIText.RefSpecPanel_modeDelete
						: UIText.RefSpecPanel_modeUpdate);
			}

			@Override
			public Image getImage(Object element) {
				return (isDeleteRefSpec(element) ? imageRegistry
						.get(IMAGE_DELETE) : imageRegistry.get(IMAGE_ADD));
			}

			@Override
			public String getToolTipText(Object element) {
				if (isDeleteRefSpec(element))
					return UIText.RefSpecPanel_modeDeleteDescription + '\n'
							+ UIText.RefSpecPanel_clickToChange;
				return UIText.RefSpecPanel_modeUpdateDescription + '\n'
						+ UIText.RefSpecPanel_clickToChange;
			}
		});
		column.setEditingSupport(new EditingSupport(tableViewer) {
			@Override
			protected boolean canEdit(final Object element) {
				return true;
			}

			@Override
			protected CellEditor getCellEditor(final Object element) {
				return modeCellEditor;
			}

			@SuppressWarnings("boxing")
			@Override
			protected Object getValue(final Object element) {
				return isDeleteRefSpec(element);
			}

			@SuppressWarnings("boxing")
			@Override
			protected void setValue(final Object element, final Object value) {
				final RefSpec oldSpec = (RefSpec) element;
				final RefSpec newSpec;
				if ((Boolean) value) {
					newSpec = setRefSpecSource(oldSpec, null);
					setRefSpec(oldSpec, newSpec);
				} else {
					newSpec = setRefSpecSource(oldSpec,
							UIText.RefSpecPanel_refChooseSome);
					setRefSpec(oldSpec, newSpec);
					tableViewer.getControl().getDisplay().asyncExec(
							new Runnable() {
								public void run() {
									tableViewer.editElement(newSpec,
											srcColumnIndex);
								}
							});
				}
			}
		});
	}

	private void createSrcColumn(final TableColumnLayout columnLayout) {
		final TableViewerColumn column = createColumn(columnLayout,
				UIText.RefSpecPanel_columnSrc, COLUMN_SRC_WEIGHT, SWT.LEFT);
		column.setLabelProvider(new ColumnLabelProvider() {
			@Override
			public String getText(final Object element) {
				return ((RefSpec) element).getSource();
			}

			@Override
			public String getToolTipText(Object element) {
				if (isInvalidSpec(element))
					return errorMessage;
				if (isDeleteRefSpec(element))
					return UIText.RefSpecPanel_srcDeleteDescription;
				if (pushSpecs)
					return UIText.RefSpecPanel_srcPushDescription;
				return UIText.RefSpecPanel_srcFetchDescription;
			}

			@Override
			public Color getBackground(final Object element) {
				if (isInvalidSpec(element))
					return errorBackgroundColor;
				return null;
			}

			@Override
			public Color getToolTipForegroundColor(Object element) {
				if (isInvalidSpec(element))
					return errorTextColor;
				return null;
			}
		});
		column.setEditingSupport(new EditingSupport(tableViewer) {
			@Override
			protected boolean canEdit(final Object element) {
				return !isDeleteRefSpec(element);
			}

			@Override
			protected CellEditor getCellEditor(final Object element) {
				return (pushSpecs ? localRefCellEditor : remoteRefCellEditor);
			}

			@Override
			protected Object getValue(final Object element) {
				return ((RefSpec) element).getSource();
			}

			@Override
			protected void setValue(final Object element, final Object value) {
				if (value == null || ((String) value).length() == 0
						|| ObjectId.zeroId().name().equals(value)) {
					// Ignore empty strings or null objects - do not set them in
					// model.User won't loose any information if we just fall
					// back to the old value.
					// If user want to delete ref, let change the mode.
					return;
				}

				final RefSpec oldSpec = (RefSpec) element;
				final RefSpec newSpec = setRefSpecSource(oldSpec,
						(String) value);
				setRefSpec(oldSpec, newSpec);
			}
		});

		// find index of this column - for later usage
		final TableColumn[] columns = tableViewer.getTable().getColumns();
		for (srcColumnIndex = 0; srcColumnIndex < columns.length; srcColumnIndex++)
			if (columns[srcColumnIndex] == column.getColumn())
				break;

	}

	private void createDstColumn(final TableColumnLayout columnLayout) {
		final TableViewerColumn column = createColumn(columnLayout,
				UIText.RefSpecPanel_columnDst, COLUMN_DST_WEIGHT, SWT.LEFT);
		column.setLabelProvider(new ColumnLabelProvider() {
			@Override
			public String getText(final Object element) {
				return ((RefSpec) element).getDestination();
			}

			@Override
			public String getToolTipText(Object element) {
				if (isInvalidSpec(element))
					return errorMessage;
				if (isDeleteRefSpec(element))
					return UIText.RefSpecPanel_dstDeletionDescription;
				if (pushSpecs)
					return UIText.RefSpecPanel_dstPushDescription;
				return UIText.RefSpecPanel_dstFetchDescription;
			}

			@Override
			public Color getBackground(final Object element) {
				if (isInvalidSpec(element))
					return errorBackgroundColor;
				return null;
			}

			@Override
			public Color getToolTipForegroundColor(Object element) {
				if (isInvalidSpec(element))
					return errorTextColor;
				return null;
			}
		});
		column.setEditingSupport(new EditingSupport(tableViewer) {
			@Override
			protected boolean canEdit(final Object element) {
				return true;
			}

			@Override
			protected CellEditor getCellEditor(final Object element) {
				return (pushSpecs ? remoteRefCellEditor : localRefCellEditor);
			}

			@Override
			protected Object getValue(final Object element) {
				return ((RefSpec) element).getDestination();
			}

			@Override
			protected void setValue(final Object element, final Object value) {
				if (value == null || ((String) value).length() == 0) {
					// Ignore empty strings - do not set them in model.
					// User won't loose any information if we just fall back
					// to the old value.
					return;
				}

				final RefSpec oldSpec = (RefSpec) element;
				final RefSpec newSpec = setRefSpecDestination(oldSpec,
						(String) value);
				setRefSpec(oldSpec, newSpec);
			}
		});
	}

	private void createForceColumn(final TableColumnLayout columnLayout) {
		final TableViewerColumn column = createColumn(columnLayout,
				UIText.RefSpecPanel_columnForce, COLUMN_FORCE_WEIGHT,
				SWT.CENTER);
		column.setLabelProvider(new CheckboxLabelProvider(tableViewer
				.getControl()) {
			@Override
			protected boolean isChecked(final Object element) {
				return ((RefSpec) element).isForceUpdate();
			}

			@Override
			protected boolean isEnabled(Object element) {
				return !isDeleteRefSpec(element);
			}

			@Override
			public String getToolTipText(Object element) {
				if (!isEnabled(element))
					return UIText.RefSpecPanel_forceDeleteDescription;
				if (isChecked(element))
					return UIText.RefSpecPanel_forceTrueDescription + '\n'
							+ UIText.RefSpecPanel_clickToChange;
				return UIText.RefSpecPanel_forceFalseDescription + '\n'
						+ UIText.RefSpecPanel_clickToChange;
			}
		});
		column.setEditingSupport(new EditingSupport(tableViewer) {
			@Override
			protected boolean canEdit(final Object element) {
				return !isDeleteRefSpec(element);
			}

			@Override
			protected CellEditor getCellEditor(final Object element) {
				return forceUpdateCellEditor;
			}

			@SuppressWarnings("boxing")
			@Override
			protected Object getValue(final Object element) {
				return ((RefSpec) element).isForceUpdate();
			}

			@SuppressWarnings("boxing")
			@Override
			protected void setValue(final Object element, final Object value) {
				final RefSpec oldSpec = (RefSpec) element;
				final RefSpec newSpec = oldSpec.setForceUpdate((Boolean) value);
				setRefSpec(oldSpec, newSpec);
			}
		});
	}

	private void createRemoveColumn(TableColumnLayout columnLayout) {
		final TableViewerColumn column = createColumn(columnLayout,
				UIText.RefSpecPanel_columnRemove, COLUMN_REMOVE_WEIGHT,
				SWT.CENTER);
		column.setLabelProvider(new CenteredImageLabelProvider() {
			@Override
			public Image getImage(Object element) {
				return imageRegistry.get(IMAGE_TRASH);
			}

			@Override
			public String getToolTipText(Object element) {
				return NLS.bind(UIText.RefSpecPanel_removeDescription,
						typeString());
			}
		});
		column.setEditingSupport(new EditingSupport(tableViewer) {
			@Override
			protected boolean canEdit(Object element) {
				return true;
			}

			@Override
			protected CellEditor getCellEditor(Object element) {
				return removeSpecCellEditor;
			}

			@Override
			protected Object getValue(Object element) {
				return null;
			}

			@Override
			protected void setValue(Object element, Object value) {
				removeRefSpec((RefSpec) element);
			}
		});
	}

	private TableViewerColumn createColumn(
			final TableColumnLayout columnLayout, final String text,
			final int weight, final int style) {
		final TableViewerColumn viewerColumn = new TableViewerColumn(
				tableViewer, style);
		final TableColumn column = viewerColumn.getColumn();
		column.setText(text);
		columnLayout.setColumnData(column, new ColumnWeightData(weight));
		return viewerColumn;
	}

	private void createCellEditors(final Table table) {
		if (pushSpecs)
			modeCellEditor = new CheckboxCellEditor(table);
		localRefCellEditor = createLocalRefCellEditor(table);
		remoteRefCellEditor = createRemoteRefCellEditor(table);
		forceUpdateCellEditor = new CheckboxCellEditor(table);
		removeSpecCellEditor = new ClickableCellEditor(table);
	}

	private CellEditor createLocalRefCellEditor(final Table table) {
		return createRefCellEditor(table, getRefsProposalProvider(true));
	}

	private CellEditor createRemoteRefCellEditor(final Table table) {
		return createRefCellEditor(table, getRefsProposalProvider(false));
	}

	private CellEditor createRefCellEditor(final Table table,
			final IContentProposalProvider proposalProvider) {
		final CellEditor cellEditor = new TextCellEditor(table);

		final Text text = (Text) cellEditor.getControl();
		final ContentAssistCommandAdapter assist = new ContentAssistCommandAdapter(
				text, new TextContentAdapter(), proposalProvider, null, null,
				true);
		assist
				.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE);

		return cellEditor;
	}

	private void createSpecsButtonsPanel(final Composite parent) {
		final Composite specsPanel = new Composite(parent, SWT.NONE);
		specsPanel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true,
				false));
		final RowLayout layout = new RowLayout();
		layout.spacing = 10;
		specsPanel.setLayout(layout);

		forceUpdateAllButton = new Button(specsPanel, SWT.PUSH);
		forceUpdateAllButton.setText(UIText.RefSpecPanel_forceAll);
		forceUpdateAllButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				final List<RefSpec> specsCopy = new ArrayList<RefSpec>(specs);
				for (final RefSpec spec : specsCopy) {
					if (!isDeleteRefSpec(spec))
						setRefSpec(spec, spec.setForceUpdate(true));
				}
			}
		});
		forceUpdateAllButton
				.setToolTipText(UIText.RefSpecPanel_forceAllDescription);
		updateForceUpdateAllButton();

		removeAllSpecButton = new Button(specsPanel, SWT.PUSH);
		removeAllSpecButton.setImage(imageRegistry.get(IMAGE_CLEAR));
		removeAllSpecButton.setText(UIText.RefSpecPanel_removeAll);
		removeAllSpecButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				clearRefSpecs();
			}
		});
		removeAllSpecButton
				.setToolTipText(UIText.RefSpecPanel_removeAllDescription);
		updateRemoveAllSpecButton();

		addRefSpecTableListener(new SelectionChangeListener() {
			public void selectionChanged() {
				updateForceUpdateAllButton();
				updateRemoveAllSpecButton();
			}
		});
	}

	private void tryAutoCompleteSrcToDst() {
		final String src = creationSrcCombo.getText();
		final String dst = creationDstCombo.getText();

		if (src == null || src.length() == 0)
			return;

		if (dst != null && dst.length() > 0) {
			// dst is already there, just fix wildcards if needed
			final String newDst;
			if (RefSpec.isWildcard(src))
				newDst = wildcardSpecComponent(dst);
			else
				newDst = unwildcardSpecComponent(dst, src);
			creationDstCombo.setText(newDst);
			return;
		}

		if (!isValidRefExpression(src)) {
			// no way to be smarter than user here
			return;
		}

		// dst is empty, src is ref or wildcard, so we can rewrite it as user
		// would perhaps
		if (pushSpecs)
			creationDstCombo.setText(src);
		else {
			for (final RefSpec spec : predefinedConfigured) {
				if (spec.matchSource(src)) {
					final String newDst = spec.expandFromSource(src)
							.getDestination();
					creationDstCombo.setText(newDst);
					return;
				}
			}
			if (remoteConfig != null && src.startsWith(Constants.R_HEADS)) {
				final String newDst = Constants.R_REMOTES + remoteConfig + '/'
						+ src.substring(Constants.R_HEADS.length());
				creationDstCombo.setText(newDst);
			}
		}
	}

	private void tryAutoCompleteDstToSrc() {
		final String src = creationSrcCombo.getText();
		final String dst = creationDstCombo.getText();

		if (dst == null || dst.length() == 0)
			return;

		if (src != null && src.length() > 0) {
			// src is already there, fix wildcards if needed
			final String newSrc;
			if (RefSpec.isWildcard(dst))
				newSrc = wildcardSpecComponent(src);
			else
				newSrc = unwildcardSpecComponent(src, dst);
			creationSrcCombo.setText(newSrc);
			return;
		}
	}

	private void validateCreationPanel() {
		final String src = creationSrcCombo.getText();
		final String dst = creationDstCombo.getText();

		// check src ref field
		boolean srcOk = false;
		final boolean srcWildcard = RefSpec.isWildcard(src);
		if (src == null || src.length() == 0)
			setControlDecoration(creationSrcDecoration,
					FieldDecorationRegistry.DEC_REQUIRED,
					UIText.RefSpecPanel_validationSrcUpdateRequired);
		else if (pushSpecs) {
			if (!srcWildcard && !isLocalRef(src))
				setControlDecoration(creationSrcDecoration,
						FieldDecorationRegistry.DEC_ERROR, NLS.bind(
								UIText.RefSpecPanel_validationRefInvalidLocal,
								src));
			else if (srcWildcard && !isValidRefExpression(src))
				setControlDecoration(
						creationSrcDecoration,
						FieldDecorationRegistry.DEC_ERROR,
						NLS
								.bind(
										UIText.RefSpecPanel_validationRefInvalidExpression,
										src));
			else {
				srcOk = true;
				if (srcWildcard && !isMatchingAny(src, localRefNames))
					setControlDecoration(
							creationSrcDecoration,
							FieldDecorationRegistry.DEC_WARNING,
							NLS
									.bind(
											UIText.RefSpecPanel_validationRefNonMatchingLocal,
											src));
				else
					creationSrcDecoration.hide();
			}
		} else {
			if (!srcWildcard && !isRemoteRef(src))
				setControlDecoration(
						creationSrcDecoration,
						FieldDecorationRegistry.DEC_ERROR,
						NLS
								.bind(
										UIText.RefSpecPanel_validationRefNonExistingRemote,
										src));
			else if (srcWildcard && !isMatchingAny(src, remoteRefNames)) {
				setControlDecoration(
						creationSrcDecoration,
						FieldDecorationRegistry.DEC_WARNING,
						NLS
								.bind(
										UIText.RefSpecPanel_validationRefNonMatchingRemote,
										src));
				srcOk = true;
			} else {
				srcOk = true;
				creationSrcDecoration.hide();
			}
		}

		// check dst ref field
		boolean dstOk = false;
		if (dst == null || dst.length() == 0)
			setControlDecoration(creationDstDecoration,
					FieldDecorationRegistry.DEC_REQUIRED,
					UIText.RefSpecPanel_validationDstRequired);
		else if (!isValidRefExpression(dst))
			setControlDecoration(creationDstDecoration,
					FieldDecorationRegistry.DEC_ERROR, NLS.bind(
							UIText.RefSpecPanel_validationDstInvalidExpression,
							dst));
		else {
			creationDstDecoration.hide();
			dstOk = true;
		}
		// leave duplicates dst checking for validateSpecs()

		// check the wildcard synergy
		boolean wildcardOk = true;
		if (srcOk && dstOk && (srcWildcard ^ RefSpec.isWildcard(dst))) {
			setControlDecoration(creationSrcDecoration,
					FieldDecorationRegistry.DEC_ERROR,
					UIText.RefSpecPanel_validationWildcardInconsistent);
			setControlDecoration(creationDstDecoration,
					FieldDecorationRegistry.DEC_ERROR,
					UIText.RefSpecPanel_validationWildcardInconsistent);
			wildcardOk = false;
		}

		creationButton.setEnabled(srcOk && dstOk && wildcardOk);
	}

	private void validateDeleteCreationPanel() {
		final String ref = deleteRefCombo.getText();

		deleteButton.setEnabled(false);
		if (ref == null || ref.length() == 0)
			setControlDecoration(deleteRefDecoration,
					FieldDecorationRegistry.DEC_REQUIRED,
					UIText.RefSpecPanel_validationRefDeleteRequired);
		else if (!isValidRefExpression(ref))
			setControlDecoration(deleteRefDecoration,
					FieldDecorationRegistry.DEC_ERROR, NLS.bind(
							UIText.RefSpecPanel_validationRefInvalidExpression,
							ref));
		else if (RefSpec.isWildcard(ref))
			setControlDecoration(deleteRefDecoration,
					FieldDecorationRegistry.DEC_ERROR,
					UIText.RefSpecPanel_validationRefDeleteWildcard);
		else if (!isRemoteRef(ref))
			setControlDecoration(
					deleteRefDecoration,
					FieldDecorationRegistry.DEC_ERROR,
					NLS
							.bind(
									UIText.RefSpecPanel_validationRefNonExistingRemoteDelete,
									ref));
		else {
			deleteRefDecoration.hide();
			deleteButton.setEnabled(true);
		}
	}

	private void validateSpecs() {
		// validate spec; display max. 1 error message for user at time
		final RefSpec oldInvalidSpec = invalidSpec;
		final RefSpec oldInvalidSpecSameDst = invalidSpecSameDst;
		errorMessage = null;
		invalidSpec = null;
		invalidSpecSameDst = null;
		for (final RefSpec spec : specs) {
			errorMessage = validateSpec(spec);
			if (errorMessage != null) {
				invalidSpec = spec;
				break;
			}
		}
		if (errorMessage == null)
			validateSpecsCrossDst();
		if (invalidSpec != oldInvalidSpec
				|| invalidSpecSameDst != oldInvalidSpecSameDst)
			tableViewer.refresh();
	}

	private String validateSpec(final RefSpec spec) {
		final String src = spec.getSource();
		final String dst = spec.getDestination();
		final boolean wildcard = spec.isWildcard();

		// check src
		if (pushSpecs) {
			if (!isDeleteRefSpec(spec)) {
				if (src.length() == 0)
					return UIText.RefSpecPanel_validationSrcUpdateRequired;
				else if (!wildcard && !isLocalRef(src))
					return NLS.bind(
							UIText.RefSpecPanel_validationRefInvalidLocal, src);
				else if (wildcard && !isValidRefExpression(src))
					return NLS.bind(
							UIText.RefSpecPanel_validationRefInvalidExpression,
							src);
				// ignore non-matching wildcard specs
			}
		} else {
			if (src == null || src.length() == 0)
				return UIText.RefSpecPanel_validationSrcUpdateRequired;
			else if (!wildcard && !isRemoteRef(src))
				return NLS
						.bind(
								UIText.RefSpecPanel_validationRefNonExistingRemote,
								src);
			// ignore non-matching wildcard specs
		}

		// check dst
		if (dst == null || dst.length() == 0) {
			if (isDeleteRefSpec(spec))
				return UIText.RefSpecPanel_validationRefDeleteRequired;
			return UIText.RefSpecPanel_validationDstRequired;
		} else if (!isValidRefExpression(dst))
			return NLS.bind(UIText.RefSpecPanel_validationRefInvalidExpression,
					dst);
		else if (isDeleteRefSpec(spec) && !isRemoteRef(dst))
			return NLS.bind(
					UIText.RefSpecPanel_validationRefNonExistingRemoteDelete,
					dst);

		return null;
	}

	private boolean isInvalidSpec(Object element) {
		return element == invalidSpec || element == invalidSpecSameDst;
	}

	private void validateSpecsCrossDst() {
		final Map<String, RefSpec> dstsSpecsMap = new HashMap<String, RefSpec>();
		try {
			for (final RefSpec spec : specs) {
				if (!spec.isWildcard()) {
					if (!tryAddDestination(dstsSpecsMap, spec.getDestination(),
							spec))
						return;
				} else {
					final Collection<String> srcNames;
					if (pushSpecs)
						srcNames = localRefNames;
					else
						srcNames = remoteRefNames;

					for (final String src : srcNames) {
						if (spec.matchSource(src)) {
							final String dst = spec.expandFromSource(src)
									.getDestination();
							if (!tryAddDestination(dstsSpecsMap, dst, spec))
								return;
						}
					}
				}
			}
		} finally {
			matchingAnyRefs = !dstsSpecsMap.isEmpty();
		}
	}

	private boolean tryAddDestination(final Map<String, RefSpec> dstsSpecsMap,
			final String dst, final RefSpec spec) {
		final RefSpec other = dstsSpecsMap.put(dst, spec);
		if (other != null) {
			errorMessage = NLS
					.bind(
							UIText.RefSpecPanel_validationSpecificationsOverlappingDestination,
							dst);
			invalidSpec = other;
			invalidSpecSameDst = spec;
			return false;
		}
		return true;
	}

	private void updateAddPredefinedButton(final Button button,
			final List<RefSpec> predefined) {
		boolean enable = false;
		if (predefined != null) {
			for (final RefSpec pre : predefined) {
				if (!specs.contains(pre)) {
					enable = true;
					break;
				}
			}
		}
		button.setEnabled(enable);
	}

	private void updateAddPredefinedButton(Button button,
			final RefSpec predefined) {
		button.setEnabled(!specs.contains(predefined));
	}

	private void updateForceUpdateAllButton() {
		boolean enable = false;
		for (final RefSpec spec : specs) {
			if (!isDeleteRefSpec(spec) && !spec.isForceUpdate()) {
				enable = true;
				break;
			}
		}
		forceUpdateAllButton.setEnabled(enable);
	}

	private void updateRemoveAllSpecButton() {
		removeAllSpecButton.setEnabled(!specs.isEmpty());
	}

	private String typeString() {
		return (pushSpecs ? UIText.RefSpecPanel_push
				: UIText.RefSpecPanel_fetch);
	}

	private void addPredefinedRefSpecs(final RefSpec predefined) {
		addPredefinedRefSpecs(Collections.singletonList(predefined));
	}

	private void addPredefinedRefSpecs(final List<RefSpec> predefined) {
		for (final RefSpec pre : predefined) {
			if (!specs.contains(pre))
				addRefSpec(pre);
		}
	}

	private List<RefContentProposal> createContentProposals(
			final Collection<Ref> refs, final Ref HEAD) {
		final TreeSet<Ref> set = new TreeSet<Ref>(new Comparator<Ref>() {
			public int compare(Ref o1, Ref o2) {
				// lexicographical ordering by name seems to be fine
				return o1.getName().compareTo(o2.getName());
			}
		});
		set.addAll(refs);
		if (HEAD != null)
			set.add(HEAD);

		final List<RefContentProposal> result = new ArrayList<RefContentProposal>(
				set.size());
		for (final Ref r : set)
			result.add(new RefContentProposal(localDb, r));
		return result;
	}

	private List<RefContentProposal> createProposalsFilteredLocal(
			final List<RefContentProposal> proposals) {
		final List<RefContentProposal> result = new ArrayList<RefContentProposal>();
		for (final RefContentProposal p : proposals) {
			final String content = p.getContent();
			if (pushSpecs) {
				if (content.equals(Constants.HEAD)
						|| content.startsWith(Constants.R_HEADS))
					result.add(p);
			} else {
				if (content.startsWith(Constants.R_REMOTES))
					result.add(p);
			}
		}
		return result;
	}

	private boolean isRemoteRef(String ref) {
		return remoteRefNames.contains(ref);
	}

	private boolean isLocalRef(final String ref) {
		return tryResolveLocalRef(ref) != null;
	}

	private boolean isMatchingAny(final String ref,
			final Collection<String> names) {
		// strip wildcard sign
		final String prefix = ref.substring(0, ref.length() - 1);
		for (final String name : names)
			if (name.startsWith(prefix))
				return true;
		return false;
	}

	private ObjectId tryResolveLocalRef(final String ref) {
		try {
			return localDb.resolve(ref);
		} catch (final IOException e) {
			Activator.logError(
					"I/O error occurred during resolving expression: " //$NON-NLS-1$
							+ ref, e);
			return null;
		}
	}

	private class RefContentProposalProvider implements
			IContentProposalProvider {
		private List<RefContentProposal> proposals = Collections.emptyList();

		private final boolean tryResolvingLocally;

		private RefContentProposalProvider(final boolean tryResolvingLocally) {
			this.tryResolvingLocally = tryResolvingLocally;
		}

		private void setProposals(final List<RefContentProposal> proposals) {
			this.proposals = proposals;
		}

		public IContentProposal[] getProposals(final String contents,
				int position) {
			final List<RefContentProposal> result = new ArrayList<RefContentProposal>();

			if (contents.indexOf('*') != -1 || contents.indexOf('?') != -1) {
				// contents contains wildcards

				// check if contents can be safely added as wildcard spec
				if (isValidRefExpression(contents))
					result.add(new RefContentProposal(localDb, contents, null));

				// let's expand wildcards
				final String regex = ".*" //$NON-NLS-1$
						+ contents.replace("*", ".*").replace("?", ".?") + ".*"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
				final Pattern p = Pattern.compile(regex);
				for (final RefContentProposal prop : proposals)
					if (p.matcher(prop.getContent()).matches())
						result.add(prop);
			} else {
				for (final RefContentProposal prop : proposals)
					if (prop.getContent().contains(contents))
						result.add(prop);

				if (tryResolvingLocally && result.isEmpty()) {
					final ObjectId id = tryResolveLocalRef(contents);
					if (id != null)
						result
								.add(new RefContentProposal(localDb, contents,
										id));
				}
			}
			return result.toArray(new IContentProposal[0]);
		}
	}
}

Back to the top