proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
languagetool-org_languagetool
|
languagetool/languagetool-tools/src/main/java/org/languagetool/tools/POSDictionaryBuilder.java
|
POSDictionaryBuilder
|
main
|
class POSDictionaryBuilder extends DictionaryBuilder {
public POSDictionaryBuilder(File infoFile) throws IOException {
super(infoFile);
}
public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>}
public File build(File dictFile) throws Exception {
return buildDict(convertTabToSeparator(dictFile));
}
}
|
BuilderOptions builderOptions = new BuilderOptions();
builderOptions.addOption(BuilderOptions.INPUT_OPTION, true,
BuilderOptions.TAB_INPUT_HELP, true);
builderOptions.addOption(BuilderOptions.INFO_OPTION, true,
BuilderOptions.INFO_HELP, true);
builderOptions.addOption(BuilderOptions.FREQ_OPTION, true,
BuilderOptions.FREQ_HELP, false);
CommandLine cmdLine = builderOptions.parseArguments(args, POSDictionaryBuilder.class);
POSDictionaryBuilder builder = new POSDictionaryBuilder(new File(cmdLine.getOptionValue(BuilderOptions.INFO_OPTION)));
builder.setOutputFilename(cmdLine.getOptionValue(BuilderOptions.OUTPUT_OPTION));
File inputFile = new File(cmdLine.getOptionValue(BuilderOptions.INPUT_OPTION));
if (cmdLine.hasOption(BuilderOptions.FREQ_OPTION)) {
builder.readFreqList(new File(cmdLine.getOptionValue(BuilderOptions.FREQ_OPTION)));
inputFile = builder.addFreqData(inputFile, false);
}
builder.build(inputFile);
| 100
| 304
| 404
|
<methods><variables>private static final int FIRST_RANGE_CODE,private static final int FREQ_RANGES_IN,private static final int FREQ_RANGES_OUT,private final Map<java.lang.String,java.lang.Integer> freqList,private java.lang.String outputFilename,private final java.util.regex.Pattern pFreqEntry,private final java.util.regex.Pattern pTaggerEntry,private final java.util.Properties props,private static final SerializationFormat serializationFormat
|
languagetool-org_languagetool
|
languagetool/languagetool-tools/src/main/java/org/languagetool/tools/SpellDictionaryBuilder.java
|
SpellDictionaryBuilder
|
build
|
class SpellDictionaryBuilder extends DictionaryBuilder {
SpellDictionaryBuilder(File infoFile) throws IOException {
super(infoFile);
}
public static void main(String[] args) throws Exception {
BuilderOptions builderOptions = new BuilderOptions();
builderOptions.addOption(BuilderOptions.INPUT_OPTION, true,
"plain text dictionary file, e.g. created from a Hunspell dictionary by 'unmunch'", true);
builderOptions.addOption(BuilderOptions.INFO_OPTION, true,
BuilderOptions.INFO_HELP, true);
builderOptions.addOption(BuilderOptions.FREQ_OPTION, true,
BuilderOptions.FREQ_HELP, false);
CommandLine cmdLine = builderOptions.parseArguments(args, SpellDictionaryBuilder.class);
String plainTextFile = cmdLine.getOptionValue(BuilderOptions.INPUT_OPTION);
String infoFile = cmdLine.getOptionValue(BuilderOptions.INFO_OPTION);
SpellDictionaryBuilder builder = new SpellDictionaryBuilder(new File(infoFile));
builder.setOutputFilename(cmdLine.getOptionValue(BuilderOptions.OUTPUT_OPTION));
File inputFile = new File(plainTextFile);
if (cmdLine.hasOption(BuilderOptions.FREQ_OPTION)) {
builder.readFreqList(new File(cmdLine.getOptionValue(BuilderOptions.FREQ_OPTION)));
inputFile = builder.addFreqData(inputFile, true);
}
builder.build(inputFile);
}
private File build(File plainTextDictFile) throws Exception {<FILL_FUNCTION_BODY>}
private File tokenizeInput(File plainTextDictFile) throws IOException {
// Tokenizer wordTokenizer = language.getWordTokenizer();
String encoding = getOption("fsa.dict.encoding");
String separatorChar = hasOption("fsa.dict.separator") ? getOption("fsa.dict.separator") : "";
File tempFile = File.createTempFile(SpellDictionaryBuilder.class.getSimpleName(), ".txt");
tempFile.deleteOnExit();
try (Scanner scanner = new Scanner(plainTextDictFile, encoding)) {
try (Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFile), encoding))) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
int sepPos = separatorChar.isEmpty() ? -1 : line.indexOf(separatorChar);
String occurrences = sepPos != -1 ? line.substring(sepPos + separatorChar.length()) : "";
String lineWithoutOcc = sepPos != -1 ? line.substring(0, sepPos) : line;
// List<String> tokens = wordTokenizer.tokenize(lineWithoutOcc);
List<String> tokens = Arrays.asList(lineWithoutOcc);
for (String token : tokens) {
if (token.length() > 0) {
out.write(token);
if (sepPos != -1) {
out.write(separatorChar);
if (tokens.size() == 1) {
out.write(occurrences);
} else {
// TODO: as the word occurrence data from
// https://github.com/mozilla-b2g/gaia/tree/master/apps/keyboard/js/imes/latin/dictionaries
// has already been assigned in a previous step, we now cannot just use
// that value after having changed the tokenization...
out.write('A'); // assume least frequent
}
}
out.write('\n');
}
}
}
}
}
return tempFile;
}
}
|
File tempFile = null;
try {
tempFile = tokenizeInput(plainTextDictFile);
return buildFSA(tempFile);
} finally {
if (tempFile != null) {
tempFile.delete();
}
}
| 943
| 69
| 1,012
|
<methods><variables>private static final int FIRST_RANGE_CODE,private static final int FREQ_RANGES_IN,private static final int FREQ_RANGES_OUT,private final Map<java.lang.String,java.lang.Integer> freqList,private java.lang.String outputFilename,private final java.util.regex.Pattern pFreqEntry,private final java.util.regex.Pattern pTaggerEntry,private final java.util.Properties props,private static final SerializationFormat serializationFormat
|
languagetool-org_languagetool
|
languagetool/languagetool-tools/src/main/java/org/languagetool/tools/SynthDictionaryBuilder.java
|
SynthDictionaryBuilder
|
getPosTagIgnoreRegex
|
class SynthDictionaryBuilder extends DictionaryBuilder {
/**
* It makes sense to remove all forms from the synthesizer dict where POS tags indicate "unknown form",
* "foreign word" etc., as they only take space. Probably nobody will ever use them:
*/
private static final String POLISH_IGNORE_REGEX = ":neg|qub|depr";
private static String tagsFilename;
SynthDictionaryBuilder(File infoFile) throws IOException {
super(infoFile);
}
public static void main(String[] args) throws Exception {
BuilderOptions builderOptions = new BuilderOptions();
builderOptions.addOption(BuilderOptions.INPUT_OPTION, true,
BuilderOptions.TAB_INPUT_HELP, true);
builderOptions.addOption(BuilderOptions.INFO_OPTION, true,
BuilderOptions.INFO_HELP, true);
CommandLine cmdLine = builderOptions.parseArguments(args, SynthDictionaryBuilder.class);
File plainTextDictFile = new File(cmdLine.getOptionValue(BuilderOptions.INPUT_OPTION));
File infoFile = new File(cmdLine.getOptionValue(BuilderOptions.INFO_OPTION));
SynthDictionaryBuilder builder = new SynthDictionaryBuilder(infoFile);
builder.setOutputFilename(cmdLine.getOptionValue(BuilderOptions.OUTPUT_OPTION));
tagsFilename = cmdLine.getOptionValue(BuilderOptions.OUTPUT_OPTION) + "_tags.txt";
builder.build(plainTextDictFile, infoFile);
}
File build(File plainTextDictFile, File infoFile) throws Exception {
String outputFilename = this.getOutputFilename();
File outputDirectory = new File(outputFilename).getParentFile();
File tempFile = File.createTempFile(SynthDictionaryBuilder.class.getSimpleName(), ".txt", outputDirectory);
File reversedFile = null;
try {
Set<String> itemsToBeIgnored = getIgnoreItems(new File(infoFile.getParent(), "filter-archaic.txt"));
Pattern ignorePosRegex = getPosTagIgnoreRegex(infoFile);
reversedFile = reverseLineContent(plainTextDictFile, itemsToBeIgnored, ignorePosRegex);
writePosTagsToFile(plainTextDictFile, new File(tagsFilename));
return buildDict(reversedFile);
} finally {
tempFile.delete();
if (reversedFile != null) {
reversedFile.delete();
}
}
}
private Set<String> getIgnoreItems(File file) throws FileNotFoundException {
Set<String> result = new HashSet<>();
if (file.exists()) {
try (Scanner scanner = new Scanner(file, getOption("fsa.dict.encoding"))) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (!line.startsWith("#")) {
result.add(line);
}
}
}
System.out.println("Loaded " + result.size() + " words to be ignored from " + file);
} else {
System.out.println("File " + file.getAbsolutePath() + " does not exist, no items will be ignored");
}
return result;
}
@Nullable
private Pattern getPosTagIgnoreRegex(File infoFile) {<FILL_FUNCTION_BODY>}
private File reverseLineContent(File plainTextDictFile, Set<String> itemsToBeIgnored, Pattern ignorePosRegex) throws IOException {
File reversedFile = File.createTempFile(SynthDictionaryBuilder.class.getSimpleName() + "_reversed", ".txt");
reversedFile.deleteOnExit();
String separator = getOption("fsa.dict.separator");
if (separator == null || separator.trim().isEmpty()) {
throw new IOException("A separator character (fsa.dict.separator) must be defined in the dictionary info file.");
}
String encoding = getOption("fsa.dict.encoding");
int posIgnoreCount = 0;
Scanner scanner = new Scanner(plainTextDictFile, encoding);
try (Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(reversedFile), encoding))) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (itemsToBeIgnored.contains(line)) {
System.out.println("Ignoring: " + line);
continue;
}
String[] parts = line.split("\t");
if (parts.length == 3) {
String posTag = parts[2];
if (ignorePosRegex != null && ignorePosRegex.matcher(posTag).find()) {
posIgnoreCount++;
continue;
}
out.write(parts[0] + separator + parts[1] + "|" + posTag );
out.write('\n');
} else {
System.err.println("Invalid input, expected three tab-separated columns in " + plainTextDictFile + ": " + line + " => ignoring");
}
}
scanner.close();
}
System.out.println("Number of lines ignored due to POS tag filter ('" + ignorePosRegex + "'): " + posIgnoreCount);
return reversedFile;
}
private void writePosTagsToFile(File plainTextDictFile, File tagFile) throws IOException {
Set<String> posTags = collectTags(plainTextDictFile);
List<String> sortedTags = new ArrayList<>(posTags);
Collections.sort(sortedTags);
System.out.println("Writing tag file to " + tagFile);
try (FileWriter out = new FileWriter(tagFile)) {
for (String tag : sortedTags) {
out.write(tag);
out.write('\n');
}
}
}
private Set<String> collectTags(File plainTextDictFile) throws IOException {
Set<String> posTags = new HashSet<>();
try (Scanner scanner = new Scanner(plainTextDictFile, getOption("fsa.dict.encoding"))) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] parts = line.split("\t");
if (parts.length == 3) {
String posTag = parts[2];
posTags.add(posTag);
} else {
System.err.println("Invalid input, expected three tab-separated columns in " + plainTextDictFile + ": " + line + " => ignoring");
}
}
}
return posTags;
}
}
|
String fileName = infoFile.getName();
int underscorePos = fileName.indexOf('_');
if (underscorePos == -1) {
throw new IllegalArgumentException("Please specify an .info file for a synthesizer as the second parameter, named '<xyz>_synth.info', with <xyz> being a language'");
}
String baseName = fileName.substring(0, underscorePos);
if (baseName.equals("polish")) {
return Pattern.compile(POLISH_IGNORE_REGEX);
}
return null;
| 1,697
| 146
| 1,843
|
<methods><variables>private static final int FIRST_RANGE_CODE,private static final int FREQ_RANGES_IN,private static final int FREQ_RANGES_OUT,private final Map<java.lang.String,java.lang.Integer> freqList,private java.lang.String outputFilename,private final java.util.regex.Pattern pFreqEntry,private final java.util.regex.Pattern pTaggerEntry,private final java.util.Properties props,private static final SerializationFormat serializationFormat
|
languagetool-org_languagetool
|
languagetool/languagetool-wikipedia/src/main/java/org/languagetool/dev/RareWordsFinder.java
|
RareWordsFinder
|
run
|
class RareWordsFinder {
private static final String dictInClassPath = "/en/hunspell/en_US.dict";
private final HunspellDictionary hunspell;
private RareWordsFinder(String hunspellBase) throws IOException {
hunspell = Hunspell.getDictionary(Paths.get(hunspellBase + ".dic"), Paths.get(hunspellBase + ".aff"));
}
private void run(File input, int minimum) throws FileNotFoundException, CharacterCodingException {<FILL_FUNCTION_BODY>}
private boolean suggestionsMightBeUseful(String word, List<String> suggestions) {
return suggestions.size() > 0 &&
!suggestions.get(0).contains(" ") &&
!suggestions.get(0).equals(word + "s") &&
!suggestions.get(0).equals(word.replaceFirst("s$", ""));
}
public static void main(String[] args) throws IOException {
if (args.length != 3) {
System.out.println("Usage: " + RareWordsFinder.class.getSimpleName() + " <wordFile> <hunspellBase> <limit>");
System.out.println(" <wordFile> is a word file with occurrence counts, separated by tabs");
System.out.println(" <hunspellBase> is the hunspell file without suffix, e.g. '/path/to/en_US'");
System.out.println(" <limit> only words with this many or less occurrences are considered");
System.exit(1);
}
RareWordsFinder finder = new RareWordsFinder(args[1]);
File input = new File(args[0]);
int minimum = Integer.parseInt(args[2]);
finder.run(input, minimum);
}
}
|
MorfologikSpeller speller = new MorfologikSpeller(dictInClassPath, 1);
int lineCount = 0;
int wordCount = 0;
try (Scanner s = new Scanner(input)) {
while (s.hasNextLine()) {
String line = s.nextLine();
String[] parts = line.split("\t");
String word = parts[0];
long count = Long.parseLong(parts[1]);
if (count <= minimum) {
if (word.matches("[a-zA-Z]+") && !word.matches("[A-Z]+") && !word.matches("[a-zA-Z]+[A-Z]+[a-zA-Z]*") && !word.matches("[A-Z].*")) {
boolean isMisspelled = speller.isMisspelled(word);
if (!isMisspelled) {
//List<String> suggestions = speller.getSuggestions(word); // seems to work only for words that are actually misspellings
List<String> suggestions = hunspell.suggest(word);
suggestions.remove(word);
if (suggestionsMightBeUseful(word, suggestions)) {
System.out.println(word + "\t" + count + " -> " + String.join(", ", suggestions));
wordCount++;
}
}
}
}
lineCount++;
if (lineCount % 1_000_000 == 0) {
System.out.println("lineCount: " + lineCount + ", words found: " + wordCount);
}
}
System.out.println("Done. lineCount: " + lineCount + ", words found: " + wordCount);
}
| 472
| 447
| 919
|
<no_super_class>
|
languagetool-org_languagetool
|
languagetool/languagetool-wikipedia/src/main/java/org/languagetool/dev/dumpcheck/AfterTheDeadlineChecker.java
|
AfterTheDeadlineChecker
|
main
|
class AfterTheDeadlineChecker {
private final String urlPrefix;
private final int maxSentenceCount;
AfterTheDeadlineChecker(String urlPrefix, int maxSentenceCount) {
this.urlPrefix = urlPrefix;
this.maxSentenceCount = maxSentenceCount;
}
private void run(Language lang, List<String> fileNames) throws IOException, XPathExpressionException {
MixingSentenceSource mixingSource = MixingSentenceSource.create(fileNames, lang);
int sentenceCount = 0;
while (mixingSource.hasNext()) {
Sentence sentence = mixingSource.next();
String resultXml = queryAtDServer(sentence.getText());
System.out.println("==========================");
System.out.println(sentence.getSource() + ": " + sentence.getText());
List<String> matches = getMatches(resultXml);
for (String match : matches) {
System.out.println(" " + match);
}
sentenceCount++;
if (maxSentenceCount > 0 && sentenceCount > maxSentenceCount) {
System.err.println("Limit reached, stopping at sentence #" + sentenceCount);
break;
}
}
}
private String queryAtDServer(String text) {
try {
URL url = new URL(urlPrefix + URLEncoder.encode(text, "UTF-8"));
InputStream contentStream = (InputStream) url.getContent();
return StringTools.streamToString(contentStream, "UTF-8");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private List<String> getMatches(String resultXml) throws XPathExpressionException {
List<String> matches = new ArrayList<>();
Document document = getDocument(resultXml);
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList errors = (NodeList)xPath.evaluate("//error", document, XPathConstants.NODESET);
for (int i = 0; i < errors.getLength(); i++) {
Node error = errors.item(i);
String string = xPath.evaluate("string", error);
String description = xPath.evaluate("description", error);
matches.add(description + ": " + string);
}
return matches;
}
private Document getDocument(String xml) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource inputSource = new InputSource(new StringReader(xml));
return builder.parse(inputSource);
} catch (Exception e) {
throw new RuntimeException("Could not parse XML: " + xml, e);
}
}
public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>}
}
|
if (args.length < 4) {
System.out.println("Usage: " + AfterTheDeadlineChecker.class.getSimpleName() + " <langCode> <atdUrlPrefix> <file...>");
System.out.println(" <langCode> a language code like 'en' for English");
System.out.println(" <atdUrlPrefix> URL prefix of After the Deadline server, like 'http://localhost:1059/checkDocument?data='");
System.out.println(" <sentenceLimit> Maximum number of sentences to check, or 0 for no limit");
System.out.println(" <file...> Wikipedia and/or Tatoeba file(s)");
System.exit(1);
}
Language language = Languages.getLanguageForShortCode(args[0]);
String urlPrefix = args[1];
int maxSentenceCount = Integer.parseInt(args[2]);
List<String> files = Arrays.asList(args).subList(3, args.length);
AfterTheDeadlineChecker atdChecker = new AfterTheDeadlineChecker(urlPrefix, maxSentenceCount);
atdChecker.run(language, files);
| 716
| 298
| 1,014
|
<no_super_class>
|
languagetool-org_languagetool
|
languagetool/languagetool-wikipedia/src/main/java/org/languagetool/dev/dumpcheck/CSVHandler.java
|
CSVHandler
|
handleResult
|
class CSVHandler extends ResultHandler {
CSVHandler(int maxSentences, int maxErrors) {
super(maxSentences, maxErrors);
}
@Override
protected void handleResult(Sentence sentence, List<RuleMatch> ruleMatches, Language language) {<FILL_FUNCTION_BODY>}
private String noTabs(String s) {
return s.replace("\t", "\\t");
}
@Override
public void close() throws Exception {
}
}
|
String sentenceStr = sentence.getText();
if (ruleMatches.size() > 0) {
for (RuleMatch match : ruleMatches) {
sentenceStr = noTabs(sentenceStr.substring(0, match.getFromPos())) +
"__" +
noTabs(sentenceStr.substring(match.getFromPos(), match.getToPos())) +
"__" +
noTabs(sentenceStr.substring(match.getToPos()));
System.out.println("MATCH\t" + match.getRule().getFullId() + "\t" + noTabs(sentenceStr));
checkMaxErrors(++errorCount);
}
} else {
System.out.println("NOMATCH\t\t" + noTabs(sentenceStr));
}
checkMaxSentences(++sentenceCount);
| 129
| 216
| 345
|
<methods><variables>protected static final int CONTEXT_SIZE,protected static final java.lang.String MARKER_END,protected static final java.lang.String MARKER_START,protected int errorCount,private final non-sealed int maxErrors,private final non-sealed int maxSentences,protected int sentenceCount
|
languagetool-org_languagetool
|
languagetool/languagetool-wikipedia/src/main/java/org/languagetool/dev/dumpcheck/CommonCrawlSentenceSource.java
|
CommonCrawlSentenceSource
|
fillSentences
|
class CommonCrawlSentenceSource extends SentenceSource {
private static final int MIN_LENGTH = 15;
private static final int MAX_LENGTH = 250;
private final List<CommonCrawlSentence> sentences;
private final XZInputStream xzIn;
private int tooShort = 0;
private int tooLong = 0;
private int empty = 0;
private int wrongStartChar = 0;
private int wrongEndChar = 0;
private int count = 0;
private int lineCount = 0;
CommonCrawlSentenceSource(InputStream input, Language language, Pattern filter) throws IOException {
super(language, filter);
sentences = new ArrayList<>();
xzIn = new XZInputStream(input);
}
@Override
public boolean hasNext() {
fillSentences();
return sentences.size() > 0;
}
@Override
public Sentence next() {
fillSentences();
if (sentences.isEmpty()) {
throw new NoSuchElementException();
}
CommonCrawlSentence ccSentence = sentences.remove(0);
return new Sentence(ccSentence.sentence, getSource(), null, null, ccSentence.articleCount);
}
@Override
public String getSource() {
return "commoncrawl";
}
private void fillSentences() {<FILL_FUNCTION_BODY>}
private void printStats() {
System.out.println("lines : " + lineCount);
System.out.println("indexed sentences: " + count);
System.out.println("tooShort : " + tooShort);
System.out.println("tooLong : " + tooLong);
System.out.println("empty : " + empty);
System.out.println("wrongStartChar : " + wrongStartChar);
System.out.println("wrongEndChar : " + wrongEndChar);
}
private static class CommonCrawlSentence {
final String sentence;
final int articleCount;
CommonCrawlSentence(String sentence, int articleCount) {
this.sentence = sentence;
this.articleCount = articleCount;
}
}
}
|
byte[] buffer = new byte[8192];
int n;
try {
while (sentences.isEmpty() && (n = xzIn.read(buffer)) != -1) {
String buf = new String(buffer, 0, n); // TODO: not always correct, we need to wait for line end first?
String[] lines = buf.split("\n");
for (String line : lines) {
lineCount++;
line = line.trim();
if (line.isEmpty()) {
empty++;
continue;
}
boolean startLower = Character.isLowerCase(line.charAt(0));
if (startLower) {
//System.out.println("IGNORING, lc start: " + line);
wrongStartChar++;
} else if (line.length() < MIN_LENGTH) {
//System.out.println("IGNORING, too short: " + line);
tooShort++;
} else if (line.length() > MAX_LENGTH) {
//System.out.println("IGNORING, too long (" + line.length() + "): " + line);
tooLong++;
} else if (line.endsWith(".") || line.endsWith("!") || line.endsWith("?") || line.endsWith(":")) {
//System.out.println(line);
sentences.add(new CommonCrawlSentence(line, count++));
} else {
wrongEndChar++;
// well, this way we also miss headlines and the sentences that are split
// over more than one line, but I see now simple way to merge them...
//System.out.println("IGNORING, wrong end char: " + line);
}
}
}
} catch (IOException e) {
printStats();
throw new RuntimeException(e);
}
| 564
| 463
| 1,027
|
<methods>public abstract java.lang.String getSource() ,public abstract boolean hasNext() ,public abstract org.languagetool.dev.dumpcheck.Sentence next() ,public void remove() ,public java.lang.String toString() <variables>static final int MAX_SENTENCE_LENGTH,static final int MIN_SENTENCE_LENGTH,static final int MIN_SENTENCE_TOKEN_COUNT,private final non-sealed java.util.regex.Pattern acceptPattern,private int ignoreCount,private final non-sealed org.languagetool.tokenizers.Tokenizer wordTokenizer
|
languagetool-org_languagetool
|
languagetool/languagetool-wikipedia/src/main/java/org/languagetool/dev/dumpcheck/DatabaseHandler.java
|
DatabaseHandler
|
handleResult
|
class DatabaseHandler extends ResultHandler {
private static final int MAX_CONTEXT_LENGTH = 500;
private static final int SMALL_CONTEXT_LENGTH = 40; // do not modify - it would break lookup of errors marked as 'false alarm'
private final Connection conn;
private final ContextTools contextTools;
private final ContextTools smallContextTools;
private final PreparedStatement insertSt;
private final int batchSize;
private int batchCount = 0;
DatabaseHandler(File propertiesFile, int maxSentences, int maxErrors) {
super(maxSentences, maxErrors);
String insertSql = "INSERT INTO corpus_match " +
"(version, language_code, ruleid, rule_category, rule_subid, rule_description, message, error_context, small_error_context, corpus_date, " +
"check_date, sourceuri, source_type, is_visible) "+
"VALUES (0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)";
Properties dbProperties = new Properties();
try (FileInputStream inStream = new FileInputStream(propertiesFile)) {
dbProperties.load(inStream);
String dbUrl = getProperty(dbProperties, "dbUrl");
String dbUser = getProperty(dbProperties, "dbUser");
String dbPassword = getProperty(dbProperties, "dbPassword");
batchSize = Integer.decode(dbProperties.getProperty("batchSize", "1"));
conn = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
insertSt = conn.prepareStatement(insertSql);
} catch (SQLException | IOException e) {
throw new RuntimeException(e);
}
contextTools = new ContextTools();
contextTools.setContextSize(MAX_CONTEXT_LENGTH);
contextTools.setErrorMarker(MARKER_START, MARKER_END);
contextTools.setEscapeHtml(false);
smallContextTools = new ContextTools();
smallContextTools.setContextSize(SMALL_CONTEXT_LENGTH);
smallContextTools.setErrorMarker(MARKER_START, MARKER_END);
smallContextTools.setEscapeHtml(false);
}
private String getProperty(Properties prop, String key) {
String value = prop.getProperty(key);
if (value == null) {
throw new RuntimeException("Required key '" + key + "' not found in properties");
}
return value;
}
@Override
protected void handleResult(Sentence sentence, List<RuleMatch> ruleMatches, Language language) {<FILL_FUNCTION_BODY>}
private void executeBatch() throws SQLException {
boolean autoCommit = conn.getAutoCommit();
conn.setAutoCommit(false);
try {
insertSt.executeBatch();
if (autoCommit) {
conn.commit();
}
} finally {
conn.setAutoCommit(autoCommit);
}
}
@Override
public void close() throws Exception {
if (insertSt != null) {
if (batchCount > 0) {
executeBatch();
}
insertSt.close();
}
if (conn != null) {
conn.close();
}
}
}
|
try {
java.sql.Date nowDate = new java.sql.Date(new Date().getTime());
for (RuleMatch match : ruleMatches) {
String smallContext = smallContextTools.getContext(match.getFromPos(), match.getToPos(), sentence.getText());
insertSt.setString(1, language.getShortCode());
Rule rule = match.getRule();
insertSt.setString(2, rule.getId());
insertSt.setString(3, rule.getCategory().getName());
if (rule instanceof AbstractPatternRule) {
AbstractPatternRule patternRule = (AbstractPatternRule) rule;
insertSt.setString(4, patternRule.getSubId());
} else {
insertSt.setNull(4, Types.VARCHAR);
}
insertSt.setString(5, rule.getDescription());
insertSt.setString(6, StringUtils.abbreviate(match.getMessage(), 255));
String context = contextTools.getContext(match.getFromPos(), match.getToPos(), sentence.getText());
if (context.length() > MAX_CONTEXT_LENGTH) {
// let's skip these strange cases, as shortening the text might leave us behind with invalid markup etc
continue;
}
insertSt.setString(7, context);
insertSt.setString(8, StringUtils.abbreviate(smallContext, 255));
insertSt.setDate(9, nowDate); // should actually be the dump's date, but isn't really used anyway...
insertSt.setDate(10, nowDate);
insertSt.setString(11, sentence.getUrl());
insertSt.setString(12, sentence.getSource());
insertSt.addBatch();
if (++batchCount >= batchSize){
executeBatch();
batchCount = 0;
}
checkMaxErrors(++errorCount);
if (errorCount % 100 == 0) {
System.out.println("Storing error #" + errorCount + " for text:");
System.out.println(" " + sentence.getText());
}
}
checkMaxSentences(++sentenceCount);
} catch (DocumentLimitReachedException | ErrorLimitReachedException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("Error storing matches for '" + sentence.getTitle() + "'", e);
}
| 831
| 606
| 1,437
|
<methods><variables>protected static final int CONTEXT_SIZE,protected static final java.lang.String MARKER_END,protected static final java.lang.String MARKER_START,protected int errorCount,private final non-sealed int maxErrors,private final non-sealed int maxSentences,protected int sentenceCount
|
languagetool-org_languagetool
|
languagetool/languagetool-wikipedia/src/main/java/org/languagetool/dev/dumpcheck/MixingSentenceSource.java
|
MixingSentenceSource
|
hasNext
|
class MixingSentenceSource extends SentenceSource {
private final List<SentenceSource> sources;
private final Map<String, Integer> sourceDistribution = new HashMap<>();
private int count;
public static MixingSentenceSource create(List<String> dumpFileNames, Language language) throws IOException {
return create(dumpFileNames, language, null);
}
public static MixingSentenceSource create(List<String> dumpFileNames, Language language, Pattern filter) throws IOException {
List<SentenceSource> sources = new ArrayList<>();
for (String dumpFileName : dumpFileNames) {
File file = new File(dumpFileName);
if (file.getName().endsWith(".xml")) {
sources.add(new WikipediaSentenceSource(new FileInputStream(dumpFileName), language, filter));
} else if (file.getName().startsWith("tatoeba-")) {
sources.add(new TatoebaSentenceSource(new FileInputStream(dumpFileName), language, filter));
} else if (file.getName().endsWith(".txt")) {
sources.add(new PlainTextSentenceSource(new FileInputStream(dumpFileName), language, filter));
} else if (file.getName().endsWith(".xz")) {
sources.add(new CommonCrawlSentenceSource(new FileInputStream(dumpFileName), language, filter));
} else {
throw new RuntimeException("Could not find a source handler for " + dumpFileName +
" - Wikipedia files must be named '*.xml', Tatoeba files must be named 'tatoeba-*', CommonCrawl files '*.xz', plain text files '*.txt'");
}
}
return new MixingSentenceSource(sources, language);
}
private MixingSentenceSource(List<SentenceSource> sources, Language language) {
super(language);
this.sources = sources;
}
Map<String, Integer> getSourceDistribution() {
return sourceDistribution;
}
@Override
public boolean hasNext() {<FILL_FUNCTION_BODY>}
@Override
public Sentence next() {
SentenceSource sentenceSource = sources.get(count % sources.size());
while (!sentenceSource.hasNext()) {
sources.remove(sentenceSource);
if (sources.isEmpty()) {
throw new NoSuchElementException();
}
count++;
sentenceSource = sources.get(count % sources.size());
}
count++;
Sentence next = sentenceSource.next();
updateDistributionMap(next);
return next;
}
private void updateDistributionMap(Sentence next) {
Integer prevCount = sourceDistribution.get(next.getSource());
if (prevCount != null) {
sourceDistribution.put(next.getSource(), prevCount + 1);
} else {
sourceDistribution.put(next.getSource(), 1);
}
}
@Override
public String getSource() {
return StringUtils.join(sources, ", ");
}
int getIgnoredCount() {
int sum = 0;
for (SentenceSource source : sources) {
sum += source.getIgnoredCount();
}
return sum;
}
}
|
for (SentenceSource source : sources) {
if (source.hasNext()) {
return true;
}
}
return false;
| 812
| 41
| 853
|
<methods>public abstract java.lang.String getSource() ,public abstract boolean hasNext() ,public abstract org.languagetool.dev.dumpcheck.Sentence next() ,public void remove() ,public java.lang.String toString() <variables>static final int MAX_SENTENCE_LENGTH,static final int MIN_SENTENCE_LENGTH,static final int MIN_SENTENCE_TOKEN_COUNT,private final non-sealed java.util.regex.Pattern acceptPattern,private int ignoreCount,private final non-sealed org.languagetool.tokenizers.Tokenizer wordTokenizer
|
languagetool-org_languagetool
|
languagetool/languagetool-wikipedia/src/main/java/org/languagetool/dev/dumpcheck/PlainTextSentenceSource.java
|
PlainTextSentenceSource
|
fillSentences
|
class PlainTextSentenceSource extends SentenceSource {
private final List<String> sentences;
private final Scanner scanner;
// Each sentence is one article, but count anyway so it's coherent with what the Wikipedia code does:
private int articleCount = 0;
private String currentUrl = null;
public PlainTextSentenceSource(InputStream textInput, Language language) {
this(textInput, language, null);
}
/** @since 3.0 */
public PlainTextSentenceSource(InputStream textInput, Language language, Pattern filter) {
super(language, filter);
scanner = new Scanner(textInput);
sentences = new ArrayList<>();
}
@Override
public boolean hasNext() {
fillSentences();
return sentences.size() > 0;
}
@Override
public Sentence next() {
fillSentences();
if (sentences.isEmpty()) {
throw new NoSuchElementException();
}
return new Sentence(sentences.remove(0), getSource(), "<plaintext>", null, ++articleCount);
}
@Override
public String getSource() {
return currentUrl;
}
private void fillSentences() {<FILL_FUNCTION_BODY>}
}
|
while (sentences.isEmpty() && scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.isEmpty()) {
continue;
}
if (line.startsWith("# source:")) {
currentUrl = line.substring("# source: ".length());
continue;
}
if (acceptSentence(line)) {
sentences.add(line);
}
}
| 326
| 109
| 435
|
<methods>public abstract java.lang.String getSource() ,public abstract boolean hasNext() ,public abstract org.languagetool.dev.dumpcheck.Sentence next() ,public void remove() ,public java.lang.String toString() <variables>static final int MAX_SENTENCE_LENGTH,static final int MIN_SENTENCE_LENGTH,static final int MIN_SENTENCE_TOKEN_COUNT,private final non-sealed java.util.regex.Pattern acceptPattern,private int ignoreCount,private final non-sealed org.languagetool.tokenizers.Tokenizer wordTokenizer
|
languagetool-org_languagetool
|
languagetool/languagetool-wikipedia/src/main/java/org/languagetool/dev/dumpcheck/ResultHandler.java
|
ResultHandler
|
checkMaxErrors
|
class ResultHandler implements AutoCloseable {
protected static final int CONTEXT_SIZE = 50;
protected static final String MARKER_START = "<err>";
protected static final String MARKER_END = "</err>";
protected int sentenceCount = 0;
protected int errorCount = 0;
protected abstract void handleResult(Sentence sentence, List<RuleMatch> ruleMatches, Language language);
private final int maxSentences;
private final int maxErrors;
protected ResultHandler(int maxSentences, int maxErrors) {
this.maxSentences = maxSentences;
this.maxErrors = maxErrors;
}
protected void checkMaxSentences(int i) {
if (maxSentences > 0 && sentenceCount >= maxSentences) {
throw new DocumentLimitReachedException(maxSentences);
}
}
protected void checkMaxErrors(int i) {<FILL_FUNCTION_BODY>}
}
|
if (maxErrors > 0 && errorCount >= maxErrors) {
throw new ErrorLimitReachedException(maxErrors);
}
| 244
| 35
| 279
|
<no_super_class>
|
languagetool-org_languagetool
|
languagetool/languagetool-wikipedia/src/main/java/org/languagetool/dev/dumpcheck/SentenceSource.java
|
SentenceSource
|
acceptSentence
|
class SentenceSource implements Iterator<Sentence> {
static final int MIN_SENTENCE_LENGTH = 10;
static final int MIN_SENTENCE_TOKEN_COUNT = 4;
static final int MAX_SENTENCE_LENGTH = 300;
private final Tokenizer wordTokenizer;
private final Pattern acceptPattern;
private int ignoreCount = 0;
SentenceSource(Language language) {
this(language, null);
}
/** @since 3.0 */
SentenceSource(Language language, Pattern acceptPattern) {
wordTokenizer = language.getWordTokenizer();
this.acceptPattern = acceptPattern;
}
@Override
public abstract boolean hasNext();
/**
* Return the next sentence. Sentences from the source are filtered by length
* to remove very short and very long sentences.
*/
@Override
public abstract Sentence next();
public abstract String getSource();
@Override
public void remove() {
throw new UnsupportedOperationException("remove not supported");
}
@Override
public String toString() {
return getSource() + "-" + super.toString();
}
protected boolean acceptSentence(String sentence) {<FILL_FUNCTION_BODY>}
int getIgnoredCount() {
return ignoreCount;
}
private int countTokens(String sentence) {
int realTokens = 0;
List<String> allTokens = wordTokenizer.tokenize(sentence);
for (String token : allTokens) {
if (!token.trim().isEmpty()) {
realTokens++;
}
}
return realTokens;
}
}
|
if (acceptPattern != null) {
if (!acceptPattern.matcher(sentence).find()) {
// useful speedup: we don't consider sentences that cannot match anyway
ignoreCount++;
return false;
}
}
String trimSentence = sentence.trim();
boolean accept = trimSentence.length() >= MIN_SENTENCE_LENGTH && trimSentence.length() <= MAX_SENTENCE_LENGTH
&& countTokens(trimSentence) >= MIN_SENTENCE_TOKEN_COUNT;
if (accept) {
return true;
} else {
ignoreCount++;
return false;
}
| 439
| 166
| 605
|
<no_super_class>
|
languagetool-org_languagetool
|
languagetool/languagetool-wikipedia/src/main/java/org/languagetool/dev/dumpcheck/SentenceSourceIndexer.java
|
SentenceSourceIndexer
|
writeMetaDocuments
|
class SentenceSourceIndexer extends DefaultHandler implements AutoCloseable {
public static final String MAX_DOC_COUNT_VALUE = "maxDocCountValue";
public static final String MAX_DOC_COUNT_FIELD = "maxDocCount";
public static final String MAX_DOC_COUNT_FIELD_VAL = "1";
private static final boolean LC_ONLY = true;
private final Indexer indexer;
private final int maxSentences;
private boolean stopped = false;
private int sentenceCount = 0;
SentenceSourceIndexer(Directory dir, Language language, int maxSentences, Analyzer analyzer) {
if (analyzer == null) {
this.indexer = new Indexer(dir, language);
} else {
this.indexer = new Indexer(dir, language, analyzer);
}
this.indexer.setLowercaseOnly(LC_ONLY);
this.maxSentences = maxSentences;
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
super.run();
stopped = true;
System.out.println("----- Got SIGHUP, will commit and exit ----");
try {
indexer.commit();
System.out.println("----- commit done, will exit now ----");
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
SentenceSourceIndexer(Directory dir, Language language, int maxSentences) {
this(dir, language, maxSentences, null);
}
@Override
public void close() throws Exception {
indexer.close();
}
private void run(List<String> dumpFileNames, Language language) throws IOException {
MixingSentenceSource mixingSource = MixingSentenceSource.create(dumpFileNames, language);
while (mixingSource.hasNext()) {
if (stopped) {
return;
}
Sentence sentence = mixingSource.next();
if (sentenceCount % 10_000 == 0) {
//System.out.println("Indexing sentence #" + sentenceCount + " (" + mixingSource.getSourceDistribution() + "):"); // doesn't work well with URLs as source
System.out.println("Indexing sentence #" + sentenceCount + ":");
System.out.println(" [" + sentence.getSource() + "] " + sentence);
}
indexer.indexSentence(sentence, sentenceCount);
sentenceCount++;
if (maxSentences > 0 && sentenceCount >= maxSentences) {
throw new DocumentLimitReachedException(maxSentences);
}
}
}
private void writeMetaDocuments() throws IOException {<FILL_FUNCTION_BODY>}
public static void main(String... args) throws Exception {
if (args.length != 5) {
System.out.println("Usage: " + SentenceSourceIndexer.class.getSimpleName() + " <dataFile...> <indexDir> <languageCode> <maxSentences> <indexPosTags>");
System.out.println("\t<dataFiles> comma-separated list of a Wikipedia XML dump (*.xml) and/or Tatoeba files (tatoeba-*)");
System.out.println("\t<indexDir> directory where Lucene index will be written to, existing index content will be removed");
System.out.println("\t<languageCode> short code like en for English, de for German etc");
System.out.println("\t<maxSentences> maximum number of sentences to be indexed, use 0 for no limit");
System.out.println("\t<indexPosTags> 1 to also index POS tags (i.e. analyze text by LT), 0 to index only the plain text");
System.exit(1);
}
List<String> dumpFilesNames = Arrays.asList(args[0].split(","));
File indexDir = new File(args[1]);
String languageCode = args[2];
int maxSentences = Integer.parseInt(args[3]);
Language language = Languages.getLanguageForShortCode(languageCode);
if (maxSentences == 0) {
System.out.println("Going to index contents from " + dumpFilesNames);
} else {
System.out.println("Going to index up to " + maxSentences + " sentences from " + dumpFilesNames);
}
System.out.println("Output index dir: " + indexDir);
long start = System.currentTimeMillis();
Analyzer analyzer;
String indexPos = args[4];
if (indexPos.equals("1")) {
analyzer = null; // this will use LanguageToolAnalyzer
} else if (indexPos.equals("0")) {
analyzer = new StandardAnalyzer(new CharArraySet(Collections.emptyList(), false));
} else {
throw new IllegalArgumentException("Unknown value '" + indexPos + "' for indexPosTags parameter, use 0 or 1");
}
try (FSDirectory fsDirectory = FSDirectory.open(indexDir.toPath());
SentenceSourceIndexer indexer = new SentenceSourceIndexer(fsDirectory, language, maxSentences, analyzer)) {
try {
indexer.run(dumpFilesNames, language);
} catch (DocumentLimitReachedException e) {
System.out.println("Sentence limit (" + e.getLimit() + ") reached, stopping indexing");
} finally {
indexer.writeMetaDocuments();
}
if (analyzer != null) {
analyzer.close();
}
}
long end = System.currentTimeMillis();
float minutes = (end - start) / (float)(1000 * 60);
System.out.printf("Indexing took %.2f minutes\n", minutes);
}
}
|
Document doc = new Document();
doc.add(new StringField(MAX_DOC_COUNT_FIELD, MAX_DOC_COUNT_FIELD_VAL, Field.Store.YES));
doc.add(new StringField(MAX_DOC_COUNT_VALUE, sentenceCount + "", Field.Store.YES));
indexer.add(doc);
| 1,456
| 87
| 1,543
|
<methods>public void <init>() ,public void characters(char[], int, int) throws org.xml.sax.SAXException,public void endDocument() throws org.xml.sax.SAXException,public void endElement(java.lang.String, java.lang.String, java.lang.String) throws org.xml.sax.SAXException,public void endPrefixMapping(java.lang.String) throws org.xml.sax.SAXException,public void error(org.xml.sax.SAXParseException) throws org.xml.sax.SAXException,public void fatalError(org.xml.sax.SAXParseException) throws org.xml.sax.SAXException,public void ignorableWhitespace(char[], int, int) throws org.xml.sax.SAXException,public void notationDecl(java.lang.String, java.lang.String, java.lang.String) throws org.xml.sax.SAXException,public void processingInstruction(java.lang.String, java.lang.String) throws org.xml.sax.SAXException,public org.xml.sax.InputSource resolveEntity(java.lang.String, java.lang.String) throws java.io.IOException, org.xml.sax.SAXException,public void setDocumentLocator(org.xml.sax.Locator) ,public void skippedEntity(java.lang.String) throws org.xml.sax.SAXException,public void startDocument() throws org.xml.sax.SAXException,public void startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) throws org.xml.sax.SAXException,public void startPrefixMapping(java.lang.String, java.lang.String) throws org.xml.sax.SAXException,public void unparsedEntityDecl(java.lang.String, java.lang.String, java.lang.String, java.lang.String) throws org.xml.sax.SAXException,public void warning(org.xml.sax.SAXParseException) throws org.xml.sax.SAXException<variables>
|
languagetool-org_languagetool
|
languagetool/languagetool-wikipedia/src/main/java/org/languagetool/dev/dumpcheck/StdoutHandler.java
|
StdoutHandler
|
handleResult
|
class StdoutHandler extends ResultHandler {
private final ContextTools contextTools = new ContextTools();
private final boolean verbose;
StdoutHandler(int maxSentences, int maxErrors) {
this(maxSentences, maxErrors, CONTEXT_SIZE);
}
StdoutHandler(int maxSentences, int maxErrors, int contextSize) {
this(maxSentences, maxErrors, contextSize, false);
}
StdoutHandler(int maxSentences, int maxErrors, int contextSize, boolean verbose) {
super(maxSentences, maxErrors);
contextTools.setContextSize(contextSize);
this.verbose = verbose;
//contextTools.setContextSize(100);
//contextTools.setErrorMarker("**", "**");
//contextTools.setEscapeHtml(false);
}
@Override
protected void handleResult(Sentence sentence, List<RuleMatch> ruleMatches, Language language) {<FILL_FUNCTION_BODY>}
@Override
public void close() throws Exception {
}
}
|
if (ruleMatches.size() > 0) {
int i = 1;
System.out.println("\nTitle: " + sentence.getTitle());
for (RuleMatch match : ruleMatches) {
String output = i + ".) Line " + (match.getLine() + 1) + ", column "
+ match.getColumn() + ", Rule ID: " + match.getSpecificRuleId(); //match.getRule().getId();
if (match.getRule() instanceof AbstractPatternRule) {
AbstractPatternRule pRule = (AbstractPatternRule) match.getRule();
output += "[" + pRule.getSubId() + "]";
}
if (match.getRule().isDefaultTempOff()) {
output += " [temp_off]";
}
if (verbose && match.getRule() instanceof AbstractPatternRule) {
AbstractPatternRule pRule = (AbstractPatternRule) match.getRule();
output += " ruleLine=" + pRule.getXmlLineNumber();
}
System.out.println(output);
String msg = match.getMessage();
msg = msg.replaceAll("<suggestion>", "'");
msg = msg.replaceAll("</suggestion>", "'");
System.out.println("Message: " + msg);
List<String> replacements = match.getSuggestedReplacements();
if (!replacements.isEmpty()) {
System.out.println("Suggestion: " + String.join("; ", replacements.subList(0, Math.min(replacements.size(), 5))));
}
if (match.getRule() instanceof AbstractPatternRule) {
AbstractPatternRule pRule = (AbstractPatternRule) match.getRule();
if (pRule.getSourceFile() != null) {
System.out.println("Rule source: " + pRule.getSourceFile());
}
}
System.out.println(contextTools.getPlainTextContext(match.getFromPos(), match.getToPos(), sentence.getText()));
//System.out.println(contextTools.getContext(match.getFromPos(), match.getToPos(), sentence.getText()));
i++;
checkMaxErrors(++errorCount);
}
}
checkMaxSentences(++sentenceCount);
| 274
| 569
| 843
|
<methods><variables>protected static final int CONTEXT_SIZE,protected static final java.lang.String MARKER_END,protected static final java.lang.String MARKER_START,protected int errorCount,private final non-sealed int maxErrors,private final non-sealed int maxSentences,protected int sentenceCount
|
languagetool-org_languagetool
|
languagetool/languagetool-wikipedia/src/main/java/org/languagetool/dev/dumpcheck/TatoebaSentenceSource.java
|
TatoebaSentenceSource
|
fillSentences
|
class TatoebaSentenceSource extends SentenceSource {
private final List<TatoebaSentence> sentences;
private final Scanner scanner;
// Each sentence is one article, but count anyway so it's coherent with what the Wikipedia code does:
private int articleCount = 0;
TatoebaSentenceSource(InputStream textInput, Language language) {
this(textInput, language, null);
}
/** @since 3.0 */
TatoebaSentenceSource(InputStream textInput, Language language, Pattern filter) {
super(language, filter);
scanner = new Scanner(textInput);
sentences = new ArrayList<>();
}
@Override
public boolean hasNext() {
fillSentences();
return sentences.size() > 0;
}
@Override
public Sentence next() {
fillSentences();
if (sentences.isEmpty()) {
throw new NoSuchElementException();
}
TatoebaSentence sentence = sentences.remove(0);
String title = "Tatoeba-" + sentence.id;
return new Sentence(sentence.sentence, getSource(), title, "http://tatoeba.org", ++articleCount);
}
@Override
public String getSource() {
return "tatoeba";
}
private void fillSentences() {<FILL_FUNCTION_BODY>}
private static class TatoebaSentence {
long id;
String sentence;
private TatoebaSentence(long id, String sentence) {
this.id = id;
this.sentence = Objects.requireNonNull(sentence);
}
}
}
|
while (sentences.isEmpty() && scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.isEmpty()) {
continue;
}
String[] parts = line.split("\t");
if (parts.length != 3) {
System.err.println("Unexpected line format: expected three tab-separated columns: '" + line + "', skipping");
continue;
}
long id = Long.parseLong(parts[0]);
String sentence = parts[2]; // actually it's sometimes two (short) sentences, but anyway...
if (acceptSentence(sentence)) {
sentences.add(new TatoebaSentence(id, sentence));
}
}
| 429
| 185
| 614
|
<methods>public abstract java.lang.String getSource() ,public abstract boolean hasNext() ,public abstract org.languagetool.dev.dumpcheck.Sentence next() ,public void remove() ,public java.lang.String toString() <variables>static final int MAX_SENTENCE_LENGTH,static final int MIN_SENTENCE_LENGTH,static final int MIN_SENTENCE_TOKEN_COUNT,private final non-sealed java.util.regex.Pattern acceptPattern,private int ignoreCount,private final non-sealed org.languagetool.tokenizers.Tokenizer wordTokenizer
|
languagetool-org_languagetool
|
languagetool/languagetool-wikipedia/src/main/java/org/languagetool/dev/dumpcheck/WikipediaSentenceExtractor.java
|
WikipediaSentenceExtractor
|
extract
|
class WikipediaSentenceExtractor {
private void extract(Language language, String xmlDumpPath, String outputFile) throws IOException, CompressorException {<FILL_FUNCTION_BODY>}
private boolean skipSentence(String sentence) {
return sentence.trim().length() == 0 || Character.isLowerCase(sentence.trim().charAt(0));
}
public static void main(String[] args) throws IOException, CompressorException {
if (args.length != 3) {
System.out.println("Usage: " + WikipediaSentenceExtractor.class.getSimpleName() + " <langCode> <wikipediaXmlDump> <output>");
System.exit(1);
}
WikipediaSentenceExtractor extractor = new WikipediaSentenceExtractor();
extractor.extract(Languages.getLanguageForShortCode(args[0]), args[1], args[2]);
}
}
|
try (FileInputStream fis = new FileInputStream(xmlDumpPath);
BufferedInputStream bis = new BufferedInputStream(fis);
FileWriter fw = new FileWriter(outputFile)) {
InputStream input;
if (xmlDumpPath.endsWith(".bz2")) {
input = new CompressorStreamFactory().createCompressorInputStream(bis);
} else if (xmlDumpPath.endsWith(".xml")) {
input = bis;
} else {
throw new IllegalArgumentException("Unknown file name, expected '.xml' or '.bz2': " + xmlDumpPath);
}
int sentenceCount = 0;
WikipediaSentenceSource source = new WikipediaSentenceSource(input, language);
while (source.hasNext()) {
String sentence = source.next().getText();
if (skipSentence(sentence)) {
continue;
}
//System.out.println(sentence);
fw.write(sentence);
fw.write('\n');
sentenceCount++;
if (sentenceCount % 1000 == 0) {
System.err.println("Exporting sentence #" + sentenceCount + "...");
}
}
}
| 226
| 301
| 527
|
<no_super_class>
|
languagetool-org_languagetool
|
languagetool/languagetool-wikipedia/src/main/java/org/languagetool/dev/dumpcheck/WikipediaSentenceSource.java
|
WikipediaSentenceSource
|
handleTextElement
|
class WikipediaSentenceSource extends SentenceSource {
private static final boolean ONLY_ARTICLES = false;
private static final String ARTICLE_NAMESPACE = "0";
private final SwebleWikipediaTextFilter textFilter = new SwebleWikipediaTextFilter();
private final XMLEventReader reader;
private final Tokenizer sentenceTokenizer;
private final List<WikipediaSentence> sentences;
private final Language language;
private int articleCount = 0;
private int namespaceSkipCount = 0;
private int redirectSkipCount = 0;
WikipediaSentenceSource(InputStream xmlInput, Language language) {
this(xmlInput, language, null);
}
/** @since 3.0 */
WikipediaSentenceSource(InputStream xmlInput, Language language, Pattern filter) {
super(language, filter);
textFilter.enableMapping(false); // improves performance
try {
System.setProperty("jdk.xml.totalEntitySizeLimit", String.valueOf(Integer.MAX_VALUE)); // see https://github.com/dbpedia/extraction-framework/issues/487
XMLInputFactory factory = XMLInputFactory.newInstance();
reader = factory.createXMLEventReader(xmlInput);
sentenceTokenizer = language.getSentenceTokenizer();
sentences = new ArrayList<>();
this.language = language;
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
}
@Override
public boolean hasNext() {
try {
fillSentences();
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
return sentences.size() > 0;
}
@Override
public Sentence next() {
try {
fillSentences();
if (sentences.isEmpty()) {
throw new NoSuchElementException();
}
WikipediaSentence wikiSentence = sentences.remove(0);
String url = "http://" + language.getShortCode() + ".wikipedia.org/wiki/" + wikiSentence.title;
return new Sentence(wikiSentence.sentence, getSource(), wikiSentence.title, url, wikiSentence.articleCount);
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
}
@Override
public String getSource() {
return "wikipedia";
}
private void fillSentences() throws XMLStreamException {
String title = null;
String namespace = null;
while (sentences.isEmpty() && reader.hasNext()) {
XMLEvent event = reader.nextEvent();
if (event.getEventType() == XMLStreamConstants.START_ELEMENT) {
String elementName = event.asStartElement().getName().getLocalPart();
switch (elementName) {
case "title":
event = reader.nextEvent();
title = event.asCharacters().getData();
articleCount++;
if (articleCount % 100 == 0) {
System.out.println("Article: " + articleCount);
}
break;
case "ns":
event = reader.nextEvent();
namespace = event.asCharacters().getData();
break;
case "text":
handleTextElement(namespace, title, articleCount);
break;
}
}
}
}
private void handleTextElement(String namespace, String title, int articleCount) throws XMLStreamException {<FILL_FUNCTION_BODY>}
private static class WikipediaSentence {
final String sentence;
final String title;
final int articleCount;
WikipediaSentence(String sentence, String title, int articleCount) {
this.sentence = sentence;
this.title = title;
this.articleCount = articleCount;
}
}
}
|
if (ONLY_ARTICLES && !ARTICLE_NAMESPACE.equals(namespace)) {
namespaceSkipCount++;
return;
}
//System.out.println(articleCount + " (nsSkip:" + namespaceSkipCount + ", redirectSkip:" + redirectSkipCount + "). " + title);
XMLEvent event = reader.nextEvent();
StringBuilder sb = new StringBuilder();
while (event.isCharacters()) {
sb.append(event.asCharacters().getData());
event = reader.nextEvent();
}
try {
if (sb.toString().trim().toLowerCase().startsWith("#redirect")) {
redirectSkipCount++;
return;
}
String textToCheck = textFilter.filter(sb.toString()).getPlainText();
for (String sentence : sentenceTokenizer.tokenize(textToCheck)) {
if (acceptSentence(sentence)) {
// Create an artificial ID - as we treat each sentence as a single document
// in e.g. the nightly checks, this helps with detection of whether a match
// is new or a duplicate:
String titleWithId = title + "/" + sentence.hashCode();
sentences.add(new WikipediaSentence(sentence, titleWithId, articleCount));
}
}
} catch (Exception e) {
System.err.println("Could not extract text, skipping document: " + e + ", full stacktrace follows:");
e.printStackTrace();
}
| 956
| 372
| 1,328
|
<methods>public abstract java.lang.String getSource() ,public abstract boolean hasNext() ,public abstract org.languagetool.dev.dumpcheck.Sentence next() ,public void remove() ,public java.lang.String toString() <variables>static final int MAX_SENTENCE_LENGTH,static final int MIN_SENTENCE_LENGTH,static final int MIN_SENTENCE_TOKEN_COUNT,private final non-sealed java.util.regex.Pattern acceptPattern,private int ignoreCount,private final non-sealed org.languagetool.tokenizers.Tokenizer wordTokenizer
|
languagetool-org_languagetool
|
languagetool/languagetool-wikipedia/src/main/java/org/languagetool/dev/index/AnyCharTokenizer.java
|
AnyCharTokenizer
|
incrementToken
|
class AnyCharTokenizer extends Tokenizer {
private static final int MAX_WORD_LEN = Integer.MAX_VALUE; // extend the word length!
private final CharacterUtils.CharacterBuffer ioBuffer = CharacterUtils.newCharacterBuffer(4096);
private final CharacterUtils charUtils = CharacterUtils.getInstance();
private final CharTermAttribute termAtt = this.addAttribute(CharTermAttribute.class);
private final OffsetAttribute offsetAtt = this.addAttribute(OffsetAttribute.class);
private int bufferIndex = 0;
private int dataLen = 0;
private int offset = 0;
private int finalOffset = 0;
/**
* Construct a new AnyCharTokenizer.
*/
public AnyCharTokenizer() {
super();
}
/**
* Construct a new AnyCharTokenizer using a given
* {@link org.apache.lucene.util.AttributeFactory}.
* @param factory the attribute factory to use for this {@link org.apache.lucene.analysis.Tokenizer}
*/
public AnyCharTokenizer(AttributeFactory factory) {
super(factory);
}
/**
* Collects any characters.
*/
protected boolean isTokenChar(int c) {
return true;
}
protected int normalize(int c) {
return c;
}
@Override
public boolean incrementToken() throws IOException {<FILL_FUNCTION_BODY>}
@Override
public void end() throws IOException {
super.end();
this.offsetAtt.setOffset(this.finalOffset, this.finalOffset);
}
@Override
public void reset() throws IOException {
super.reset();
this.bufferIndex = 0;
this.offset = 0;
this.dataLen = 0;
this.finalOffset = 0;
this.ioBuffer.reset();
}
}
|
this.clearAttributes();
int length = 0;
int start = -1;
int end = -1;
char[] buffer = this.termAtt.buffer();
while(true) {
if(this.bufferIndex >= this.dataLen) {
this.offset += this.dataLen;
this.charUtils.fill(this.ioBuffer, this.input);
if(this.ioBuffer.getLength() == 0) {
this.dataLen = 0;
if(length <= 0) {
this.finalOffset = this.correctOffset(this.offset);
return false;
}
break;
}
this.dataLen = this.ioBuffer.getLength();
this.bufferIndex = 0;
}
int c = this.charUtils.codePointAt(this.ioBuffer.getBuffer(), this.bufferIndex, this.ioBuffer.getLength());
int charCount = Character.charCount(c);
this.bufferIndex += charCount;
if(this.isTokenChar(c)) {
if(length == 0) {
assert start == -1;
start = this.offset + this.bufferIndex - charCount;
end = start;
} else if(length >= buffer.length - 1) {
buffer = this.termAtt.resizeBuffer(2 + length);
}
end += charCount;
length += Character.toChars(this.normalize(c), buffer, length);
if(length >= MAX_WORD_LEN) {
break;
}
} else if(length > 0) {
break;
}
}
this.termAtt.setLength(length);
assert start != -1;
this.offsetAtt.setOffset(this.correctOffset(start), this.finalOffset = this.correctOffset(end));
return true;
| 469
| 467
| 936
|
<no_super_class>
|
languagetool-org_languagetool
|
languagetool/languagetool-wikipedia/src/main/java/org/languagetool/dev/index/DoNotUseAnalyzer.java
|
DoNotUseAnalyzer
|
createComponents
|
class DoNotUseAnalyzer extends Analyzer {
@Override
protected TokenStreamComponents createComponents(String s) {<FILL_FUNCTION_BODY>}
}
|
throw new RuntimeException("This analyzer is not supposed to be called");
| 47
| 20
| 67
|
<no_super_class>
|
languagetool-org_languagetool
|
languagetool/languagetool-wikipedia/src/main/java/org/languagetool/dev/index/Indexer.java
|
Indexer
|
add
|
class Indexer implements AutoCloseable {
static final String TITLE_FIELD_NAME = "title";
private final Random random = new Random(4235);
private final IndexWriter writer;
private final SentenceTokenizer sentenceTokenizer;
private boolean lowercaseOnly;
public Indexer(Directory dir, Language language) {
this(dir, language, getAnalyzer(language));
}
public Indexer(Directory dir, Language language, Analyzer analyzer) {
try {
IndexWriterConfig writerConfig = getIndexWriterConfig(analyzer);
writerConfig.setOpenMode(OpenMode.CREATE);
writer = new IndexWriter(dir, writerConfig);
sentenceTokenizer = language.getSentenceTokenizer();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Set to true to index only a lowercase field (makes index smaller).
*/
public void setLowercaseOnly(boolean lowercaseOnly) {
this.lowercaseOnly = lowercaseOnly;
}
public static void main(String[] args) throws IOException {
ensureCorrectUsageOrExit(args);
run(args[0], args[1], args[2]);
}
static Analyzer getAnalyzer(Language language) {
Map<String, Analyzer> analyzerMap = new HashMap<>();
analyzerMap.put(FIELD_NAME, new LanguageToolAnalyzer(new JLanguageTool(language), false));
analyzerMap.put(FIELD_NAME_LOWERCASE, new LanguageToolAnalyzer(new JLanguageTool(language), true));
return new PerFieldAnalyzerWrapper(new DoNotUseAnalyzer(), analyzerMap);
}
static IndexWriterConfig getIndexWriterConfig(Analyzer analyzer) {
return new IndexWriterConfig(analyzer);
}
private static void ensureCorrectUsageOrExit(String[] args) {
if (args.length != 3) {
System.err.println("Usage: Indexer <textFile> <indexDir> <languageCode>");
System.err.println("\ttextFile path to a text file to be indexed (line end implies sentence end)");
System.err.println("\tindexDir path to a directory storing the index");
System.err.println("\tlanguageCode short language code, e.g. en for English");
System.exit(1);
}
}
private static void run(String textFile, String indexDir, String languageCode) throws IOException {
File file = new File(textFile);
if (!file.exists() || !file.canRead()) {
System.out.println("Text file '" + file.getAbsolutePath()
+ "' does not exist or is not readable, please check the path");
System.exit(1);
}
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
System.out.println("Indexing to directory '" + indexDir + "'...");
try (FSDirectory directory = FSDirectory.open(new File(indexDir).toPath())) {
Language language = Languages.getLanguageForShortCode(languageCode);
try (Indexer indexer = new Indexer(directory, language)) {
indexer.indexText(reader);
}
}
}
System.out.println("Index complete!");
}
public static void run(String content, Directory dir, Language language) throws IOException {
BufferedReader br = new BufferedReader(new StringReader(content));
try (Indexer indexer = new Indexer(dir, language)) {
indexer.indexText(br);
}
}
public void indexSentence(Sentence sentence, int docCount) throws IOException {
BufferedReader reader = new BufferedReader(new StringReader(sentence.getText()));
String line;
while ((line = reader.readLine()) != null) {
add(line, sentence.getSource(), sentence.getTitle(), docCount);
}
}
public void indexText(BufferedReader reader) throws IOException {
String line;
StringBuilder paragraph = new StringBuilder();
int i = 0;
int addCount = 0;
while ((line = reader.readLine()) != null) {
if (!(line.equals("")) && paragraph.length() + line.length() < Integer.MAX_VALUE) {
paragraph.append(line).append('\n');
} else {
List<String> sentences = sentenceTokenizer.tokenize(paragraph.toString());
for (String sentence : sentences) {
if (sentence.trim().length() > 0) {
if (++addCount % 1000 == 0) {
System.out.println("(1) Adding item " + addCount);
}
add(sentence.replaceAll(" \n"," "), null, null, -1);
}
}
if (paragraph.length() + line.length() >= Integer.MAX_VALUE) {
List<String> lastSentences = sentenceTokenizer.tokenize(line);
for (String sentence : lastSentences) {
if (++addCount % 1000 == 0) {
System.out.println("(2) Adding item " + addCount);
}
add(sentence, null, null, -1);
}
}
paragraph.setLength(0);
}
if (++i % 10_000 == 0) {
System.out.println("Loading line " + i);
}
}
if (paragraph.length() > 0) {
List<String> sentences = sentenceTokenizer.tokenize(paragraph.toString());
for (String sentence : sentences) {
if (++addCount % 1000 == 0) {
System.out.println("(3) Adding item " + addCount);
}
add(sentence, null, null, -1);
}
}
}
public void add(Document doc) throws IOException {
writer.addDocument(doc);
}
private void add(String sentence, String source, String title, int docCount) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public void close() throws IOException {
writer.close();
}
public void commit() throws IOException {
if (writer.isOpen()) {
writer.commit();
}
}
}
|
Document doc = new Document();
FieldType type = new FieldType();
type.setStored(true);
type.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS);
type.setTokenized(true);
if (!lowercaseOnly) {
doc.add(new Field(FIELD_NAME, sentence, type));
}
doc.add(new Field(FIELD_NAME_LOWERCASE, sentence, type));
if (docCount != -1) {
FieldType countType = new FieldType();
countType.setStored(true);
countType.setIndexOptions(IndexOptions.NONE);
doc.add(new Field("docCount", String.valueOf(docCount), countType));
}
if (title != null) {
FieldType titleType = new FieldType();
titleType.setStored(true);
titleType.setIndexOptions(IndexOptions.NONE);
titleType.setTokenized(false);
doc.add(new Field(TITLE_FIELD_NAME, title, titleType));
}
if (source != null) {
FieldType sourceType = new FieldType();
sourceType.setStored(true);
sourceType.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS);
sourceType.setTokenized(false);
doc.add(new Field(SOURCE_FIELD_NAME, source, sourceType));
}
int rnd = random.nextInt();
doc.add(new SortedNumericDocValuesField(RANDOM_FIELD, rnd)); // allow random sorting on search
writer.addDocument(doc);
| 1,587
| 436
| 2,023
|
<no_super_class>
|
languagetool-org_languagetool
|
languagetool/languagetool-wikipedia/src/main/java/org/languagetool/dev/index/LanguageToolAnalyzer.java
|
LanguageToolAnalyzer
|
createComponents
|
class LanguageToolAnalyzer extends Analyzer {
private final JLanguageTool languageTool;
private final boolean toLowerCase;
public LanguageToolAnalyzer(JLanguageTool languageTool, boolean toLowerCase) {
super();
this.languageTool = languageTool;
this.toLowerCase = toLowerCase;
}
@Override
protected TokenStreamComponents createComponents(String s) {<FILL_FUNCTION_BODY>}
}
|
Tokenizer tokenizer = new AnyCharTokenizer();
TokenStream result = new LanguageToolFilter(tokenizer, languageTool, toLowerCase);
return new TokenStreamComponents(tokenizer, result);
| 130
| 58
| 188
|
<no_super_class>
|
languagetool-org_languagetool
|
languagetool/languagetool-wikipedia/src/main/java/org/languagetool/dev/index/LanguageToolFilter.java
|
LanguageToolFilter
|
incrementToken
|
class LanguageToolFilter extends TokenFilter {
static final String POS_PREFIX = "_POS_";
static final String LEMMA_PREFIX = "_LEMMA_";
private final JLanguageTool languageTool;
private final boolean toLowerCase;
private final Stack<String> posStack;
private final CharTermAttribute termAtt;
private final OffsetAttribute offsetAtt;
private final PositionIncrementAttribute posIncrAtt;
private final TypeAttribute typeAtt;
private final StringBuilder collectedInput = new StringBuilder();
private AttributeSource.State current;
private Iterator<AnalyzedTokenReadings> tokenIter;
LanguageToolFilter(TokenStream input, JLanguageTool languageTool, boolean toLowerCase) {
super(input);
this.languageTool = languageTool;
this.toLowerCase = toLowerCase;
posStack = new Stack<>();
termAtt = addAttribute(CharTermAttribute.class);
offsetAtt = addAttribute(OffsetAttribute.class);
posIncrAtt = addAttribute(PositionIncrementAttribute.class);
typeAtt = addAttribute(TypeAttribute.class);
}
@Override
public boolean incrementToken() throws IOException {<FILL_FUNCTION_BODY>}
}
|
if (posStack.size() > 0) {
String pop = posStack.pop();
restoreState(current);
termAtt.append(pop);
posIncrAtt.setPositionIncrement(0);
typeAtt.setType("pos");
return true;
}
if (tokenIter == null || !tokenIter.hasNext()) {
// there are no remaining tokens from the current sentence... are there more sentences?
if (input.incrementToken()) {
// a new sentence is available: process it.
String sentenceStr = termAtt.toString();
collectedInput.append(sentenceStr);
if (sentenceStr.length() >= 255) {
// Long sentences get split, so keep collecting data to avoid errors
// later. See https://github.com/languagetool-org/languagetool/issues/364
return true;
} else {
sentenceStr = collectedInput.toString();
collectedInput.setLength(0);
}
AnalyzedSentence sentence = languageTool.getAnalyzedSentence(sentenceStr);
List<AnalyzedTokenReadings> tokenBuffer = Arrays.asList(sentence.getTokens());
tokenIter = tokenBuffer.iterator();
/*
* it should not be possible to have a sentence with 0 words, check just in case. returning
* EOS isn't the best either, but it's the behavior of the original code.
*/
if (!tokenIter.hasNext()) {
return false;
}
} else {
return false; // no more sentences, end of stream!
}
}
// It must clear attributes, as it is creating new tokens.
clearAttributes();
AnalyzedTokenReadings tr = tokenIter.next();
// add POS tag for sentence start.
if (tr.isSentenceStart()) {
// TODO: would be needed so negated tokens can match on something (see testNegatedMatchAtSentenceStart())
// but breaks other cases:
//termAtt.append("SENT_START");
typeAtt.setType("pos");
String posTag = tr.getAnalyzedToken(0).getPOSTag();
String lemma = tr.getAnalyzedToken(0).getLemma();
if (toLowerCase) {
termAtt.append(POS_PREFIX.toLowerCase()).append(posTag.toLowerCase());
if (lemma != null) {
termAtt.append(LEMMA_PREFIX.toLowerCase()).append(lemma.toLowerCase());
}
} else {
termAtt.append(POS_PREFIX).append(posTag);
if (lemma != null) {
termAtt.append(LEMMA_PREFIX).append(lemma);
}
}
return true;
}
// by pass the white spaces.
if (tr.isWhitespace()) {
return this.incrementToken();
}
offsetAtt.setOffset(tr.getStartPos(), tr.getEndPos());
for (AnalyzedToken token : tr) {
if (token.getPOSTag() != null) {
if (toLowerCase) {
posStack.push(POS_PREFIX.toLowerCase() + token.getPOSTag().toLowerCase());
} else {
posStack.push(POS_PREFIX + token.getPOSTag());
}
}
if (token.getLemma() != null) {
if (toLowerCase) {
posStack.push(LEMMA_PREFIX.toLowerCase() + token.getLemma().toLowerCase());
} else {
// chances are good this is the same for all loop iterations, store it anyway...
posStack.push(LEMMA_PREFIX + token.getLemma());
}
}
}
current = captureState();
if (toLowerCase) {
termAtt.append(tr.getAnalyzedToken(0).getToken().toLowerCase());
} else {
termAtt.append(tr.getAnalyzedToken(0).getToken());
}
return true;
| 337
| 1,120
| 1,457
|
<no_super_class>
|
languagetool-org_languagetool
|
languagetool/languagetool-wikipedia/src/main/java/org/languagetool/dev/index/Searcher.java
|
SearchRunnable
|
run
|
class SearchRunnable implements Runnable {
private final IndexSearcher indexSearcher;
private final Query query;
private final Language language;
private final PatternRule rule;
private List<MatchingSentence> matchingSentences;
private Exception exception;
private boolean tooManyLuceneMatches;
private int luceneMatchCount;
private int maxDocChecked;
private int docsChecked;
private int numDocs;
SearchRunnable(IndexSearcher indexSearcher, Query query, Language language, PatternRule rule) {
this.indexSearcher = indexSearcher;
this.query = query;
this.language = language;
this.rule = rule;
}
@Override
public void run() {<FILL_FUNCTION_BODY>}
Exception getException() {
return exception;
}
/**
* There were more Lucene matches than we can actually check with LanguageTool in
* an acceptable time, so real matches might be lost.
*/
boolean hasTooManyLuceneMatches() {
return tooManyLuceneMatches;
}
int getLuceneMatchCount() {
return luceneMatchCount;
}
List<MatchingSentence> getMatchingSentences() {
return matchingSentences;
}
int getMaxDocChecked() {
return maxDocChecked;
}
}
|
try {
long t1 = System.currentTimeMillis();
JLanguageTool languageTool = getLanguageToolWithOneRule(language, rule);
long langToolCreationTime = System.currentTimeMillis() - t1;
long t2 = System.currentTimeMillis();
PossiblyLimitedTopDocs limitedTopDocs = getTopDocs(query);
long luceneTime = System.currentTimeMillis() - t2;
long t3 = System.currentTimeMillis();
luceneMatchCount = limitedTopDocs.topDocs.totalHits;
tooManyLuceneMatches = limitedTopDocs.topDocs.scoreDocs.length >= maxHits;
MatchingSentencesResult res = findMatchingSentences(indexSearcher, limitedTopDocs.topDocs, languageTool);
matchingSentences = res.matchingSentences;
maxDocChecked = res.maxDocChecked;
docsChecked = res.docsChecked;
numDocs = indexSearcher.getIndexReader().numDocs();
System.out.println("Check done in " + langToolCreationTime + "/" + luceneTime + "/" + (System.currentTimeMillis() - t3)
+ "ms (LT creation/Lucene/matching) for " + limitedTopDocs.topDocs.scoreDocs.length + " docs");
} catch (Exception e) {
exception = e;
}
| 364
| 361
| 725
|
<no_super_class>
|
languagetool-org_languagetool
|
languagetool/languagetool-wikipedia/src/main/java/org/languagetool/dev/wikipedia/IpaExtractor.java
|
IpaExtractor
|
run
|
class IpaExtractor {
private static final Pattern FULL_IPA_PATTERN = Pattern.compile("'''?(.*?)'''?\\s+\\[?\\{\\{IPA\\|([^}]*)\\}\\}");
private static final Pattern IPA_PATTERN = Pattern.compile("\\{\\{IPA\\|([^}]*)\\}\\}");
private int articleCount = 0;
private int ipaCount = 0;
public static void main(String[] args) throws XMLStreamException, FileNotFoundException {
if (args.length == 0) {
System.out.println("Usage: " + IpaExtractor.class.getSimpleName() + " <xml-dump...>");
System.exit(1);
}
IpaExtractor extractor = new IpaExtractor();
for (String filename : args) {
FileInputStream fis = new FileInputStream(filename);
extractor.run(fis);
}
System.err.println("articleCount: " + extractor.articleCount);
System.err.println("IPA count: " + extractor.ipaCount);
}
private void run(FileInputStream fis) throws XMLStreamException {<FILL_FUNCTION_BODY>}
private int handleTextElement(String title, XMLEventReader reader) throws XMLStreamException {
XMLEvent event = reader.nextEvent();
StringBuilder sb = new StringBuilder();
while (event.isCharacters()) {
sb.append(event.asCharacters().getData());
event = reader.nextEvent();
}
String wikiText = sb.toString();
int index = wikiText.indexOf("{{IPA");
if (index != -1) {
Matcher matcher = FULL_IPA_PATTERN.matcher(wikiText);
if (matcher.find()) {
System.out.println(title + ": " + matcher.group(1) + " -> " + matcher.group(2));
return 1;
} else {
Matcher matcher2 = IPA_PATTERN.matcher(wikiText);
if (matcher2.find()) {
System.out.println(title + ": " + matcher2.group(1));
return 1;
} else {
System.out.println(title + ": (no pattern found)");
}
}
}
return 0;
}
}
|
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLEventReader reader = factory.createXMLEventReader(fis);
String title = null;
while (reader.hasNext()) {
XMLEvent event = reader.nextEvent();
if (event.getEventType() == XMLStreamConstants.START_ELEMENT) {
String elementName = event.asStartElement().getName().getLocalPart();
switch (elementName) {
case "title":
XMLEvent nextEvent = reader.nextEvent();
title = nextEvent.asCharacters().getData();
articleCount++;
break;
case "text":
ipaCount += handleTextElement(title, reader);
break;
}
}
}
| 612
| 192
| 804
|
<no_super_class>
|
languagetool-org_languagetool
|
languagetool/languagetool-wikipedia/src/main/java/org/languagetool/dev/wikipedia/LocationHelper.java
|
LocationHelper
|
absolutePositionFor
|
class LocationHelper {
private LocationHelper() {
}
/**
* Get an absolute position (character-based) for a line/column-based location.
*/
public static int absolutePositionFor(Location location, String text) {<FILL_FUNCTION_BODY>}
private static boolean isReferenceStart(String text, int i) {
return text.startsWith("<ref", i);
}
private static boolean isFullReferenceEndTag(String text, int i) {
return text.startsWith("</ref>", i);
}
private static boolean isShortReferenceEndTag(String text, int i) {
return text.startsWith("/>", i);
}
private static boolean isHtmlCommentStart(String text, int i) {
return text.startsWith("<!--", i);
}
private static boolean isHtmlCommentEnd(String text, int i) {
return text.startsWith("-->", i);
}
}
|
int line = 1;
int col = 1;
int pos = 0;
int ignoreLevel = 0;
boolean inReference = false;
StringBuilder relevantLine = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
if (line == location.line) {
relevantLine.append(ch);
}
//System.out.println(line + "/" + col + ", ignoreLevel: " + ignoreLevel);
if (line == location.line && col == location.column) {
return pos;
}
char prevCh = i > 0 ? text.charAt(i - 1) : '-';
if (isReferenceStart(text, i)) {
ignoreLevel++;
inReference = true;
} else if (inReference && (isFullReferenceEndTag(text, i) || isShortReferenceEndTag(text, i))) {
ignoreLevel--;
inReference = false;
if (isShortReferenceEndTag(text, i)) {
// this makes SuggestionReplacerTest.testReference2() work, not sure why
col++;
}
} else if (isHtmlCommentStart(text, i)) {
ignoreLevel++;
} else if (isHtmlCommentEnd(text, i)) {
ignoreLevel--;
} else if (ch == '}' && prevCh == '}') {
if (ignoreLevel > 0) {
ignoreLevel--;
}
} else if (ch == '{' && prevCh == '{') {
// ignore templates
ignoreLevel++;
} else if (ch == '\n' && ignoreLevel == 0) {
line++;
col = 1;
} else if (ignoreLevel == 0) {
col++;
}
pos++;
}
if (line == location.line && col == location.column) {
return pos;
}
throw new RuntimeException("Could not find location " + location + " in text. " +
"Max line/col was: " + line + "/" + col + ", Content of relevant line (" + location.line + "): '"
+ relevantLine + "' (" + relevantLine.length() + " chars)");
| 252
| 559
| 811
|
<no_super_class>
|
languagetool-org_languagetool
|
languagetool/languagetool-wikipedia/src/main/java/org/languagetool/dev/wikipedia/Main.java
|
Main
|
printUsageAndExit
|
class Main {
public static void main(String[] args) throws Exception {
JnaTools.setBugWorkaroundProperty();
if (args.length == 0) {
printUsageAndExit();
} else {
String[] remainingArgs = Arrays.copyOfRange(args, 1, args.length);
String command = args[0];
switch (command) {
case "check-data":
SentenceSourceChecker.main(remainingArgs);
break;
case "index-data":
SentenceSourceIndexer.main(remainingArgs);
break;
case "wiki-check":
WikipediaQuickCheck.main(remainingArgs);
break;
case "index":
Indexer.main(remainingArgs);
break;
case "search":
Searcher.main(remainingArgs);
break;
case "version":
System.out.println(JLanguageTool.VERSION + " (" + JLanguageTool.BUILD_DATE + ")");
break;
default:
System.out.println("Error: unknown command '" + command + "'");
printUsageAndExit();
break;
}
}
}
private static void printUsageAndExit() {<FILL_FUNCTION_BODY>}
}
|
System.out.println("Usage: " + Main.class.getName() + " <command> <command-specific-arguments>");
System.out.println("Where <command> is one of:");
System.out.println(" check-data - check a Wikipedia XML dump like those available from");
System.out.println(" http://dumps.wikimedia.org/backup-index.html");
System.out.println(" and/or a Tatoeba file (http://tatoeba.org)");
System.out.println(" index-data - fulltext-index a Wikipedia XML dump and/or a Tatoeba file");
System.out.println(" wiki-check - check a single Wikipedia page, fetched via the Mediawiki API");
System.out.println(" index - index a plain text file, putting the analysis in a Lucene index for faster rule match search");
System.out.println(" search - search for rule matches in an index created with 'index' or 'wiki-index'");
System.out.println(" version - print LanguageTool version number and build date");
System.out.println();
System.out.println("All commands have different usages. Call them without arguments to get help.");
System.out.println();
System.out.println("Example for a call with valid arguments:");
System.out.println(" java -jar languagetool-wikipedia.jar wiki-check http://de.wikipedia.org/wiki/Bielefeld");
System.exit(1);
| 320
| 374
| 694
|
<no_super_class>
|
languagetool-org_languagetool
|
languagetool/languagetool-wikipedia/src/main/java/org/languagetool/dev/wikipedia/PlainTextMapping.java
|
PlainTextMapping
|
getOriginalTextPositionFor
|
class PlainTextMapping {
private final String plainText;
private final Map<Integer,Location> mapping;
public PlainTextMapping(String plainText, Map<Integer, Location> mapping) {
this.plainText = plainText;
this.mapping = mapping;
}
public String getPlainText() {
return plainText;
}
public Map<Integer, Location> getMapping() {
return mapping;
}
/**
* @param plainTextPosition not zero-based - smallest value is 1!
*/
public Location getOriginalTextPositionFor(int plainTextPosition) {<FILL_FUNCTION_BODY>}
}
|
if (plainTextPosition < 1) {
throw new RuntimeException("plainTextPosition must be > 0 - its value starts at 1");
}
Location origPosition = mapping.get(plainTextPosition);
if (origPosition != null) {
//System.out.println("mapping " + plainTextPosition + " to " + origPosition + " [direct]");
return origPosition;
}
int minDiff = Integer.MAX_VALUE;
Location bestMatch = null;
//Integer bestMaybeClosePosition = null;
// algorithm: find the closest lower position
for (Map.Entry<Integer, Location> entry : mapping.entrySet()) {
int maybeClosePosition = entry.getKey();
if (plainTextPosition > maybeClosePosition) {
int diff = plainTextPosition - maybeClosePosition;
if (diff >= 0 && diff < minDiff) {
bestMatch = entry.getValue();
//bestMaybeClosePosition = maybeClosePosition;
minDiff = diff;
}
}
}
if (bestMatch == null) {
throw new RuntimeException("Could not map " + plainTextPosition + " to original position. Mapping: " + mapping);
}
// we assume that when we have found the closest match there's a one-to-one mapping
// in this region, thus we can add 'minDiff' to get the exact position:
//System.out.println("mapping " + plainTextPosition + " to line " + bestMatch.line + ", column " +
// bestMatch.column + "+" + minDiff + ", bestMatch was: " + bestMaybeClosePosition +"=>"+ bestMatch);
return new Location(bestMatch.file, bestMatch.line, bestMatch.column + minDiff);
| 170
| 425
| 595
|
<no_super_class>
|
languagetool-org_languagetool
|
languagetool/languagetool-wikipedia/src/main/java/org/languagetool/dev/wikipedia/RuleMatchApplication.java
|
RuleMatchApplication
|
getContext
|
class RuleMatchApplication {
private final RuleMatch ruleMatch;
private final String text;
private final String textWithCorrection;
private final ErrorMarker errorMarker;
private final boolean hasRealReplacement;
static RuleMatchApplication forMatchWithReplacement(RuleMatch ruleMatch, String text, String textWithCorrection, ErrorMarker errorMarker) {
return new RuleMatchApplication(ruleMatch, text, textWithCorrection, errorMarker, true);
}
static RuleMatchApplication forMatchWithoutReplacement(RuleMatch ruleMatch, String text, String textWithCorrection, ErrorMarker errorMarker) {
return new RuleMatchApplication(ruleMatch, text, textWithCorrection, errorMarker, false);
}
private RuleMatchApplication(RuleMatch ruleMatch, String text, String textWithCorrection, ErrorMarker errorMarker, boolean hasRealReplacement) {
if (!textWithCorrection.contains(errorMarker.getStartMarker())) {
throw new IllegalArgumentException("No start error marker (" + errorMarker.getStartMarker() + ") found in text with correction");
}
if (!textWithCorrection.contains(errorMarker.getEndMarker())) {
throw new IllegalArgumentException("No end error marker (" + errorMarker.getEndMarker() + ") found in text with correction");
}
this.ruleMatch = ruleMatch;
this.text = text;
this.textWithCorrection = textWithCorrection;
this.errorMarker = errorMarker;
this.hasRealReplacement = hasRealReplacement;
}
public String getOriginalErrorContext(int contextSize) {
return getContext(text, contextSize);
}
public String getCorrectedErrorContext(int contextSize) {
return getContext(textWithCorrection, contextSize);
}
private String getContext(String text, int contextSize) {<FILL_FUNCTION_BODY>}
public RuleMatch getRuleMatch() {
return ruleMatch;
}
public String getOriginalText() {
return text;
}
public String getTextWithCorrection() {
return textWithCorrection;
}
/** @since 2.6 */
public ErrorMarker getErrorMarker() {
return errorMarker;
}
public boolean hasRealReplacement() {
return hasRealReplacement;
}
@Override
public String toString() {
return ruleMatch.toString();
}
}
|
int errorStart = textWithCorrection.indexOf(errorMarker.getStartMarker());
int errorEnd = textWithCorrection.indexOf(errorMarker.getEndMarker());
int errorContextStart = Math.max(errorStart - contextSize, 0);
int errorContentEnd = Math.min(errorEnd + contextSize, text.length());
return text.substring(errorContextStart, errorContentEnd);
| 594
| 100
| 694
|
<no_super_class>
|
languagetool-org_languagetool
|
languagetool/languagetool-wikipedia/src/main/java/org/languagetool/dev/wikipedia/SuggestionReplacer.java
|
SuggestionReplacer
|
findNextWhitespaceToTheRight
|
class SuggestionReplacer {
private final PlainTextMapping textMapping;
private final String originalText;
private final ErrorMarker errorMarker;
/**
* @param originalText the original text that includes markup
*/
public SuggestionReplacer(PlainTextMapping textMapping, String originalText) {
// use <<span>> to avoid clashes with <span> in original markup:
this(textMapping, originalText, new ErrorMarker("<<span class=\"error\">>", "<</span>>"));
}
/**
* @since 2.6
*/
public SuggestionReplacer(PlainTextMapping textMapping, String originalText, ErrorMarker errorMarker) {
this.textMapping = textMapping;
this.originalText = originalText;
this.errorMarker = errorMarker;
}
/**
* Applies the suggestions from the rule to the original text. For rules that
* have no suggestion, a pseudo-correction is generated that contains the same
* text as before.
*/
public List<RuleMatchApplication> applySuggestionsToOriginalText(RuleMatch match) {
List<String> replacements = new ArrayList<>(match.getSuggestedReplacements());
boolean hasRealReplacements = replacements.size() > 0;
if (!hasRealReplacements) {
// create a pseudo replacement with the error text itself
String plainText = textMapping.getPlainText();
replacements.add(plainText.substring(match.getFromPos(), match.getToPos()));
}
List<RuleMatchApplication> ruleMatchApplications = new ArrayList<>();
Location fromPosLocation = textMapping.getOriginalTextPositionFor(match.getFromPos() + 1); // not zero-based!
Location toPosLocation = textMapping.getOriginalTextPositionFor(match.getToPos() + 1);
/*System.out.println("=========");
System.out.println(textMapping.getMapping());
System.out.println("=========");
System.out.println(textMapping.getPlainText());
System.out.println("=========");
System.out.println(originalText);
System.out.println("=========");*/
int fromPos = LocationHelper.absolutePositionFor(fromPosLocation, originalText);
int toPos = LocationHelper.absolutePositionFor(toPosLocation, originalText);
for (String replacement : replacements) {
String errorText = textMapping.getPlainText().substring(match.getFromPos(), match.getToPos());
// the algorithm is off a bit sometimes due to the complex syntax, so consider the next whitespace:
int contextFrom = findNextWhitespaceToTheLeft(originalText, fromPos);
int contextTo = findNextWhitespaceToTheRight(originalText, toPos);
/*System.out.println(match + ":");
System.out.println("match.getFrom/ToPos(): " + match.getFromPos() + "/" + match.getToPos());
System.out.println("from/toPosLocation: " + fromPosLocation + "/" + toPosLocation);
System.out.println("from/toPos: " + fromPos + "/" + toPos);
System.out.println("contextFrom/To: " + contextFrom + "/" + contextTo);*/
String context = originalText.substring(contextFrom, contextTo);
String text = originalText.substring(0, contextFrom)
+ errorMarker.getStartMarker()
+ context
+ errorMarker.getEndMarker()
+ originalText.substring(contextTo);
String newContext;
if (StringUtils.countMatches(context, errorText) == 1) {
newContext = context.replace(errorText, replacement);
} else {
// This may happen especially for very short strings. As this is an
// error, we don't claim to have real replacements:
newContext = context;
hasRealReplacements = false;
}
String newText = originalText.substring(0, contextFrom)
// we do a simple string replacement as that works even if our mapping is off a bit:
+ errorMarker.getStartMarker()
+ newContext
+ errorMarker.getEndMarker()
+ originalText.substring(contextTo);
RuleMatchApplication application;
if (hasRealReplacements) {
application = RuleMatchApplication.forMatchWithReplacement(match, text, newText, errorMarker);
} else {
application = RuleMatchApplication.forMatchWithoutReplacement(match, text, newText, errorMarker);
}
ruleMatchApplications.add(application);
}
return ruleMatchApplications;
}
int findNextWhitespaceToTheRight(String text, int position) {<FILL_FUNCTION_BODY>}
int findNextWhitespaceToTheLeft(String text, int position) {
for (int i = position; i >= 0; i--) {
if (Character.isWhitespace(text.charAt(i))) {
return i + 1;
}
}
return 0;
}
}
|
for (int i = position; i < text.length(); i++) {
if (Character.isWhitespace(text.charAt(i))) {
return i;
}
}
return text.length();
| 1,286
| 59
| 1,345
|
<no_super_class>
|
languagetool-org_languagetool
|
languagetool/languagetool-wikipedia/src/main/java/org/languagetool/dev/wikipedia/SwebleWikipediaTextFilter.java
|
SwebleWikipediaTextFilter
|
filter
|
class SwebleWikipediaTextFilter implements TextMapFilter {
private static final int WRAP_COL = Integer.MAX_VALUE;
//private final SimpleWikiConfiguration config;
// private final Compiler compiler;
// private final PageId pageId;
private boolean enableMapping = true;
public SwebleWikipediaTextFilter() {
// try {
// config = new SimpleWikiConfiguration(
// "classpath:/org/languagetool/resource/dev/SimpleWikiConfiguration.xml");
// compiler = new Compiler(config);
// PageTitle pageTitle = PageTitle.make(config, "fileTitle");
// pageId = new PageId(pageTitle, -1);
// } catch (Exception e) {
// throw new RuntimeException("Could not set up text filter", e);
// }
}
@Override
public PlainTextMapping filter(String wikiText) {<FILL_FUNCTION_BODY>}
/**
* Set this to {@code false} for better performance. The result of {@link #filter(String)}
* will then have a {@code null} mapping.
*/
public void enableMapping(boolean enable) {
enableMapping = enable;
}
}
|
// try {
// CompiledPage compiledPage = compiler.postprocess(pageId, wikiText, null);
// TextConverter textConverter = new TextConverter(config, WRAP_COL);
// textConverter.enableMapping(enableMapping);
// String plainText = (String) textConverter.go(compiledPage.getPage());
// if (enableMapping) {
// return new PlainTextMapping(plainText, textConverter.getMapping());
// } else {
// return new PlainTextMapping(plainText, null);
// }
// } catch (Exception e) {
// throw new RuntimeException("Could not extract plain text from MediaWiki syntax: '"
// + StringUtils.abbreviate(wikiText, 500) + "'", e);
// }
return new PlainTextMapping("", null);
| 308
| 206
| 514
|
<no_super_class>
|
ffay_lanproxy
|
lanproxy/proxy-client/src/main/java/org/fengfei/lanproxy/client/ClientChannelMannager.java
|
ClientChannelMannager
|
returnProxyChanel
|
class ClientChannelMannager {
private static Logger logger = LoggerFactory.getLogger(ClientChannelMannager.class);
private static final AttributeKey<Boolean> USER_CHANNEL_WRITEABLE = AttributeKey.newInstance("user_channel_writeable");
private static final AttributeKey<Boolean> CLIENT_CHANNEL_WRITEABLE = AttributeKey.newInstance("client_channel_writeable");
private static final int MAX_POOL_SIZE = 100;
private static Map<String, Channel> realServerChannels = new ConcurrentHashMap<String, Channel>();
private static ConcurrentLinkedQueue<Channel> proxyChannelPool = new ConcurrentLinkedQueue<Channel>();
private static volatile Channel cmdChannel;
private static Config config = Config.getInstance();
public static void borrowProxyChanel(Bootstrap bootstrap, final ProxyChannelBorrowListener borrowListener) {
Channel channel = proxyChannelPool.poll();
if (channel != null) {
borrowListener.success(channel);
return;
}
bootstrap.connect(config.getStringValue("server.host"), config.getIntValue("server.port")).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
borrowListener.success(future.channel());
} else {
logger.warn("connect proxy server failed", future.cause());
borrowListener.error(future.cause());
}
}
});
}
public static void returnProxyChanel(Channel proxyChanel) {<FILL_FUNCTION_BODY>}
public static void removeProxyChanel(Channel proxyChanel) {
proxyChannelPool.remove(proxyChanel);
}
public static void setCmdChannel(Channel cmdChannel) {
ClientChannelMannager.cmdChannel = cmdChannel;
}
public static Channel getCmdChannel() {
return cmdChannel;
}
public static void setRealServerChannelUserId(Channel realServerChannel, String userId) {
realServerChannel.attr(Constants.USER_ID).set(userId);
}
public static String getRealServerChannelUserId(Channel realServerChannel) {
return realServerChannel.attr(Constants.USER_ID).get();
}
public static Channel getRealServerChannel(String userId) {
return realServerChannels.get(userId);
}
public static void addRealServerChannel(String userId, Channel realServerChannel) {
realServerChannels.put(userId, realServerChannel);
}
public static Channel removeRealServerChannel(String userId) {
return realServerChannels.remove(userId);
}
public static boolean isRealServerReadable(Channel realServerChannel) {
return realServerChannel.attr(CLIENT_CHANNEL_WRITEABLE).get() && realServerChannel.attr(USER_CHANNEL_WRITEABLE).get();
}
public static void clearRealServerChannels() {
logger.warn("channel closed, clear real server channels");
Iterator<Entry<String, Channel>> ite = realServerChannels.entrySet().iterator();
while (ite.hasNext()) {
Channel realServerChannel = ite.next().getValue();
if (realServerChannel.isActive()) {
realServerChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
}
}
realServerChannels.clear();
}
}
|
if (proxyChannelPool.size() > MAX_POOL_SIZE) {
proxyChanel.close();
} else {
proxyChanel.config().setOption(ChannelOption.AUTO_READ, true);
proxyChanel.attr(Constants.NEXT_CHANNEL).remove();
proxyChannelPool.offer(proxyChanel);
logger.debug("return ProxyChanel to the pool, channel is {}, pool size is {} ", proxyChanel, proxyChannelPool.size());
}
| 900
| 131
| 1,031
|
<no_super_class>
|
ffay_lanproxy
|
lanproxy/proxy-client/src/main/java/org/fengfei/lanproxy/client/ProxyClientContainer.java
|
ProxyClientContainer
|
connectProxyServer
|
class ProxyClientContainer implements Container, ChannelStatusListener {
private static Logger logger = LoggerFactory.getLogger(ProxyClientContainer.class);
private static final int MAX_FRAME_LENGTH = 1024 * 1024;
private static final int LENGTH_FIELD_OFFSET = 0;
private static final int LENGTH_FIELD_LENGTH = 4;
private static final int INITIAL_BYTES_TO_STRIP = 0;
private static final int LENGTH_ADJUSTMENT = 0;
private NioEventLoopGroup workerGroup;
private Bootstrap bootstrap;
private Bootstrap realServerBootstrap;
private Config config = Config.getInstance();
private SSLContext sslContext;
private long sleepTimeMill = 1000;
public ProxyClientContainer() {
workerGroup = new NioEventLoopGroup();
realServerBootstrap = new Bootstrap();
realServerBootstrap.group(workerGroup);
realServerBootstrap.channel(NioSocketChannel.class);
realServerBootstrap.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new RealServerChannelHandler());
}
});
bootstrap = new Bootstrap();
bootstrap.group(workerGroup);
bootstrap.channel(NioSocketChannel.class);
bootstrap.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
if (Config.getInstance().getBooleanValue("ssl.enable", false)) {
if (sslContext == null) {
sslContext = SslContextCreator.createSSLContext();
}
ch.pipeline().addLast(createSslHandler(sslContext));
}
ch.pipeline().addLast(new ProxyMessageDecoder(MAX_FRAME_LENGTH, LENGTH_FIELD_OFFSET, LENGTH_FIELD_LENGTH, LENGTH_ADJUSTMENT, INITIAL_BYTES_TO_STRIP));
ch.pipeline().addLast(new ProxyMessageEncoder());
ch.pipeline().addLast(new IdleCheckHandler(IdleCheckHandler.READ_IDLE_TIME, IdleCheckHandler.WRITE_IDLE_TIME - 10, 0));
ch.pipeline().addLast(new ClientChannelHandler(realServerBootstrap, bootstrap, ProxyClientContainer.this));
}
});
}
@Override
public void start() {
connectProxyServer();
}
private ChannelHandler createSslHandler(SSLContext sslContext) {
SSLEngine sslEngine = sslContext.createSSLEngine();
sslEngine.setUseClientMode(true);
return new SslHandler(sslEngine);
}
private void connectProxyServer() {<FILL_FUNCTION_BODY>}
@Override
public void stop() {
workerGroup.shutdownGracefully();
}
@Override
public void channelInactive(ChannelHandlerContext ctx) {
reconnectWait();
connectProxyServer();
}
private void reconnectWait() {
try {
if (sleepTimeMill > 60000) {
sleepTimeMill = 1000;
}
synchronized (this) {
sleepTimeMill = sleepTimeMill * 2;
wait(sleepTimeMill);
}
} catch (InterruptedException e) {
}
}
public static void main(String[] args) {
ContainerHelper.start(Arrays.asList(new Container[] { new ProxyClientContainer() }));
}
}
|
bootstrap.connect(config.getStringValue("server.host"), config.getIntValue("server.port")).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
// 连接成功,向服务器发送客户端认证信息(clientKey)
ClientChannelMannager.setCmdChannel(future.channel());
ProxyMessage proxyMessage = new ProxyMessage();
proxyMessage.setType(ProxyMessage.C_TYPE_AUTH);
proxyMessage.setUri(config.getStringValue("client.key"));
future.channel().writeAndFlush(proxyMessage);
sleepTimeMill = 1000;
logger.info("connect proxy server success, {}", future.channel());
} else {
logger.warn("connect proxy server failed", future.cause());
// 连接失败,发起重连
reconnectWait();
connectProxyServer();
}
}
});
| 949
| 251
| 1,200
|
<no_super_class>
|
ffay_lanproxy
|
lanproxy/proxy-client/src/main/java/org/fengfei/lanproxy/client/SslContextCreator.java
|
SslContextCreator
|
initSSLContext
|
class SslContextCreator {
private static Logger logger = LoggerFactory.getLogger(SslContextCreator.class);
public static SSLContext createSSLContext() {
return new SslContextCreator().initSSLContext();
}
public SSLContext initSSLContext() {<FILL_FUNCTION_BODY>}
private InputStream jksDatastore(String jksPath) throws FileNotFoundException {
URL jksUrl = getClass().getClassLoader().getResource(jksPath);
if (jksUrl != null) {
logger.info("Starting with jks at {}, jks normal {}", jksUrl.toExternalForm(), jksUrl);
return getClass().getClassLoader().getResourceAsStream(jksPath);
}
logger.warn("No keystore has been found in the bundled resources. Scanning filesystem...");
File jksFile = new File(jksPath);
if (jksFile.exists()) {
logger.info("Loading external keystore. Url = {}.", jksFile.getAbsolutePath());
return new FileInputStream(jksFile);
}
logger.warn("The keystore file does not exist. Url = {}.", jksFile.getAbsolutePath());
return null;
}
}
|
logger.info("Checking SSL configuration properties...");
final String jksPath = Config.getInstance().getStringValue("ssl.jksPath");
logger.info("Initializing SSL context. KeystorePath = {}.", jksPath);
if (jksPath == null || jksPath.isEmpty()) {
// key_store_password or key_manager_password are empty
logger.warn("The keystore path is null or empty. The SSL context won't be initialized.");
return null;
}
// if we have the port also the jks then keyStorePassword and
// keyManagerPassword
// has to be defined
final String keyStorePassword = Config.getInstance().getStringValue("ssl.keyStorePassword");
// if client authentification is enabled a trustmanager needs to be
// added to the ServerContext
try {
logger.info("Loading keystore. KeystorePath = {}.", jksPath);
InputStream jksInputStream = jksDatastore(jksPath);
SSLContext clientSSLContext = SSLContext.getInstance("TLS");
final KeyStore ks = KeyStore.getInstance("JKS");
ks.load(jksInputStream, keyStorePassword.toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
TrustManager[] trustManagers = tmf.getTrustManagers();
// init sslContext
logger.info("Initializing SSL context...");
clientSSLContext.init(null, trustManagers, null);
logger.info("The SSL context has been initialized successfully.");
return clientSSLContext;
} catch (NoSuchAlgorithmException | CertificateException | KeyStoreException | KeyManagementException
| IOException ex) {
logger.error("Unable to initialize SSL context. Cause = {}, errorMessage = {}.", ex.getCause(),
ex.getMessage());
return null;
}
| 321
| 479
| 800
|
<no_super_class>
|
ffay_lanproxy
|
lanproxy/proxy-client/src/main/java/org/fengfei/lanproxy/client/handlers/ClientChannelHandler.java
|
ClientChannelHandler
|
operationComplete
|
class ClientChannelHandler extends SimpleChannelInboundHandler<ProxyMessage> {
private static Logger logger = LoggerFactory.getLogger(ClientChannelHandler.class);
private Bootstrap bootstrap;
private Bootstrap proxyBootstrap;
private ChannelStatusListener channelStatusListener;
public ClientChannelHandler(Bootstrap bootstrap, Bootstrap proxyBootstrap, ChannelStatusListener channelStatusListener) {
this.bootstrap = bootstrap;
this.proxyBootstrap = proxyBootstrap;
this.channelStatusListener = channelStatusListener;
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, ProxyMessage proxyMessage) throws Exception {
logger.debug("recieved proxy message, type is {}", proxyMessage.getType());
switch (proxyMessage.getType()) {
case ProxyMessage.TYPE_CONNECT:
handleConnectMessage(ctx, proxyMessage);
break;
case ProxyMessage.TYPE_DISCONNECT:
handleDisconnectMessage(ctx, proxyMessage);
break;
case ProxyMessage.P_TYPE_TRANSFER:
handleTransferMessage(ctx, proxyMessage);
break;
default:
break;
}
}
private void handleTransferMessage(ChannelHandlerContext ctx, ProxyMessage proxyMessage) {
Channel realServerChannel = ctx.channel().attr(Constants.NEXT_CHANNEL).get();
if (realServerChannel != null) {
ByteBuf buf = ctx.alloc().buffer(proxyMessage.getData().length);
buf.writeBytes(proxyMessage.getData());
logger.debug("write data to real server, {}", realServerChannel);
realServerChannel.writeAndFlush(buf);
}
}
private void handleDisconnectMessage(ChannelHandlerContext ctx, ProxyMessage proxyMessage) {
Channel realServerChannel = ctx.channel().attr(Constants.NEXT_CHANNEL).get();
logger.debug("handleDisconnectMessage, {}", realServerChannel);
if (realServerChannel != null) {
ctx.channel().attr(Constants.NEXT_CHANNEL).remove();
ClientChannelMannager.returnProxyChanel(ctx.channel());
realServerChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
}
}
private void handleConnectMessage(ChannelHandlerContext ctx, ProxyMessage proxyMessage) {
final Channel cmdChannel = ctx.channel();
final String userId = proxyMessage.getUri();
String[] serverInfo = new String(proxyMessage.getData()).split(":");
String ip = serverInfo[0];
int port = Integer.parseInt(serverInfo[1]);
bootstrap.connect(ip, port).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {<FILL_FUNCTION_BODY>}
});
}
@Override
public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
Channel realServerChannel = ctx.channel().attr(Constants.NEXT_CHANNEL).get();
if (realServerChannel != null) {
realServerChannel.config().setOption(ChannelOption.AUTO_READ, ctx.channel().isWritable());
}
super.channelWritabilityChanged(ctx);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
// 控制连接
if (ClientChannelMannager.getCmdChannel() == ctx.channel()) {
ClientChannelMannager.setCmdChannel(null);
ClientChannelMannager.clearRealServerChannels();
channelStatusListener.channelInactive(ctx);
} else {
// 数据传输连接
Channel realServerChannel = ctx.channel().attr(Constants.NEXT_CHANNEL).get();
if (realServerChannel != null && realServerChannel.isActive()) {
realServerChannel.close();
}
}
ClientChannelMannager.removeProxyChanel(ctx.channel());
super.channelInactive(ctx);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
logger.error("exception caught", cause);
super.exceptionCaught(ctx, cause);
}
}
|
// 连接后端服务器成功
if (future.isSuccess()) {
final Channel realServerChannel = future.channel();
logger.debug("connect realserver success, {}", realServerChannel);
realServerChannel.config().setOption(ChannelOption.AUTO_READ, false);
// 获取连接
ClientChannelMannager.borrowProxyChanel(proxyBootstrap, new ProxyChannelBorrowListener() {
@Override
public void success(Channel channel) {
// 连接绑定
channel.attr(Constants.NEXT_CHANNEL).set(realServerChannel);
realServerChannel.attr(Constants.NEXT_CHANNEL).set(channel);
// 远程绑定
ProxyMessage proxyMessage = new ProxyMessage();
proxyMessage.setType(ProxyMessage.TYPE_CONNECT);
proxyMessage.setUri(userId + "@" + Config.getInstance().getStringValue("client.key"));
channel.writeAndFlush(proxyMessage);
realServerChannel.config().setOption(ChannelOption.AUTO_READ, true);
ClientChannelMannager.addRealServerChannel(userId, realServerChannel);
ClientChannelMannager.setRealServerChannelUserId(realServerChannel, userId);
}
@Override
public void error(Throwable cause) {
ProxyMessage proxyMessage = new ProxyMessage();
proxyMessage.setType(ProxyMessage.TYPE_DISCONNECT);
proxyMessage.setUri(userId);
cmdChannel.writeAndFlush(proxyMessage);
}
});
} else {
ProxyMessage proxyMessage = new ProxyMessage();
proxyMessage.setType(ProxyMessage.TYPE_DISCONNECT);
proxyMessage.setUri(userId);
cmdChannel.writeAndFlush(proxyMessage);
}
| 1,075
| 464
| 1,539
|
<no_super_class>
|
ffay_lanproxy
|
lanproxy/proxy-client/src/main/java/org/fengfei/lanproxy/client/handlers/RealServerChannelHandler.java
|
RealServerChannelHandler
|
channelInactive
|
class RealServerChannelHandler extends SimpleChannelInboundHandler<ByteBuf> {
private static Logger logger = LoggerFactory.getLogger(RealServerChannelHandler.class);
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf buf) throws Exception {
Channel realServerChannel = ctx.channel();
Channel channel = realServerChannel.attr(Constants.NEXT_CHANNEL).get();
if (channel == null) {
// 代理客户端连接断开
ctx.channel().close();
} else {
byte[] bytes = new byte[buf.readableBytes()];
buf.readBytes(bytes);
String userId = ClientChannelMannager.getRealServerChannelUserId(realServerChannel);
ProxyMessage proxyMessage = new ProxyMessage();
proxyMessage.setType(ProxyMessage.P_TYPE_TRANSFER);
proxyMessage.setUri(userId);
proxyMessage.setData(bytes);
channel.writeAndFlush(proxyMessage);
logger.debug("write data to proxy server, {}, {}", realServerChannel, channel);
}
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
super.channelActive(ctx);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
Channel realServerChannel = ctx.channel();
Channel proxyChannel = realServerChannel.attr(Constants.NEXT_CHANNEL).get();
if (proxyChannel != null) {
proxyChannel.config().setOption(ChannelOption.AUTO_READ, realServerChannel.isWritable());
}
super.channelWritabilityChanged(ctx);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
logger.error("exception caught", cause);
super.exceptionCaught(ctx, cause);
}
}
|
Channel realServerChannel = ctx.channel();
String userId = ClientChannelMannager.getRealServerChannelUserId(realServerChannel);
ClientChannelMannager.removeRealServerChannel(userId);
Channel channel = realServerChannel.attr(Constants.NEXT_CHANNEL).get();
if (channel != null) {
logger.debug("channelInactive, {}", realServerChannel);
ProxyMessage proxyMessage = new ProxyMessage();
proxyMessage.setType(ProxyMessage.TYPE_DISCONNECT);
proxyMessage.setUri(userId);
channel.writeAndFlush(proxyMessage);
}
super.channelInactive(ctx);
| 505
| 170
| 675
|
<no_super_class>
|
ffay_lanproxy
|
lanproxy/proxy-common/src/main/java/org/fengfei/lanproxy/common/Config.java
|
Config
|
getStringValue
|
class Config {
private static final String DEFAULT_CONF = "config.properties";
private static Map<String, Config> instances = new ConcurrentHashMap<String, Config>();
private Properties configuration = new Properties();
private Config() {
initConfig(DEFAULT_CONF);
}
private Config(String configFile) {
initConfig(configFile);
}
private void initConfig(String configFile) {
InputStream is = Config.class.getClassLoader().getResourceAsStream(configFile);
try {
configuration.load(is);
is.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
/**
* 获得Configuration实例。 默认为config.property
*
* @return Configuration实例
*/
public static Config getInstance() {
return getInstance(DEFAULT_CONF);
}
/**
* 自定义文件解析**.property
*
* @param configFile
* @return
*/
public static Config getInstance(String configFile) {
Config config = instances.get(configFile);
if (config == null) {
synchronized (instances) {
config = instances.get(configFile);
if (config == null) {
config = new Config(configFile);
instances.put(configFile, config);
}
}
}
return config;
}
/**
* 获得配置项。
*
* @param key 配置关键字
*
* @return 配置项
*/
public String getStringValue(String key) {
return configuration.getProperty(key);
}
public String getStringValue(String key, String defaultValue) {<FILL_FUNCTION_BODY>}
public int getIntValue(String key, int defaultValue) {
return LangUtil.parseInt(configuration.getProperty(key), defaultValue);
}
public int getIntValue(String key) {
return LangUtil.parseInt(configuration.getProperty(key));
}
public double getDoubleValue(String key, Double defaultValue) {
return LangUtil.parseDouble(configuration.getProperty(key), defaultValue);
}
public double getDoubleValue(String key) {
return LangUtil.parseDouble(configuration.getProperty(key));
}
public double getLongValue(String key, Long defaultValue) {
return LangUtil.parseLong(configuration.getProperty(key), defaultValue);
}
public double getLongValue(String key) {
return LangUtil.parseLong(configuration.getProperty(key));
}
public Boolean getBooleanValue(String key, Boolean defaultValue) {
return LangUtil.parseBoolean(configuration.getProperty(key), defaultValue);
}
public Boolean getBooleanValue(String key) {
return LangUtil.parseBoolean(configuration.getProperty(key));
}
}
|
String value = this.getStringValue(key);
if (value == null) {
return defaultValue;
} else {
return value;
}
| 746
| 43
| 789
|
<no_super_class>
|
ffay_lanproxy
|
lanproxy/proxy-common/src/main/java/org/fengfei/lanproxy/common/JsonUtil.java
|
JsonUtil
|
json2object
|
class JsonUtil {
@SuppressWarnings("unchecked")
public static <T> T json2object(String json, TypeToken<T> typeToken) {<FILL_FUNCTION_BODY>}
/**
*
* java对象转为json对象
*
*/
public static String object2json(Object obj) {
Gson gson = new Gson();
return gson.toJson(obj);
}
}
|
try {
Gson gson = new Gson();
return (T) gson.fromJson(json, typeToken.getType());
} catch (Exception e) {
}
return null;
| 117
| 55
| 172
|
<no_super_class>
|
ffay_lanproxy
|
lanproxy/proxy-common/src/main/java/org/fengfei/lanproxy/common/LangUtil.java
|
LangUtil
|
parseBoolean
|
class LangUtil {
private static Logger logger = LoggerFactory.getLogger(LangUtil.class);
public static Boolean parseBoolean(Object value) {<FILL_FUNCTION_BODY>}
public static boolean parseBoolean(Object value, boolean defaultValue) {
if (value != null) {
if (value instanceof Boolean) {
return (Boolean) value;
} else if (value instanceof String) {
try {
return Boolean.valueOf((String) value);
} catch (Exception e) {
logger.warn("parse boolean value({}) failed.", value);
}
}
}
return defaultValue;
}
/**
* @Title: parseInt
* @Description: Int解析方法,可传入Integer或String值
* @param value Integer或String值
* @return Integer 返回类型
*/
public static Integer parseInt(Object value) {
if (value != null) {
if (value instanceof Integer) {
return (Integer) value;
} else if (value instanceof String) {
return Integer.valueOf((String) value);
}
}
return null;
}
public static Integer parseInt(Object value, Integer defaultValue) {
if (value != null) {
if (value instanceof Integer) {
return (Integer) value;
} else if (value instanceof String) {
try {
return Integer.valueOf((String) value);
} catch (Exception e) {
logger.warn("parse Integer value({}) failed.", value);
}
}
}
return defaultValue;
}
/***
*
* @Title: parseLong
* @Description: long解析方法,可传入Long或String值
* @param value Integer或String值
* @param @return
* @return Long 返回类型
*/
public static Long parseLong(Object value) {
if (value != null) {
if (value instanceof Long) {
return (Long) value;
} else if (value instanceof String) {
return Long.valueOf((String) value);
}
}
return null;
}
public static Long parseLong(Object value, Long defaultValue) {
if (value != null) {
if (value instanceof Long) {
return (Long) value;
} else if (value instanceof String) {
try {
return Long.valueOf((String) value);
} catch (NumberFormatException e) {
logger.warn("parse Long value({}) failed.", value);
}
}
}
return defaultValue;
}
/**
* @Title: parseDouble
* @Description: Double解析方法,可传入Double或String值
* @param value Double或String值
* @return Double 返回类型
*/
public static Double parseDouble(Object value) {
if (value != null) {
if (value instanceof Double) {
return (Double) value;
} else if (value instanceof String) {
return Double.valueOf((String) value);
}
}
return null;
}
/**
* @Title: parseDouble
* @Description: Double解析方法,可传入Double或String值
* @param value Double或String值
* @return Double 返回类型
*/
public static Double parseDouble(Object value, Double defaultValue) {
if (value != null) {
if (value instanceof Double) {
return (Double) value;
} else if (value instanceof String) {
try {
return Double.valueOf((String) value);
} catch (NumberFormatException e) {
logger.warn("parse Double value({}) failed.", value);
}
}
}
return defaultValue;
}
}
|
if (value != null) {
if (value instanceof Boolean) {
return (Boolean) value;
} else if (value instanceof String) {
return Boolean.valueOf((String) value);
}
}
return null;
| 960
| 64
| 1,024
|
<no_super_class>
|
ffay_lanproxy
|
lanproxy/proxy-common/src/main/java/org/fengfei/lanproxy/common/container/ContainerHelper.java
|
ContainerHelper
|
start
|
class ContainerHelper {
private static Logger logger = LoggerFactory.getLogger(ContainerHelper.class);
private static volatile boolean running = true;
private static List<Container> cachedContainers;
public static void start(List<Container> containers) {<FILL_FUNCTION_BODY>}
private static void startContainers() {
for (Container container : cachedContainers) {
logger.info("starting container [{}]", container.getClass().getName());
container.start();
logger.info("container [{}] started", container.getClass().getName());
}
}
private static void stopContainers() {
for (Container container : cachedContainers) {
logger.info("stopping container [{}]", container.getClass().getName());
try {
container.stop();
logger.info("container [{}] stopped", container.getClass().getName());
} catch (Exception ex) {
logger.warn("container stopped with error", ex);
}
}
}
}
|
cachedContainers = containers;
// 启动所有容器
startContainers();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
synchronized (ContainerHelper.class) {
// 停止所有容器.
stopContainers();
running = false;
ContainerHelper.class.notify();
}
}
});
synchronized (ContainerHelper.class) {
while (running) {
try {
ContainerHelper.class.wait();
} catch (Throwable e) {
}
}
}
| 262
| 164
| 426
|
<no_super_class>
|
ffay_lanproxy
|
lanproxy/proxy-protocol/src/main/java/org/fengfei/lanproxy/protocol/IdleCheckHandler.java
|
IdleCheckHandler
|
channelIdle
|
class IdleCheckHandler extends IdleStateHandler {
public static final int USER_CHANNEL_READ_IDLE_TIME = 1200;
public static final int READ_IDLE_TIME = 60;
public static final int WRITE_IDLE_TIME = 40;
private static Logger logger = LoggerFactory.getLogger(IdleCheckHandler.class);
public IdleCheckHandler(int readerIdleTimeSeconds, int writerIdleTimeSeconds, int allIdleTimeSeconds) {
super(readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds);
}
@Override
protected void channelIdle(ChannelHandlerContext ctx, IdleStateEvent evt) throws Exception {<FILL_FUNCTION_BODY>}
}
|
if (IdleStateEvent.FIRST_WRITER_IDLE_STATE_EVENT == evt) {
logger.debug("channel write timeout {}", ctx.channel());
ProxyMessage proxyMessage = new ProxyMessage();
proxyMessage.setType(ProxyMessage.TYPE_HEARTBEAT);
ctx.channel().writeAndFlush(proxyMessage);
} else if (IdleStateEvent.FIRST_READER_IDLE_STATE_EVENT == evt) {
logger.warn("channel read timeout {}", ctx.channel());
ctx.channel().close();
}
super.channelIdle(ctx, evt);
| 201
| 158
| 359
|
<no_super_class>
|
ffay_lanproxy
|
lanproxy/proxy-protocol/src/main/java/org/fengfei/lanproxy/protocol/ProxyMessage.java
|
ProxyMessage
|
toString
|
class ProxyMessage {
/** 心跳消息 */
public static final byte TYPE_HEARTBEAT = 0x07;
/** 认证消息,检测clientKey是否正确 */
public static final byte C_TYPE_AUTH = 0x01;
// /** 保活确认消息 */
// public static final byte TYPE_ACK = 0x02;
/** 代理后端服务器建立连接消息 */
public static final byte TYPE_CONNECT = 0x03;
/** 代理后端服务器断开连接消息 */
public static final byte TYPE_DISCONNECT = 0x04;
/** 代理数据传输 */
public static final byte P_TYPE_TRANSFER = 0x05;
/** 用户与代理服务器以及代理客户端与真实服务器连接是否可写状态同步 */
public static final byte C_TYPE_WRITE_CONTROL = 0x06;
/** 消息类型 */
private byte type;
/** 消息流水号 */
private long serialNumber;
/** 消息命令请求信息 */
private String uri;
/** 消息传输数据 */
private byte[] data;
public void setUri(String uri) {
this.uri = uri;
}
public String getUri() {
return uri;
}
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data;
}
public byte getType() {
return type;
}
public void setType(byte type) {
this.type = type;
}
public long getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(long serialNumber) {
this.serialNumber = serialNumber;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "ProxyMessage [type=" + type + ", serialNumber=" + serialNumber + ", uri=" + uri + ", data=" + Arrays.toString(data) + "]";
| 494
| 48
| 542
|
<no_super_class>
|
ffay_lanproxy
|
lanproxy/proxy-protocol/src/main/java/org/fengfei/lanproxy/protocol/ProxyMessageDecoder.java
|
ProxyMessageDecoder
|
decode
|
class ProxyMessageDecoder extends LengthFieldBasedFrameDecoder {
private static final byte HEADER_SIZE = 4;
private static final int TYPE_SIZE = 1;
private static final int SERIAL_NUMBER_SIZE = 8;
private static final int URI_LENGTH_SIZE = 1;
/**
* @param maxFrameLength
* @param lengthFieldOffset
* @param lengthFieldLength
* @param lengthAdjustment
* @param initialBytesToStrip
*/
public ProxyMessageDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment,
int initialBytesToStrip) {
super(maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment, initialBytesToStrip);
}
/**
* @param maxFrameLength
* @param lengthFieldOffset
* @param lengthFieldLength
* @param lengthAdjustment
* @param initialBytesToStrip
* @param failFast
*/
public ProxyMessageDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment,
int initialBytesToStrip, boolean failFast) {
super(maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment, initialBytesToStrip, failFast);
}
@Override
protected ProxyMessage decode(ChannelHandlerContext ctx, ByteBuf in2) throws Exception {<FILL_FUNCTION_BODY>}
}
|
ByteBuf in = (ByteBuf) super.decode(ctx, in2);
if (in == null) {
return null;
}
if (in.readableBytes() < HEADER_SIZE) {
return null;
}
int frameLength = in.readInt();
if (in.readableBytes() < frameLength) {
return null;
}
ProxyMessage proxyMessage = new ProxyMessage();
byte type = in.readByte();
long sn = in.readLong();
proxyMessage.setSerialNumber(sn);
proxyMessage.setType(type);
byte uriLength = in.readByte();
byte[] uriBytes = new byte[uriLength];
in.readBytes(uriBytes);
proxyMessage.setUri(new String(uriBytes));
byte[] data = new byte[frameLength - TYPE_SIZE - SERIAL_NUMBER_SIZE - URI_LENGTH_SIZE - uriLength];
in.readBytes(data);
proxyMessage.setData(data);
in.release();
return proxyMessage;
| 372
| 274
| 646
|
<no_super_class>
|
ffay_lanproxy
|
lanproxy/proxy-protocol/src/main/java/org/fengfei/lanproxy/protocol/ProxyMessageEncoder.java
|
ProxyMessageEncoder
|
encode
|
class ProxyMessageEncoder extends MessageToByteEncoder<ProxyMessage> {
private static final int TYPE_SIZE = 1;
private static final int SERIAL_NUMBER_SIZE = 8;
private static final int URI_LENGTH_SIZE = 1;
@Override
protected void encode(ChannelHandlerContext ctx, ProxyMessage msg, ByteBuf out) throws Exception {<FILL_FUNCTION_BODY>}
}
|
int bodyLength = TYPE_SIZE + SERIAL_NUMBER_SIZE + URI_LENGTH_SIZE;
byte[] uriBytes = null;
if (msg.getUri() != null) {
uriBytes = msg.getUri().getBytes();
bodyLength += uriBytes.length;
}
if (msg.getData() != null) {
bodyLength += msg.getData().length;
}
// write the total packet length but without length field's length.
out.writeInt(bodyLength);
out.writeByte(msg.getType());
out.writeLong(msg.getSerialNumber());
if (uriBytes != null) {
out.writeByte((byte) uriBytes.length);
out.writeBytes(uriBytes);
} else {
out.writeByte((byte) 0x00);
}
if (msg.getData() != null) {
out.writeBytes(msg.getData());
}
| 106
| 249
| 355
|
<no_super_class>
|
ffay_lanproxy
|
lanproxy/proxy-server/src/main/java/org/fengfei/lanproxy/server/ProxyServerContainer.java
|
ProxyServerContainer
|
start
|
class ProxyServerContainer implements Container, ConfigChangedListener {
/**
* max packet is 2M.
*/
private static final int MAX_FRAME_LENGTH = 2 * 1024 * 1024;
private static final int LENGTH_FIELD_OFFSET = 0;
private static final int LENGTH_FIELD_LENGTH = 4;
private static final int INITIAL_BYTES_TO_STRIP = 0;
private static final int LENGTH_ADJUSTMENT = 0;
private static Logger logger = LoggerFactory.getLogger(ProxyServerContainer.class);
private NioEventLoopGroup serverWorkerGroup;
private NioEventLoopGroup serverBossGroup;
public ProxyServerContainer() {
serverBossGroup = new NioEventLoopGroup();
serverWorkerGroup = new NioEventLoopGroup();
ProxyConfig.getInstance().addConfigChangedListener(this);
}
@Override
public void start() {<FILL_FUNCTION_BODY>}
private void initializeSSLTCPTransport(String host, int port, final SSLContext sslContext) {
ServerBootstrap b = new ServerBootstrap();
b.group(serverBossGroup, serverWorkerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
try {
pipeline.addLast("ssl", createSslHandler(sslContext, Config.getInstance().getBooleanValue("server.ssl.needsClientAuth", false)));
ch.pipeline().addLast(new ProxyMessageDecoder(MAX_FRAME_LENGTH, LENGTH_FIELD_OFFSET, LENGTH_FIELD_LENGTH, LENGTH_ADJUSTMENT, INITIAL_BYTES_TO_STRIP));
ch.pipeline().addLast(new ProxyMessageEncoder());
ch.pipeline().addLast(new IdleCheckHandler(IdleCheckHandler.READ_IDLE_TIME, IdleCheckHandler.WRITE_IDLE_TIME, 0));
ch.pipeline().addLast(new ServerChannelHandler());
} catch (Throwable th) {
logger.error("Severe error during pipeline creation", th);
throw th;
}
}
});
try {
// Bind and start to accept incoming connections.
ChannelFuture f = b.bind(host, port);
f.sync();
logger.info("proxy ssl server start on port {}", port);
} catch (InterruptedException ex) {
logger.error("An interruptedException was caught while initializing server", ex);
}
}
private void startUserPort() {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(serverBossGroup, serverWorkerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addFirst(new BytesMetricsHandler());
ch.pipeline().addLast(new UserChannelHandler());
}
});
List<Integer> ports = ProxyConfig.getInstance().getUserPorts();
for (int port : ports) {
try {
bootstrap.bind(port).get();
logger.info("bind user port " + port);
} catch (Exception ex) {
// BindException表示该端口已经绑定过
if (!(ex.getCause() instanceof BindException)) {
throw new RuntimeException(ex);
}
}
}
}
@Override
public void onChanged() {
startUserPort();
}
@Override
public void stop() {
serverBossGroup.shutdownGracefully();
serverWorkerGroup.shutdownGracefully();
}
private ChannelHandler createSslHandler(SSLContext sslContext, boolean needsClientAuth) {
SSLEngine sslEngine = sslContext.createSSLEngine();
sslEngine.setUseClientMode(false);
if (needsClientAuth) {
sslEngine.setNeedClientAuth(true);
}
return new SslHandler(sslEngine);
}
public static void main(String[] args) {
ContainerHelper.start(Arrays.asList(new Container[] { new ProxyServerContainer(), new WebConfigContainer() }));
}
}
|
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(serverBossGroup, serverWorkerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new ProxyMessageDecoder(MAX_FRAME_LENGTH, LENGTH_FIELD_OFFSET, LENGTH_FIELD_LENGTH, LENGTH_ADJUSTMENT, INITIAL_BYTES_TO_STRIP));
ch.pipeline().addLast(new ProxyMessageEncoder());
ch.pipeline().addLast(new IdleCheckHandler(IdleCheckHandler.READ_IDLE_TIME, IdleCheckHandler.WRITE_IDLE_TIME, 0));
ch.pipeline().addLast(new ServerChannelHandler());
}
});
try {
bootstrap.bind(ProxyConfig.getInstance().getServerBind(), ProxyConfig.getInstance().getServerPort()).get();
logger.info("proxy server start on port " + ProxyConfig.getInstance().getServerPort());
} catch (Exception ex) {
throw new RuntimeException(ex);
}
if (Config.getInstance().getBooleanValue("server.ssl.enable", false)) {
String host = Config.getInstance().getStringValue("server.ssl.bind", "0.0.0.0");
int port = Config.getInstance().getIntValue("server.ssl.port");
initializeSSLTCPTransport(host, port, new SslContextCreator().initSSLContext());
}
startUserPort();
| 1,141
| 404
| 1,545
|
<no_super_class>
|
ffay_lanproxy
|
lanproxy/proxy-server/src/main/java/org/fengfei/lanproxy/server/SslContextCreator.java
|
SslContextCreator
|
initSSLContext
|
class SslContextCreator {
private static Logger logger = LoggerFactory.getLogger(SslContextCreator.class);
public SSLContext initSSLContext() {<FILL_FUNCTION_BODY>}
private InputStream jksDatastore(String jksPath) throws FileNotFoundException {
URL jksUrl = getClass().getClassLoader().getResource(jksPath);
if (jksUrl != null) {
logger.info("Starting with jks at {}, jks normal {}", jksUrl.toExternalForm(), jksUrl);
return getClass().getClassLoader().getResourceAsStream(jksPath);
}
logger.warn("No keystore has been found in the bundled resources. Scanning filesystem...");
File jksFile = new File(jksPath);
if (jksFile.exists()) {
logger.info("Loading external keystore. Url = {}.", jksFile.getAbsolutePath());
return new FileInputStream(jksFile);
}
logger.warn("The keystore file does not exist. Url = {}.", jksFile.getAbsolutePath());
return null;
}
}
|
logger.info("Checking SSL configuration properties...");
final String jksPath = Config.getInstance().getStringValue("server.ssl.jksPath");
logger.info("Initializing SSL context. KeystorePath = {}.", jksPath);
if (jksPath == null || jksPath.isEmpty()) {
// key_store_password or key_manager_password are empty
logger.warn("The keystore path is null or empty. The SSL context won't be initialized.");
return null;
}
// if we have the port also the jks then keyStorePassword and
// keyManagerPassword
// has to be defined
final String keyStorePassword = Config.getInstance().getStringValue("server.ssl.keyStorePassword");
final String keyManagerPassword = Config.getInstance().getStringValue("server.ssl.keyManagerPassword");
if (keyStorePassword == null || keyStorePassword.isEmpty()) {
// key_store_password or key_manager_password are empty
logger.warn("The keystore password is null or empty. The SSL context won't be initialized.");
return null;
}
if (keyManagerPassword == null || keyManagerPassword.isEmpty()) {
// key_manager_password or key_manager_password are empty
logger.warn("The key manager password is null or empty. The SSL context won't be initialized.");
return null;
}
// if client authentification is enabled a trustmanager needs to be
// added to the ServerContext
boolean needsClientAuth = Config.getInstance().getBooleanValue("server.ssl.needsClientAuth", false);
try {
logger.info("Loading keystore. KeystorePath = {}.", jksPath);
InputStream jksInputStream = jksDatastore(jksPath);
SSLContext serverContext = SSLContext.getInstance("TLS");
final KeyStore ks = KeyStore.getInstance("JKS");
ks.load(jksInputStream, keyStorePassword.toCharArray());
logger.info("Initializing key manager...");
final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, keyManagerPassword.toCharArray());
TrustManager[] trustManagers = null;
if (needsClientAuth) {
logger.warn(
"Client authentication is enabled. The keystore will be used as a truststore. KeystorePath = {}.",
jksPath);
// use keystore as truststore, as server needs to trust
// certificates signed by the
// server certificates
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
trustManagers = tmf.getTrustManagers();
}
// init sslContext
logger.info("Initializing SSL context...");
serverContext.init(kmf.getKeyManagers(), trustManagers, null);
logger.info("The SSL context has been initialized successfully.");
return serverContext;
} catch (NoSuchAlgorithmException | UnrecoverableKeyException | CertificateException | KeyStoreException
| KeyManagementException | IOException ex) {
logger.error("Unable to initialize SSL context. Cause = {}, errorMessage = {}.", ex.getCause(),
ex.getMessage());
return null;
}
| 292
| 819
| 1,111
|
<no_super_class>
|
ffay_lanproxy
|
lanproxy/proxy-server/src/main/java/org/fengfei/lanproxy/server/config/web/ApiRoute.java
|
ApiRoute
|
run
|
class ApiRoute {
private static Logger logger = LoggerFactory.getLogger(ApiRoute.class);
/** 接口路由 */
private static Map<String, RequestHandler> routes = new ConcurrentHashMap<String, RequestHandler>();
/** 拦截器,初始化后不会在变化 */
private static List<RequestMiddleware> middlewares = new ArrayList<RequestMiddleware>();
/**
* 增加接口请求路由
*
* @param uri
* @param requestHandler
*/
public static void addRoute(String uri, RequestHandler requestHandler) {
if (routes.containsKey(uri)) {
throw new IllegalArgumentException("Duplicate uri:" + uri);
}
logger.info("add route {}", uri);
routes.put(uri, requestHandler);
}
/**
* 增加拦截器
*
* @param requestMiddleware
*/
public static void addMiddleware(RequestMiddleware requestMiddleware) {
if (middlewares.contains(requestMiddleware)) {
throw new IllegalArgumentException("Duplicate RequestMiddleware:" + requestMiddleware);
}
logger.info("add requestMiddleware {}", requestMiddleware);
middlewares.add(requestMiddleware);
}
/**
* 请求执行
*
* @param request
* @return
*/
public static ResponseInfo run(FullHttpRequest request) {<FILL_FUNCTION_BODY>}
}
|
try {
// 拦截器中如果不能通过以异常的方式进行反馈
for (RequestMiddleware middleware : middlewares) {
middleware.preRequest(request);
}
URI uri = new URI(request.getUri());
RequestHandler handler = routes.get(uri.getPath());
ResponseInfo responseInfo = null;
if (handler != null) {
responseInfo = handler.request(request);
} else {
responseInfo = ResponseInfo.build(ResponseInfo.CODE_API_NOT_FOUND, "api not found");
}
return responseInfo;
} catch (Exception ex) {
if (ex instanceof ContextException) {
return ResponseInfo.build(((ContextException) ex).getCode(), ex.getMessage());
}
logger.error("request error", ex);
}
return null;
| 388
| 220
| 608
|
<no_super_class>
|
ffay_lanproxy
|
lanproxy/proxy-server/src/main/java/org/fengfei/lanproxy/server/config/web/HttpRequestHandler.java
|
HttpRequestHandler
|
outputPages
|
class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
private static final String PAGE_FOLDER = System.getProperty("app.home", System.getProperty("user.dir"))
+ "/webpages";
private static final String SERVER_VS = "LPS-0.1";
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
// GET返回页面;POST请求接口
if (request.getMethod() != HttpMethod.POST) {
outputPages(ctx, request);
return;
}
ResponseInfo responseInfo = ApiRoute.run(request);
// 错误码规则:除100取整为http状态码
outputContent(ctx, request, responseInfo.getCode() / 100, JsonUtil.object2json(responseInfo),
"Application/json;charset=utf-8");
}
private void outputContent(ChannelHandlerContext ctx, FullHttpRequest request, int code, String content,
String mimeType) {
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(code),
Unpooled.wrappedBuffer(content.getBytes(Charset.forName("UTF-8"))));
response.headers().set(Names.CONTENT_TYPE, mimeType);
response.headers().set(Names.CONTENT_LENGTH, response.content().readableBytes());
response.headers().set(Names.SERVER, SERVER_VS);
ChannelFuture future = ctx.writeAndFlush(response);
if (!HttpHeaders.isKeepAlive(request)) {
future.addListener(ChannelFutureListener.CLOSE);
}
}
/**
* 输出静态资源数据
*
* @param ctx
* @param request
* @throws Exception
*/
private void outputPages(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {<FILL_FUNCTION_BODY>}
private static void send100Continue(ChannelHandlerContext ctx) {
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE);
ctx.writeAndFlush(response);
}
}
|
HttpResponseStatus status = HttpResponseStatus.OK;
URI uri = new URI(request.getUri());
String uriPath = uri.getPath();
if (uriPath.contains("../")) {
status = HttpResponseStatus.FORBIDDEN;
outputContent(ctx, request, status.code(), status.toString(), "text/html");
return;
}
uriPath = uriPath.equals("/") ? "/index.html" : uriPath;
String path = PAGE_FOLDER + uriPath;
File rfile = new File(path);
if (rfile.isDirectory()) {
path = path + "/index.html";
rfile = new File(path);
}
if (!rfile.exists()) {
status = HttpResponseStatus.NOT_FOUND;
outputContent(ctx, request, status.code(), status.toString(), "text/html");
return;
}
if (HttpHeaders.is100ContinueExpected(request)) {
send100Continue(ctx);
}
String mimeType = MimeType.getMimeType(MimeType.parseSuffix(path));
long length = 0;
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(rfile, "r");
length = raf.length();
} finally {
if (length < 0 && raf != null) {
raf.close();
}
}
HttpResponse response = new DefaultHttpResponse(request.getProtocolVersion(), status);
response.headers().set(HttpHeaders.Names.CONTENT_TYPE, mimeType);
boolean keepAlive = HttpHeaders.isKeepAlive(request);
if (keepAlive) {
response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, length);
response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
}
response.headers().set(Names.SERVER, SERVER_VS);
ctx.write(response);
if (ctx.pipeline().get(SslHandler.class) == null) {
ctx.write(new DefaultFileRegion(raf.getChannel(), 0, length));
} else {
ctx.write(new ChunkedNioFile(raf.getChannel()));
}
ChannelFuture future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
if (!keepAlive) {
future.addListener(ChannelFutureListener.CLOSE);
}
| 572
| 643
| 1,215
|
<no_super_class>
|
ffay_lanproxy
|
lanproxy/proxy-server/src/main/java/org/fengfei/lanproxy/server/config/web/WebConfigContainer.java
|
WebConfigContainer
|
initChannel
|
class WebConfigContainer implements Container {
private static Logger logger = LoggerFactory.getLogger(WebConfigContainer.class);
private NioEventLoopGroup serverWorkerGroup;
private NioEventLoopGroup serverBossGroup;
public WebConfigContainer() {
// 配置管理,并发处理很小,使用单线程处理网络事件
serverBossGroup = new NioEventLoopGroup(1);
serverWorkerGroup = new NioEventLoopGroup(1);
}
@Override
public void start() {
ServerBootstrap httpServerBootstrap = new ServerBootstrap();
httpServerBootstrap.group(serverBossGroup, serverWorkerGroup).channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {<FILL_FUNCTION_BODY>}
});
try {
httpServerBootstrap.bind(ProxyConfig.getInstance().getConfigServerBind(),
ProxyConfig.getInstance().getConfigServerPort()).get();
logger.info("http server start on port " + ProxyConfig.getInstance().getConfigServerPort());
} catch (Exception ex) {
throw new RuntimeException(ex);
}
RouteConfig.init();
}
@Override
public void stop() {
serverBossGroup.shutdownGracefully();
serverWorkerGroup.shutdownGracefully();
}
}
|
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new HttpObjectAggregator(8 * 1024 * 1024));
pipeline.addLast(new ChunkedWriteHandler());
pipeline.addLast(new HttpRequestHandler());
| 370
| 82
| 452
|
<no_super_class>
|
ffay_lanproxy
|
lanproxy/proxy-server/src/main/java/org/fengfei/lanproxy/server/config/web/routes/RouteConfig.java
|
RouteConfig
|
request
|
class RouteConfig {
protected static final String AUTH_COOKIE_KEY = "token";
private static Logger logger = LoggerFactory.getLogger(RouteConfig.class);
/** 管理员不能同时在多个地方登录 */
private static String token;
public static void init() {
ApiRoute.addMiddleware(new RequestMiddleware() {
@Override
public void preRequest(FullHttpRequest request) {
String cookieHeader = request.headers().get(HttpHeaders.Names.COOKIE);
boolean authenticated = false;
if (cookieHeader != null) {
String[] cookies = cookieHeader.split(";");
for (String cookie : cookies) {
String[] cookieArr = cookie.split("=");
if (AUTH_COOKIE_KEY.equals(cookieArr[0].trim())) {
if (cookieArr.length == 2 && cookieArr[1].equals(token)) {
authenticated = true;
}
}
}
}
String auth = request.headers().get(HttpHeaders.Names.AUTHORIZATION);
if (!authenticated && auth != null) {
String[] authArr = auth.split(" ");
if (authArr.length == 2 && authArr[0].equals(ProxyConfig.getInstance().getConfigAdminUsername()) && authArr[1].equals(ProxyConfig.getInstance().getConfigAdminPassword())) {
authenticated = true;
}
}
if (!request.getUri().equals("/login") && !authenticated) {
throw new ContextException(ResponseInfo.CODE_UNAUTHORIZED);
}
logger.info("handle request for api {}", request.getUri());
}
});
// 获取配置详细信息
ApiRoute.addRoute("/config/detail", new RequestHandler() {
@Override
public ResponseInfo request(FullHttpRequest request) {
List<Client> clients = ProxyConfig.getInstance().getClients();
for (Client client : clients) {
Channel channel = ProxyChannelManager.getCmdChannel(client.getClientKey());
if (channel != null) {
client.setStatus(1);// online
} else {
client.setStatus(0);// offline
}
}
return ResponseInfo.build(ProxyConfig.getInstance().getClients());
}
});
// 更新配置
ApiRoute.addRoute("/config/update", new RequestHandler() {
@Override
public ResponseInfo request(FullHttpRequest request) {<FILL_FUNCTION_BODY>}
});
ApiRoute.addRoute("/login", new RequestHandler() {
@Override
public ResponseInfo request(FullHttpRequest request) {
byte[] buf = new byte[request.content().readableBytes()];
request.content().readBytes(buf);
String config = new String(buf);
Map<String, String> loginParams = JsonUtil.json2object(config, new TypeToken<Map<String, String>>() {
});
if (loginParams == null) {
return ResponseInfo.build(ResponseInfo.CODE_INVILID_PARAMS, "Error login info");
}
String username = loginParams.get("username");
String password = loginParams.get("password");
if (username == null || password == null) {
return ResponseInfo.build(ResponseInfo.CODE_INVILID_PARAMS, "Error username or password");
}
if (username.equals(ProxyConfig.getInstance().getConfigAdminUsername()) && password.equals(ProxyConfig.getInstance().getConfigAdminPassword())) {
token = UUID.randomUUID().toString().replace("-", "");
return ResponseInfo.build(token);
}
return ResponseInfo.build(ResponseInfo.CODE_INVILID_PARAMS, "Error username or password");
}
});
ApiRoute.addRoute("/logout", new RequestHandler() {
@Override
public ResponseInfo request(FullHttpRequest request) {
token = null;
return ResponseInfo.build(ResponseInfo.CODE_OK, "success");
}
});
ApiRoute.addRoute("/metrics/get", new RequestHandler() {
@Override
public ResponseInfo request(FullHttpRequest request) {
return ResponseInfo.build(MetricsCollector.getAllMetrics());
}
});
ApiRoute.addRoute("/metrics/getandreset", new RequestHandler() {
@Override
public ResponseInfo request(FullHttpRequest request) {
return ResponseInfo.build(MetricsCollector.getAndResetAllMetrics());
}
});
}
}
|
byte[] buf = new byte[request.content().readableBytes()];
request.content().readBytes(buf);
String config = new String(buf, Charset.forName("UTF-8"));
List<Client> clients = JsonUtil.json2object(config, new TypeToken<List<Client>>() {
});
if (clients == null) {
return ResponseInfo.build(ResponseInfo.CODE_INVILID_PARAMS, "Error json config");
}
try {
ProxyConfig.getInstance().update(config);
} catch (Exception ex) {
logger.error("config update error", ex);
return ResponseInfo.build(ResponseInfo.CODE_INVILID_PARAMS, ex.getMessage());
}
return ResponseInfo.build(ResponseInfo.CODE_OK, "success");
| 1,295
| 224
| 1,519
|
<no_super_class>
|
ffay_lanproxy
|
lanproxy/proxy-server/src/main/java/org/fengfei/lanproxy/server/handlers/UserChannelHandler.java
|
UserChannelHandler
|
channelInactive
|
class UserChannelHandler extends SimpleChannelInboundHandler<ByteBuf> {
private static AtomicLong userIdProducer = new AtomicLong(0);
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
// 当出现异常就关闭连接
ctx.close();
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf buf) throws Exception {
// 通知代理客户端
Channel userChannel = ctx.channel();
Channel proxyChannel = userChannel.attr(Constants.NEXT_CHANNEL).get();
if (proxyChannel == null) {
// 该端口还没有代理客户端
ctx.channel().close();
} else {
byte[] bytes = new byte[buf.readableBytes()];
buf.readBytes(bytes);
String userId = ProxyChannelManager.getUserChannelUserId(userChannel);
ProxyMessage proxyMessage = new ProxyMessage();
proxyMessage.setType(ProxyMessage.P_TYPE_TRANSFER);
proxyMessage.setUri(userId);
proxyMessage.setData(bytes);
proxyChannel.writeAndFlush(proxyMessage);
}
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
Channel userChannel = ctx.channel();
InetSocketAddress sa = (InetSocketAddress) userChannel.localAddress();
Channel cmdChannel = ProxyChannelManager.getCmdChannel(sa.getPort());
if (cmdChannel == null) {
// 该端口还没有代理客户端
ctx.channel().close();
} else {
String userId = newUserId();
String lanInfo = ProxyConfig.getInstance().getLanInfo(sa.getPort());
// 用户连接到代理服务器时,设置用户连接不可读,等待代理后端服务器连接成功后再改变为可读状态
userChannel.config().setOption(ChannelOption.AUTO_READ, false);
ProxyChannelManager.addUserChannelToCmdChannel(cmdChannel, userId, userChannel);
ProxyMessage proxyMessage = new ProxyMessage();
proxyMessage.setType(ProxyMessage.TYPE_CONNECT);
proxyMessage.setUri(userId);
proxyMessage.setData(lanInfo.getBytes());
cmdChannel.writeAndFlush(proxyMessage);
}
super.channelActive(ctx);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
// 通知代理客户端
Channel userChannel = ctx.channel();
InetSocketAddress sa = (InetSocketAddress) userChannel.localAddress();
Channel cmdChannel = ProxyChannelManager.getCmdChannel(sa.getPort());
if (cmdChannel == null) {
// 该端口还没有代理客户端
ctx.channel().close();
} else {
Channel proxyChannel = userChannel.attr(Constants.NEXT_CHANNEL).get();
if (proxyChannel != null) {
proxyChannel.config().setOption(ChannelOption.AUTO_READ, userChannel.isWritable());
}
}
super.channelWritabilityChanged(ctx);
}
/**
* 为用户连接产生ID
*
* @return
*/
private static String newUserId() {
return String.valueOf(userIdProducer.incrementAndGet());
}
}
|
// 通知代理客户端
Channel userChannel = ctx.channel();
InetSocketAddress sa = (InetSocketAddress) userChannel.localAddress();
Channel cmdChannel = ProxyChannelManager.getCmdChannel(sa.getPort());
if (cmdChannel == null) {
// 该端口还没有代理客户端
ctx.channel().close();
} else {
// 用户连接断开,从控制连接中移除
String userId = ProxyChannelManager.getUserChannelUserId(userChannel);
ProxyChannelManager.removeUserChannelFromCmdChannel(cmdChannel, userId);
Channel proxyChannel = userChannel.attr(Constants.NEXT_CHANNEL).get();
if (proxyChannel != null && proxyChannel.isActive()) {
proxyChannel.attr(Constants.NEXT_CHANNEL).remove();
proxyChannel.attr(Constants.CLIENT_KEY).remove();
proxyChannel.attr(Constants.USER_ID).remove();
proxyChannel.config().setOption(ChannelOption.AUTO_READ, true);
// 通知客户端,用户连接已经断开
ProxyMessage proxyMessage = new ProxyMessage();
proxyMessage.setType(ProxyMessage.TYPE_DISCONNECT);
proxyMessage.setUri(userId);
proxyChannel.writeAndFlush(proxyMessage);
}
}
super.channelInactive(ctx);
| 887
| 349
| 1,236
|
<no_super_class>
|
ffay_lanproxy
|
lanproxy/proxy-server/src/main/java/org/fengfei/lanproxy/server/metrics/MetricsCollector.java
|
MetricsCollector
|
getCollector
|
class MetricsCollector {
private static Map<Integer, MetricsCollector> metricsCollectors = new ConcurrentHashMap<Integer, MetricsCollector>();
private Integer port;
private AtomicLong readBytes = new AtomicLong();
private AtomicLong wroteBytes = new AtomicLong();
private AtomicLong readMsgs = new AtomicLong();
private AtomicLong wroteMsgs = new AtomicLong();
private AtomicInteger channels = new AtomicInteger();
private MetricsCollector() {
}
public static MetricsCollector getCollector(Integer port) {<FILL_FUNCTION_BODY>}
public static List<Metrics> getAndResetAllMetrics() {
List<Metrics> allMetrics = new ArrayList<Metrics>();
Iterator<Entry<Integer, MetricsCollector>> ite = metricsCollectors.entrySet().iterator();
while (ite.hasNext()) {
allMetrics.add(ite.next().getValue().getAndResetMetrics());
}
return allMetrics;
}
public static List<Metrics> getAllMetrics() {
List<Metrics> allMetrics = new ArrayList<Metrics>();
Iterator<Entry<Integer, MetricsCollector>> ite = metricsCollectors.entrySet().iterator();
while (ite.hasNext()) {
allMetrics.add(ite.next().getValue().getMetrics());
}
return allMetrics;
}
public Metrics getAndResetMetrics() {
Metrics metrics = new Metrics();
metrics.setChannels(channels.get());
metrics.setPort(port);
metrics.setReadBytes(readBytes.getAndSet(0));
metrics.setWroteBytes(wroteBytes.getAndSet(0));
metrics.setTimestamp(System.currentTimeMillis());
metrics.setReadMsgs(readMsgs.getAndSet(0));
metrics.setWroteMsgs(wroteMsgs.getAndSet(0));
return metrics;
}
public Metrics getMetrics() {
Metrics metrics = new Metrics();
metrics.setChannels(channels.get());
metrics.setPort(port);
metrics.setReadBytes(readBytes.get());
metrics.setWroteBytes(wroteBytes.get());
metrics.setTimestamp(System.currentTimeMillis());
metrics.setReadMsgs(readMsgs.get());
metrics.setWroteMsgs(wroteMsgs.get());
return metrics;
}
public void incrementReadBytes(long bytes) {
readBytes.addAndGet(bytes);
}
public void incrementWroteBytes(long bytes) {
wroteBytes.addAndGet(bytes);
}
public void incrementReadMsgs(long msgs) {
readMsgs.addAndGet(msgs);
}
public void incrementWroteMsgs(long msgs) {
wroteMsgs.addAndGet(msgs);
}
public AtomicInteger getChannels() {
return channels;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
}
|
MetricsCollector collector = metricsCollectors.get(port);
if (collector == null) {
synchronized (metricsCollectors) {
collector = metricsCollectors.get(port);
if (collector == null) {
collector = new MetricsCollector();
collector.setPort(port);
metricsCollectors.put(port, collector);
}
}
}
return collector;
| 805
| 108
| 913
|
<no_super_class>
|
ffay_lanproxy
|
lanproxy/proxy-server/src/main/java/org/fengfei/lanproxy/server/metrics/handler/BytesMetricsHandler.java
|
BytesMetricsHandler
|
write
|
class BytesMetricsHandler extends ChannelDuplexHandler {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
InetSocketAddress sa = (InetSocketAddress) ctx.channel().localAddress();
MetricsCollector metricsCollector = MetricsCollector.getCollector(sa.getPort());
metricsCollector.incrementReadBytes(((ByteBuf) msg).readableBytes());
metricsCollector.incrementReadMsgs(1);
ctx.fireChannelRead(msg);
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
InetSocketAddress sa = (InetSocketAddress) ctx.channel().localAddress();
MetricsCollector.getCollector(sa.getPort()).getChannels().incrementAndGet();
super.channelActive(ctx);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
InetSocketAddress sa = (InetSocketAddress) ctx.channel().localAddress();
MetricsCollector.getCollector(sa.getPort()).getChannels().decrementAndGet();
super.channelInactive(ctx);
}
}
|
InetSocketAddress sa = (InetSocketAddress) ctx.channel().localAddress();
MetricsCollector metricsCollector = MetricsCollector.getCollector(sa.getPort());
metricsCollector.incrementWroteBytes(((ByteBuf) msg).readableBytes());
metricsCollector.incrementWroteMsgs(1);
super.write(ctx, msg, promise);
| 329
| 97
| 426
|
<no_super_class>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/TerminalRectangle.java
|
TerminalRectangle
|
toString
|
class TerminalRectangle {
// one of the benefits of immutable: ease of usage
public final TerminalPosition position;
public final TerminalSize size;
public final int x;
public final int y;
public final int width;
public final int height;
public final int xAndWidth;
public final int yAndHeight;
/**
* Creates a new terminal rect representation at the supplied x y position with the supplied width and height.
*
* Both width and height must be at least zero (non negative) as checked in TerminalSize.
*
* @param width number of columns
* @param height number of rows
*/
public TerminalRectangle(int x, int y, int width, int height) {
position = new TerminalPosition(x, y);
size = new TerminalSize(width, height);
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.xAndWidth = x + width;
this.yAndHeight = y + height;
}
/**
* @return Returns the width of this rect, in number of columns
*/
public int getColumns() {
return width;
}
/**
* @return Returns the height of this rect representation, in number of rows
*/
public int getRows() {
return height;
}
/**
* Creates a new rect based on this rect, but with a different width
* @param columns Width of the new rect, in columns
* @return New rect based on this one, but with a new width
*/
public TerminalRectangle withColumns(int columns) {
return new TerminalRectangle(x, y, columns, height);
}
/**
* Creates a new rect based on this rect, but with a different height
* @param rows Height of the new rect, in rows
* @return New rect based on this one, but with a new height
*/
public TerminalRectangle withRows(int rows) {
return new TerminalRectangle(x, y, width, rows);
}
public boolean whenContains(TerminalPosition p, Runnable op) {
return whenContains(p.getColumn(), p.getRow(), op);
}
public boolean whenContains(int x, int y, Runnable op) {
if (this.x <= x && x < this.xAndWidth && this.y <= y && y < this.yAndHeight) {
op.run();
return true;
}
return false;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
@Override
public boolean equals(Object obj) {
return obj != null
&& obj.getClass() == getClass()
&& Objects.equals(position, ((TerminalRectangle)obj).position)
&& Objects.equals(size, ((TerminalRectangle)obj).size);
}
@Override
public int hashCode() {
return Objects.hash(position, size);
}
}
|
return "{x: " + x + ", y: " + y + ", width: " + width + ", height: " + height + "}";
| 776
| 38
| 814
|
<no_super_class>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/TerminalSize.java
|
TerminalSize
|
equals
|
class TerminalSize {
public static final TerminalSize ZERO = new TerminalSize(0, 0);
public static final TerminalSize ONE = new TerminalSize(1, 1);
private final int columns;
private final int rows;
/**
* Creates a new terminal size representation with a given width (columns) and height (rows)
* @param columns Width, in number of columns
* @param rows Height, in number of columns
*/
public TerminalSize(int columns, int rows) {
if (columns < 0 || rows < 0) {
throw new IllegalArgumentException("TerminalSize dimensions cannot be less than 0: [columns: " + columns + ", rows: " + rows + "]");
}
this.columns = columns;
this.rows = rows;
}
/**
* @return Returns the width of this size representation, in number of columns
*/
public int getColumns() {
return columns;
}
/**
* Creates a new size based on this size, but with a different width
* @param columns Width of the new size, in columns
* @return New size based on this one, but with a new width
*/
public TerminalSize withColumns(int columns) {
if(this.columns == columns) {
return this;
}
if(columns == 0 && this.rows == 0) {
return ZERO;
}
return new TerminalSize(columns, this.rows);
}
/**
* @return Returns the height of this size representation, in number of rows
*/
public int getRows() {
return rows;
}
/**
* Creates a new size based on this size, but with a different height
* @param rows Height of the new size, in rows
* @return New size based on this one, but with a new height
*/
public TerminalSize withRows(int rows) {
if(this.rows == rows) {
return this;
}
if(rows == 0 && this.columns == 0) {
return ZERO;
}
return new TerminalSize(this.columns, rows);
}
/**
* Creates a new TerminalSize object representing a size with the same number of rows, but with a column size offset by a
* supplied value. Calling this method with delta 0 will return this, calling it with a positive delta will return
* a terminal size <i>delta</i> number of columns wider and for negative numbers shorter.
* @param delta Column offset
* @return New terminal size based off this one but with an applied transformation
*/
public TerminalSize withRelativeColumns(int delta) {
if(delta == 0) {
return this;
}
// Prevent going below 0 (which would throw an exception)
return withColumns(Math.max(0, columns + delta));
}
/**
* Creates a new TerminalSize object representing a size with the same number of columns, but with a row size offset by a
* supplied value. Calling this method with delta 0 will return this, calling it with a positive delta will return
* a terminal size <i>delta</i> number of rows longer and for negative numbers shorter.
* @param delta Row offset
* @return New terminal size based off this one but with an applied transformation
*/
public TerminalSize withRelativeRows(int delta) {
if(delta == 0) {
return this;
}
// Prevent going below 0 (which would throw an exception)
return withRows(Math.max(0, rows + delta));
}
/**
* Creates a new TerminalSize object representing a size based on this object's size but with a delta applied.
* This is the same as calling
* <code>withRelativeColumns(delta.getColumns()).withRelativeRows(delta.getRows())</code>
* @param delta Column and row offset
* @return New terminal size based off this one but with an applied resize
*/
public TerminalSize withRelative(TerminalSize delta) {
return withRelative(delta.getColumns(), delta.getRows());
}
/**
* Creates a new TerminalSize object representing a size based on this object's size but with a delta applied.
* This is the same as calling
* <code>withRelativeColumns(deltaColumns).withRelativeRows(deltaRows)</code>
* @param deltaColumns How many extra columns the new TerminalSize will have (negative values are allowed)
* @param deltaRows How many extra rows the new TerminalSize will have (negative values are allowed)
* @return New terminal size based off this one but with an applied resize
*/
public TerminalSize withRelative(int deltaColumns, int deltaRows) {
return withRelativeRows(deltaRows).withRelativeColumns(deltaColumns);
}
/**
* Takes a different TerminalSize and returns a new TerminalSize that has the largest dimensions of the two,
* measured separately. So calling 3x5 on a 5x3 will return 5x5.
* @param other Other TerminalSize to compare with
* @return TerminalSize that combines the maximum width between the two and the maximum height
*/
public TerminalSize max(TerminalSize other) {
return withColumns(Math.max(columns, other.columns))
.withRows(Math.max(rows, other.rows));
}
/**
* Takes a different TerminalSize and returns a new TerminalSize that has the smallest dimensions of the two,
* measured separately. So calling 3x5 on a 5x3 will return 3x3.
* @param other Other TerminalSize to compare with
* @return TerminalSize that combines the minimum width between the two and the minimum height
*/
public TerminalSize min(TerminalSize other) {
return withColumns(Math.min(columns, other.columns))
.withRows(Math.min(rows, other.rows));
}
/**
* Returns itself if it is equal to the supplied size, otherwise the supplied size. You can use this if you have a
* size field which is frequently recalculated but often resolves to the same size; it will keep the same object
* in memory instead of swapping it out every cycle.
* @param size Size you want to return
* @return Itself if this size equals the size passed in, otherwise the size passed in
*/
public TerminalSize with(TerminalSize size) {
if(equals(size)) {
return this;
}
return size;
}
@Override
public String toString() {
return "{" + columns + "x" + rows + "}";
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
int hash = 5;
hash = 53 * hash + this.columns;
hash = 53 * hash + this.rows;
return hash;
}
}
|
if(this == obj) {
return true;
}
if (!(obj instanceof TerminalSize)) {
return false;
}
TerminalSize other = (TerminalSize) obj;
return columns == other.columns
&& rows == other.rows;
| 1,726
| 70
| 1,796
|
<no_super_class>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/bundle/BundleLocator.java
|
UTF8Control
|
newBundle
|
class UTF8Control extends ResourceBundle.Control {
public ResourceBundle newBundle
(String baseName, Locale locale, String format, ClassLoader loader, boolean reload)
throws IOException
{<FILL_FUNCTION_BODY>}
}
|
// The below is a copy of the default implementation.
String bundleName = toBundleName(baseName, locale);
String resourceName = toResourceName(bundleName, "properties");
ResourceBundle bundle = null;
InputStream stream = null;
if (reload) {
URL url = loader.getResource(resourceName);
if (url != null) {
URLConnection connection = url.openConnection();
if (connection != null) {
connection.setUseCaches(false);
stream = connection.getInputStream();
}
}
} else {
stream = loader.getResourceAsStream(resourceName);
}
if (stream != null) {
try {
// Only this line is changed to make it to read properties files as UTF-8.
bundle = new PropertyResourceBundle(new InputStreamReader(stream, StandardCharsets.UTF_8));
} finally {
stream.close();
}
}
return bundle;
| 63
| 244
| 307
|
<no_super_class>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/bundle/LanternaThemes.java
|
LanternaThemes
|
registerTheme
|
class LanternaThemes {
private LanternaThemes() {
// No instantiation
}
private static final ConcurrentHashMap<String, Theme> REGISTERED_THEMES = new ConcurrentHashMap<>();
static {
// Register the default theme first
Properties defaultThemeProperties = loadPropTheme("default-theme.properties");
if (defaultThemeProperties != null) {
registerPropTheme("default", defaultThemeProperties);
}
else {
// If we couldn't load it from file, use the hard-coded one instead
registerTheme("default", new DefaultTheme());
}
// Now register all bundled themes that are defined in property files (if found)
registerPropTheme("bigsnake", loadPropTheme("bigsnake-theme.properties"));
registerPropTheme("businessmachine", loadPropTheme("businessmachine-theme.properties"));
registerPropTheme("conqueror", loadPropTheme("conqueror-theme.properties"));
registerPropTheme("defrost", loadPropTheme("defrost-theme.properties"));
registerPropTheme("blaster", loadPropTheme("blaster-theme.properties"));
}
/**
* Returns a collection of all themes registered with this class, by their name. To get the associated {@link Theme}
* object, please use {@link #getRegisteredTheme(String)}.
* @return Collection of theme names
*/
public static Collection<String> getRegisteredThemes() {
return new ArrayList<>(REGISTERED_THEMES.keySet());
}
/**
* Returns the {@link Theme} registered with this class under {@code name}, or {@code null} if there is no such
* registration.
* @param name Name of the theme to retrieve
* @return {@link Theme} registered with the supplied name, or {@code null} if none
*/
public static Theme getRegisteredTheme(String name) {
return REGISTERED_THEMES.get(name);
}
/**
* Registers a {@link Theme} with this class under a certain name so that calling
* {@link #getRegisteredTheme(String)} on that name will return this theme and calling
* {@link #getRegisteredThemes()} will return a collection including this name.
* @param name Name to register the theme under
* @param theme Theme to register with this name
*/
public static void registerTheme(String name, Theme theme) {<FILL_FUNCTION_BODY>}
/**
* Returns lanterna's default theme which is used if no other theme is selected.
* @return Lanterna's default theme, as a {@link Theme}
*/
public static Theme getDefaultTheme() {
return REGISTERED_THEMES.get("default");
}
private static void registerPropTheme(String name, Properties properties) {
if(properties != null) {
registerTheme(name, new PropertyTheme(properties, false));
}
}
private static Properties loadPropTheme(String resourceFileName) {
Properties properties = new Properties();
try {
ClassLoader classLoader = AbstractTextGUI.class.getClassLoader();
InputStream resourceAsStream = classLoader.getResourceAsStream(resourceFileName);
if(resourceAsStream == null) {
resourceAsStream = new FileInputStream("src/main/resources/" + resourceFileName);
}
properties.load(resourceAsStream);
resourceAsStream.close();
return properties;
}
catch(IOException e) {
// Failed to load theme, return null
return null;
}
}
}
|
if(theme == null) {
throw new IllegalArgumentException("Name cannot be null");
}
else if(name.isEmpty()) {
throw new IllegalArgumentException("Name cannot be empty");
}
Theme result = REGISTERED_THEMES.putIfAbsent(name, theme);
if(result != null && result != theme) {
throw new IllegalArgumentException("There is already a theme registered with the name '" + name + "'");
}
| 899
| 117
| 1,016
|
<no_super_class>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/graphics/DoublePrintingTextGraphics.java
|
DoublePrintingTextGraphics
|
setCharacter
|
class DoublePrintingTextGraphics extends AbstractTextGraphics {
private final TextGraphics underlyingTextGraphics;
/**
* Creates a new {@code DoublePrintingTextGraphics} on top of a supplied {@code TextGraphics}
* @param underlyingTextGraphics backend {@code TextGraphics} to forward all the calls to
*/
public DoublePrintingTextGraphics(TextGraphics underlyingTextGraphics) {
this.underlyingTextGraphics = underlyingTextGraphics;
}
@Override
public TextGraphics setCharacter(int columnIndex, int rowIndex, TextCharacter textCharacter) {<FILL_FUNCTION_BODY>}
@Override
public TextCharacter getCharacter(int columnIndex, int rowIndex) {
columnIndex = columnIndex * 2;
return underlyingTextGraphics.getCharacter(columnIndex, rowIndex);
}
@Override
public TerminalSize getSize() {
TerminalSize size = underlyingTextGraphics.getSize();
return size.withColumns(size.getColumns() / 2);
}
}
|
columnIndex = columnIndex * 2;
underlyingTextGraphics.setCharacter(columnIndex, rowIndex, textCharacter);
underlyingTextGraphics.setCharacter(columnIndex + 1, rowIndex, textCharacter);
return this;
| 247
| 57
| 304
|
<methods>public com.googlecode.lanterna.graphics.TextGraphics clearModifiers() ,public transient com.googlecode.lanterna.graphics.TextGraphics disableModifiers(com.googlecode.lanterna.SGR[]) ,public com.googlecode.lanterna.graphics.TextGraphics drawImage(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.graphics.TextImage) ,public com.googlecode.lanterna.graphics.TextGraphics drawImage(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.graphics.TextImage, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalSize) ,public com.googlecode.lanterna.graphics.TextGraphics drawLine(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, char) ,public com.googlecode.lanterna.graphics.TextGraphics drawLine(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TextCharacter) ,public com.googlecode.lanterna.graphics.TextGraphics drawLine(int, int, int, int, char) ,public com.googlecode.lanterna.graphics.TextGraphics drawLine(int, int, int, int, com.googlecode.lanterna.TextCharacter) ,public com.googlecode.lanterna.graphics.TextGraphics drawRectangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalSize, char) ,public com.googlecode.lanterna.graphics.TextGraphics drawRectangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalSize, com.googlecode.lanterna.TextCharacter) ,public com.googlecode.lanterna.graphics.TextGraphics drawTriangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, char) ,public com.googlecode.lanterna.graphics.TextGraphics drawTriangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TextCharacter) ,public transient com.googlecode.lanterna.graphics.TextGraphics enableModifiers(com.googlecode.lanterna.SGR[]) ,public com.googlecode.lanterna.graphics.TextGraphics fill(char) ,public com.googlecode.lanterna.graphics.TextGraphics fillRectangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalSize, char) ,public com.googlecode.lanterna.graphics.TextGraphics fillRectangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalSize, com.googlecode.lanterna.TextCharacter) ,public com.googlecode.lanterna.graphics.TextGraphics fillTriangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, char) ,public com.googlecode.lanterna.graphics.TextGraphics fillTriangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TextCharacter) ,public EnumSet<com.googlecode.lanterna.SGR> getActiveModifiers() ,public com.googlecode.lanterna.TextColor getBackgroundColor() ,public com.googlecode.lanterna.TextCharacter getCharacter(com.googlecode.lanterna.TerminalPosition) ,public com.googlecode.lanterna.TextColor getForegroundColor() ,public com.googlecode.lanterna.screen.TabBehaviour getTabBehaviour() ,public com.googlecode.lanterna.graphics.TextGraphics newTextGraphics(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalSize) throws java.lang.IllegalArgumentException,public synchronized com.googlecode.lanterna.graphics.TextGraphics putCSIStyledString(int, int, java.lang.String) ,public com.googlecode.lanterna.graphics.TextGraphics putCSIStyledString(com.googlecode.lanterna.TerminalPosition, java.lang.String) ,public com.googlecode.lanterna.graphics.TextGraphics putString(int, int, java.lang.String) ,public com.googlecode.lanterna.graphics.TextGraphics putString(com.googlecode.lanterna.TerminalPosition, java.lang.String) ,public transient com.googlecode.lanterna.graphics.TextGraphics putString(int, int, java.lang.String, com.googlecode.lanterna.SGR, com.googlecode.lanterna.SGR[]) ,public com.googlecode.lanterna.graphics.TextGraphics putString(int, int, java.lang.String, Collection<com.googlecode.lanterna.SGR>) ,public transient com.googlecode.lanterna.graphics.TextGraphics putString(com.googlecode.lanterna.TerminalPosition, java.lang.String, com.googlecode.lanterna.SGR, com.googlecode.lanterna.SGR[]) ,public com.googlecode.lanterna.graphics.TextGraphics setBackgroundColor(com.googlecode.lanterna.TextColor) ,public com.googlecode.lanterna.graphics.TextGraphics setCharacter(int, int, char) ,public com.googlecode.lanterna.graphics.TextGraphics setCharacter(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TextCharacter) ,public com.googlecode.lanterna.graphics.TextGraphics setCharacter(com.googlecode.lanterna.TerminalPosition, char) ,public com.googlecode.lanterna.graphics.TextGraphics setForegroundColor(com.googlecode.lanterna.TextColor) ,public synchronized com.googlecode.lanterna.graphics.TextGraphics setModifiers(EnumSet<com.googlecode.lanterna.SGR>) ,public com.googlecode.lanterna.graphics.TextGraphics setStyleFrom(StyleSet<?>) ,public com.googlecode.lanterna.graphics.TextGraphics setTabBehaviour(com.googlecode.lanterna.screen.TabBehaviour) <variables>protected final non-sealed EnumSet<com.googlecode.lanterna.SGR> activeModifiers,protected com.googlecode.lanterna.TextColor backgroundColor,protected com.googlecode.lanterna.TextColor foregroundColor,private final non-sealed com.googlecode.lanterna.graphics.ShapeRenderer shapeRenderer,protected com.googlecode.lanterna.screen.TabBehaviour tabBehaviour
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/graphics/PropertyTheme.java
|
PropertyTheme
|
getDefinition
|
class PropertyTheme extends AbstractTheme {
/**
* Creates a new {@code PropertyTheme} that is initialized by the properties passed in. If the properties refer to
* a class that cannot be resolved, it will throw {@code IllegalArgumentException}.
* @param properties Properties to initialize this theme with
*/
public PropertyTheme(Properties properties) {
this(properties, false);
}
/**
* Creates a new {@code PropertyTheme} that is initialized by the properties value and optionally prevents it from
* throwing an exception if there are invalid definitions in the properties object.
* @param properties Properties to initialize this theme with
* @param ignoreUnknownClasses If {@code true}, will not throw an exception if there is an invalid entry in the
* properties object
*/
public PropertyTheme(Properties properties, boolean ignoreUnknownClasses) {
super( (WindowPostRenderer)instanceByClassName(properties.getProperty("postrenderer", "")),
(WindowDecorationRenderer)instanceByClassName(properties.getProperty("windowdecoration", "")));
for(String key: properties.stringPropertyNames()) {
String definition = getDefinition(key);
if(!addStyle(definition, getStyle(key), properties.getProperty(key))) {
if(!ignoreUnknownClasses) {
throw new IllegalArgumentException("Unknown class encountered when parsing theme: '" + definition + "'");
}
}
}
}
private String getDefinition(String propertyName) {<FILL_FUNCTION_BODY>}
private String getStyle(String propertyName) {
if(!propertyName.contains(".")) {
return propertyName;
}
else {
return propertyName.substring(propertyName.lastIndexOf(".") + 1);
}
}
}
|
if(!propertyName.contains(".")) {
return "";
}
else {
return propertyName.substring(0, propertyName.lastIndexOf("."));
}
| 430
| 49
| 479
|
<methods>public List<java.lang.String> findRedundantDeclarations() ,public com.googlecode.lanterna.graphics.ThemeDefinition getDefaultDefinition() ,public com.googlecode.lanterna.graphics.ThemeDefinition getDefinition(Class<?>) ,public com.googlecode.lanterna.gui2.WindowDecorationRenderer getWindowDecorationRenderer() ,public com.googlecode.lanterna.gui2.WindowPostRenderer getWindowPostRenderer() <variables>private static final java.lang.String STYLE_ACTIVE,private static final java.util.regex.Pattern STYLE_FORMAT,private static final java.lang.String STYLE_INSENSITIVE,private static final java.lang.String STYLE_NORMAL,private static final java.lang.String STYLE_PRELIGHT,private static final java.lang.String STYLE_SELECTED,private final non-sealed com.googlecode.lanterna.graphics.AbstractTheme.ThemeTreeNode rootNode,private final non-sealed com.googlecode.lanterna.gui2.WindowDecorationRenderer windowDecorationRenderer,private final non-sealed com.googlecode.lanterna.gui2.WindowPostRenderer windowPostRenderer
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/graphics/SubTextGraphics.java
|
SubTextGraphics
|
setCharacter
|
class SubTextGraphics extends AbstractTextGraphics {
private final TextGraphics underlyingTextGraphics;
private final TerminalPosition topLeft;
private final TerminalSize writableAreaSize;
SubTextGraphics(TextGraphics underlyingTextGraphics, TerminalPosition topLeft, TerminalSize writableAreaSize) {
this.underlyingTextGraphics = underlyingTextGraphics;
this.topLeft = topLeft;
this.writableAreaSize = writableAreaSize;
}
private TerminalPosition project(int column, int row) {
return topLeft.withRelative(column, row);
}
@Override
public TextGraphics setCharacter(int columnIndex, int rowIndex, TextCharacter textCharacter) {<FILL_FUNCTION_BODY>}
@Override
public TerminalSize getSize() {
return writableAreaSize;
}
@Override
public TextCharacter getCharacter(int column, int row) {
TerminalPosition projectedPosition = project(column, row);
return underlyingTextGraphics.getCharacter(projectedPosition.getColumn(), projectedPosition.getRow());
}
}
|
TerminalSize writableArea = getSize();
if(columnIndex < 0 || columnIndex >= writableArea.getColumns() ||
rowIndex < 0 || rowIndex >= writableArea.getRows()) {
return this;
}
TerminalPosition projectedPosition = project(columnIndex, rowIndex);
underlyingTextGraphics.setCharacter(projectedPosition, textCharacter);
return this;
| 263
| 96
| 359
|
<methods>public com.googlecode.lanterna.graphics.TextGraphics clearModifiers() ,public transient com.googlecode.lanterna.graphics.TextGraphics disableModifiers(com.googlecode.lanterna.SGR[]) ,public com.googlecode.lanterna.graphics.TextGraphics drawImage(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.graphics.TextImage) ,public com.googlecode.lanterna.graphics.TextGraphics drawImage(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.graphics.TextImage, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalSize) ,public com.googlecode.lanterna.graphics.TextGraphics drawLine(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, char) ,public com.googlecode.lanterna.graphics.TextGraphics drawLine(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TextCharacter) ,public com.googlecode.lanterna.graphics.TextGraphics drawLine(int, int, int, int, char) ,public com.googlecode.lanterna.graphics.TextGraphics drawLine(int, int, int, int, com.googlecode.lanterna.TextCharacter) ,public com.googlecode.lanterna.graphics.TextGraphics drawRectangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalSize, char) ,public com.googlecode.lanterna.graphics.TextGraphics drawRectangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalSize, com.googlecode.lanterna.TextCharacter) ,public com.googlecode.lanterna.graphics.TextGraphics drawTriangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, char) ,public com.googlecode.lanterna.graphics.TextGraphics drawTriangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TextCharacter) ,public transient com.googlecode.lanterna.graphics.TextGraphics enableModifiers(com.googlecode.lanterna.SGR[]) ,public com.googlecode.lanterna.graphics.TextGraphics fill(char) ,public com.googlecode.lanterna.graphics.TextGraphics fillRectangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalSize, char) ,public com.googlecode.lanterna.graphics.TextGraphics fillRectangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalSize, com.googlecode.lanterna.TextCharacter) ,public com.googlecode.lanterna.graphics.TextGraphics fillTriangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, char) ,public com.googlecode.lanterna.graphics.TextGraphics fillTriangle(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TextCharacter) ,public EnumSet<com.googlecode.lanterna.SGR> getActiveModifiers() ,public com.googlecode.lanterna.TextColor getBackgroundColor() ,public com.googlecode.lanterna.TextCharacter getCharacter(com.googlecode.lanterna.TerminalPosition) ,public com.googlecode.lanterna.TextColor getForegroundColor() ,public com.googlecode.lanterna.screen.TabBehaviour getTabBehaviour() ,public com.googlecode.lanterna.graphics.TextGraphics newTextGraphics(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TerminalSize) throws java.lang.IllegalArgumentException,public synchronized com.googlecode.lanterna.graphics.TextGraphics putCSIStyledString(int, int, java.lang.String) ,public com.googlecode.lanterna.graphics.TextGraphics putCSIStyledString(com.googlecode.lanterna.TerminalPosition, java.lang.String) ,public com.googlecode.lanterna.graphics.TextGraphics putString(int, int, java.lang.String) ,public com.googlecode.lanterna.graphics.TextGraphics putString(com.googlecode.lanterna.TerminalPosition, java.lang.String) ,public transient com.googlecode.lanterna.graphics.TextGraphics putString(int, int, java.lang.String, com.googlecode.lanterna.SGR, com.googlecode.lanterna.SGR[]) ,public com.googlecode.lanterna.graphics.TextGraphics putString(int, int, java.lang.String, Collection<com.googlecode.lanterna.SGR>) ,public transient com.googlecode.lanterna.graphics.TextGraphics putString(com.googlecode.lanterna.TerminalPosition, java.lang.String, com.googlecode.lanterna.SGR, com.googlecode.lanterna.SGR[]) ,public com.googlecode.lanterna.graphics.TextGraphics setBackgroundColor(com.googlecode.lanterna.TextColor) ,public com.googlecode.lanterna.graphics.TextGraphics setCharacter(int, int, char) ,public com.googlecode.lanterna.graphics.TextGraphics setCharacter(com.googlecode.lanterna.TerminalPosition, com.googlecode.lanterna.TextCharacter) ,public com.googlecode.lanterna.graphics.TextGraphics setCharacter(com.googlecode.lanterna.TerminalPosition, char) ,public com.googlecode.lanterna.graphics.TextGraphics setForegroundColor(com.googlecode.lanterna.TextColor) ,public synchronized com.googlecode.lanterna.graphics.TextGraphics setModifiers(EnumSet<com.googlecode.lanterna.SGR>) ,public com.googlecode.lanterna.graphics.TextGraphics setStyleFrom(StyleSet<?>) ,public com.googlecode.lanterna.graphics.TextGraphics setTabBehaviour(com.googlecode.lanterna.screen.TabBehaviour) <variables>protected final non-sealed EnumSet<com.googlecode.lanterna.SGR> activeModifiers,protected com.googlecode.lanterna.TextColor backgroundColor,protected com.googlecode.lanterna.TextColor foregroundColor,private final non-sealed com.googlecode.lanterna.graphics.ShapeRenderer shapeRenderer,protected com.googlecode.lanterna.screen.TabBehaviour tabBehaviour
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/AbsoluteLayout.java
|
AbsoluteLayout
|
getPreferredSize
|
class AbsoluteLayout implements LayoutManager {
@Override
public TerminalSize getPreferredSize(List<Component> components) {<FILL_FUNCTION_BODY>}
@Override
public void doLayout(TerminalSize area, List<Component> components) {
//Do nothing
}
@Override
public boolean hasChanged() {
return false;
}
}
|
TerminalSize size = TerminalSize.ZERO;
for(Component component: components) {
size = size.max(
new TerminalSize(
component.getPosition().getColumn() + component.getSize().getColumns(),
component.getPosition().getRow() + component.getSize().getRows()));
}
return size;
| 98
| 88
| 186
|
<no_super_class>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/AbstractBasePane.java
|
ContentHolder
|
createDefaultRenderer
|
class ContentHolder extends AbstractComposite<Container> {
private MenuBar menuBar;
ContentHolder() {
this.menuBar = new EmptyMenuBar();
}
private void setMenuBar(MenuBar menuBar) {
if (menuBar == null) {
menuBar = new EmptyMenuBar();
}
if (this.menuBar != menuBar) {
menuBar.onAdded(this);
this.menuBar.onRemoved(this);
this.menuBar = menuBar;
if(focusedInteractable == null) {
setFocusedInteractable(menuBar.nextFocus(null));
}
invalidate();
}
}
private MenuBar getMenuBar() {
return menuBar;
}
@Override
public boolean isInvalid() {
return super.isInvalid() || menuBar.isInvalid();
}
@Override
public void invalidate() {
super.invalidate();
menuBar.invalidate();
}
@Override
public void updateLookupMap(InteractableLookupMap interactableLookupMap) {
super.updateLookupMap(interactableLookupMap);
menuBar.updateLookupMap(interactableLookupMap);
}
@Override
public void setComponent(Component component) {
if(getComponent() == component) {
return;
}
setFocusedInteractable(null);
super.setComponent(component);
if(focusedInteractable == null && component instanceof Interactable) {
setFocusedInteractable((Interactable)component);
}
else if(focusedInteractable == null && component instanceof Container) {
setFocusedInteractable(((Container)component).nextFocus(null));
}
}
public boolean removeComponent(Component component) {
boolean removed = super.removeComponent(component);
if (removed) {
focusedInteractable = null;
}
return removed;
}
@Override
public TextGUI getTextGUI() {
return AbstractBasePane.this.getTextGUI();
}
@Override
protected ComponentRenderer<Container> createDefaultRenderer() {<FILL_FUNCTION_BODY>}
@Override
public TerminalPosition toGlobal(TerminalPosition position) {
return AbstractBasePane.this.toGlobal(position);
}
@Override
public TerminalPosition toBasePane(TerminalPosition position) {
return position;
}
@Override
public BasePane getBasePane() {
return AbstractBasePane.this;
}
}
|
return new ComponentRenderer<Container>() {
@Override
public TerminalSize getPreferredSize(Container component) {
Component subComponent = getComponent();
if(subComponent == null) {
return TerminalSize.ZERO;
}
return subComponent.getPreferredSize();
}
@Override
public void drawComponent(TextGUIGraphics graphics, Container component) {
if (!(menuBar instanceof EmptyMenuBar)) {
int menuBarHeight = menuBar.getPreferredSize().getRows();
TextGUIGraphics menuGraphics = graphics.newTextGraphics(TerminalPosition.TOP_LEFT_CORNER, graphics.getSize().withRows(menuBarHeight));
menuBar.draw(menuGraphics);
graphics = graphics.newTextGraphics(TerminalPosition.TOP_LEFT_CORNER.withRelativeRow(menuBarHeight), graphics.getSize().withRelativeRows(-menuBarHeight));
}
Component subComponent = getComponent();
if(subComponent == null) {
return;
}
subComponent.draw(graphics);
}
};
| 663
| 278
| 941
|
<no_super_class>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/AbstractBorder.java
|
AbstractBorder
|
toGlobal
|
class AbstractBorder extends AbstractComposite<Border> implements Border {
@Override
public void setComponent(Component component) {
super.setComponent(component);
if(component != null) {
component.setPosition(TerminalPosition.TOP_LEFT_CORNER);
}
}
@Override
public BorderRenderer getRenderer() {
return (BorderRenderer)super.getRenderer();
}
@Override
public Border setSize(TerminalSize size) {
super.setSize(size);
getComponent().setSize(getWrappedComponentSize(size));
return self();
}
@Override
public LayoutData getLayoutData() {
if(getComponent() == null) {
return super.getLayoutData();
}
return getComponent().getLayoutData();
}
@Override
public Border setLayoutData(LayoutData ld) {
if(getComponent() == null) {
super.setLayoutData(ld);
} else {
getComponent().setLayoutData(ld);
}
return this;
}
@Override
public TerminalPosition toBasePane(TerminalPosition position) {
TerminalPosition terminalPosition = super.toBasePane(position);
if(terminalPosition == null) {
return null;
}
return terminalPosition.withRelative(getWrappedComponentTopLeftOffset());
}
@Override
public TerminalPosition toGlobal(TerminalPosition position) {<FILL_FUNCTION_BODY>}
private TerminalPosition getWrappedComponentTopLeftOffset() {
return getRenderer().getWrappedComponentTopLeftOffset();
}
private TerminalSize getWrappedComponentSize(TerminalSize borderSize) {
return getRenderer().getWrappedComponentSize(borderSize);
}
}
|
TerminalPosition terminalPosition = super.toGlobal(position);
if(terminalPosition == null) {
return null;
}
return terminalPosition.withRelative(getWrappedComponentTopLeftOffset());
| 454
| 53
| 507
|
<methods>public void <init>() ,public boolean containsComponent(com.googlecode.lanterna.gui2.Component) ,public int getChildCount() ,public Collection<com.googlecode.lanterna.gui2.Component> getChildren() ,public List<com.googlecode.lanterna.gui2.Component> getChildrenList() ,public com.googlecode.lanterna.gui2.Component getComponent() ,public boolean handleInput(com.googlecode.lanterna.input.KeyStroke) ,public void invalidate() ,public boolean isInvalid() ,public com.googlecode.lanterna.gui2.Interactable nextFocus(com.googlecode.lanterna.gui2.Interactable) ,public com.googlecode.lanterna.gui2.Interactable previousFocus(com.googlecode.lanterna.gui2.Interactable) ,public boolean removeComponent(com.googlecode.lanterna.gui2.Component) ,public void setComponent(com.googlecode.lanterna.gui2.Component) ,public void updateLookupMap(com.googlecode.lanterna.gui2.InteractableLookupMap) <variables>private com.googlecode.lanterna.gui2.Component component
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/AbstractComposite.java
|
AbstractComposite
|
setComponent
|
class AbstractComposite<T extends Container> extends AbstractComponent<T> implements Composite, Container {
private Component component;
/**
* Default constructor
*/
public AbstractComposite() {
component = null;
}
@Override
public void setComponent(Component component) {<FILL_FUNCTION_BODY>}
@Override
public Component getComponent() {
return component;
}
@Override
public int getChildCount() {
return component != null ? 1 : 0;
}
@Override
public List<Component> getChildrenList() {
if(component != null) {
return Collections.singletonList(component);
}
else {
return Collections.emptyList();
}
}
@Override
public Collection<Component> getChildren() {
return getChildrenList();
}
@Override
public boolean containsComponent(Component component) {
return component != null && component.hasParent(this);
}
@Override
public boolean removeComponent(Component component) {
if(this.component == component) {
this.component = null;
component.onRemoved(this);
invalidate();
return true;
}
return false;
}
@Override
public boolean isInvalid() {
return component != null && component.isInvalid();
}
@Override
public void invalidate() {
super.invalidate();
//Propagate
if(component != null) {
component.invalidate();
}
}
@Override
public Interactable nextFocus(Interactable fromThis) {
if(fromThis == null && getComponent() instanceof Interactable) {
Interactable interactable = (Interactable) getComponent();
if(interactable.isEnabled()) {
return interactable;
}
}
else if(getComponent() instanceof Container) {
return ((Container)getComponent()).nextFocus(fromThis);
}
return null;
}
@Override
public Interactable previousFocus(Interactable fromThis) {
if(fromThis == null && getComponent() instanceof Interactable) {
Interactable interactable = (Interactable) getComponent();
if(interactable.isEnabled()) {
return interactable;
}
}
else if(getComponent() instanceof Container) {
return ((Container)getComponent()).previousFocus(fromThis);
}
return null;
}
@Override
public boolean handleInput(KeyStroke key) {
return false;
}
@Override
public void updateLookupMap(InteractableLookupMap interactableLookupMap) {
if(getComponent() instanceof Container) {
((Container)getComponent()).updateLookupMap(interactableLookupMap);
}
else if(getComponent() instanceof Interactable) {
interactableLookupMap.add((Interactable)getComponent());
}
}
}
|
Component oldComponent = this.component;
if(oldComponent == component) {
return;
}
if(oldComponent != null) {
removeComponent(oldComponent);
}
if (component != null) {
this.component = component;
component.onAdded(this);
if (getBasePane() != null) {
MenuBar menuBar = getBasePane().getMenuBar();
if (menuBar == null || menuBar.isEmptyMenuBar()) {
component.setPosition(TerminalPosition.TOP_LEFT_CORNER);
} else {
component.setPosition(TerminalPosition.TOP_LEFT_CORNER.withRelativeRow(1));
}
}
invalidate();
}
| 771
| 192
| 963
|
<methods>public void <init>() ,public synchronized T addTo(com.googlecode.lanterna.gui2.Panel) ,public final synchronized void draw(com.googlecode.lanterna.gui2.TextGUIGraphics) ,public com.googlecode.lanterna.gui2.BasePane getBasePane() ,public com.googlecode.lanterna.TerminalPosition getGlobalPosition() ,public com.googlecode.lanterna.gui2.LayoutData getLayoutData() ,public com.googlecode.lanterna.gui2.Container getParent() ,public com.googlecode.lanterna.TerminalPosition getPosition() ,public final com.googlecode.lanterna.TerminalSize getPreferredSize() ,public synchronized ComponentRenderer<T> getRenderer() ,public com.googlecode.lanterna.TerminalSize getSize() ,public com.googlecode.lanterna.gui2.TextGUI getTextGUI() ,public synchronized com.googlecode.lanterna.graphics.Theme getTheme() ,public com.googlecode.lanterna.graphics.ThemeDefinition getThemeDefinition() ,public boolean hasParent(com.googlecode.lanterna.gui2.Container) ,public void invalidate() ,public boolean isInside(com.googlecode.lanterna.gui2.Container) ,public boolean isInvalid() ,public boolean isVisible() ,public synchronized void onAdded(com.googlecode.lanterna.gui2.Container) ,public synchronized void onRemoved(com.googlecode.lanterna.gui2.Container) ,public synchronized T setLayoutData(com.googlecode.lanterna.gui2.LayoutData) ,public synchronized T setPosition(com.googlecode.lanterna.TerminalPosition) ,public final synchronized T setPreferredSize(com.googlecode.lanterna.TerminalSize) ,public T setRenderer(ComponentRenderer<T>) ,public synchronized T setSize(com.googlecode.lanterna.TerminalSize) ,public synchronized com.googlecode.lanterna.gui2.Component setTheme(com.googlecode.lanterna.graphics.Theme) ,public T setVisible(boolean) ,public com.googlecode.lanterna.TerminalPosition toBasePane(com.googlecode.lanterna.TerminalPosition) ,public com.googlecode.lanterna.TerminalPosition toGlobal(com.googlecode.lanterna.TerminalPosition) ,public synchronized com.googlecode.lanterna.gui2.Border withBorder(com.googlecode.lanterna.gui2.Border) <variables>private ComponentRenderer<T> defaultRenderer,private com.googlecode.lanterna.TerminalSize explicitPreferredSize,private boolean invalid,private com.googlecode.lanterna.gui2.LayoutData layoutData,private ComponentRenderer<T> overrideRenderer,private com.googlecode.lanterna.gui2.Container parent,private com.googlecode.lanterna.TerminalPosition position,private com.googlecode.lanterna.TerminalSize size,private com.googlecode.lanterna.graphics.Theme themeOverride,private ComponentRenderer<T> themeRenderer,private com.googlecode.lanterna.graphics.Theme themeRenderersTheme,private boolean visible
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/AbstractInteractableComponent.java
|
AbstractInteractableComponent
|
isMouseActivationStroke
|
class AbstractInteractableComponent<T extends AbstractInteractableComponent<T>> extends AbstractComponent<T> implements Interactable {
private InputFilter inputFilter;
private boolean inFocus;
private boolean enabled;
/**
* Default constructor
*/
protected AbstractInteractableComponent() {
inputFilter = null;
inFocus = false;
enabled = true;
}
@Override
public T takeFocus() {
if(!isEnabled()) {
return self();
}
BasePane basePane = getBasePane();
if(basePane != null) {
basePane.setFocusedInteractable(this);
}
return self();
}
/**
* {@inheritDoc}
* <p>
* This method is final in {@code AbstractInteractableComponent}, please override {@code afterEnterFocus} instead
*/
@Override
public final void onEnterFocus(FocusChangeDirection direction, Interactable previouslyInFocus) {
inFocus = true;
afterEnterFocus(direction, previouslyInFocus);
}
/**
* Called by {@code AbstractInteractableComponent} automatically after this component has received input focus. You
* can override this method if you need to trigger some action based on this.
* @param direction How focus was transferred, keep in mind this is from the previous component's point of view so
* if this parameter has value DOWN, focus came in from above
* @param previouslyInFocus Which interactable component had focus previously
*/
@SuppressWarnings("EmptyMethod")
protected void afterEnterFocus(FocusChangeDirection direction, Interactable previouslyInFocus) {
//By default no action
}
/**
* {@inheritDoc}
* <p>
* This method is final in {@code AbstractInteractableComponent}, please override {@code afterLeaveFocus} instead
*/
@Override
public final void onLeaveFocus(FocusChangeDirection direction, Interactable nextInFocus) {
inFocus = false;
afterLeaveFocus(direction, nextInFocus);
}
/**
* Called by {@code AbstractInteractableComponent} automatically after this component has lost input focus. You
* can override this method if you need to trigger some action based on this.
* @param direction How focus was transferred, keep in mind this is from the this component's point of view so
* if this parameter has value DOWN, focus is moving down to a component below
* @param nextInFocus Which interactable component is going to receive focus
*/
@SuppressWarnings("EmptyMethod")
protected void afterLeaveFocus(FocusChangeDirection direction, Interactable nextInFocus) {
//By default no action
}
@Override
protected abstract InteractableRenderer<T> createDefaultRenderer();
@Override
public InteractableRenderer<T> getRenderer() {
return (InteractableRenderer<T>)super.getRenderer();
}
@Override
public boolean isFocused() {
return inFocus;
}
@Override
public synchronized T setEnabled(boolean enabled) {
this.enabled = enabled;
if(!enabled && isFocused()) {
BasePane basePane = getBasePane();
if(basePane != null) {
basePane.setFocusedInteractable(null);
}
}
return self();
}
@Override
public boolean isEnabled() {
return enabled;
}
@Override
public boolean isFocusable() {
return true;
}
@Override
public final synchronized Result handleInput(KeyStroke keyStroke) {
if(inputFilter == null || inputFilter.onInput(this, keyStroke)) {
return handleKeyStroke(keyStroke);
}
else {
return Result.UNHANDLED;
}
}
/**
* This method can be overridden to handle various user input (mostly from the keyboard) when this component is in
* focus. The input method from the interface, {@code handleInput(..)} is final in
* {@code AbstractInteractableComponent} to ensure the input filter is properly handled. If the filter decides that
* this event should be processed, it will call this method.
* @param keyStroke What input was entered by the user
* @return Result of processing the key-stroke
*/
protected Result handleKeyStroke(KeyStroke keyStroke) {
// Skip the keystroke if ctrl, alt or shift was down
if(!keyStroke.isAltDown() && !keyStroke.isCtrlDown() && !keyStroke.isShiftDown()) {
switch(keyStroke.getKeyType()) {
case ARROW_DOWN:
return Result.MOVE_FOCUS_DOWN;
case ARROW_LEFT:
return Result.MOVE_FOCUS_LEFT;
case ARROW_RIGHT:
return Result.MOVE_FOCUS_RIGHT;
case ARROW_UP:
return Result.MOVE_FOCUS_UP;
case TAB:
return Result.MOVE_FOCUS_NEXT;
case REVERSE_TAB:
return Result.MOVE_FOCUS_PREVIOUS;
case MOUSE_EVENT:
if (isMouseMove(keyStroke)) {
// do nothing
return Result.UNHANDLED;
}
getBasePane().setFocusedInteractable(this);
return Result.HANDLED;
default:
}
}
return Result.UNHANDLED;
}
@Override
public TerminalPosition getCursorLocation() {
return getRenderer().getCursorLocation(self());
}
@Override
public InputFilter getInputFilter() {
return inputFilter;
}
@Override
public synchronized T setInputFilter(InputFilter inputFilter) {
this.inputFilter = inputFilter;
return self();
}
public boolean isKeyboardActivationStroke(KeyStroke keyStroke) {
boolean isKeyboardActivation = (keyStroke.getKeyType() == KeyType.CHARACTER && keyStroke.getCharacter() == ' ') || keyStroke.getKeyType() == KeyType.ENTER;
return isFocused() && isKeyboardActivation;
}
public boolean isMouseActivationStroke(KeyStroke keyStroke) {<FILL_FUNCTION_BODY>}
public boolean isActivationStroke(KeyStroke keyStroke) {
boolean isKeyboardActivationStroke = isKeyboardActivationStroke(keyStroke);
boolean isMouseActivationStroke = isMouseActivationStroke(keyStroke);
return isKeyboardActivationStroke || isMouseActivationStroke;
}
public boolean isMouseDown(KeyStroke keyStroke) {
return keyStroke.getKeyType() == KeyType.MOUSE_EVENT && ((MouseAction)keyStroke).isMouseDown();
}
public boolean isMouseDrag(KeyStroke keyStroke) {
return keyStroke.getKeyType() == KeyType.MOUSE_EVENT && ((MouseAction)keyStroke).isMouseDrag();
}
public boolean isMouseMove(KeyStroke keyStroke) {
return keyStroke.getKeyType() == KeyType.MOUSE_EVENT && ((MouseAction)keyStroke).isMouseMove();
}
public boolean isMouseUp(KeyStroke keyStroke) {
return keyStroke.getKeyType() == KeyType.MOUSE_EVENT && ((MouseAction)keyStroke).isMouseUp();
}
}
|
boolean isMouseActivation = false;
if (keyStroke instanceof MouseAction) {
MouseAction action = (MouseAction)keyStroke;
isMouseActivation = action.getActionType() == MouseActionType.CLICK_DOWN;
}
return isMouseActivation;
| 1,919
| 76
| 1,995
|
<methods>public void <init>() ,public synchronized T addTo(com.googlecode.lanterna.gui2.Panel) ,public final synchronized void draw(com.googlecode.lanterna.gui2.TextGUIGraphics) ,public com.googlecode.lanterna.gui2.BasePane getBasePane() ,public com.googlecode.lanterna.TerminalPosition getGlobalPosition() ,public com.googlecode.lanterna.gui2.LayoutData getLayoutData() ,public com.googlecode.lanterna.gui2.Container getParent() ,public com.googlecode.lanterna.TerminalPosition getPosition() ,public final com.googlecode.lanterna.TerminalSize getPreferredSize() ,public synchronized ComponentRenderer<T> getRenderer() ,public com.googlecode.lanterna.TerminalSize getSize() ,public com.googlecode.lanterna.gui2.TextGUI getTextGUI() ,public synchronized com.googlecode.lanterna.graphics.Theme getTheme() ,public com.googlecode.lanterna.graphics.ThemeDefinition getThemeDefinition() ,public boolean hasParent(com.googlecode.lanterna.gui2.Container) ,public void invalidate() ,public boolean isInside(com.googlecode.lanterna.gui2.Container) ,public boolean isInvalid() ,public boolean isVisible() ,public synchronized void onAdded(com.googlecode.lanterna.gui2.Container) ,public synchronized void onRemoved(com.googlecode.lanterna.gui2.Container) ,public synchronized T setLayoutData(com.googlecode.lanterna.gui2.LayoutData) ,public synchronized T setPosition(com.googlecode.lanterna.TerminalPosition) ,public final synchronized T setPreferredSize(com.googlecode.lanterna.TerminalSize) ,public T setRenderer(ComponentRenderer<T>) ,public synchronized T setSize(com.googlecode.lanterna.TerminalSize) ,public synchronized com.googlecode.lanterna.gui2.Component setTheme(com.googlecode.lanterna.graphics.Theme) ,public T setVisible(boolean) ,public com.googlecode.lanterna.TerminalPosition toBasePane(com.googlecode.lanterna.TerminalPosition) ,public com.googlecode.lanterna.TerminalPosition toGlobal(com.googlecode.lanterna.TerminalPosition) ,public synchronized com.googlecode.lanterna.gui2.Border withBorder(com.googlecode.lanterna.gui2.Border) <variables>private ComponentRenderer<T> defaultRenderer,private com.googlecode.lanterna.TerminalSize explicitPreferredSize,private boolean invalid,private com.googlecode.lanterna.gui2.LayoutData layoutData,private ComponentRenderer<T> overrideRenderer,private com.googlecode.lanterna.gui2.Container parent,private com.googlecode.lanterna.TerminalPosition position,private com.googlecode.lanterna.TerminalSize size,private com.googlecode.lanterna.graphics.Theme themeOverride,private ComponentRenderer<T> themeRenderer,private com.googlecode.lanterna.graphics.Theme themeRenderersTheme,private boolean visible
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/AbstractTextGUI.java
|
AbstractTextGUI
|
fireUnhandledKeyStroke
|
class AbstractTextGUI implements TextGUI {
private final Screen screen;
private final List<Listener> listeners;
private boolean blockingIO;
private boolean dirty;
private TextGUIThread textGUIThread;
private Theme guiTheme;
/**
* Constructor for {@code AbstractTextGUI} that requires a {@code Screen} and a factory for creating the GUI thread
* @param textGUIThreadFactory Factory class to use for creating the {@code TextGUIThread} class
* @param screen What underlying {@code Screen} to use for this text GUI
*/
protected AbstractTextGUI(TextGUIThreadFactory textGUIThreadFactory, Screen screen) {
if(screen == null) {
throw new IllegalArgumentException("Creating a TextGUI requires an underlying Screen");
}
this.screen = screen;
this.listeners = new CopyOnWriteArrayList<>();
this.blockingIO = false;
this.dirty = false;
this.guiTheme = LanternaThemes.getDefaultTheme();
this.textGUIThread = textGUIThreadFactory.createTextGUIThread(this);
}
/**
* Reads one key from the input queue, blocking or non-blocking depending on if blocking I/O has been enabled. To
* enable blocking I/O (disabled by default), use {@code setBlockingIO(true)}.
* @return One piece of user input as a {@code KeyStroke} or {@code null} if blocking I/O is disabled and there was
* no input waiting
* @throws IOException In case of an I/O error while reading input
*/
protected KeyStroke readKeyStroke() throws IOException {
return blockingIO ? screen.readInput() : pollInput();
}
/**
* Polls the underlying input queue for user input, returning either a {@code KeyStroke} or {@code null}
* @return {@code KeyStroke} representing the user input or {@code null} if there was none
* @throws IOException In case of an I/O error while reading input
*/
protected KeyStroke pollInput() throws IOException {
return screen.pollInput();
}
@Override
public synchronized boolean processInput() throws IOException {
boolean gotInput = false;
KeyStroke keyStroke = readKeyStroke();
if(keyStroke != null) {
gotInput = true;
do {
if (keyStroke.getKeyType() == KeyType.EOF) {
throw new EOFException();
}
boolean handled = handleInput(keyStroke);
if(!handled) {
handled = fireUnhandledKeyStroke(keyStroke);
}
dirty = handled || dirty;
keyStroke = pollInput();
} while(keyStroke != null);
}
return gotInput;
}
@Override
public void setTheme(Theme theme) {
if(theme != null) {
this.guiTheme = theme;
}
}
@Override
public Theme getTheme() {
return guiTheme;
}
@Override
public synchronized void updateScreen() throws IOException {
screen.doResizeIfNecessary();
drawGUI(new DefaultTextGUIGraphics(this, screen.newTextGraphics()));
screen.setCursorPosition(getCursorPosition());
screen.refresh();
dirty = false;
}
@Override
public Screen getScreen() {
return screen;
}
@Override
public boolean isPendingUpdate() {
return screen.doResizeIfNecessary() != null || dirty;
}
@Override
public TextGUIThread getGUIThread() {
return textGUIThread;
}
@Override
public void addListener(Listener listener) {
listeners.add(listener);
}
@Override
public void removeListener(Listener listener) {
listeners.remove(listener);
}
/**
* Enables blocking I/O, causing calls to {@code readKeyStroke()} to block until there is input available. Notice
* that you can still poll for input using {@code pollInput()}.
* @param blockingIO Set this to {@code true} if blocking I/O should be enabled, otherwise {@code false}
*/
public void setBlockingIO(boolean blockingIO) {
this.blockingIO = blockingIO;
}
/**
* Checks if blocking I/O is enabled or not
* @return {@code true} if blocking I/O is enabled, otherwise {@code false}
*/
public boolean isBlockingIO() {
return blockingIO;
}
/**
* This method should be called when there was user input that wasn't handled by the GUI. It will fire the
* {@code onUnhandledKeyStroke(..)} method on any registered listener.
* @param keyStroke The {@code KeyStroke} that wasn't handled by the GUI
* @return {@code true} if at least one of the listeners handled the key stroke, this will signal to the GUI that it
* needs to be redrawn again.
*/
protected final boolean fireUnhandledKeyStroke(KeyStroke keyStroke) {<FILL_FUNCTION_BODY>}
/**
* Marks the whole text GUI as invalid and that it needs to be redrawn at next opportunity
*/
protected void invalidate() {
dirty = true;
}
/**
* Draws the entire GUI using a {@code TextGUIGraphics} object
* @param graphics Graphics object to draw using
*/
protected abstract void drawGUI(TextGUIGraphics graphics);
/**
* Top-level method for drilling in to the GUI and figuring out, in global coordinates, where to place the text
* cursor on the screen at this time.
* @return Where to place the text cursor, or {@code null} if the cursor should be hidden
*/
protected abstract TerminalPosition getCursorPosition();
/**
* This method should take the user input and feed it to the focused component for handling.
* @param key {@code KeyStroke} representing the user input
* @return {@code true} if the input was recognized and handled by the GUI, indicating that the GUI should be redrawn
*/
protected abstract boolean handleInput(KeyStroke key);
}
|
boolean handled = false;
for(Listener listener: listeners) {
handled = listener.onUnhandledKeyStroke(this, keyStroke) || handled;
}
return handled;
| 1,574
| 51
| 1,625
|
<no_super_class>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/AbstractTextGUIThread.java
|
AbstractTextGUIThread
|
invokeAndWait
|
class AbstractTextGUIThread implements TextGUIThread {
protected final TextGUI textGUI;
protected final Queue<Runnable> customTasks;
protected ExceptionHandler exceptionHandler;
/**
* Sets up this {@link AbstractTextGUIThread} for operations on the supplies {@link TextGUI}
* @param textGUI Text GUI this {@link TextGUIThread} implementations will be operating on
*/
public AbstractTextGUIThread(TextGUI textGUI) {
this.exceptionHandler = new ExceptionHandler() {
@Override
public boolean onIOException(IOException e) {
e.printStackTrace();
return true;
}
@Override
public boolean onRuntimeException(RuntimeException e) {
e.printStackTrace();
return true;
}
};
this.textGUI = textGUI;
this.customTasks = new LinkedBlockingQueue<>();
}
@Override
public void invokeLater(Runnable runnable) throws IllegalStateException {
customTasks.add(runnable);
}
@Override
public void setExceptionHandler(ExceptionHandler exceptionHandler) {
if(exceptionHandler == null) {
throw new IllegalArgumentException("Cannot call setExceptionHandler(null)");
}
this.exceptionHandler = exceptionHandler;
}
@Override
public synchronized boolean processEventsAndUpdate() throws IOException {
if(getThread() != Thread.currentThread()) {
throw new IllegalStateException("Calling processEventAndUpdate outside of GUI thread");
}
try {
textGUI.processInput();
while (!customTasks.isEmpty()) {
Runnable r = customTasks.poll();
if (r != null) {
r.run();
}
}
if (textGUI.isPendingUpdate()) {
textGUI.updateScreen();
return true;
}
return false;
}
catch (EOFException e) {
// Always re-throw EOFExceptions so the UI system knows we've closed the terminal
throw e;
}
catch (IOException e) {
if (exceptionHandler != null) {
exceptionHandler.onIOException(e);
}
else {
throw e;
}
}
catch (RuntimeException e) {
if (exceptionHandler != null) {
exceptionHandler.onRuntimeException(e);
}
else {
throw e;
}
}
return true;
}
@Override
public void invokeAndWait(final Runnable runnable) throws IllegalStateException, InterruptedException {<FILL_FUNCTION_BODY>}
}
|
Thread guiThread = getThread();
if(guiThread == null || Thread.currentThread() == guiThread) {
runnable.run();
}
else {
final CountDownLatch countDownLatch = new CountDownLatch(1);
invokeLater(() -> {
try {
runnable.run();
}
finally {
countDownLatch.countDown();
}
});
countDownLatch.await();
}
| 670
| 125
| 795
|
<no_super_class>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/ActionListBox.java
|
ActionListBox
|
handleKeyStroke
|
class ActionListBox extends AbstractListBox<Runnable, ActionListBox> {
/**
* Default constructor, creates an {@code ActionListBox} with no pre-defined size that will request to be big enough
* to display all items
*/
public ActionListBox() {
this(null);
}
/**
* Creates a new {@code ActionListBox} with a pre-set size. If the items don't fit in within this size, scrollbars
* will be used to accommodate. Calling {@code new ActionListBox(null)} has the same effect as calling
* {@code new ActionListBox()}.
* @param preferredSize Preferred size of this {@link ActionListBox}
*/
public ActionListBox(TerminalSize preferredSize) {
super(preferredSize);
}
/**
* {@inheritDoc}
*
* The label of the item in the list box will be the result of calling {@code .toString()} on the runnable, which
* might not be what you want to have unless you explicitly declare it. Consider using
* {@code addItem(String label, Runnable action} instead, if you want to just set the label easily without having
* to override {@code .toString()}.
*
* @param object Runnable to execute when the action was selected and fired in the list
* @return Itself
*/
@Override
public ActionListBox addItem(Runnable object) {
return super.addItem(object);
}
/**
* Adds a new item to the list, which is displayed in the list using a supplied label.
* @param label Label to use in the list for the new item
* @param action Runnable to invoke when this action is selected and then triggered
* @return Itself
*/
public ActionListBox addItem(final String label, final Runnable action) {
return addItem(new Runnable() {
@Override
public void run() {
action.run();
}
@Override
public String toString() {
return label;
}
});
}
@Override
public TerminalPosition getCursorLocation() {
return null;
}
@Override
public Result handleKeyStroke(KeyStroke keyStroke) {<FILL_FUNCTION_BODY>}
public void runSelectedItem() {
Object selectedItem = getSelectedItem();
if (selectedItem != null) {
((Runnable) selectedItem).run();
}
}
}
|
if (isKeyboardActivationStroke(keyStroke)) {
runSelectedItem();
return Result.HANDLED;
} else if (keyStroke.getKeyType() == KeyType.MOUSE_EVENT) {
MouseAction mouseAction = (MouseAction) keyStroke;
MouseActionType actionType = mouseAction.getActionType();
if (isMouseMove(keyStroke)
|| actionType == MouseActionType.CLICK_RELEASE
|| actionType == MouseActionType.SCROLL_UP
|| actionType == MouseActionType.SCROLL_DOWN) {
return super.handleKeyStroke(keyStroke);
}
// includes mouse drag
int existingIndex = getSelectedIndex();
int newIndex = getIndexByMouseAction(mouseAction);
if (existingIndex != newIndex || !isFocused() || actionType == MouseActionType.CLICK_DOWN) {
// the index has changed, or the focus needs to be obtained, or the user is clicking on the current selection to perform the action again
Result result = super.handleKeyStroke(keyStroke);
runSelectedItem();
return result;
}
return Result.HANDLED;
} else {
Result result = super.handleKeyStroke(keyStroke);
//runSelectedItem();
return result;
}
| 630
| 338
| 968
|
<methods>public synchronized com.googlecode.lanterna.gui2.ActionListBox addItem(java.lang.Runnable) ,public synchronized com.googlecode.lanterna.gui2.ActionListBox clearItems() ,public synchronized java.lang.Runnable getItemAt(int) ,public synchronized int getItemCount() ,public synchronized List<java.lang.Runnable> getItems() ,public int getSelectedIndex() ,public synchronized java.lang.Runnable getSelectedItem() ,public synchronized com.googlecode.lanterna.gui2.Interactable.Result handleKeyStroke(com.googlecode.lanterna.input.KeyStroke) ,public synchronized int indexOf(java.lang.Runnable) ,public synchronized boolean isEmpty() ,public boolean isFocusable() ,public synchronized java.lang.Runnable removeItem(int) ,public synchronized com.googlecode.lanterna.gui2.ActionListBox setListItemRenderer(ListItemRenderer<java.lang.Runnable,com.googlecode.lanterna.gui2.ActionListBox>) ,public synchronized com.googlecode.lanterna.gui2.ActionListBox setSelectedIndex(int) <variables>private final non-sealed List<java.lang.Runnable> items,private ListItemRenderer<java.lang.Runnable,com.googlecode.lanterna.gui2.ActionListBox> listItemRenderer,protected com.googlecode.lanterna.TerminalPosition scrollOffset,private int selectedIndex
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/AnimatedLabel.java
|
AnimationTimerTask
|
run
|
class AnimationTimerTask extends TimerTask {
private final WeakReference<AnimatedLabel> labelRef;
private AnimationTimerTask(AnimatedLabel label) {
this.labelRef = new WeakReference<>(label);
}
@Override
public void run() {<FILL_FUNCTION_BODY>}
}
|
AnimatedLabel animatedLabel = labelRef.get();
if(animatedLabel == null) {
cancel();
canCloseTimer();
}
else {
if(animatedLabel.getBasePane() == null) {
animatedLabel.stopAnimation();
}
else {
animatedLabel.nextFrame();
}
}
| 86
| 89
| 175
|
<methods>public void <init>(java.lang.String) ,public synchronized com.googlecode.lanterna.gui2.Label addStyle(com.googlecode.lanterna.SGR) ,public com.googlecode.lanterna.TextColor getBackgroundColor() ,public com.googlecode.lanterna.TextColor getForegroundColor() ,public java.lang.Integer getLabelWidth() ,public synchronized java.lang.String getText() ,public synchronized com.googlecode.lanterna.gui2.Label removeStyle(com.googlecode.lanterna.SGR) ,public synchronized com.googlecode.lanterna.gui2.Label setBackgroundColor(com.googlecode.lanterna.TextColor) ,public synchronized com.googlecode.lanterna.gui2.Label setForegroundColor(com.googlecode.lanterna.TextColor) ,public synchronized com.googlecode.lanterna.gui2.Label setLabelWidth(java.lang.Integer) ,public synchronized void setText(java.lang.String) <variables>private final non-sealed EnumSet<com.googlecode.lanterna.SGR> additionalStyles,private com.googlecode.lanterna.TextColor backgroundColor,private com.googlecode.lanterna.TextColor foregroundColor,private com.googlecode.lanterna.TerminalSize labelSize,private java.lang.Integer labelWidth,private java.lang.String[] lines
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/BorderLayout.java
|
BorderLayout
|
makeLookupMap
|
class BorderLayout implements LayoutManager {
/**
* This type is what you use as the layout data for components added to a panel using {@code BorderLayout} for its
* layout manager. This values specified where inside the panel the component should be added.
*/
public enum Location implements LayoutData {
/**
* The component with this value as its layout data will occupy the center space, whatever is remaining after
* the other components (if any) have allocated their space.
*/
CENTER,
/**
* The component with this value as its layout data will occupy the left side of the container, attempting to
* allocate the preferred width of the component and at least the preferred height, but could be more depending
* on the other components added.
*/
LEFT,
/**
* The component with this value as its layout data will occupy the right side of the container, attempting to
* allocate the preferred width of the component and at least the preferred height, but could be more depending
* on the other components added.
*/
RIGHT,
/**
* The component with this value as its layout data will occupy the top side of the container, attempting to
* allocate the preferred height of the component and at least the preferred width, but could be more depending
* on the other components added.
*/
TOP,
/**
* The component with this value as its layout data will occupy the bottom side of the container, attempting to
* allocate the preferred height of the component and at least the preferred width, but could be more depending
* on the other components added.
*/
BOTTOM,
;
}
//When components don't have a location, we'll assign an available location based on this order
private static final List<Location> AUTO_ASSIGN_ORDER = Collections.unmodifiableList(Arrays.asList(
Location.CENTER,
Location.TOP,
Location.BOTTOM,
Location.LEFT,
Location.RIGHT));
@Override
public TerminalSize getPreferredSize(List<Component> components) {
EnumMap<Location, Component> layout = makeLookupMap(components);
int preferredHeight =
(layout.containsKey(Location.TOP) ? layout.get(Location.TOP).getPreferredSize().getRows() : 0)
+
Math.max(
layout.containsKey(Location.LEFT) ? layout.get(Location.LEFT).getPreferredSize().getRows() : 0,
Math.max(
layout.containsKey(Location.CENTER) ? layout.get(Location.CENTER).getPreferredSize().getRows() : 0,
layout.containsKey(Location.RIGHT) ? layout.get(Location.RIGHT).getPreferredSize().getRows() : 0))
+
(layout.containsKey(Location.BOTTOM) ? layout.get(Location.BOTTOM).getPreferredSize().getRows() : 0);
int preferredWidth =
Math.max(
(layout.containsKey(Location.LEFT) ? layout.get(Location.LEFT).getPreferredSize().getColumns() : 0) +
(layout.containsKey(Location.CENTER) ? layout.get(Location.CENTER).getPreferredSize().getColumns() : 0) +
(layout.containsKey(Location.RIGHT) ? layout.get(Location.RIGHT).getPreferredSize().getColumns() : 0),
Math.max(
layout.containsKey(Location.TOP) ? layout.get(Location.TOP).getPreferredSize().getColumns() : 0,
layout.containsKey(Location.BOTTOM) ? layout.get(Location.BOTTOM).getPreferredSize().getColumns() : 0));
return new TerminalSize(preferredWidth, preferredHeight);
}
@Override
public void doLayout(TerminalSize area, List<Component> components) {
EnumMap<Location, Component> layout = makeLookupMap(components);
int availableHorizontalSpace = area.getColumns();
int availableVerticalSpace = area.getRows();
//We'll need this later on
int topComponentHeight = 0;
int leftComponentWidth = 0;
//First allocate the top
if(layout.containsKey(Location.TOP)) {
Component topComponent = layout.get(Location.TOP);
topComponentHeight = Math.min(topComponent.getPreferredSize().getRows(), availableVerticalSpace);
topComponent.setPosition(TerminalPosition.TOP_LEFT_CORNER);
topComponent.setSize(new TerminalSize(availableHorizontalSpace, topComponentHeight));
availableVerticalSpace -= topComponentHeight;
}
//Next allocate the bottom
if(layout.containsKey(Location.BOTTOM)) {
Component bottomComponent = layout.get(Location.BOTTOM);
int bottomComponentHeight = Math.min(bottomComponent.getPreferredSize().getRows(), availableVerticalSpace);
bottomComponent.setPosition(new TerminalPosition(0, area.getRows() - bottomComponentHeight));
bottomComponent.setSize(new TerminalSize(availableHorizontalSpace, bottomComponentHeight));
availableVerticalSpace -= bottomComponentHeight;
}
//Now divide the remaining space between LEFT, CENTER and RIGHT
if(layout.containsKey(Location.LEFT)) {
Component leftComponent = layout.get(Location.LEFT);
leftComponentWidth = Math.min(leftComponent.getPreferredSize().getColumns(), availableHorizontalSpace);
leftComponent.setPosition(new TerminalPosition(0, topComponentHeight));
leftComponent.setSize(new TerminalSize(leftComponentWidth, availableVerticalSpace));
availableHorizontalSpace -= leftComponentWidth;
}
if(layout.containsKey(Location.RIGHT)) {
Component rightComponent = layout.get(Location.RIGHT);
int rightComponentWidth = Math.min(rightComponent.getPreferredSize().getColumns(), availableHorizontalSpace);
rightComponent.setPosition(new TerminalPosition(area.getColumns() - rightComponentWidth, topComponentHeight));
rightComponent.setSize(new TerminalSize(rightComponentWidth, availableVerticalSpace));
availableHorizontalSpace -= rightComponentWidth;
}
if(layout.containsKey(Location.CENTER)) {
Component centerComponent = layout.get(Location.CENTER);
centerComponent.setPosition(new TerminalPosition(leftComponentWidth, topComponentHeight));
centerComponent.setSize(new TerminalSize(availableHorizontalSpace, availableVerticalSpace));
}
//Set the remaining components to 0x0
for(Component component: components) {
if(component.isVisible() && !layout.containsValue(component)) {
component.setPosition(TerminalPosition.TOP_LEFT_CORNER);
component.setSize(TerminalSize.ZERO);
}
}
}
private EnumMap<Location, Component> makeLookupMap(List<Component> components) {<FILL_FUNCTION_BODY>}
@Override
public boolean hasChanged() {
//No internal state
return false;
}
}
|
EnumMap<Location, Component> map = new EnumMap<>(Location.class);
List<Component> unassignedComponents = new ArrayList<>();
for(Component component: components) {
if (!component.isVisible()) {
continue;
}
if(component.getLayoutData() instanceof Location) {
map.put((Location)component.getLayoutData(), component);
}
else {
unassignedComponents.add(component);
}
}
//Try to assign components to available locations
for(Component component: unassignedComponents) {
for(Location location: AUTO_ASSIGN_ORDER) {
if(!map.containsKey(location)) {
map.put(location, component);
break;
}
}
}
return map;
| 1,775
| 203
| 1,978
|
<no_super_class>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/Borders.java
|
AbstractBorderRenderer
|
getPreferredSize
|
class AbstractBorderRenderer implements Border.BorderRenderer {
private final BorderStyle borderStyle;
protected AbstractBorderRenderer(BorderStyle borderStyle) {
this.borderStyle = borderStyle;
}
@Override
public TerminalSize getPreferredSize(Border component) {<FILL_FUNCTION_BODY>}
@Override
public TerminalPosition getWrappedComponentTopLeftOffset() {
return TerminalPosition.OFFSET_1x1;
}
@Override
public TerminalSize getWrappedComponentSize(TerminalSize borderSize) {
return borderSize
.withRelativeColumns(-Math.min(2, borderSize.getColumns()))
.withRelativeRows(-Math.min(2, borderSize.getRows()));
}
@Override
public void drawComponent(TextGUIGraphics graphics, Border component) {
StandardBorder border = (StandardBorder)component;
Component wrappedComponent = border.getComponent();
if(wrappedComponent == null) {
return;
}
TerminalSize drawableArea = graphics.getSize();
char horizontalLine = getHorizontalLine(component.getTheme());
char verticalLine = getVerticalLine(component.getTheme());
char bottomLeftCorner = getBottomLeftCorner(component.getTheme());
char topLeftCorner = getTopLeftCorner(component.getTheme());
char bottomRightCorner = getBottomRightCorner(component.getTheme());
char topRightCorner = getTopRightCorner(component.getTheme());
char titleLeft = getTitleLeft(component.getTheme());
char titleRight = getTitleRight(component.getTheme());
ThemeDefinition themeDefinition = component.getTheme().getDefinition(AbstractBorder.class);
if(borderStyle == BorderStyle.Bevel) {
graphics.applyThemeStyle(themeDefinition.getPreLight());
}
else {
graphics.applyThemeStyle(themeDefinition.getNormal());
}
graphics.setCharacter(0, drawableArea.getRows() - 1, bottomLeftCorner);
if(drawableArea.getRows() > 2) {
graphics.drawLine(new TerminalPosition(0, drawableArea.getRows() - 2), new TerminalPosition(0, 1), verticalLine);
}
graphics.setCharacter(0, 0, topLeftCorner);
if(drawableArea.getColumns() > 2) {
graphics.drawLine(new TerminalPosition(1, 0), new TerminalPosition(drawableArea.getColumns() - 2, 0), horizontalLine);
}
if(borderStyle == BorderStyle.ReverseBevel) {
graphics.applyThemeStyle(themeDefinition.getPreLight());
}
else {
graphics.applyThemeStyle(themeDefinition.getNormal());
}
graphics.setCharacter(drawableArea.getColumns() - 1, 0, topRightCorner);
if(drawableArea.getRows() > 2) {
graphics.drawLine(new TerminalPosition(drawableArea.getColumns() - 1, 1),
new TerminalPosition(drawableArea.getColumns() - 1, drawableArea.getRows() - 2),
verticalLine);
}
graphics.setCharacter(drawableArea.getColumns() - 1, drawableArea.getRows() - 1, bottomRightCorner);
if(drawableArea.getColumns() > 2) {
graphics.drawLine(new TerminalPosition(1, drawableArea.getRows() - 1),
new TerminalPosition(drawableArea.getColumns() - 2, drawableArea.getRows() - 1),
horizontalLine);
}
if(border.getTitle() != null && !border.getTitle().isEmpty() &&
drawableArea.getColumns() >= TerminalTextUtils.getColumnWidth(border.getTitle()) + 4) {
graphics.applyThemeStyle(themeDefinition.getActive());
graphics.putString(2, 0, border.getTitle());
if(borderStyle == BorderStyle.Bevel) {
graphics.applyThemeStyle(themeDefinition.getPreLight());
}
else {
graphics.applyThemeStyle(themeDefinition.getNormal());
}
graphics.setCharacter(1, 0, titleLeft);
graphics.setCharacter(2 + TerminalTextUtils.getColumnWidth(border.getTitle()), 0, titleRight);
}
wrappedComponent.draw(graphics.newTextGraphics(getWrappedComponentTopLeftOffset(), getWrappedComponentSize(drawableArea)));
joinLinesWithFrame(graphics);
}
protected abstract char getHorizontalLine(Theme theme);
protected abstract char getVerticalLine(Theme theme);
protected abstract char getBottomLeftCorner(Theme theme);
protected abstract char getTopLeftCorner(Theme theme);
protected abstract char getBottomRightCorner(Theme theme);
protected abstract char getTopRightCorner(Theme theme);
protected abstract char getTitleLeft(Theme theme);
protected abstract char getTitleRight(Theme theme);
}
|
StandardBorder border = (StandardBorder)component;
Component wrappedComponent = border.getComponent();
TerminalSize preferredSize;
if (wrappedComponent == null) {
preferredSize = TerminalSize.ZERO;
} else {
preferredSize = wrappedComponent.getPreferredSize();
}
preferredSize = preferredSize.withRelativeColumns(2).withRelativeRows(2);
String borderTitle = border.getTitle();
return preferredSize.max(new TerminalSize((borderTitle.isEmpty() ? 2 : TerminalTextUtils.getColumnWidth(borderTitle) + 4), 2));
| 1,237
| 148
| 1,385
|
<no_super_class>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/Button.java
|
DefaultButtonRenderer
|
drawComponent
|
class DefaultButtonRenderer implements ButtonRenderer {
@Override
public TerminalPosition getCursorLocation(Button button) {
if(button.getThemeDefinition().isCursorVisible()) {
return new TerminalPosition(1 + getLabelShift(button, button.getSize()), 0);
}
else {
return null;
}
}
@Override
public TerminalSize getPreferredSize(Button button) {
return new TerminalSize(Math.max(8, TerminalTextUtils.getColumnWidth(button.getLabel()) + 2), 1);
}
@Override
public void drawComponent(TextGUIGraphics graphics, Button button) {<FILL_FUNCTION_BODY>}
private int getLabelShift(Button button, TerminalSize size) {
int availableSpace = size.getColumns() - 2;
if(availableSpace <= 0) {
return 0;
}
int labelShift = 0;
int widthInColumns = TerminalTextUtils.getColumnWidth(button.getLabel());
if(availableSpace > widthInColumns) {
labelShift = (size.getColumns() - 2 - widthInColumns) / 2;
}
return labelShift;
}
}
|
ThemeDefinition themeDefinition = button.getThemeDefinition();
if(button.isFocused()) {
graphics.applyThemeStyle(themeDefinition.getActive());
}
else {
graphics.applyThemeStyle(themeDefinition.getInsensitive());
}
graphics.fill(' ');
graphics.setCharacter(0, 0, themeDefinition.getCharacter("LEFT_BORDER", '<'));
graphics.setCharacter(graphics.getSize().getColumns() - 1, 0, themeDefinition.getCharacter("RIGHT_BORDER", '>'));
if(button.isFocused()) {
graphics.applyThemeStyle(themeDefinition.getActive());
}
else {
graphics.applyThemeStyle(themeDefinition.getPreLight());
}
int labelShift = getLabelShift(button, graphics.getSize());
graphics.setCharacter(1 + labelShift, 0, button.getLabel().charAt(0));
if(TerminalTextUtils.getColumnWidth(button.getLabel()) == 1) {
return;
}
if(button.isFocused()) {
graphics.applyThemeStyle(themeDefinition.getSelected());
}
else {
graphics.applyThemeStyle(themeDefinition.getNormal());
}
graphics.putString(1 + labelShift + 1, 0, button.getLabel().substring(1));
| 300
| 338
| 638
|
<methods>public com.googlecode.lanterna.TerminalPosition getCursorLocation() ,public com.googlecode.lanterna.gui2.InputFilter getInputFilter() ,public InteractableRenderer<com.googlecode.lanterna.gui2.Button> getRenderer() ,public final synchronized com.googlecode.lanterna.gui2.Interactable.Result handleInput(com.googlecode.lanterna.input.KeyStroke) ,public boolean isActivationStroke(com.googlecode.lanterna.input.KeyStroke) ,public boolean isEnabled() ,public boolean isFocusable() ,public boolean isFocused() ,public boolean isKeyboardActivationStroke(com.googlecode.lanterna.input.KeyStroke) ,public boolean isMouseActivationStroke(com.googlecode.lanterna.input.KeyStroke) ,public boolean isMouseDown(com.googlecode.lanterna.input.KeyStroke) ,public boolean isMouseDrag(com.googlecode.lanterna.input.KeyStroke) ,public boolean isMouseMove(com.googlecode.lanterna.input.KeyStroke) ,public boolean isMouseUp(com.googlecode.lanterna.input.KeyStroke) ,public final void onEnterFocus(com.googlecode.lanterna.gui2.Interactable.FocusChangeDirection, com.googlecode.lanterna.gui2.Interactable) ,public final void onLeaveFocus(com.googlecode.lanterna.gui2.Interactable.FocusChangeDirection, com.googlecode.lanterna.gui2.Interactable) ,public synchronized com.googlecode.lanterna.gui2.Button setEnabled(boolean) ,public synchronized com.googlecode.lanterna.gui2.Button setInputFilter(com.googlecode.lanterna.gui2.InputFilter) ,public com.googlecode.lanterna.gui2.Button takeFocus() <variables>private boolean enabled,private boolean inFocus,private com.googlecode.lanterna.gui2.InputFilter inputFilter
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/CheckBox.java
|
CheckBox
|
handleKeyStroke
|
class CheckBox extends AbstractInteractableComponent<CheckBox> {
/**
* Listener interface that can be used to catch user events on the check box
*/
public interface Listener {
/**
* This is fired when the user has altered the checked state of this {@code CheckBox}
* @param checked If the {@code CheckBox} is now toggled on, this is set to {@code true}, otherwise
* {@code false}
*/
void onStatusChanged(boolean checked);
}
private final List<Listener> listeners;
private String label;
private boolean checked;
/**
* Creates a new checkbox with no label, initially set to un-checked
*/
public CheckBox() {
this("");
}
/**
* Creates a new checkbox with a specific label, initially set to un-checked
* @param label Label to assign to the check box
*/
public CheckBox(String label) {
if(label == null) {
throw new IllegalArgumentException("Cannot create a CheckBox with null label");
}
else if(label.contains("\n") || label.contains("\r")) {
throw new IllegalArgumentException("Multiline checkbox labels are not supported");
}
this.listeners = new CopyOnWriteArrayList<>();
this.label = label;
this.checked = false;
}
/**
* Programmatically updated the check box to a particular checked state
* @param checked If {@code true}, the check box will be set to toggled on, otherwise {@code false}
* @return Itself
*/
public synchronized CheckBox setChecked(final boolean checked) {
this.checked = checked;
runOnGUIThreadIfExistsOtherwiseRunDirect(() -> {
for(Listener listener : listeners) {
listener.onStatusChanged(checked);
}
});
invalidate();
return this;
}
/**
* Returns the checked state of this check box
* @return {@code true} if the check box is toggled on, otherwise {@code false}
*/
public boolean isChecked() {
return checked;
}
@Override
public Result handleKeyStroke(KeyStroke keyStroke) {<FILL_FUNCTION_BODY>}
/**
* Updates the label of the checkbox
* @param label New label to assign to the check box
* @return Itself
*/
public synchronized CheckBox setLabel(String label) {
if(label == null) {
throw new IllegalArgumentException("Cannot set CheckBox label to null");
}
this.label = label;
invalidate();
return this;
}
/**
* Returns the label of check box
* @return Label currently assigned to the check box
*/
public String getLabel() {
return label;
}
/**
* Adds a listener to this check box so that it will be notificed on certain user actions
* @param listener Listener to fire events on
* @return Itself
*/
public CheckBox addListener(Listener listener) {
if(listener != null && !listeners.contains(listener)) {
listeners.add(listener);
}
return this;
}
/**
* Removes a listener from this check box so that, if it was previously added, it will no long receive any events
* @param listener Listener to remove from the check box
* @return Itself
*/
public CheckBox removeListener(Listener listener) {
listeners.remove(listener);
return this;
}
@Override
protected CheckBoxRenderer createDefaultRenderer() {
return new DefaultCheckBoxRenderer();
}
/**
* Helper interface that doesn't add any new methods but makes coding new check box renderers a little bit more clear
*/
public static abstract class CheckBoxRenderer implements InteractableRenderer<CheckBox> {
}
/**
* The default renderer that is used unless overridden. This renderer will draw the checkbox label on the right side
* of a "[ ]" block which will contain a "X" inside it if the check box has toggle status on
*/
public static class DefaultCheckBoxRenderer extends CheckBoxRenderer {
private static final TerminalPosition CURSOR_LOCATION = new TerminalPosition(1, 0);
@Override
public TerminalPosition getCursorLocation(CheckBox component) {
if(component.getThemeDefinition().isCursorVisible()) {
return CURSOR_LOCATION;
}
else {
return null;
}
}
@Override
public TerminalSize getPreferredSize(CheckBox component) {
int width = 3;
if(!component.label.isEmpty()) {
width += 1 + TerminalTextUtils.getColumnWidth(component.label);
}
return new TerminalSize(width, 1);
}
@Override
public void drawComponent(TextGUIGraphics graphics, CheckBox component) {
ThemeDefinition themeDefinition = component.getThemeDefinition();
if(component.isFocused()) {
graphics.applyThemeStyle(themeDefinition.getActive());
}
else {
graphics.applyThemeStyle(themeDefinition.getNormal());
}
graphics.fill(' ');
graphics.putString(4, 0, component.label);
if(component.isFocused()) {
graphics.applyThemeStyle(themeDefinition.getPreLight());
}
else {
graphics.applyThemeStyle(themeDefinition.getInsensitive());
}
graphics.setCharacter(0, 0, themeDefinition.getCharacter("LEFT_BRACKET", '['));
graphics.setCharacter(2, 0, themeDefinition.getCharacter("RIGHT_BRACKET", ']'));
graphics.setCharacter(3, 0, ' ');
if(component.isFocused()) {
graphics.applyThemeStyle(themeDefinition.getSelected());
}
else {
graphics.applyThemeStyle(themeDefinition.getNormal());
}
graphics.setCharacter(1, 0, (component.isChecked() ? themeDefinition.getCharacter("MARKER", 'x') : ' '));
}
}
}
|
if (isKeyboardActivationStroke(keyStroke)) {
setChecked(!isChecked());
return Result.HANDLED;
} else if (isMouseActivationStroke(keyStroke)) {
getBasePane().setFocusedInteractable(this);
setChecked(!isChecked());
return Result.HANDLED;
}
return super.handleKeyStroke(keyStroke);
| 1,544
| 108
| 1,652
|
<methods>public com.googlecode.lanterna.TerminalPosition getCursorLocation() ,public com.googlecode.lanterna.gui2.InputFilter getInputFilter() ,public InteractableRenderer<com.googlecode.lanterna.gui2.CheckBox> getRenderer() ,public final synchronized com.googlecode.lanterna.gui2.Interactable.Result handleInput(com.googlecode.lanterna.input.KeyStroke) ,public boolean isActivationStroke(com.googlecode.lanterna.input.KeyStroke) ,public boolean isEnabled() ,public boolean isFocusable() ,public boolean isFocused() ,public boolean isKeyboardActivationStroke(com.googlecode.lanterna.input.KeyStroke) ,public boolean isMouseActivationStroke(com.googlecode.lanterna.input.KeyStroke) ,public boolean isMouseDown(com.googlecode.lanterna.input.KeyStroke) ,public boolean isMouseDrag(com.googlecode.lanterna.input.KeyStroke) ,public boolean isMouseMove(com.googlecode.lanterna.input.KeyStroke) ,public boolean isMouseUp(com.googlecode.lanterna.input.KeyStroke) ,public final void onEnterFocus(com.googlecode.lanterna.gui2.Interactable.FocusChangeDirection, com.googlecode.lanterna.gui2.Interactable) ,public final void onLeaveFocus(com.googlecode.lanterna.gui2.Interactable.FocusChangeDirection, com.googlecode.lanterna.gui2.Interactable) ,public synchronized com.googlecode.lanterna.gui2.CheckBox setEnabled(boolean) ,public synchronized com.googlecode.lanterna.gui2.CheckBox setInputFilter(com.googlecode.lanterna.gui2.InputFilter) ,public com.googlecode.lanterna.gui2.CheckBox takeFocus() <variables>private boolean enabled,private boolean inFocus,private com.googlecode.lanterna.gui2.InputFilter inputFilter
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/ComboBox.java
|
DefaultComboBoxRenderer
|
getPreferredSize
|
class DefaultComboBoxRenderer<V> extends ComboBoxRenderer<V> {
private int textVisibleLeftPosition;
/**
* Default constructor
*/
public DefaultComboBoxRenderer() {
this.textVisibleLeftPosition = 0;
}
@Override
public TerminalPosition getCursorLocation(ComboBox<V> comboBox) {
if(comboBox.isDropDownFocused()) {
if(comboBox.getThemeDefinition().isCursorVisible()) {
return new TerminalPosition(comboBox.getSize().getColumns() - 1, 0);
}
else {
return null;
}
}
else {
int textInputPosition = comboBox.getTextInputPosition();
int textInputColumn = TerminalTextUtils.getColumnWidth(comboBox.getText().substring(0, textInputPosition));
return new TerminalPosition(textInputColumn - textVisibleLeftPosition, 0);
}
}
@Override
public TerminalSize getPreferredSize(final ComboBox<V> comboBox) {<FILL_FUNCTION_BODY>}
@Override
public void drawComponent(TextGUIGraphics graphics, ComboBox<V> comboBox) {
ThemeDefinition themeDefinition = comboBox.getThemeDefinition();
if(comboBox.isReadOnly()) {
graphics.applyThemeStyle(themeDefinition.getNormal());
}
else {
if(comboBox.isFocused()) {
graphics.applyThemeStyle(themeDefinition.getActive());
}
else {
graphics.applyThemeStyle(themeDefinition.getPreLight());
}
}
graphics.fill(' ');
int editableArea = graphics.getSize().getColumns() - 2; //This is exclusing the 'drop-down arrow'
int textInputPosition = comboBox.getTextInputPosition();
int columnsToInputPosition = TerminalTextUtils.getColumnWidth(comboBox.getText().substring(0, textInputPosition));
if(columnsToInputPosition < textVisibleLeftPosition) {
textVisibleLeftPosition = columnsToInputPosition;
}
if(columnsToInputPosition - textVisibleLeftPosition >= editableArea) {
textVisibleLeftPosition = columnsToInputPosition - editableArea + 1;
}
if(columnsToInputPosition - textVisibleLeftPosition + 1 == editableArea &&
comboBox.getText().length() > textInputPosition &&
TerminalTextUtils.isCharCJK(comboBox.getText().charAt(textInputPosition))) {
textVisibleLeftPosition++;
}
String textToDraw = TerminalTextUtils.fitString(comboBox.getText(), textVisibleLeftPosition, editableArea);
graphics.putString(0, 0, textToDraw);
graphics.applyThemeStyle(themeDefinition.getInsensitive());
graphics.setCharacter(editableArea, 0, themeDefinition.getCharacter("POPUP_SEPARATOR", Symbols.SINGLE_LINE_VERTICAL));
if(comboBox.isFocused() && comboBox.isDropDownFocused()) {
graphics.applyThemeStyle(themeDefinition.getSelected());
}
graphics.setCharacter(editableArea + 1, 0, themeDefinition.getCharacter("POPUP", Symbols.TRIANGLE_DOWN_POINTING_BLACK));
}
}
|
TerminalSize size = TerminalSize.ONE.withColumns(
(comboBox.getItemCount() == 0 ? TerminalTextUtils.getColumnWidth(comboBox.getText()) : 0) + 2);
//noinspection SynchronizationOnLocalVariableOrMethodParameter
synchronized(comboBox) {
for(int i = 0; i < comboBox.getItemCount(); i++) {
V item = comboBox.getItem(i);
size = size.max(new TerminalSize(TerminalTextUtils.getColumnWidth(item.toString()) + 2 + 1, 1)); // +1 to add a single column of space
}
}
return size;
| 824
| 167
| 991
|
<methods>public com.googlecode.lanterna.TerminalPosition getCursorLocation() ,public com.googlecode.lanterna.gui2.InputFilter getInputFilter() ,public InteractableRenderer<ComboBox<V>> getRenderer() ,public final synchronized com.googlecode.lanterna.gui2.Interactable.Result handleInput(com.googlecode.lanterna.input.KeyStroke) ,public boolean isActivationStroke(com.googlecode.lanterna.input.KeyStroke) ,public boolean isEnabled() ,public boolean isFocusable() ,public boolean isFocused() ,public boolean isKeyboardActivationStroke(com.googlecode.lanterna.input.KeyStroke) ,public boolean isMouseActivationStroke(com.googlecode.lanterna.input.KeyStroke) ,public boolean isMouseDown(com.googlecode.lanterna.input.KeyStroke) ,public boolean isMouseDrag(com.googlecode.lanterna.input.KeyStroke) ,public boolean isMouseMove(com.googlecode.lanterna.input.KeyStroke) ,public boolean isMouseUp(com.googlecode.lanterna.input.KeyStroke) ,public final void onEnterFocus(com.googlecode.lanterna.gui2.Interactable.FocusChangeDirection, com.googlecode.lanterna.gui2.Interactable) ,public final void onLeaveFocus(com.googlecode.lanterna.gui2.Interactable.FocusChangeDirection, com.googlecode.lanterna.gui2.Interactable) ,public synchronized ComboBox<V> setEnabled(boolean) ,public synchronized ComboBox<V> setInputFilter(com.googlecode.lanterna.gui2.InputFilter) ,public ComboBox<V> takeFocus() <variables>private boolean enabled,private boolean inFocus,private com.googlecode.lanterna.gui2.InputFilter inputFilter
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/DefaultWindowDecorationRenderer.java
|
DefaultWindowDecorationRenderer
|
draw
|
class DefaultWindowDecorationRenderer implements WindowDecorationRenderer {
private static final int TITLE_POSITION_WITH_PADDING = 4;
private static final int TITLE_POSITION_WITHOUT_PADDING = 3;
@Override
public TextGUIGraphics draw(WindowBasedTextGUI textGUI, TextGUIGraphics graphics, Window window) {<FILL_FUNCTION_BODY>}
@Override
public TerminalSize getDecoratedSize(Window window, TerminalSize contentAreaSize) {
ThemeDefinition themeDefinition = window.getTheme().getDefinition(DefaultWindowDecorationRenderer.class);
boolean useTitlePadding = themeDefinition.getBooleanProperty("TITLE_PADDING", false);
int titleWidth = TerminalTextUtils.getColumnWidth(window.getTitle());
int minPadding = TITLE_POSITION_WITHOUT_PADDING * 2;
if(useTitlePadding) {
minPadding = TITLE_POSITION_WITH_PADDING * 2;
}
return contentAreaSize
.withRelativeColumns(2)
.withRelativeRows(2)
.max(new TerminalSize(titleWidth + minPadding, 1)); //Make sure the title fits!
}
private static final TerminalPosition OFFSET = new TerminalPosition(1, 1);
@Override
public TerminalPosition getOffset(Window window) {
return OFFSET;
}
}
|
String title = window.getTitle();
if(title == null) {
title = "";
}
TerminalSize drawableArea = graphics.getSize();
ThemeDefinition themeDefinition = window.getTheme().getDefinition(DefaultWindowDecorationRenderer.class);
char horizontalLine = themeDefinition.getCharacter("HORIZONTAL_LINE", Symbols.SINGLE_LINE_HORIZONTAL);
char verticalLine = themeDefinition.getCharacter("VERTICAL_LINE", Symbols.SINGLE_LINE_VERTICAL);
char bottomLeftCorner = themeDefinition.getCharacter("BOTTOM_LEFT_CORNER", Symbols.SINGLE_LINE_BOTTOM_LEFT_CORNER);
char topLeftCorner = themeDefinition.getCharacter("TOP_LEFT_CORNER", Symbols.SINGLE_LINE_TOP_LEFT_CORNER);
char bottomRightCorner = themeDefinition.getCharacter("BOTTOM_RIGHT_CORNER", Symbols.SINGLE_LINE_BOTTOM_RIGHT_CORNER);
char topRightCorner = themeDefinition.getCharacter("TOP_RIGHT_CORNER", Symbols.SINGLE_LINE_TOP_RIGHT_CORNER);
char titleSeparatorLeft = themeDefinition.getCharacter("TITLE_SEPARATOR_LEFT", Symbols.SINGLE_LINE_HORIZONTAL);
char titleSeparatorRight = themeDefinition.getCharacter("TITLE_SEPARATOR_RIGHT", Symbols.SINGLE_LINE_HORIZONTAL);
boolean useTitlePadding = themeDefinition.getBooleanProperty("TITLE_PADDING", false);
boolean centerTitle = themeDefinition.getBooleanProperty("CENTER_TITLE", false);
int titleHorizontalPosition = useTitlePadding ? TITLE_POSITION_WITH_PADDING : TITLE_POSITION_WITHOUT_PADDING;
int titleMaxColumns = drawableArea.getColumns() - titleHorizontalPosition * 2;
if(centerTitle) {
titleHorizontalPosition = (drawableArea.getColumns() / 2) - (TerminalTextUtils.getColumnWidth(title) / 2);
titleHorizontalPosition = Math.max(titleHorizontalPosition, useTitlePadding ? TITLE_POSITION_WITH_PADDING : TITLE_POSITION_WITHOUT_PADDING);
}
String actualTitle = TerminalTextUtils.fitString(title, titleMaxColumns);
int titleActualColumns = TerminalTextUtils.getColumnWidth(actualTitle);
// Don't draw highlights on menu popup windows
if (window.getHints().contains(Window.Hint.MENU_POPUP)) {
graphics.applyThemeStyle(themeDefinition.getNormal());
}
else {
graphics.applyThemeStyle(themeDefinition.getPreLight());
}
graphics.drawLine(new TerminalPosition(0, drawableArea.getRows() - 2), new TerminalPosition(0, 1), verticalLine);
graphics.drawLine(new TerminalPosition(1, 0), new TerminalPosition(drawableArea.getColumns() - 2, 0), horizontalLine);
graphics.setCharacter(0, 0, topLeftCorner);
graphics.setCharacter(0, drawableArea.getRows() - 1, bottomLeftCorner);
if(!actualTitle.isEmpty() && drawableArea.getColumns() > 8) {
int separatorOffset = 1;
if(useTitlePadding) {
graphics.setCharacter(titleHorizontalPosition - 1, 0, ' ');
graphics.setCharacter(titleHorizontalPosition + titleActualColumns, 0, ' ');
separatorOffset = 2;
}
graphics.setCharacter(titleHorizontalPosition - separatorOffset, 0, titleSeparatorLeft);
graphics.setCharacter(titleHorizontalPosition + titleActualColumns + separatorOffset - 1, 0, titleSeparatorRight);
}
graphics.applyThemeStyle(themeDefinition.getNormal());
graphics.drawLine(
new TerminalPosition(drawableArea.getColumns() - 1, 1),
new TerminalPosition(drawableArea.getColumns() - 1, drawableArea.getRows() - 2),
verticalLine);
graphics.drawLine(
new TerminalPosition(1, drawableArea.getRows() - 1),
new TerminalPosition(drawableArea.getColumns() - 2, drawableArea.getRows() - 1),
horizontalLine);
graphics.setCharacter(drawableArea.getColumns() - 1, 0, topRightCorner);
graphics.setCharacter(drawableArea.getColumns() - 1, drawableArea.getRows() - 1, bottomRightCorner);
if(!actualTitle.isEmpty()) {
if(textGUI.getActiveWindow() == window) {
graphics.applyThemeStyle(themeDefinition.getActive());
}
else {
graphics.applyThemeStyle(themeDefinition.getInsensitive());
}
graphics.putString(titleHorizontalPosition, 0, actualTitle);
}
return graphics.newTextGraphics(
new TerminalPosition(1, 1),
drawableArea
// Make sure we don't make the new graphic's area smaller than 0
.withRelativeColumns(-(Math.min(2, drawableArea.getColumns())))
.withRelativeRows(-(Math.min(2, drawableArea.getRows()))));
| 363
| 1,355
| 1,718
|
<no_super_class>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/EmptySpace.java
|
EmptySpace
|
createDefaultRenderer
|
class EmptySpace extends AbstractComponent<EmptySpace> {
private final TerminalSize size;
private TextColor color;
/**
* Creates an EmptySpace with size 1x1 and a default color chosen from the theme
*/
public EmptySpace() {
this(null, TerminalSize.ONE);
}
/**
* Creates an EmptySpace with a specified color and preferred size of 1x1
* @param color Color to use (null will make it use the theme)
*/
public EmptySpace(TextColor color) {
this(color, TerminalSize.ONE);
}
/**
* Creates an EmptySpace with a specified preferred size (color will be chosen from the theme)
* @param size Preferred size
*/
public EmptySpace(TerminalSize size) {
this(null, size);
}
/**
* Creates an EmptySpace with a specified color (null will make it use a color from the theme) and preferred size
* @param color Color to use (null will make it use the theme)
* @param size Preferred size
*/
public EmptySpace(TextColor color, TerminalSize size) {
this.color = color;
this.size = size;
}
/**
* Changes the color this component will use when drawn
* @param color New color to draw the component with, if {@code null} then the component will use the theme's
* default color
*/
public void setColor(TextColor color) {
this.color = color;
}
/**
* Returns the color this component is drawn with, or {@code null} if this component uses whatever the default color
* the theme is set to use
* @return Color used when drawing or {@code null} if it's using the theme
*/
public TextColor getColor() {
return color;
}
@Override
protected ComponentRenderer<EmptySpace> createDefaultRenderer() {<FILL_FUNCTION_BODY>}
}
|
return new ComponentRenderer<EmptySpace>() {
@Override
public TerminalSize getPreferredSize(EmptySpace component) {
return size;
}
@Override
public void drawComponent(TextGUIGraphics graphics, EmptySpace component) {
graphics.applyThemeStyle(component.getThemeDefinition().getNormal());
if(color != null) {
graphics.setBackgroundColor(color);
}
graphics.fill(' ');
}
};
| 501
| 122
| 623
|
<methods>public void <init>() ,public synchronized com.googlecode.lanterna.gui2.EmptySpace addTo(com.googlecode.lanterna.gui2.Panel) ,public final synchronized void draw(com.googlecode.lanterna.gui2.TextGUIGraphics) ,public com.googlecode.lanterna.gui2.BasePane getBasePane() ,public com.googlecode.lanterna.TerminalPosition getGlobalPosition() ,public com.googlecode.lanterna.gui2.LayoutData getLayoutData() ,public com.googlecode.lanterna.gui2.Container getParent() ,public com.googlecode.lanterna.TerminalPosition getPosition() ,public final com.googlecode.lanterna.TerminalSize getPreferredSize() ,public synchronized ComponentRenderer<com.googlecode.lanterna.gui2.EmptySpace> getRenderer() ,public com.googlecode.lanterna.TerminalSize getSize() ,public com.googlecode.lanterna.gui2.TextGUI getTextGUI() ,public synchronized com.googlecode.lanterna.graphics.Theme getTheme() ,public com.googlecode.lanterna.graphics.ThemeDefinition getThemeDefinition() ,public boolean hasParent(com.googlecode.lanterna.gui2.Container) ,public void invalidate() ,public boolean isInside(com.googlecode.lanterna.gui2.Container) ,public boolean isInvalid() ,public boolean isVisible() ,public synchronized void onAdded(com.googlecode.lanterna.gui2.Container) ,public synchronized void onRemoved(com.googlecode.lanterna.gui2.Container) ,public synchronized com.googlecode.lanterna.gui2.EmptySpace setLayoutData(com.googlecode.lanterna.gui2.LayoutData) ,public synchronized com.googlecode.lanterna.gui2.EmptySpace setPosition(com.googlecode.lanterna.TerminalPosition) ,public final synchronized com.googlecode.lanterna.gui2.EmptySpace setPreferredSize(com.googlecode.lanterna.TerminalSize) ,public com.googlecode.lanterna.gui2.EmptySpace setRenderer(ComponentRenderer<com.googlecode.lanterna.gui2.EmptySpace>) ,public synchronized com.googlecode.lanterna.gui2.EmptySpace setSize(com.googlecode.lanterna.TerminalSize) ,public synchronized com.googlecode.lanterna.gui2.Component setTheme(com.googlecode.lanterna.graphics.Theme) ,public com.googlecode.lanterna.gui2.EmptySpace setVisible(boolean) ,public com.googlecode.lanterna.TerminalPosition toBasePane(com.googlecode.lanterna.TerminalPosition) ,public com.googlecode.lanterna.TerminalPosition toGlobal(com.googlecode.lanterna.TerminalPosition) ,public synchronized com.googlecode.lanterna.gui2.Border withBorder(com.googlecode.lanterna.gui2.Border) <variables>private ComponentRenderer<com.googlecode.lanterna.gui2.EmptySpace> defaultRenderer,private com.googlecode.lanterna.TerminalSize explicitPreferredSize,private boolean invalid,private com.googlecode.lanterna.gui2.LayoutData layoutData,private ComponentRenderer<com.googlecode.lanterna.gui2.EmptySpace> overrideRenderer,private com.googlecode.lanterna.gui2.Container parent,private com.googlecode.lanterna.TerminalPosition position,private com.googlecode.lanterna.TerminalSize size,private com.googlecode.lanterna.graphics.Theme themeOverride,private ComponentRenderer<com.googlecode.lanterna.gui2.EmptySpace> themeRenderer,private com.googlecode.lanterna.graphics.Theme themeRenderersTheme,private boolean visible
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/FatWindowDecorationRenderer.java
|
FatWindowDecorationRenderer
|
draw
|
class FatWindowDecorationRenderer implements WindowDecorationRenderer {
@Override
public TextGUIGraphics draw(WindowBasedTextGUI textGUI, TextGUIGraphics graphics, Window window) {<FILL_FUNCTION_BODY>}
@Override
public TerminalSize getDecoratedSize(Window window, TerminalSize contentAreaSize) {
if(hasTitle(window)) {
return contentAreaSize
.withRelativeColumns(2)
.withRelativeRows(4)
.max(new TerminalSize(TerminalTextUtils.getColumnWidth(window.getTitle()) + 4, 1)); //Make sure the title fits!
}
else {
return contentAreaSize
.withRelativeColumns(2)
.withRelativeRows(2)
.max(new TerminalSize(3, 1));
}
}
private static final TerminalPosition OFFSET_WITH_TITLE = new TerminalPosition(1, 3);
private static final TerminalPosition OFFSET_WITHOUT_TITLE = new TerminalPosition(1, 1);
@Override
public TerminalPosition getOffset(Window window) {
if(hasTitle(window)) {
return OFFSET_WITH_TITLE;
}
else {
return OFFSET_WITHOUT_TITLE;
}
}
private boolean hasTitle(Window window) {
return !(window.getTitle() == null || window.getTitle().trim().isEmpty());
}
}
|
String title = window.getTitle();
if(title == null) {
title = "";
}
boolean hasTitle = !title.trim().isEmpty();
if(hasTitle) {
title = " " + title.trim() + " ";
}
ThemeDefinition themeDefinition = window.getTheme().getDefinition(FatWindowDecorationRenderer.class);
char horizontalLine = themeDefinition.getCharacter("HORIZONTAL_LINE", Symbols.SINGLE_LINE_HORIZONTAL);
char verticalLine = themeDefinition.getCharacter("VERTICAL_LINE", Symbols.SINGLE_LINE_VERTICAL);
char bottomLeftCorner = themeDefinition.getCharacter("BOTTOM_LEFT_CORNER", Symbols.SINGLE_LINE_BOTTOM_LEFT_CORNER);
char topLeftCorner = themeDefinition.getCharacter("TOP_LEFT_CORNER", Symbols.SINGLE_LINE_TOP_LEFT_CORNER);
char bottomRightCorner = themeDefinition.getCharacter("BOTTOM_RIGHT_CORNER", Symbols.SINGLE_LINE_BOTTOM_RIGHT_CORNER);
char topRightCorner = themeDefinition.getCharacter("TOP_RIGHT_CORNER", Symbols.SINGLE_LINE_TOP_RIGHT_CORNER);
char leftJunction = themeDefinition.getCharacter("LEFT_JUNCTION", Symbols.SINGLE_LINE_T_RIGHT);
char rightJunction = themeDefinition.getCharacter("RIGHT_JUNCTION", Symbols.SINGLE_LINE_T_LEFT);
TerminalSize drawableArea = graphics.getSize();
if(hasTitle) {
graphics.applyThemeStyle(themeDefinition.getPreLight());
graphics.drawLine(0, drawableArea.getRows() - 2, 0, 1, verticalLine);
graphics.drawLine(1, 0, drawableArea.getColumns() - 2, 0, horizontalLine);
graphics.drawLine(1, 2, drawableArea.getColumns() - 2, 2, horizontalLine);
graphics.setCharacter(0, 0, topLeftCorner);
graphics.setCharacter(0, 2, leftJunction);
graphics.setCharacter(0, drawableArea.getRows() - 1, bottomLeftCorner);
graphics.applyThemeStyle(themeDefinition.getNormal());
graphics.drawLine(
drawableArea.getColumns() - 1, 1,
drawableArea.getColumns() - 1, drawableArea.getRows() - 2,
verticalLine);
graphics.drawLine(
1, drawableArea.getRows() - 1,
drawableArea.getColumns() - 2, drawableArea.getRows() - 1,
horizontalLine);
graphics.setCharacter(drawableArea.getColumns() - 1, 0, topRightCorner);
graphics.setCharacter(drawableArea.getColumns() - 1, 2, rightJunction);
graphics.setCharacter(drawableArea.getColumns() - 1, drawableArea.getRows() - 1, bottomRightCorner);
graphics.applyThemeStyle(themeDefinition.getActive());
graphics.drawLine(1, 1, drawableArea.getColumns() - 2, 1, ' ');
graphics.putString(1, 1, TerminalTextUtils.fitString(title, drawableArea.getColumns() - 3));
return graphics.newTextGraphics(OFFSET_WITH_TITLE, graphics.getSize().withRelativeColumns(-2).withRelativeRows(-4));
}
else {
graphics.applyThemeStyle(themeDefinition.getPreLight());
graphics.drawLine(0, drawableArea.getRows() - 2, 0, 1, verticalLine);
graphics.drawLine(1, 0, drawableArea.getColumns() - 2, 0, horizontalLine);
graphics.setCharacter(0, 0, topLeftCorner);
graphics.setCharacter(0, drawableArea.getRows() - 1, bottomLeftCorner);
graphics.applyThemeStyle(themeDefinition.getNormal());
graphics.drawLine(
drawableArea.getColumns() - 1, 1,
drawableArea.getColumns() - 1, drawableArea.getRows() - 2,
verticalLine);
graphics.drawLine(
1, drawableArea.getRows() - 1,
drawableArea.getColumns() - 2, drawableArea.getRows() - 1,
horizontalLine);
graphics.setCharacter(drawableArea.getColumns() - 1, 0, topRightCorner);
graphics.setCharacter(drawableArea.getColumns() - 1, drawableArea.getRows() - 1, bottomRightCorner);
return graphics.newTextGraphics(OFFSET_WITHOUT_TITLE, graphics.getSize().withRelativeColumns(-2).withRelativeRows(-2));
}
| 367
| 1,247
| 1,614
|
<no_super_class>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/GUIBackdrop.java
|
GUIBackdrop
|
createDefaultRenderer
|
class GUIBackdrop extends EmptySpace {
@Override
protected ComponentRenderer<EmptySpace> createDefaultRenderer() {<FILL_FUNCTION_BODY>}
}
|
return new ComponentRenderer<EmptySpace>() {
@Override
public TerminalSize getPreferredSize(EmptySpace component) {
return TerminalSize.ONE;
}
@Override
public void drawComponent(TextGUIGraphics graphics, EmptySpace component) {
ThemeDefinition themeDefinition = component.getTheme().getDefinition(GUIBackdrop.class);
graphics.applyThemeStyle(themeDefinition.getNormal());
graphics.fill(themeDefinition.getCharacter("BACKGROUND", ' '));
}
};
| 42
| 134
| 176
|
<methods>public void <init>() ,public void <init>(com.googlecode.lanterna.TextColor) ,public void <init>(com.googlecode.lanterna.TerminalSize) ,public void <init>(com.googlecode.lanterna.TextColor, com.googlecode.lanterna.TerminalSize) ,public com.googlecode.lanterna.TextColor getColor() ,public void setColor(com.googlecode.lanterna.TextColor) <variables>private com.googlecode.lanterna.TextColor color,private final non-sealed com.googlecode.lanterna.TerminalSize size
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/LocalizedString.java
|
LocalizedString
|
toString
|
class LocalizedString {
/**
* "OK"
*/
public final static LocalizedString OK = new LocalizedString("short.label.ok", "OK");
/**
* "Cancel"
*/
public final static LocalizedString Cancel = new LocalizedString("short.label.cancel", "Cancel");
/**
* "Yes"
*/
public final static LocalizedString Yes = new LocalizedString("short.label.yes", "Yes");
/**
* "No"
*/
public final static LocalizedString No = new LocalizedString("short.label.no", "No");
/**
* "Close"
*/
public final static LocalizedString Close = new LocalizedString("short.label.close", "Close");
/**
* "Abort"
*/
public final static LocalizedString Abort = new LocalizedString("short.label.abort", "Abort");
/**
* "Ignore"
*/
public final static LocalizedString Ignore = new LocalizedString("short.label.ignore", "Ignore");
/**
* "Retry"
*/
public final static LocalizedString Retry = new LocalizedString("short.label.retry", "Retry");
/**
* "Continue"
*/
public final static LocalizedString Continue = new LocalizedString("short.label.continue", "Continue");
/**
* "Open"
*/
public final static LocalizedString Open = new LocalizedString("short.label.open", "Open");
/**
* "Save"
*/
public final static LocalizedString Save = new LocalizedString("short.label.save", "Save");
private final String defaultValue;
private final String bundleKey;
private LocalizedString(final String bundleKey, final String defaultValue) {
this.bundleKey = bundleKey;
this.defaultValue = defaultValue;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
String localizedString = LocalizedUIBundle.get(Locale.getDefault(), bundleKey);
if (localizedString == null) {
localizedString = defaultValue;
}
return localizedString;
| 502
| 53
| 555
|
<no_super_class>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/MenuPopupWindow.java
|
MenuPopupWindow
|
addMenuItem
|
class MenuPopupWindow extends AbstractWindow {
private final Panel menuItemPanel;
/**
* Creates a new popup window with a relative position to the component supplied.
* @param parent Component that this popup menu is triggered from
*/
public MenuPopupWindow(Component parent) {
setHints(Arrays.asList(Hint.MODAL, Hint.MENU_POPUP, Hint.FIXED_POSITION));
if (parent != null) {
TerminalPosition menuPositionGlobal = parent.toGlobal(TerminalPosition.TOP_LEFT_CORNER);
setPosition(menuPositionGlobal.withRelative(0, 1));
}
menuItemPanel = new Panel(new LinearLayout(Direction.VERTICAL));
setComponent(menuItemPanel);
}
/**
* Adds a new menu item to this popup window. The item will automatically be selected if it's the first one added.
* @param menuItem Menu item to add to the popup window.
*/
public void addMenuItem(MenuItem menuItem) {<FILL_FUNCTION_BODY>}
}
|
menuItemPanel.addComponent(menuItem);
menuItem.setLayoutData(LinearLayout.createLayoutData(LinearLayout.Alignment.FILL));
if (menuItemPanel.getChildCount() == 1) {
setFocusedInteractable(menuItem);
}
invalidate();
| 282
| 76
| 358
|
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void addWindowListener(com.googlecode.lanterna.gui2.WindowListener) ,public void close() ,public void draw(com.googlecode.lanterna.gui2.TextGUIGraphics) ,public com.googlecode.lanterna.TerminalPosition fromGlobal(com.googlecode.lanterna.TerminalPosition) ,public com.googlecode.lanterna.TerminalPosition fromGlobalToContentRelative(com.googlecode.lanterna.TerminalPosition) ,public com.googlecode.lanterna.TerminalPosition fromGlobalToDecoratedRelative(com.googlecode.lanterna.TerminalPosition) ,public final com.googlecode.lanterna.TerminalSize getDecoratedSize() ,public Set<com.googlecode.lanterna.gui2.Window.Hint> getHints() ,public final com.googlecode.lanterna.TerminalPosition getPosition() ,public com.googlecode.lanterna.gui2.WindowPostRenderer getPostRenderer() ,public com.googlecode.lanterna.TerminalSize getPreferredSize() ,public final com.googlecode.lanterna.TerminalSize getSize() ,public com.googlecode.lanterna.gui2.WindowBasedTextGUI getTextGUI() ,public java.lang.String getTitle() ,public boolean handleInput(com.googlecode.lanterna.input.KeyStroke) ,public boolean isVisible() ,public void removeWindowListener(com.googlecode.lanterna.gui2.WindowListener) ,public void setCloseWindowWithEscape(boolean) ,public void setContentOffset(com.googlecode.lanterna.TerminalPosition) ,public final void setDecoratedSize(com.googlecode.lanterna.TerminalSize) ,public void setFixedSize(com.googlecode.lanterna.TerminalSize) ,public void setHints(Collection<com.googlecode.lanterna.gui2.Window.Hint>) ,public final void setPosition(com.googlecode.lanterna.TerminalPosition) ,public void setSize(com.googlecode.lanterna.TerminalSize) ,public void setTextGUI(com.googlecode.lanterna.gui2.WindowBasedTextGUI) ,public void setTitle(java.lang.String) ,public void setVisible(boolean) ,public void setWindowPostRenderer(com.googlecode.lanterna.gui2.WindowPostRenderer) ,public com.googlecode.lanterna.TerminalPosition toGlobal(com.googlecode.lanterna.TerminalPosition) ,public com.googlecode.lanterna.TerminalPosition toGlobalFromContentRelative(com.googlecode.lanterna.TerminalPosition) ,public com.googlecode.lanterna.TerminalPosition toGlobalFromDecoratedRelative(com.googlecode.lanterna.TerminalPosition) ,public void waitUntilClosed() <variables>private boolean closeWindowWithEscape,private com.googlecode.lanterna.TerminalPosition contentOffset,private Set<com.googlecode.lanterna.gui2.Window.Hint> hints,private com.googlecode.lanterna.TerminalSize lastKnownDecoratedSize,private com.googlecode.lanterna.TerminalPosition lastKnownPosition,private com.googlecode.lanterna.TerminalSize lastKnownSize,private com.googlecode.lanterna.gui2.WindowBasedTextGUI textGUI,private java.lang.String title,private boolean visible,private com.googlecode.lanterna.gui2.WindowPostRenderer windowPostRenderer
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/Panel.java
|
DefaultPanelRenderer
|
nextFocus
|
class DefaultPanelRenderer implements ComponentRenderer<Panel> {
private boolean fillAreaBeforeDrawingComponents = true;
/**
* If setting this to {@code false} (default is {@code true}), the {@link Panel} will not reset it's drawable
* area with the space character ' ' before drawing all the components. Usually you <b>do</b> want to reset this
* area before drawing but you might have a custom renderer that has prepared the area already and just want the
* panel renderer to layout and draw the components in the panel without touching the existing content. One such
* example is the {@code FullScreenTextGUITest}.
* @param fillAreaBeforeDrawingComponents Should the panels area be cleared before drawing components?
*/
public void setFillAreaBeforeDrawingComponents(boolean fillAreaBeforeDrawingComponents) {
this.fillAreaBeforeDrawingComponents = fillAreaBeforeDrawingComponents;
}
@Override
public TerminalSize getPreferredSize(Panel component) {
synchronized(components) {
cachedPreferredSize = layoutManager.getPreferredSize(components);
}
return cachedPreferredSize;
}
@Override
public void drawComponent(TextGUIGraphics graphics, Panel panel) {
if(isInvalid()) {
layout(graphics.getSize());
}
if (fillAreaBeforeDrawingComponents) {
// Reset the area
graphics.applyThemeStyle(getThemeDefinition().getNormal());
if (fillColorOverride != null) {
graphics.setBackgroundColor(fillColorOverride);
}
graphics.fill(' ');
}
synchronized(components) {
for(Component child: components) {
if (!child.isVisible()) {
continue;
}
TextGUIGraphics componentGraphics = graphics.newTextGraphics(child.getPosition(), child.getSize());
child.draw(componentGraphics);
}
}
}
}
@Override
public TerminalSize calculatePreferredSize() {
if(cachedPreferredSize != null && !isInvalid()) {
return cachedPreferredSize;
}
return super.calculatePreferredSize();
}
@Override
public boolean isInvalid() {
synchronized(components) {
for(Component component: components) {
if(component.isVisible() && component.isInvalid()) {
return true;
}
}
}
return super.isInvalid() || layoutManager.hasChanged();
}
@Override
public Interactable nextFocus(Interactable fromThis) {<FILL_FUNCTION_BODY>
|
boolean chooseNextAvailable = (fromThis == null);
synchronized(components) {
for(Component component : components) {
if(!component.isVisible()) {
continue;
}
if(chooseNextAvailable) {
if(component instanceof Interactable && ((Interactable) component).isEnabled() && ((Interactable) component).isFocusable()) {
return (Interactable) component;
}
else if(component instanceof Container) {
Interactable firstInteractable = ((Container) (component)).nextFocus(null);
if(firstInteractable != null) {
return firstInteractable;
}
}
continue;
}
if(component == fromThis) {
chooseNextAvailable = true;
continue;
}
if(component instanceof Container) {
Container container = (Container) component;
if(fromThis.isInside(container)) {
Interactable next = container.nextFocus(fromThis);
if(next == null) {
chooseNextAvailable = true;
}
else {
return next;
}
}
}
}
return null;
}
| 647
| 299
| 946
|
<methods>public void <init>() ,public synchronized com.googlecode.lanterna.gui2.Panel addTo(com.googlecode.lanterna.gui2.Panel) ,public final synchronized void draw(com.googlecode.lanterna.gui2.TextGUIGraphics) ,public com.googlecode.lanterna.gui2.BasePane getBasePane() ,public com.googlecode.lanterna.TerminalPosition getGlobalPosition() ,public com.googlecode.lanterna.gui2.LayoutData getLayoutData() ,public com.googlecode.lanterna.gui2.Container getParent() ,public com.googlecode.lanterna.TerminalPosition getPosition() ,public final com.googlecode.lanterna.TerminalSize getPreferredSize() ,public synchronized ComponentRenderer<com.googlecode.lanterna.gui2.Panel> getRenderer() ,public com.googlecode.lanterna.TerminalSize getSize() ,public com.googlecode.lanterna.gui2.TextGUI getTextGUI() ,public synchronized com.googlecode.lanterna.graphics.Theme getTheme() ,public com.googlecode.lanterna.graphics.ThemeDefinition getThemeDefinition() ,public boolean hasParent(com.googlecode.lanterna.gui2.Container) ,public void invalidate() ,public boolean isInside(com.googlecode.lanterna.gui2.Container) ,public boolean isInvalid() ,public boolean isVisible() ,public synchronized void onAdded(com.googlecode.lanterna.gui2.Container) ,public synchronized void onRemoved(com.googlecode.lanterna.gui2.Container) ,public synchronized com.googlecode.lanterna.gui2.Panel setLayoutData(com.googlecode.lanterna.gui2.LayoutData) ,public synchronized com.googlecode.lanterna.gui2.Panel setPosition(com.googlecode.lanterna.TerminalPosition) ,public final synchronized com.googlecode.lanterna.gui2.Panel setPreferredSize(com.googlecode.lanterna.TerminalSize) ,public com.googlecode.lanterna.gui2.Panel setRenderer(ComponentRenderer<com.googlecode.lanterna.gui2.Panel>) ,public synchronized com.googlecode.lanterna.gui2.Panel setSize(com.googlecode.lanterna.TerminalSize) ,public synchronized com.googlecode.lanterna.gui2.Component setTheme(com.googlecode.lanterna.graphics.Theme) ,public com.googlecode.lanterna.gui2.Panel setVisible(boolean) ,public com.googlecode.lanterna.TerminalPosition toBasePane(com.googlecode.lanterna.TerminalPosition) ,public com.googlecode.lanterna.TerminalPosition toGlobal(com.googlecode.lanterna.TerminalPosition) ,public synchronized com.googlecode.lanterna.gui2.Border withBorder(com.googlecode.lanterna.gui2.Border) <variables>private ComponentRenderer<com.googlecode.lanterna.gui2.Panel> defaultRenderer,private com.googlecode.lanterna.TerminalSize explicitPreferredSize,private boolean invalid,private com.googlecode.lanterna.gui2.LayoutData layoutData,private ComponentRenderer<com.googlecode.lanterna.gui2.Panel> overrideRenderer,private com.googlecode.lanterna.gui2.Container parent,private com.googlecode.lanterna.TerminalPosition position,private com.googlecode.lanterna.TerminalSize size,private com.googlecode.lanterna.graphics.Theme themeOverride,private ComponentRenderer<com.googlecode.lanterna.gui2.Panel> themeRenderer,private com.googlecode.lanterna.graphics.Theme themeRenderersTheme,private boolean visible
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/Panels.java
|
Panels
|
grid
|
class Panels {
/**
* Creates a new {@code Panel} with a {@code LinearLayout} layout manager in horizontal mode and adds all the
* components passed in
* @param components Components to be added to the new {@code Panel}, in order
* @return The new {@code Panel}
*/
public static Panel horizontal(Component... components) {
Panel panel = new Panel();
panel.setLayoutManager(new LinearLayout(Direction.HORIZONTAL));
for(Component component: components) {
panel.addComponent(component);
}
return panel;
}
/**
* Creates a new {@code Panel} with a {@code LinearLayout} layout manager in vertical mode and adds all the
* components passed in
* @param components Components to be added to the new {@code Panel}, in order
* @return The new {@code Panel}
*/
public static Panel vertical(Component... components) {
Panel panel = new Panel();
panel.setLayoutManager(new LinearLayout(Direction.VERTICAL));
for(Component component: components) {
panel.addComponent(component);
}
return panel;
}
/**
* Creates a new {@code Panel} with a {@code GridLayout} layout manager and adds all the components passed in
* @param columns Number of columns in the grid
* @param components Components to be added to the new {@code Panel}, in order
* @return The new {@code Panel}
*/
public static Panel grid(int columns, Component... components) {<FILL_FUNCTION_BODY>}
//Cannot instantiate
private Panels() {}
}
|
Panel panel = new Panel();
panel.setLayoutManager(new GridLayout(columns));
for(Component component: components) {
panel.addComponent(component);
}
return panel;
| 409
| 52
| 461
|
<no_super_class>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/ProgressBar.java
|
LargeProgressBarRenderer
|
drawComponent
|
class LargeProgressBarRenderer implements ComponentRenderer<ProgressBar> {
@Override
public TerminalSize getPreferredSize(ProgressBar component) {
int preferredWidth = component.getPreferredWidth();
if(preferredWidth > 0) {
return new TerminalSize(preferredWidth, 3);
}
else {
return new TerminalSize(42, 3);
}
}
@Override
public void drawComponent(TextGUIGraphics graphics, ProgressBar component) {<FILL_FUNCTION_BODY>}
}
|
TerminalSize size = graphics.getSize();
if(size.getRows() == 0 || size.getColumns() == 0) {
return;
}
ThemeDefinition themeDefinition = component.getThemeDefinition();
int columnOfProgress = (int)(component.getProgress() * (size.getColumns() - 4));
int mark25 = -1;
int mark50 = -1;
int mark75 = -1;
if(size.getColumns() > 9) {
mark50 = (size.getColumns() - 2) / 2;
}
if(size.getColumns() > 16) {
mark25 = (size.getColumns() - 2) / 4;
mark75 = mark50 + mark25;
}
// Draw header, if there are at least 3 rows available
int rowOffset = 0;
if(size.getRows() >= 3) {
graphics.applyThemeStyle(themeDefinition.getNormal());
graphics.drawLine(0, 0, size.getColumns(), 0, ' ');
if(size.getColumns() > 1) {
graphics.setCharacter(1, 0, '0');
}
if(mark25 != -1) {
if(component.getProgress() < 0.25f) {
graphics.applyThemeStyle(themeDefinition.getInsensitive());
}
graphics.putString(1 + mark25, 0, "25");
}
if(mark50 != -1) {
if(component.getProgress() < 0.50f) {
graphics.applyThemeStyle(themeDefinition.getInsensitive());
}
graphics.putString(1 + mark50, 0, "50");
}
if(mark75 != -1) {
if(component.getProgress() < 0.75f) {
graphics.applyThemeStyle(themeDefinition.getInsensitive());
}
graphics.putString(1 + mark75, 0, "75");
}
if(size.getColumns() >= 7) {
if(component.getProgress() < 1.0f) {
graphics.applyThemeStyle(themeDefinition.getInsensitive());
}
graphics.putString(size.getColumns() - 3, 0, "100");
}
rowOffset++;
}
// Draw the main indicator
for(int i = 0; i < Math.max(1, size.getRows() - 2); i++) {
graphics.applyThemeStyle(themeDefinition.getNormal());
graphics.drawLine(0, rowOffset, size.getColumns(), rowOffset, ' ');
if (size.getColumns() > 2) {
graphics.setCharacter(1, rowOffset, Symbols.SINGLE_LINE_VERTICAL);
}
if (size.getColumns() > 3) {
graphics.setCharacter(size.getColumns() - 2, rowOffset, Symbols.SINGLE_LINE_VERTICAL);
}
if (size.getColumns() > 4) {
graphics.applyThemeStyle(themeDefinition.getActive());
for(int columnOffset = 2; columnOffset < size.getColumns() - 2; columnOffset++) {
if(columnOfProgress + 2 == columnOffset) {
graphics.applyThemeStyle(themeDefinition.getNormal());
}
if(mark25 == columnOffset - 1) {
graphics.setCharacter(columnOffset, rowOffset, Symbols.SINGLE_LINE_VERTICAL);
}
else if(mark50 == columnOffset - 1) {
graphics.setCharacter(columnOffset, rowOffset, Symbols.SINGLE_LINE_VERTICAL);
}
else if(mark75 == columnOffset - 1) {
graphics.setCharacter(columnOffset, rowOffset, Symbols.SINGLE_LINE_VERTICAL);
}
else {
graphics.setCharacter(columnOffset, rowOffset, ' ');
}
}
}
if(((int)(component.getProgress() * ((size.getColumns() - 4) * 2))) % 2 == 1) {
graphics.applyThemeStyle(themeDefinition.getPreLight());
graphics.setCharacter(columnOfProgress + 2, rowOffset, '|');
}
rowOffset++;
}
// Draw footer if there are at least 2 rows, this one is easy
if(size.getRows() >= 2) {
graphics.applyThemeStyle(themeDefinition.getNormal());
graphics.drawLine(0, rowOffset, size.getColumns(), rowOffset, Symbols.SINGLE_LINE_T_UP);
graphics.setCharacter(0, rowOffset, ' ');
if (size.getColumns() > 1) {
graphics.setCharacter(size.getColumns() - 1, rowOffset, ' ');
}
if (size.getColumns() > 2) {
graphics.setCharacter(1, rowOffset, Symbols.SINGLE_LINE_BOTTOM_LEFT_CORNER);
}
if (size.getColumns() > 3) {
graphics.setCharacter(size.getColumns() - 2, rowOffset, Symbols.SINGLE_LINE_BOTTOM_RIGHT_CORNER);
}
}
| 136
| 1,334
| 1,470
|
<methods>public void <init>() ,public synchronized com.googlecode.lanterna.gui2.ProgressBar addTo(com.googlecode.lanterna.gui2.Panel) ,public final synchronized void draw(com.googlecode.lanterna.gui2.TextGUIGraphics) ,public com.googlecode.lanterna.gui2.BasePane getBasePane() ,public com.googlecode.lanterna.TerminalPosition getGlobalPosition() ,public com.googlecode.lanterna.gui2.LayoutData getLayoutData() ,public com.googlecode.lanterna.gui2.Container getParent() ,public com.googlecode.lanterna.TerminalPosition getPosition() ,public final com.googlecode.lanterna.TerminalSize getPreferredSize() ,public synchronized ComponentRenderer<com.googlecode.lanterna.gui2.ProgressBar> getRenderer() ,public com.googlecode.lanterna.TerminalSize getSize() ,public com.googlecode.lanterna.gui2.TextGUI getTextGUI() ,public synchronized com.googlecode.lanterna.graphics.Theme getTheme() ,public com.googlecode.lanterna.graphics.ThemeDefinition getThemeDefinition() ,public boolean hasParent(com.googlecode.lanterna.gui2.Container) ,public void invalidate() ,public boolean isInside(com.googlecode.lanterna.gui2.Container) ,public boolean isInvalid() ,public boolean isVisible() ,public synchronized void onAdded(com.googlecode.lanterna.gui2.Container) ,public synchronized void onRemoved(com.googlecode.lanterna.gui2.Container) ,public synchronized com.googlecode.lanterna.gui2.ProgressBar setLayoutData(com.googlecode.lanterna.gui2.LayoutData) ,public synchronized com.googlecode.lanterna.gui2.ProgressBar setPosition(com.googlecode.lanterna.TerminalPosition) ,public final synchronized com.googlecode.lanterna.gui2.ProgressBar setPreferredSize(com.googlecode.lanterna.TerminalSize) ,public com.googlecode.lanterna.gui2.ProgressBar setRenderer(ComponentRenderer<com.googlecode.lanterna.gui2.ProgressBar>) ,public synchronized com.googlecode.lanterna.gui2.ProgressBar setSize(com.googlecode.lanterna.TerminalSize) ,public synchronized com.googlecode.lanterna.gui2.Component setTheme(com.googlecode.lanterna.graphics.Theme) ,public com.googlecode.lanterna.gui2.ProgressBar setVisible(boolean) ,public com.googlecode.lanterna.TerminalPosition toBasePane(com.googlecode.lanterna.TerminalPosition) ,public com.googlecode.lanterna.TerminalPosition toGlobal(com.googlecode.lanterna.TerminalPosition) ,public synchronized com.googlecode.lanterna.gui2.Border withBorder(com.googlecode.lanterna.gui2.Border) <variables>private ComponentRenderer<com.googlecode.lanterna.gui2.ProgressBar> defaultRenderer,private com.googlecode.lanterna.TerminalSize explicitPreferredSize,private boolean invalid,private com.googlecode.lanterna.gui2.LayoutData layoutData,private ComponentRenderer<com.googlecode.lanterna.gui2.ProgressBar> overrideRenderer,private com.googlecode.lanterna.gui2.Container parent,private com.googlecode.lanterna.TerminalPosition position,private com.googlecode.lanterna.TerminalSize size,private com.googlecode.lanterna.graphics.Theme themeOverride,private ComponentRenderer<com.googlecode.lanterna.gui2.ProgressBar> themeRenderer,private com.googlecode.lanterna.graphics.Theme themeRenderersTheme,private boolean visible
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/RadioBoxList.java
|
RadioBoxListItemRenderer
|
drawItem
|
class RadioBoxListItemRenderer<V> extends ListItemRenderer<V,RadioBoxList<V>> {
@Override
public int getHotSpotPositionOnLine(int selectedIndex) {
return 1;
}
protected String getItemText(RadioBoxList<V> listBox, int index, V item) {
return (item != null ? item : "<null>").toString();
}
@Override
public String getLabel(RadioBoxList<V> listBox, int index, V item) {
String check = " ";
if(listBox.checkedIndex == index)
check = "o";
String text = getItemText(listBox, index, item);
return "<" + check + "> " + text;
}
@Override
public void drawItem(TextGUIGraphics graphics, RadioBoxList<V> listBox, int index, V item, boolean selected, boolean focused) {<FILL_FUNCTION_BODY>}
}
|
ThemeDefinition themeDefinition = listBox.getTheme().getDefinition(RadioBoxList.class);
ThemeStyle itemStyle;
if(selected && !focused) {
itemStyle = themeDefinition.getSelected();
}
else if(selected) {
itemStyle = themeDefinition.getActive();
}
else if(focused) {
itemStyle = themeDefinition.getInsensitive();
}
else {
itemStyle = themeDefinition.getNormal();
}
if(themeDefinition.getBooleanProperty("CLEAR_WITH_NORMAL", false)) {
graphics.applyThemeStyle(themeDefinition.getNormal());
graphics.fill(' ');
graphics.applyThemeStyle(itemStyle);
}
else {
graphics.applyThemeStyle(itemStyle);
graphics.fill(' ');
}
String brackets = themeDefinition.getCharacter("LEFT_BRACKET", '<') +
" " +
themeDefinition.getCharacter("RIGHT_BRACKET", '>');
if(themeDefinition.getBooleanProperty("FIXED_BRACKET_COLOR", false)) {
graphics.applyThemeStyle(themeDefinition.getPreLight());
graphics.putString(0, 0, brackets);
graphics.applyThemeStyle(itemStyle);
}
else {
graphics.putString(0, 0, brackets);
}
String text = getItemText(listBox, index, item);
graphics.putString(4, 0, text);
boolean itemChecked = listBox.checkedIndex == index;
char marker = themeDefinition.getCharacter("MARKER", 'o');
if(themeDefinition.getBooleanProperty("MARKER_WITH_NORMAL", false)) {
graphics.applyThemeStyle(themeDefinition.getNormal());
}
if(selected && focused && themeDefinition.getBooleanProperty("HOTSPOT_PRELIGHT", false)) {
graphics.applyThemeStyle(themeDefinition.getPreLight());
}
graphics.setCharacter(1, 0, (itemChecked ? marker : ' '));
| 249
| 520
| 769
|
<methods>public synchronized RadioBoxList<V> addItem(V) ,public synchronized RadioBoxList<V> clearItems() ,public synchronized V getItemAt(int) ,public synchronized int getItemCount() ,public synchronized List<V> getItems() ,public int getSelectedIndex() ,public synchronized V getSelectedItem() ,public synchronized com.googlecode.lanterna.gui2.Interactable.Result handleKeyStroke(com.googlecode.lanterna.input.KeyStroke) ,public synchronized int indexOf(V) ,public synchronized boolean isEmpty() ,public boolean isFocusable() ,public synchronized V removeItem(int) ,public synchronized RadioBoxList<V> setListItemRenderer(ListItemRenderer<V,RadioBoxList<V>>) ,public synchronized RadioBoxList<V> setSelectedIndex(int) <variables>private final non-sealed List<V> items,private ListItemRenderer<V,RadioBoxList<V>> listItemRenderer,protected com.googlecode.lanterna.TerminalPosition scrollOffset,private int selectedIndex
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/SeparateTextGUIThread.java
|
SeparateTextGUIThread
|
mainGUILoop
|
class SeparateTextGUIThread extends AbstractTextGUIThread implements AsynchronousTextGUIThread {
private volatile State state;
private final Thread textGUIThread;
private final CountDownLatch waitLatch;
private SeparateTextGUIThread(TextGUI textGUI) {
super(textGUI);
this.waitLatch = new CountDownLatch(1);
this.textGUIThread = new Thread("LanternaGUI") {
@Override
public void run() {
mainGUILoop();
}
};
state = State.CREATED;
}
@Override
public void start() {
textGUIThread.start();
state = State.STARTED;
}
@Override
public void stop() {
if(state != State.STARTED) {
return;
}
state = State.STOPPING;
}
@Override
public void waitForStop() throws InterruptedException {
waitLatch.await();
}
@Override
public void waitForStop(long time, TimeUnit unit) throws InterruptedException {
waitLatch.await(time, unit);
}
@Override
public State getState() {
return state;
}
@Override
public Thread getThread() {
return textGUIThread;
}
@Override
public void invokeLater(Runnable runnable) throws IllegalStateException {
if(state != State.STARTED) {
throw new IllegalStateException("Cannot schedule " + runnable + " for execution on the TextGUIThread " +
"because the thread is in " + state + " state");
}
super.invokeLater(runnable);
}
private void mainGUILoop() {<FILL_FUNCTION_BODY>}
/**
* Factory class for creating SeparateTextGUIThread objects
*/
public static class Factory implements TextGUIThreadFactory {
@Override
public TextGUIThread createTextGUIThread(TextGUI textGUI) {
return new SeparateTextGUIThread(textGUI);
}
}
}
|
try {
//Draw initial screen, after this only draw when the GUI is marked as invalid
try {
textGUI.updateScreen();
}
catch(IOException e) {
exceptionHandler.onIOException(e);
}
catch(RuntimeException e) {
exceptionHandler.onRuntimeException(e);
}
while(state == State.STARTED) {
try {
if (!processEventsAndUpdate()) {
try {
Thread.sleep(1);
}
catch(InterruptedException ignored) {}
}
}
catch(EOFException e) {
stop();
if (textGUI instanceof WindowBasedTextGUI) {
// Close all windows on EOF
for (Window window: ((WindowBasedTextGUI) textGUI).getWindows()) {
window.close();
}
}
break; //Break out quickly from the main loop
}
catch(IOException e) {
if(exceptionHandler.onIOException(e)) {
stop();
break;
}
}
catch(RuntimeException e) {
if(exceptionHandler.onRuntimeException(e)) {
stop();
break;
}
}
}
}
finally {
state = State.STOPPED;
waitLatch.countDown();
}
| 558
| 334
| 892
|
<methods>public void <init>(com.googlecode.lanterna.gui2.TextGUI) ,public void invokeAndWait(java.lang.Runnable) throws java.lang.IllegalStateException, java.lang.InterruptedException,public void invokeLater(java.lang.Runnable) throws java.lang.IllegalStateException,public synchronized boolean processEventsAndUpdate() throws java.io.IOException,public void setExceptionHandler(com.googlecode.lanterna.gui2.TextGUIThread.ExceptionHandler) <variables>protected final non-sealed Queue<java.lang.Runnable> customTasks,protected com.googlecode.lanterna.gui2.TextGUIThread.ExceptionHandler exceptionHandler,protected final non-sealed com.googlecode.lanterna.gui2.TextGUI textGUI
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/Separator.java
|
DefaultSeparatorRenderer
|
drawComponent
|
class DefaultSeparatorRenderer extends SeparatorRenderer {
@Override
public TerminalSize getPreferredSize(Separator component) {
return TerminalSize.ONE;
}
@Override
public void drawComponent(TextGUIGraphics graphics, Separator component) {<FILL_FUNCTION_BODY>}
}
|
ThemeDefinition themeDefinition = component.getThemeDefinition();
graphics.applyThemeStyle(themeDefinition.getNormal());
char character = themeDefinition.getCharacter(component.getDirection().name().toUpperCase(),
component.getDirection() == Direction.HORIZONTAL ? Symbols.SINGLE_LINE_HORIZONTAL : Symbols.SINGLE_LINE_VERTICAL);
graphics.fill(character);
| 82
| 107
| 189
|
<methods>public void <init>() ,public synchronized com.googlecode.lanterna.gui2.Separator addTo(com.googlecode.lanterna.gui2.Panel) ,public final synchronized void draw(com.googlecode.lanterna.gui2.TextGUIGraphics) ,public com.googlecode.lanterna.gui2.BasePane getBasePane() ,public com.googlecode.lanterna.TerminalPosition getGlobalPosition() ,public com.googlecode.lanterna.gui2.LayoutData getLayoutData() ,public com.googlecode.lanterna.gui2.Container getParent() ,public com.googlecode.lanterna.TerminalPosition getPosition() ,public final com.googlecode.lanterna.TerminalSize getPreferredSize() ,public synchronized ComponentRenderer<com.googlecode.lanterna.gui2.Separator> getRenderer() ,public com.googlecode.lanterna.TerminalSize getSize() ,public com.googlecode.lanterna.gui2.TextGUI getTextGUI() ,public synchronized com.googlecode.lanterna.graphics.Theme getTheme() ,public com.googlecode.lanterna.graphics.ThemeDefinition getThemeDefinition() ,public boolean hasParent(com.googlecode.lanterna.gui2.Container) ,public void invalidate() ,public boolean isInside(com.googlecode.lanterna.gui2.Container) ,public boolean isInvalid() ,public boolean isVisible() ,public synchronized void onAdded(com.googlecode.lanterna.gui2.Container) ,public synchronized void onRemoved(com.googlecode.lanterna.gui2.Container) ,public synchronized com.googlecode.lanterna.gui2.Separator setLayoutData(com.googlecode.lanterna.gui2.LayoutData) ,public synchronized com.googlecode.lanterna.gui2.Separator setPosition(com.googlecode.lanterna.TerminalPosition) ,public final synchronized com.googlecode.lanterna.gui2.Separator setPreferredSize(com.googlecode.lanterna.TerminalSize) ,public com.googlecode.lanterna.gui2.Separator setRenderer(ComponentRenderer<com.googlecode.lanterna.gui2.Separator>) ,public synchronized com.googlecode.lanterna.gui2.Separator setSize(com.googlecode.lanterna.TerminalSize) ,public synchronized com.googlecode.lanterna.gui2.Component setTheme(com.googlecode.lanterna.graphics.Theme) ,public com.googlecode.lanterna.gui2.Separator setVisible(boolean) ,public com.googlecode.lanterna.TerminalPosition toBasePane(com.googlecode.lanterna.TerminalPosition) ,public com.googlecode.lanterna.TerminalPosition toGlobal(com.googlecode.lanterna.TerminalPosition) ,public synchronized com.googlecode.lanterna.gui2.Border withBorder(com.googlecode.lanterna.gui2.Border) <variables>private ComponentRenderer<com.googlecode.lanterna.gui2.Separator> defaultRenderer,private com.googlecode.lanterna.TerminalSize explicitPreferredSize,private boolean invalid,private com.googlecode.lanterna.gui2.LayoutData layoutData,private ComponentRenderer<com.googlecode.lanterna.gui2.Separator> overrideRenderer,private com.googlecode.lanterna.gui2.Container parent,private com.googlecode.lanterna.TerminalPosition position,private com.googlecode.lanterna.TerminalSize size,private com.googlecode.lanterna.graphics.Theme themeOverride,private ComponentRenderer<com.googlecode.lanterna.gui2.Separator> themeRenderer,private com.googlecode.lanterna.graphics.Theme themeRenderersTheme,private boolean visible
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/SplitPanel.java
|
ScrollPanelLayoutManager
|
doLayout
|
class ScrollPanelLayoutManager implements LayoutManager {
boolean hasChanged;
public ScrollPanelLayoutManager() {
hasChanged = true;
}
@Override
public TerminalSize getPreferredSize(List<Component> components) {
TerminalSize sizeA = compA.getPreferredSize();
int aWidth = sizeA.getColumns();
int aHeight = sizeA.getRows();
TerminalSize sizeB = compB.getPreferredSize();
int bWidth = sizeB.getColumns();
int bHeight = sizeB.getRows();
int tWidth = thumb.getPreferredSize().getColumns();
int tHeight = thumb.getPreferredSize().getRows();
if (isHorizontal) {
return new TerminalSize(aWidth + tWidth + bWidth, Math.max(aHeight, Math.max(tHeight, bHeight)));
} else {
return new TerminalSize(Math.max(aWidth, Math.max(tWidth, bWidth)), aHeight + tHeight + bHeight);
}
}
@Override
public void doLayout(TerminalSize area, List<Component> components) {<FILL_FUNCTION_BODY>}
@Override
public boolean hasChanged() {
return hasChanged;
}
}
|
TerminalSize size = getSize();
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// TODO: themed
int length = isHorizontal ? size.getRows() : size.getColumns();
TerminalSize tsize = new TerminalSize(isHorizontal ? 1 : length, !isHorizontal ? 1 : length);
TextImage textImage = new BasicTextImage(tsize);
Theme theme = getTheme();
ThemeDefinition themeDefinition = theme.getDefaultDefinition();
ThemeStyle themeStyle = themeDefinition.getNormal();
TextCharacter thumbRenderer = TextCharacter.fromCharacter(
isHorizontal ? Symbols.SINGLE_LINE_VERTICAL : Symbols.SINGLE_LINE_HORIZONTAL,
themeStyle.getForeground(),
themeStyle.getBackground());
if (thumb.isFocused()) {
thumbRenderer = thumbRenderer.withModifier(SGR.BOLD);
}
textImage.setAll(thumbRenderer);
thumb.setTextImage(textImage);
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
int tWidth = thumb.getPreferredSize().getColumns();
int tHeight = thumb.getPreferredSize().getRows();
int w = size.getColumns();
int h = size.getRows();
if (isHorizontal) {
w -= tWidth;
} else {
h -= tHeight;
}
TerminalSize compAPrevSize = compA.getSize();
TerminalSize compBPrevSize = compB.getSize();
TerminalSize thumbPrevSize = thumb.getSize();
TerminalPosition compAPrevPos = compA.getPosition();
TerminalPosition compBPrevPos = compB.getPosition();
TerminalPosition thumbPrevPos = thumb.getPosition();
if (isHorizontal) {
int leftWidth = Math.max(0, (int) (w * ratio));
int leftHeight = Math.max(0, Math.min(compA.getPreferredSize().getRows(), h));
int rightWidth = Math.max(0, w - leftWidth);
int rightHeight = Math.max(0, Math.min(compB.getPreferredSize().getRows(), h));
compA.setSize(new TerminalSize(leftWidth, leftHeight));
thumb.setSize(thumb.getPreferredSize());
compB.setSize(new TerminalSize(rightWidth, rightHeight));
compA.setPosition(new TerminalPosition(0, 0));
thumb.setPosition(new TerminalPosition(leftWidth, h / 2 - tHeight / 2));
compB.setPosition(new TerminalPosition(leftWidth + tWidth, 0));
} else {
int leftWidth = Math.max(0, Math.min(compA.getPreferredSize().getColumns(), w));
int leftHeight = Math.max(0, (int) (h * ratio));
int rightWidth = Math.max(0, Math.min(compB.getPreferredSize().getColumns(), w));
int rightHeight = Math.max(0, h - leftHeight);
compA.setSize(new TerminalSize(leftWidth, leftHeight));
thumb.setSize(thumb.getPreferredSize());
compB.setSize(new TerminalSize(rightWidth, rightHeight));
compA.setPosition(new TerminalPosition(0, 0));
thumb.setPosition(new TerminalPosition(w / 2 - tWidth / 2, leftHeight));
compB.setPosition(new TerminalPosition(0, leftHeight + tHeight));
}
hasChanged = !compAPrevPos.equals(compA.getPosition()) ||
!compAPrevSize.equals(compA.getSize()) ||
!compBPrevPos.equals(compB.getPosition()) ||
!compBPrevSize.equals(compB.getSize()) ||
!thumbPrevPos.equals(thumb.getPosition()) ||
!thumbPrevSize.equals(thumb.getSize());
| 322
| 982
| 1,304
|
<methods>public void <init>() ,public void <init>(com.googlecode.lanterna.gui2.LayoutManager) ,public com.googlecode.lanterna.gui2.Panel addComponent(com.googlecode.lanterna.gui2.Component) ,public com.googlecode.lanterna.gui2.Panel addComponent(int, com.googlecode.lanterna.gui2.Component) ,public com.googlecode.lanterna.gui2.Panel addComponent(com.googlecode.lanterna.gui2.Component, com.googlecode.lanterna.gui2.LayoutData) ,public com.googlecode.lanterna.TerminalSize calculatePreferredSize() ,public boolean containsComponent(com.googlecode.lanterna.gui2.Component) ,public int getChildCount() ,public Collection<com.googlecode.lanterna.gui2.Component> getChildren() ,public List<com.googlecode.lanterna.gui2.Component> getChildrenList() ,public com.googlecode.lanterna.TextColor getFillColorOverride() ,public com.googlecode.lanterna.gui2.LayoutManager getLayoutManager() ,public boolean handleInput(com.googlecode.lanterna.input.KeyStroke) ,public void invalidate() ,public boolean isInvalid() ,public com.googlecode.lanterna.gui2.Interactable nextFocus(com.googlecode.lanterna.gui2.Interactable) ,public com.googlecode.lanterna.gui2.Interactable previousFocus(com.googlecode.lanterna.gui2.Interactable) ,public com.googlecode.lanterna.gui2.Panel removeAllComponents() ,public boolean removeComponent(com.googlecode.lanterna.gui2.Component) ,public void setFillColorOverride(com.googlecode.lanterna.TextColor) ,public synchronized com.googlecode.lanterna.gui2.Panel setLayoutManager(com.googlecode.lanterna.gui2.LayoutManager) ,public void updateLookupMap(com.googlecode.lanterna.gui2.InteractableLookupMap) <variables>private com.googlecode.lanterna.TerminalSize cachedPreferredSize,private final non-sealed List<com.googlecode.lanterna.gui2.Component> components,private com.googlecode.lanterna.TextColor fillColorOverride,private com.googlecode.lanterna.gui2.LayoutManager layoutManager
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/WindowList.java
|
WindowList
|
removeWindow
|
class WindowList {
private final List<Window> windows = new LinkedList<>();
private final List<Window> stableOrderingOfWindows = new ArrayList<>();
private Window activeWindow = null;
private boolean hadWindowAtSomePoint = false;
public List<Window> getWindowsInZOrder() {
return Collections.unmodifiableList(windows);
}
public List<Window> getWindowsInStableOrder() {
return Collections.unmodifiableList(stableOrderingOfWindows);
}
public void setActiveWindow(Window activeWindow) {
this.activeWindow = activeWindow;
if (activeWindow != null) {
moveToTop(activeWindow);
}
}
public Window getActiveWindow() {
return activeWindow;
}
public void addWindow(Window window) {
if (!stableOrderingOfWindows.contains(window)) {
stableOrderingOfWindows.add(window);
}
if(!windows.contains(window)) {
windows.add(window);
}
if(!window.getHints().contains(Window.Hint.NO_FOCUS)) {
setActiveWindow(window);
}
hadWindowAtSomePoint = true;
}
/**
* Removes the window from this WindowList.
* @return true if this WindowList contained the specified Window
*/
public boolean removeWindow(Window window) {<FILL_FUNCTION_BODY>}
public boolean isHadWindowAtSomePoint() {
return hadWindowAtSomePoint;
}
public void moveToTop(Window window) {
if(!windows.contains(window)) {
throw new IllegalArgumentException("Window " + window + " isn't in MultiWindowTextGUI " + this);
}
windows.remove(window);
windows.add(window);
}
public void moveToBottom(Window window) {
if(!windows.contains(window)) {
throw new IllegalArgumentException("Window " + window + " isn't in MultiWindowTextGUI " + this);
}
windows.remove(window);
windows.add(0, window);
}
/**
* Switches the active window by cyclically shuffling the window list. If {@code reverse} parameter is {@code false}
* then the current top window is placed at the bottom of the stack and the window immediately behind it is the new
* top. If {@code reverse} is set to {@code true} then the window at the bottom of the stack is moved up to the
* front and the previous top window will be immediately below it
* @param reverse Direction to cycle through the windows
*/
public WindowList cycleActiveWindow(boolean reverse) {
if(windows.isEmpty() || windows.size() == 1 || (activeWindow != null && activeWindow.getHints().contains(Window.Hint.MODAL))) {
return this;
}
Window originalActiveWindow = activeWindow;
Window nextWindow;
if(activeWindow == null) {
// Cycling out of active background pane
nextWindow = reverse ? windows.get(windows.size() - 1) : windows.get(0);
} else {
// Switch to the next window
nextWindow = getNextWindow(reverse, activeWindow);
}
int noFocusWindows = 0;
while(nextWindow.getHints().contains(Window.Hint.NO_FOCUS)) {
++noFocusWindows;
if(noFocusWindows == windows.size()) {
// All windows are NO_FOCUS, so give up
return this;
}
nextWindow = getNextWindow(reverse, nextWindow);
if(nextWindow == originalActiveWindow) {
return this;
}
}
if(reverse) {
moveToTop(nextWindow);
} else if (originalActiveWindow != null) {
moveToBottom(originalActiveWindow);
}
setActiveWindow(nextWindow);
return this;
}
private Window getNextWindow(boolean reverse, Window window) {
int index = windows.indexOf(window);
if(reverse) {
if(++index >= windows.size()) {
index = 0;
}
} else {
if(--index < 0) {
index = windows.size() - 1;
}
}
return windows.get(index);
}
}
|
boolean contained = windows.remove(window);
stableOrderingOfWindows.remove(window);
if(activeWindow == window) {
// in case no suitable window is found, so pass control back to the background pane
setActiveWindow(null);
//Go backward in reverse and find the first suitable window
for(int index = windows.size() - 1; index >= 0; index--) {
Window candidate = windows.get(index);
if(!candidate.getHints().contains(Window.Hint.NO_FOCUS)) {
setActiveWindow(candidate);
break;
}
}
}
return contained;
| 1,099
| 169
| 1,268
|
<no_super_class>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/WindowShadowRenderer.java
|
WindowShadowRenderer
|
postRender
|
class WindowShadowRenderer implements WindowPostRenderer {
@Override
public void postRender(
ThemedTextGraphics textGraphics,
TextGUI textGUI,
Window window) {<FILL_FUNCTION_BODY>}
}
|
TerminalPosition windowPosition = window.getPosition();
TerminalSize decoratedWindowSize = window.getDecoratedSize();
ThemeDefinition themeDefinition = window.getTheme().getDefinition(WindowShadowRenderer.class);
textGraphics.applyThemeStyle(themeDefinition.getNormal());
char filler = themeDefinition.getCharacter("FILLER", ' ');
boolean useDoubleWidth = themeDefinition.getBooleanProperty("DOUBLE_WIDTH", true);
boolean useTransparency = themeDefinition.getBooleanProperty("TRANSPARENT", false);
TerminalPosition lowerLeft = windowPosition.withRelativeColumn(useDoubleWidth ? 2 : 1).withRelativeRow(decoratedWindowSize.getRows());
TerminalPosition lowerRight = lowerLeft.withRelativeColumn(decoratedWindowSize.getColumns() - (useDoubleWidth ? 3 : 2));
for(int column = lowerLeft.getColumn(); column <= lowerRight.getColumn() + 1; column++) {
char characterToDraw = filler;
if(useTransparency) {
TextCharacter tc = textGraphics.getCharacter(column, lowerLeft.getRow());
if (tc != null) {
characterToDraw = tc.getCharacterString().charAt(0);
}
}
textGraphics.setCharacter(column, lowerLeft.getRow(), characterToDraw);
if (TerminalTextUtils.isCharDoubleWidth(characterToDraw)) {
column++;
}
}
lowerRight = lowerRight.withRelativeColumn(1);
TerminalPosition upperRight = lowerRight.withRelativeRow(-decoratedWindowSize.getRows() + 1);
boolean hasDoubleWidthShadow = false;
for(int row = upperRight.getRow(); row < lowerRight.getRow(); row++) {
char characterToDraw = filler;
if(useTransparency) {
TextCharacter tc = textGraphics.getCharacter(upperRight.getColumn(), row);
if (tc != null) {
characterToDraw = tc.getCharacterString().charAt(0);
}
}
textGraphics.setCharacter(upperRight.getColumn(), row, characterToDraw);
if (TerminalTextUtils.isCharDoubleWidth(characterToDraw)) {
hasDoubleWidthShadow = true;
}
}
textGraphics.applyThemeStyle(themeDefinition.getNormal());
if(useDoubleWidth || hasDoubleWidthShadow) {
//Fill the remaining hole
upperRight = upperRight.withRelativeColumn(1);
for(int row = upperRight.getRow(); row <= lowerRight.getRow(); row++) {
char characterToDraw = filler;
if(useTransparency) {
TextCharacter tc = textGraphics.getCharacter(upperRight.getColumn(), row);
if (tc != null && !tc.isDoubleWidth()) {
characterToDraw = tc.getCharacterString().charAt(0);
}
}
TextCharacter neighbour = textGraphics.getCharacter(upperRight.getColumn() - 1, row);
// Only need to draw this is the character to the left isn't double-width
if (neighbour != null && !neighbour.isDoubleWidth()) {
textGraphics.setCharacter(upperRight.getColumn(), row, characterToDraw);
}
}
}
| 60
| 818
| 878
|
<no_super_class>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/dialogs/AbstractDialogBuilder.java
|
AbstractDialogBuilder
|
setTitle
|
class AbstractDialogBuilder<B, T extends DialogWindow> {
protected String title;
protected String description;
protected Set<Window.Hint> extraWindowHints;
/**
* Default constructor for a dialog builder
* @param title Title to assign to the dialog
*/
public AbstractDialogBuilder(String title) {
this.title = title;
this.description = null;
this.extraWindowHints = Collections.singleton(Window.Hint.CENTERED);
}
/**
* Changes the title of the dialog
* @param title New title
* @return Itself
*/
public B setTitle(String title) {<FILL_FUNCTION_BODY>}
/**
* Returns the title that the built dialog will have
* @return Title that the built dialog will have
*/
public String getTitle() {
return title;
}
/**
* Changes the description of the dialog
* @param description New description
* @return Itself
*/
public B setDescription(String description) {
this.description = description;
return self();
}
/**
* Returns the description that the built dialog will have
* @return Description that the built dialog will have
*/
public String getDescription() {
return description;
}
/**
* Assigns a set of extra window hints that you want the built dialog to have
* @param extraWindowHints Window hints to assign to the window in addition to the ones the builder will put
* @return Itself
*/
public B setExtraWindowHints(Set<Window.Hint> extraWindowHints) {
this.extraWindowHints = extraWindowHints;
return self();
}
/**
* Returns the list of extra window hints that will be assigned to the window when built
* @return List of extra window hints that will be assigned to the window when built
*/
public Set<Window.Hint> getExtraWindowHints() {
return extraWindowHints;
}
/**
* Helper method for casting this to {@code type} parameter {@code B}
* @return {@code this} as {@code B}
*/
protected abstract B self();
/**
* Builds the dialog according to the builder implementation
* @return New dialog object
*/
protected abstract T buildDialog();
/**
* Builds a new dialog following the specifications of this builder
* @return New dialog built following the specifications of this builder
*/
public final T build() {
T dialog = buildDialog();
if(!extraWindowHints.isEmpty()) {
Set<Window.Hint> combinedHints = new HashSet<>(dialog.getHints());
combinedHints.addAll(extraWindowHints);
dialog.setHints(combinedHints);
}
return dialog;
}
}
|
if(title == null) {
title = "";
}
this.title = title;
return self();
| 719
| 33
| 752
|
<no_super_class>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/dialogs/ActionListDialog.java
|
ActionListDialog
|
showDialog
|
class ActionListDialog extends DialogWindow {
ActionListDialog(
String title,
String description,
TerminalSize actionListPreferredSize,
boolean canCancel,
final boolean closeAutomatically,
List<Runnable> actions) {
super(title);
ActionListBox listBox = new ActionListBox(actionListPreferredSize);
for(final Runnable action: actions) {
listBox.addItem(action.toString(), () -> {
action.run();
if(closeAutomatically) {
close();
}
});
}
Panel mainPanel = new Panel();
mainPanel.setLayoutManager(
new GridLayout(1)
.setLeftMarginSize(1)
.setRightMarginSize(1));
if(description != null) {
mainPanel.addComponent(new Label(description));
mainPanel.addComponent(new EmptySpace(TerminalSize.ONE));
}
listBox.setLayoutData(
GridLayout.createLayoutData(
GridLayout.Alignment.FILL,
GridLayout.Alignment.CENTER,
true,
false))
.addTo(mainPanel);
mainPanel.addComponent(new EmptySpace(TerminalSize.ONE));
if(canCancel) {
Panel buttonPanel = new Panel();
buttonPanel.setLayoutManager(new GridLayout(2).setHorizontalSpacing(1));
buttonPanel.addComponent(new Button(LocalizedString.Cancel.toString(), this::onCancel).setLayoutData(GridLayout.createLayoutData(GridLayout.Alignment.CENTER, GridLayout.Alignment.CENTER, true, false)));
buttonPanel.setLayoutData(
GridLayout.createLayoutData(
GridLayout.Alignment.END,
GridLayout.Alignment.CENTER,
false,
false))
.addTo(mainPanel);
}
setComponent(mainPanel);
}
private void onCancel() {
close();
}
/**
* Helper method for immediately displaying a {@code ActionListDialog}, the method will return when the dialog is
* closed
* @param textGUI Text GUI the dialog should be added to
* @param title Title of the dialog
* @param description Description of the dialog
* @param items Items in the {@code ActionListBox}, the label will be taken from each {@code Runnable} by calling
* {@code toString()} on each one
*/
public static void showDialog(WindowBasedTextGUI textGUI, String title, String description, Runnable... items) {<FILL_FUNCTION_BODY>}
}
|
ActionListDialog actionListDialog = new ActionListDialogBuilder()
.setTitle(title)
.setDescription(description)
.addActions(items)
.build();
actionListDialog.showDialog(textGUI);
| 665
| 60
| 725
|
<methods>public java.lang.Object showDialog(com.googlecode.lanterna.gui2.WindowBasedTextGUI) <variables>private static final Set<com.googlecode.lanterna.gui2.Window.Hint> GLOBAL_DIALOG_HINTS
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/dialogs/ActionListDialogBuilder.java
|
ActionListDialogBuilder
|
buildDialog
|
class ActionListDialogBuilder extends AbstractDialogBuilder<ActionListDialogBuilder, ActionListDialog> {
private final List<Runnable> actions;
private TerminalSize listBoxSize;
private boolean canCancel;
private boolean closeAutomatically;
/**
* Default constructor
*/
public ActionListDialogBuilder() {
super("ActionListDialogBuilder");
this.listBoxSize = null;
this.canCancel = true;
this.closeAutomatically = true;
this.actions = new ArrayList<>();
}
@Override
protected ActionListDialogBuilder self() {
return this;
}
@Override
protected ActionListDialog buildDialog() {<FILL_FUNCTION_BODY>}
/**
* Sets the size of the internal {@code ActionListBox} in columns and rows, forcing scrollbars to appear if the
* space isn't big enough to contain all the items
* @param listBoxSize Size of the {@code ActionListBox}
* @return Itself
*/
public ActionListDialogBuilder setListBoxSize(TerminalSize listBoxSize) {
this.listBoxSize = listBoxSize;
return this;
}
/**
* Returns the specified size of the internal {@code ActionListBox} or {@code null} if there is no size and the list
* box will attempt to take up enough size to draw all items
* @return Specified size of the internal {@code ActionListBox} or {@code null} if there is no size
*/
public TerminalSize getListBoxSize() {
return listBoxSize;
}
/**
* Sets if the dialog can be cancelled or not (default: {@code true})
* @param canCancel If {@code true}, the user has the option to cancel the dialog, if {@code false} there is no such
* button in the dialog
* @return Itself
*/
public ActionListDialogBuilder setCanCancel(boolean canCancel) {
this.canCancel = canCancel;
return this;
}
/**
* Returns {@code true} if the dialog can be cancelled once it's opened
* @return {@code true} if the dialog can be cancelled once it's opened
*/
public boolean isCanCancel() {
return canCancel;
}
/**
* Adds an additional action to the {@code ActionListBox} that is to be displayed when the dialog is opened
* @param label Label of the new action
* @param action Action to perform if the user selects this item
* @return Itself
*/
public ActionListDialogBuilder addAction(final String label, final Runnable action) {
return addAction(new Runnable() {
@Override
public String toString() {
return label;
}
@Override
public void run() {
action.run();
}
});
}
/**
* Adds an additional action to the {@code ActionListBox} that is to be displayed when the dialog is opened. The
* label of this item will be derived by calling {@code toString()} on the runnable
* @param action Action to perform if the user selects this item
* @return Itself
*/
public ActionListDialogBuilder addAction(Runnable action) {
this.actions.add(action);
return this;
}
/**
* Adds additional actions to the {@code ActionListBox} that is to be displayed when the dialog is opened. The
* label of the items will be derived by calling {@code toString()} on each runnable
* @param actions Items to add to the {@code ActionListBox}
* @return Itself
*/
public ActionListDialogBuilder addActions(Runnable... actions) {
this.actions.addAll(Arrays.asList(actions));
return this;
}
/**
* Returns a copy of the internal list of actions currently inside this builder that will be assigned to the
* {@code ActionListBox} in the dialog when built
* @return Copy of the internal list of actions currently inside this builder
*/
public List<Runnable> getActions() {
return new ArrayList<>(actions);
}
/**
* Sets if clicking on an action automatically closes the dialog after the action is finished (default: {@code true})
* @param closeAutomatically if {@code true} dialog will be automatically closed after choosing and finish any of the action
* @return Itself
*/
public ActionListDialogBuilder setCloseAutomaticallyOnAction(boolean closeAutomatically) {
this.closeAutomatically = closeAutomatically;
return this;
}
}
|
return new ActionListDialog(
title,
description,
listBoxSize,
canCancel,
closeAutomatically,
actions);
| 1,149
| 41
| 1,190
|
<methods>public void <init>(java.lang.String) ,public final com.googlecode.lanterna.gui2.dialogs.ActionListDialog build() ,public java.lang.String getDescription() ,public Set<com.googlecode.lanterna.gui2.Window.Hint> getExtraWindowHints() ,public java.lang.String getTitle() ,public com.googlecode.lanterna.gui2.dialogs.ActionListDialogBuilder setDescription(java.lang.String) ,public com.googlecode.lanterna.gui2.dialogs.ActionListDialogBuilder setExtraWindowHints(Set<com.googlecode.lanterna.gui2.Window.Hint>) ,public com.googlecode.lanterna.gui2.dialogs.ActionListDialogBuilder setTitle(java.lang.String) <variables>protected java.lang.String description,protected Set<com.googlecode.lanterna.gui2.Window.Hint> extraWindowHints,protected java.lang.String title
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/dialogs/DialogWindow.java
|
DialogWindow
|
showDialog
|
class DialogWindow extends AbstractWindow {
private static final Set<Hint> GLOBAL_DIALOG_HINTS =
Collections.unmodifiableSet(new HashSet<>(Collections.singletonList(Hint.MODAL)));
/**
* Default constructor, takes a title for the dialog and runs code shared for dialogs
* @param title Title of the window
*/
protected DialogWindow(String title) {
super(title);
setHints(GLOBAL_DIALOG_HINTS);
}
/**
* Opens the dialog by showing it on the GUI and doesn't return until the dialog has been closed
* @param textGUI Text GUI to add the dialog to
* @return Depending on the {@code DialogWindow} implementation, by default {@code null}
*/
public Object showDialog(WindowBasedTextGUI textGUI) {<FILL_FUNCTION_BODY>}
}
|
textGUI.addWindow(this);
//Wait for the window to close, in case the window manager doesn't honor the MODAL hint
waitUntilClosed();
return null;
| 234
| 51
| 285
|
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void addWindowListener(com.googlecode.lanterna.gui2.WindowListener) ,public void close() ,public void draw(com.googlecode.lanterna.gui2.TextGUIGraphics) ,public com.googlecode.lanterna.TerminalPosition fromGlobal(com.googlecode.lanterna.TerminalPosition) ,public com.googlecode.lanterna.TerminalPosition fromGlobalToContentRelative(com.googlecode.lanterna.TerminalPosition) ,public com.googlecode.lanterna.TerminalPosition fromGlobalToDecoratedRelative(com.googlecode.lanterna.TerminalPosition) ,public final com.googlecode.lanterna.TerminalSize getDecoratedSize() ,public Set<com.googlecode.lanterna.gui2.Window.Hint> getHints() ,public final com.googlecode.lanterna.TerminalPosition getPosition() ,public com.googlecode.lanterna.gui2.WindowPostRenderer getPostRenderer() ,public com.googlecode.lanterna.TerminalSize getPreferredSize() ,public final com.googlecode.lanterna.TerminalSize getSize() ,public com.googlecode.lanterna.gui2.WindowBasedTextGUI getTextGUI() ,public java.lang.String getTitle() ,public boolean handleInput(com.googlecode.lanterna.input.KeyStroke) ,public boolean isVisible() ,public void removeWindowListener(com.googlecode.lanterna.gui2.WindowListener) ,public void setCloseWindowWithEscape(boolean) ,public void setContentOffset(com.googlecode.lanterna.TerminalPosition) ,public final void setDecoratedSize(com.googlecode.lanterna.TerminalSize) ,public void setFixedSize(com.googlecode.lanterna.TerminalSize) ,public void setHints(Collection<com.googlecode.lanterna.gui2.Window.Hint>) ,public final void setPosition(com.googlecode.lanterna.TerminalPosition) ,public void setSize(com.googlecode.lanterna.TerminalSize) ,public void setTextGUI(com.googlecode.lanterna.gui2.WindowBasedTextGUI) ,public void setTitle(java.lang.String) ,public void setVisible(boolean) ,public void setWindowPostRenderer(com.googlecode.lanterna.gui2.WindowPostRenderer) ,public com.googlecode.lanterna.TerminalPosition toGlobal(com.googlecode.lanterna.TerminalPosition) ,public com.googlecode.lanterna.TerminalPosition toGlobalFromContentRelative(com.googlecode.lanterna.TerminalPosition) ,public com.googlecode.lanterna.TerminalPosition toGlobalFromDecoratedRelative(com.googlecode.lanterna.TerminalPosition) ,public void waitUntilClosed() <variables>private boolean closeWindowWithEscape,private com.googlecode.lanterna.TerminalPosition contentOffset,private Set<com.googlecode.lanterna.gui2.Window.Hint> hints,private com.googlecode.lanterna.TerminalSize lastKnownDecoratedSize,private com.googlecode.lanterna.TerminalPosition lastKnownPosition,private com.googlecode.lanterna.TerminalSize lastKnownSize,private com.googlecode.lanterna.gui2.WindowBasedTextGUI textGUI,private java.lang.String title,private boolean visible,private com.googlecode.lanterna.gui2.WindowPostRenderer windowPostRenderer
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/dialogs/DirectoryDialog.java
|
DoNothing
|
reloadViews
|
class DoNothing implements Runnable {
@Override
public void run() {
}
}
private void reloadViews(final File directory) {<FILL_FUNCTION_BODY>
|
dirBox.setText(directory.getAbsolutePath());
dirListBox.clearItems();
File[] entries = directory.listFiles();
if (entries == null) {
return;
}
Arrays.sort(entries, Comparator.comparing(o -> o.getName().toLowerCase()));
if (directory.getAbsoluteFile().getParentFile() != null) {
dirListBox.addItem("..", () -> {
DirectoryDialog.this.directory = directory.getAbsoluteFile().getParentFile();
reloadViews(directory.getAbsoluteFile().getParentFile());
});
}
else {
File[] roots = File.listRoots();
for (final File entry : roots) {
if (entry.canRead()) {
dirListBox.addItem('[' + entry.getPath() + ']', () -> {
DirectoryDialog.this.directory = entry;
reloadViews(entry);
});
}
}
}
for (final File entry : entries) {
if (entry.isHidden() && !showHiddenDirs) {
continue;
}
if (entry.isDirectory()) {
dirListBox.addItem(entry.getName(), () -> {
DirectoryDialog.this.directory = entry;
reloadViews(entry);
});
}
}
if (dirListBox.isEmpty()) {
dirListBox.addItem("<empty>", new DoNothing());
}
| 52
| 378
| 430
|
<methods>public java.lang.Object showDialog(com.googlecode.lanterna.gui2.WindowBasedTextGUI) <variables>private static final Set<com.googlecode.lanterna.gui2.Window.Hint> GLOBAL_DIALOG_HINTS
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/dialogs/FileDialog.java
|
DoNothing
|
reloadViews
|
class DoNothing implements Runnable {
@Override
public void run() {
}
}
private void reloadViews(final File directory) {<FILL_FUNCTION_BODY>
|
directoryListBox.clearItems();
fileListBox.clearItems();
File []entries = directory.listFiles();
if(entries == null) {
return;
}
Arrays.sort(entries, Comparator.comparing(o -> o.getName().toLowerCase()));
if (directory.getAbsoluteFile().getParentFile() !=null){
directoryListBox.addItem("..", () -> {
FileDialog.this.directory = directory.getAbsoluteFile().getParentFile();
reloadViews(directory.getAbsoluteFile().getParentFile());
});
} else {
File[] roots = File.listRoots();
for (final File entry : roots) {
if (entry.canRead()) {
directoryListBox.addItem('[' + entry.getPath() + ']', () -> {
FileDialog.this.directory = entry;
reloadViews(entry);
});
}
}
}
for(final File entry: entries) {
if(entry.isHidden() && !showHiddenFilesAndDirs) {
continue;
}
if(entry.isDirectory()) {
directoryListBox.addItem(entry.getName(), () -> {
FileDialog.this.directory = entry;
reloadViews(entry);
});
}
else {
fileListBox.addItem(entry.getName(), () -> {
fileBox.setText(entry.getName());
setFocusedInteractable(okButton);
});
}
}
if(fileListBox.isEmpty()) {
fileListBox.addItem("<empty>", new DoNothing());
}
| 52
| 423
| 475
|
<methods>public java.lang.Object showDialog(com.googlecode.lanterna.gui2.WindowBasedTextGUI) <variables>private static final Set<com.googlecode.lanterna.gui2.Window.Hint> GLOBAL_DIALOG_HINTS
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/dialogs/ListSelectDialog.java
|
ListSelectDialog
|
showDialog
|
class ListSelectDialog<T> extends DialogWindow {
private T result;
ListSelectDialog(
String title,
String description,
TerminalSize listBoxPreferredSize,
boolean canCancel,
List<T> content) {
super(title);
this.result = null;
if(content.isEmpty()) {
throw new IllegalStateException("ListSelectDialog needs at least one item");
}
ActionListBox listBox = new ActionListBox(listBoxPreferredSize);
for(final T item: content) {
listBox.addItem(item.toString(), () -> onSelect(item));
}
Panel mainPanel = new Panel();
mainPanel.setLayoutManager(
new GridLayout(1)
.setLeftMarginSize(1)
.setRightMarginSize(1));
if(description != null) {
mainPanel.addComponent(new Label(description));
mainPanel.addComponent(new EmptySpace(TerminalSize.ONE));
}
listBox.setLayoutData(
GridLayout.createLayoutData(
GridLayout.Alignment.FILL,
GridLayout.Alignment.CENTER,
true,
false))
.addTo(mainPanel);
mainPanel.addComponent(new EmptySpace(TerminalSize.ONE));
if(canCancel) {
Panel buttonPanel = new Panel();
buttonPanel.setLayoutManager(new GridLayout(2).setHorizontalSpacing(1));
buttonPanel.addComponent(new Button(LocalizedString.Cancel.toString(), this::onCancel).setLayoutData(GridLayout.createLayoutData(GridLayout.Alignment.CENTER, GridLayout.Alignment.CENTER, true, false)));
buttonPanel.setLayoutData(
GridLayout.createLayoutData(
GridLayout.Alignment.END,
GridLayout.Alignment.CENTER,
false,
false))
.addTo(mainPanel);
}
setComponent(mainPanel);
}
private void onSelect(T item) {
result = item;
close();
}
private void onCancel() {
close();
}
/**
* {@inheritDoc}
*
* @param textGUI Text GUI to add the dialog to
* @return The item in the list that was selected or {@code null} if the dialog was cancelled
*/
@Override
public T showDialog(WindowBasedTextGUI textGUI) {
result = null;
super.showDialog(textGUI);
return result;
}
/**
* Shortcut for quickly creating a new dialog
* @param textGUI Text GUI to add the dialog to
* @param title Title of the dialog
* @param description Description of the dialog
* @param items Items in the dialog
* @param <T> Type of items in the dialog
* @return The selected item or {@code null} if cancelled
*/
@SafeVarargs
public static <T> T showDialog(WindowBasedTextGUI textGUI, String title, String description, T... items) {
return showDialog(textGUI, title, description, null, items);
}
/**
* Shortcut for quickly creating a new dialog
* @param textGUI Text GUI to add the dialog to
* @param title Title of the dialog
* @param description Description of the dialog
* @param listBoxHeight Maximum height of the list box, scrollbars will be used if there are more items
* @param items Items in the dialog
* @param <T> Type of items in the dialog
* @return The selected item or {@code null} if cancelled
*/
@SafeVarargs
public static <T> T showDialog(WindowBasedTextGUI textGUI, String title, String description, int listBoxHeight, T... items) {<FILL_FUNCTION_BODY>}
/**
* Shortcut for quickly creating a new dialog
* @param textGUI Text GUI to add the dialog to
* @param title Title of the dialog
* @param description Description of the dialog
* @param listBoxSize Maximum size of the list box, scrollbars will be used if the items cannot fit
* @param items Items in the dialog
* @param <T> Type of items in the dialog
* @return The selected item or {@code null} if cancelled
*/
@SafeVarargs
public static <T> T showDialog(WindowBasedTextGUI textGUI, String title, String description, TerminalSize listBoxSize, T... items) {
ListSelectDialog<T> listSelectDialog = new ListSelectDialogBuilder<T>()
.setTitle(title)
.setDescription(description)
.setListBoxSize(listBoxSize)
.addListItems(items)
.build();
return listSelectDialog.showDialog(textGUI);
}
}
|
int width = 0;
for(T item: items) {
width = Math.max(width, TerminalTextUtils.getColumnWidth(item.toString()));
}
width += 2;
return showDialog(textGUI, title, description, new TerminalSize(width, listBoxHeight), items);
| 1,215
| 77
| 1,292
|
<methods>public java.lang.Object showDialog(com.googlecode.lanterna.gui2.WindowBasedTextGUI) <variables>private static final Set<com.googlecode.lanterna.gui2.Window.Hint> GLOBAL_DIALOG_HINTS
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/dialogs/MessageDialog.java
|
MessageDialog
|
showMessageDialog
|
class MessageDialog extends DialogWindow {
private MessageDialogButton result;
MessageDialog(
String title,
String text,
MessageDialogButton... buttons) {
super(title);
this.result = null;
if(buttons == null || buttons.length == 0) {
buttons = new MessageDialogButton[] { MessageDialogButton.OK };
}
Panel buttonPanel = new Panel();
buttonPanel.setLayoutManager(new GridLayout(buttons.length).setHorizontalSpacing(1));
for(final MessageDialogButton button: buttons) {
buttonPanel.addComponent(new Button(button.toString(), () -> {
result = button;
close();
}));
}
Panel mainPanel = new Panel();
mainPanel.setLayoutManager(
new GridLayout(1)
.setLeftMarginSize(1)
.setRightMarginSize(1));
mainPanel.addComponent(new Label(text));
mainPanel.addComponent(new EmptySpace(TerminalSize.ONE));
buttonPanel.setLayoutData(
GridLayout.createLayoutData(
GridLayout.Alignment.END,
GridLayout.Alignment.CENTER,
false,
false))
.addTo(mainPanel);
setComponent(mainPanel);
}
/**
* {@inheritDoc}
* @param textGUI Text GUI to add the dialog to
* @return The selected button's enum value
*/
@Override
public MessageDialogButton showDialog(WindowBasedTextGUI textGUI) {
result = null;
super.showDialog(textGUI);
return result;
}
/**
* Shortcut for quickly displaying a message box
* @param textGUI The GUI to display the message box on
* @param title Title of the message box
* @param text Main message of the message box
* @param buttons Buttons that the user can confirm the message box with
* @return Which button the user selected
*/
public static MessageDialogButton showMessageDialog(
WindowBasedTextGUI textGUI,
String title,
String text,
MessageDialogButton... buttons) {<FILL_FUNCTION_BODY>}
}
|
MessageDialogBuilder builder = new MessageDialogBuilder()
.setTitle(title)
.setText(text);
if(buttons.length == 0) {
builder.addButton(MessageDialogButton.OK);
}
for(MessageDialogButton button: buttons) {
builder.addButton(button);
}
return builder.build().showDialog(textGUI);
| 555
| 96
| 651
|
<methods>public java.lang.Object showDialog(com.googlecode.lanterna.gui2.WindowBasedTextGUI) <variables>private static final Set<com.googlecode.lanterna.gui2.Window.Hint> GLOBAL_DIALOG_HINTS
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/dialogs/MessageDialogBuilder.java
|
MessageDialogBuilder
|
build
|
class MessageDialogBuilder {
private String title;
private String text;
private final List<MessageDialogButton> buttons;
private final Set<Window.Hint> extraWindowHints;
/**
* Default constructor
*/
public MessageDialogBuilder() {
this.title = "MessageDialog";
this.text = "Text";
this.buttons = new ArrayList<>();
this.extraWindowHints = new HashSet<>();
this.extraWindowHints.add(Window.Hint.CENTERED);
}
/**
* Builds a new {@code MessageDialog} from the properties in the builder
* @return Newly build {@code MessageDialog}
*/
public MessageDialog build() {<FILL_FUNCTION_BODY>}
/**
* Sets the title of the {@code MessageDialog}
* @param title New title of the message dialog
* @return Itself
*/
public MessageDialogBuilder setTitle(String title) {
if(title == null) {
title = "";
}
this.title = title;
return this;
}
/**
* Sets the main text of the {@code MessageDialog}
* @param text Main text of the {@code MessageDialog}
* @return Itself
*/
public MessageDialogBuilder setText(String text) {
if(text == null) {
text = "";
}
this.text = text;
return this;
}
/**
* Assigns a set of extra window hints that you want the built dialog to have
* @param extraWindowHints Window hints to assign to the window in addition to the ones the builder will put
* @return Itself
*/
public MessageDialogBuilder setExtraWindowHints(Collection<Window.Hint> extraWindowHints) {
this.extraWindowHints.clear();
this.extraWindowHints.addAll(extraWindowHints);
return this;
}
/**
* Adds a button to the dialog
* @param button Button to add to the dialog
* @return Itself
*/
public MessageDialogBuilder addButton(MessageDialogButton button) {
if(button != null) {
buttons.add(button);
}
return this;
}
}
|
MessageDialog messageDialog = new MessageDialog(
title,
text,
buttons.toArray(new MessageDialogButton[0]));
messageDialog.setHints(extraWindowHints);
return messageDialog;
| 568
| 57
| 625
|
<no_super_class>
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/dialogs/TextInputDialog.java
|
TextInputDialog
|
showNumberDialog
|
class TextInputDialog extends DialogWindow {
private final TextBox textBox;
private final TextInputDialogResultValidator validator;
private String result;
TextInputDialog(
String title,
String description,
TerminalSize textBoxPreferredSize,
String initialContent,
TextInputDialogResultValidator validator,
boolean password) {
super(title);
this.result = null;
this.textBox = new TextBox(textBoxPreferredSize, initialContent);
this.validator = validator;
if(password) {
textBox.setMask('*');
}
Panel buttonPanel = new Panel();
buttonPanel.setLayoutManager(new GridLayout(2).setHorizontalSpacing(1));
buttonPanel.addComponent(new Button(LocalizedString.OK.toString(), this::onOK).setLayoutData(GridLayout.createLayoutData(GridLayout.Alignment.CENTER, GridLayout.Alignment.CENTER, true, false)));
buttonPanel.addComponent(new Button(LocalizedString.Cancel.toString(), this::onCancel));
Panel mainPanel = new Panel();
mainPanel.setLayoutManager(
new GridLayout(1)
.setLeftMarginSize(1)
.setRightMarginSize(1));
if(description != null) {
mainPanel.addComponent(new Label(description));
}
mainPanel.addComponent(new EmptySpace(TerminalSize.ONE));
textBox.setLayoutData(
GridLayout.createLayoutData(
GridLayout.Alignment.FILL,
GridLayout.Alignment.CENTER,
true,
false))
.addTo(mainPanel);
mainPanel.addComponent(new EmptySpace(TerminalSize.ONE));
buttonPanel.setLayoutData(
GridLayout.createLayoutData(
GridLayout.Alignment.END,
GridLayout.Alignment.CENTER,
false,
false))
.addTo(mainPanel);
setComponent(mainPanel);
}
private void onOK() {
String text = textBox.getText();
if(validator != null) {
String errorMessage = validator.validate(text);
if(errorMessage != null) {
MessageDialog.showMessageDialog(getTextGUI(), getTitle(), errorMessage, MessageDialogButton.OK);
return;
}
}
result = text;
close();
}
private void onCancel() {
close();
}
@Override
public String showDialog(WindowBasedTextGUI textGUI) {
result = null;
super.showDialog(textGUI);
return result;
}
/**
* Shortcut for quickly showing a {@code TextInputDialog}
* @param textGUI GUI to show the dialog on
* @param title Title of the dialog
* @param description Description of the dialog
* @param initialContent What content to place in the text box initially
* @return The string the user typed into the text box, or {@code null} if the dialog was cancelled
*/
public static String showDialog(WindowBasedTextGUI textGUI, String title, String description, String initialContent) {
TextInputDialog textInputDialog = new TextInputDialogBuilder()
.setTitle(title)
.setDescription(description)
.setInitialContent(initialContent)
.build();
return textInputDialog.showDialog(textGUI);
}
/**
* Shortcut for quickly showing a {@code TextInputDialog} that only accepts numbers
* @param textGUI GUI to show the dialog on
* @param title Title of the dialog
* @param description Description of the dialog
* @param initialContent What content to place in the text box initially
* @return The number the user typed into the text box, or {@code null} if the dialog was cancelled
*/
public static BigInteger showNumberDialog(WindowBasedTextGUI textGUI, String title, String description, String initialContent) {<FILL_FUNCTION_BODY>}
/**
* Shortcut for quickly showing a {@code TextInputDialog} with password masking
* @param textGUI GUI to show the dialog on
* @param title Title of the dialog
* @param description Description of the dialog
* @param initialContent What content to place in the text box initially
* @return The string the user typed into the text box, or {@code null} if the dialog was cancelled
*/
public static String showPasswordDialog(WindowBasedTextGUI textGUI, String title, String description, String initialContent) {
TextInputDialog textInputDialog = new TextInputDialogBuilder()
.setTitle(title)
.setDescription(description)
.setInitialContent(initialContent)
.setPasswordInput(true)
.build();
return textInputDialog.showDialog(textGUI);
}
}
|
TextInputDialog textInputDialog = new TextInputDialogBuilder()
.setTitle(title)
.setDescription(description)
.setInitialContent(initialContent)
.setValidationPattern(Pattern.compile("[0-9]+"), "Not a number")
.build();
String numberString = textInputDialog.showDialog(textGUI);
return numberString != null ? new BigInteger(numberString) : null;
| 1,211
| 108
| 1,319
|
<methods>public java.lang.Object showDialog(com.googlecode.lanterna.gui2.WindowBasedTextGUI) <variables>private static final Set<com.googlecode.lanterna.gui2.Window.Hint> GLOBAL_DIALOG_HINTS
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/dialogs/TextInputDialogBuilder.java
|
TextInputDialogBuilder
|
setValidationPattern
|
class TextInputDialogBuilder extends AbstractDialogBuilder<TextInputDialogBuilder, TextInputDialog> {
private String initialContent;
private TerminalSize textBoxSize;
private TextInputDialogResultValidator validator;
private boolean passwordInput;
/**
* Default constructor
*/
public TextInputDialogBuilder() {
super("TextInputDialog");
this.initialContent = "";
this.textBoxSize = null;
this.validator = null;
this.passwordInput = false;
}
@Override
protected TextInputDialogBuilder self() {
return this;
}
protected TextInputDialog buildDialog() {
TerminalSize size = textBoxSize;
if ((initialContent == null || initialContent.trim().equals("")) && size == null) {
size = new TerminalSize(40, 1);
}
return new TextInputDialog(
title,
description,
size,
initialContent,
validator,
passwordInput);
}
/**
* Sets the initial content the dialog will have
* @param initialContent Initial content the dialog will have
* @return Itself
*/
public TextInputDialogBuilder setInitialContent(String initialContent) {
this.initialContent = initialContent;
return this;
}
/**
* Returns the initial content the dialog will have
* @return Initial content the dialog will have
*/
public String getInitialContent() {
return initialContent;
}
/**
* Sets the size of the text box the dialog will have
* @param textBoxSize Size of the text box the dialog will have
* @return Itself
*/
public TextInputDialogBuilder setTextBoxSize(TerminalSize textBoxSize) {
this.textBoxSize = textBoxSize;
return this;
}
/**
* Returns the size of the text box the dialog will have
* @return Size of the text box the dialog will have
*/
public TerminalSize getTextBoxSize() {
return textBoxSize;
}
/**
* Sets the validator that will be attached to the text box in the dialog
* @param validator Validator that will be attached to the text box in the dialog
* @return Itself
*/
public TextInputDialogBuilder setValidator(TextInputDialogResultValidator validator) {
this.validator = validator;
return this;
}
/**
* Returns the validator that will be attached to the text box in the dialog
* @return validator that will be attached to the text box in the dialog
*/
public TextInputDialogResultValidator getValidator() {
return validator;
}
/**
* Helper method that assigned a validator to the text box the dialog will have which matches the pattern supplied
* @param pattern Pattern to validate the text box
* @param errorMessage Error message to show when the pattern doesn't match
* @return Itself
*/
public TextInputDialogBuilder setValidationPattern(final Pattern pattern, final String errorMessage) {<FILL_FUNCTION_BODY>}
/**
* Sets if the text box the dialog will have contains a password and should be masked (default: {@code false})
* @param passwordInput {@code true} if the text box should be password masked, {@code false} otherwise
* @return Itself
*/
public TextInputDialogBuilder setPasswordInput(boolean passwordInput) {
this.passwordInput = passwordInput;
return this;
}
/**
* Returns {@code true} if the text box the dialog will have contains a password and should be masked
* @return {@code true} if the text box the dialog will have contains a password and should be masked
*/
public boolean isPasswordInput() {
return passwordInput;
}
}
|
return setValidator(content -> {
Matcher matcher = pattern.matcher(content);
if(!matcher.matches()) {
if(errorMessage == null) {
return "Invalid input";
}
return errorMessage;
}
return null;
});
| 938
| 75
| 1,013
|
<methods>public void <init>(java.lang.String) ,public final com.googlecode.lanterna.gui2.dialogs.TextInputDialog build() ,public java.lang.String getDescription() ,public Set<com.googlecode.lanterna.gui2.Window.Hint> getExtraWindowHints() ,public java.lang.String getTitle() ,public com.googlecode.lanterna.gui2.dialogs.TextInputDialogBuilder setDescription(java.lang.String) ,public com.googlecode.lanterna.gui2.dialogs.TextInputDialogBuilder setExtraWindowHints(Set<com.googlecode.lanterna.gui2.Window.Hint>) ,public com.googlecode.lanterna.gui2.dialogs.TextInputDialogBuilder setTitle(java.lang.String) <variables>protected java.lang.String description,protected Set<com.googlecode.lanterna.gui2.Window.Hint> extraWindowHints,protected java.lang.String title
|
mabe02_lanterna
|
lanterna/src/main/java/com/googlecode/lanterna/gui2/dialogs/WaitingDialog.java
|
WaitingDialog
|
showDialog
|
class WaitingDialog extends DialogWindow {
private WaitingDialog(String title, String text) {
super(title);
Panel mainPanel = Panels.horizontal(
new Label(text),
AnimatedLabel.createClassicSpinningLine());
setComponent(mainPanel);
}
@Override
public Object showDialog(WindowBasedTextGUI textGUI) {
showDialog(textGUI, true);
return null;
}
/**
* Displays the waiting dialog and optionally blocks until another thread closes it
* @param textGUI GUI to add the dialog to
* @param blockUntilClosed If {@code true}, the method call will block until another thread calls {@code close()} on
* the dialog, otherwise the method call returns immediately
*/
public void showDialog(WindowBasedTextGUI textGUI, boolean blockUntilClosed) {<FILL_FUNCTION_BODY>}
/**
* Creates a new waiting dialog
* @param title Title of the waiting dialog
* @param text Text to display on the waiting dialog
* @return Created waiting dialog
*/
public static WaitingDialog createDialog(String title, String text) {
return new WaitingDialog(title, text);
}
/**
* Creates and displays a waiting dialog without blocking for it to finish
* @param textGUI GUI to add the dialog to
* @param title Title of the waiting dialog
* @param text Text to display on the waiting dialog
* @return Created waiting dialog
*/
public static WaitingDialog showDialog(WindowBasedTextGUI textGUI, String title, String text) {
WaitingDialog waitingDialog = createDialog(title, text);
waitingDialog.showDialog(textGUI, false);
return waitingDialog;
}
}
|
textGUI.addWindow(this);
if(blockUntilClosed) {
//Wait for the window to close, in case the window manager doesn't honor the MODAL hint
waitUntilClosed();
}
| 449
| 59
| 508
|
<methods>public java.lang.Object showDialog(com.googlecode.lanterna.gui2.WindowBasedTextGUI) <variables>private static final Set<com.googlecode.lanterna.gui2.Window.Hint> GLOBAL_DIALOG_HINTS
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.