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
|
// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.client.patches;
import com.google.gerrit.client.ui.DomUtil;
import com.google.gwt.core.client.GWT;
import com.google.gwtjsonrpc.client.JsonUtil;
public class PatchUtil {
public static final PatchConstants C = GWT.create(PatchConstants.class);
public static final PatchMessages M = GWT.create(PatchMessages.class);
public static final PatchDetailService DETAIL_SVC;
public static final int DEFAULT_LINE_LENGTH = 100;
static {
DETAIL_SVC = GWT.create(PatchDetailService.class);
JsonUtil.bind(DETAIL_SVC, "rpc/PatchDetailService");
}
public static String lineToHTML(final String src, final int lineLength) {
final boolean hasTab = src.indexOf('\t') >= 0;
String brokenSrc = wrapLines(src, hasTab, lineLength);
String html = DomUtil.escape(brokenSrc);
if (brokenSrc != src) {
// If we had line breaks inserted into the source text we need
// to expand the line breaks into <br> tags in HTML, so the
// line will wrap around.
//
html = expandLFs(html);
}
if (hasTab) {
// We had at least one horizontal tab, so we should expand it out.
//
html = expandTabs(html);
}
return html;
}
private static String wrapLines(final String src, final boolean hasTabs,
final int lineLength) {
if (lineLength <= 0) {
// Caller didn't request for line wrapping; use it unmodified.
//
return src;
}
if (src.length() < lineLength && !hasTabs) {
// We're too short and there are no horizontal tabs, line is fine
// as-is so bypass the longer line wrapping code below.
return src;
}
final StringBuilder r = new StringBuilder();
int lineLen = 0;
for (int i = 0; i < src.length(); i++) {
final char c = src.charAt(i);
final int cLen = c == '\t' ? 8 : 1;
if (lineLen >= lineLength) {
r.append('\n');
lineLen = 0;
}
r.append(c);
lineLen += cLen;
}
return r.toString();
}
private native static String expandTabs(String src)
/*-{ return src.replace(/\t/g, '<span title="Visual Tab" class="gerrit-visualtab">»</span>\t'); }-*/;
private native static String expandLFs(String src)
/*-{ return src.replace(/\n/g, '<br>'); }-*/;
}
|