prefix
stringlengths 82
32.6k
| middle
stringlengths 5
470
| suffix
stringlengths 0
81.2k
| file_path
stringlengths 6
168
| repo_name
stringlengths 16
77
| context
listlengths 5
5
| lang
stringclasses 4
values | ground_truth
stringlengths 5
470
|
---|---|---|---|---|---|---|---|
package com.projeto.workshopmongo.services;
import com.projeto.workshopmongo.domain.User;
import com.projeto.workshopmongo.dto.UserDTO;
import com.projeto.workshopmongo.repository.UserRepository;
import com.projeto.workshopmongo.services.exception.ObjectNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class UserService {
@Autowired
private UserRepository repository;
public List<User> findAll(){
return repository.findAll();
}
public User findById(String id){
Optional<User> obj= repository.findById(id);
return obj.orElseThrow(() -> new ObjectNotFoundException("Objeto não encontrado"));
}
public User insert(User obj){
return repository.insert(obj);
}
public void deleteById(String id){
findById(id);
repository.deleteById(id);
}
public User update(User obj){
User newObj = findById(obj.getId()) ;
updateData(newObj,obj);
return repository.save(newObj);
}
private void updateData(User newObj, User obj){
newObj.setId(obj.getId());
newObj.setName(obj.getName());
newObj.setEmail(obj.getEmail());
}
public User fromDTO (UserDTO objDTO){
| return new User(objDTO.getId(), objDTO.getName(), objDTO.getEmail()); |
}
}
| src/main/java/com/projeto/workshopmongo/services/UserService.java | wesleyfsousa01-workshop-spring-boot-mongoDB-2ed3895 | [
{
"filename": "src/main/java/com/projeto/workshopmongo/dto/UserDTO.java",
"retrieved_chunk": " public UserDTO(User obj){\n this.id = obj.getId();\n this.name = obj.getName();\n this.email = obj.getEmail();\n }\n public String getId() {\n return id;\n }\n public void setId(String id) {\n this.id = id;",
"score": 0.7943525910377502
},
{
"filename": "src/main/java/com/projeto/workshopmongo/domain/User.java",
"retrieved_chunk": " if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n User user = (User) o;\n return Objects.equals(id, user.id) && Objects.equals(name, user.name) && Objects.equals(email, user.email);\n }\n @Override\n public int hashCode() {\n return Objects.hash(id, name, email);\n }\n}",
"score": 0.7019078135490417
},
{
"filename": "src/main/java/com/projeto/workshopmongo/dto/AuthorDTO.java",
"retrieved_chunk": "package com.projeto.workshopmongo.dto;\nimport com.projeto.workshopmongo.domain.User;\nimport java.io.Serializable;\npublic class AuthorDTO implements Serializable {\n private String id;\n private String name;\n public AuthorDTO(){\n }\n public AuthorDTO(User obj) {\n this.id = obj.getId();",
"score": 0.7017234563827515
},
{
"filename": "src/main/java/com/projeto/workshopmongo/resources/UseResource.java",
"retrieved_chunk": " @PostMapping\n public ResponseEntity<Void> insert(@RequestBody UserDTO objDTO){\n User obj = service.fromDTO(objDTO);\n obj = service.insert(obj);\n URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path(\"/{id}\").buildAndExpand(obj.getId()).toUri();\n return ResponseEntity.created(uri).build();\n }\n @PutMapping(value = \"/{id}\")\n public ResponseEntity<Void> update(@RequestBody UserDTO objDto, @PathVariable String id){\n User obj = service.fromDTO(objDto);",
"score": 0.6982901096343994
},
{
"filename": "src/main/java/com/projeto/workshopmongo/resources/UseResource.java",
"retrieved_chunk": " public ResponseEntity<List<UserDTO>> findAll(){\n List<User>lista = service.findAll();\n List<UserDTO> listaDTO = lista.stream().map(x -> new UserDTO(x)).collect(Collectors.toList());\n return ResponseEntity.ok().body(listaDTO);\n }\n @GetMapping(value =\"/{id}\")\n public ResponseEntity<UserDTO> findById(@PathVariable String id){\n User obj = service.findById(id);\n return ResponseEntity.ok(new UserDTO(obj));\n }",
"score": 0.6929266452789307
}
] | java | return new User(objDTO.getId(), objDTO.getName(), objDTO.getEmail()); |
package net.edulive.janus.signaling_server;
import io.javalin.Javalin;
import io.javalin.http.staticfiles.Location;
import io.javalin.websocket.WsContext;
import org.eclipse.jetty.server.ServerConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
public class WebRTCSignalingApp {
private static final Map<WsContext, String> userUsernameMap = new ConcurrentHashMap<>();
private static final Logger logger = LoggerFactory.getLogger(WebRTCSignalingApp.class);
public static void main(String[] args) {
Javalin app = Javalin.create(config ->
config.staticFiles.add("/public", Location.CLASSPATH)
);
app.jettyServer().setServerHost("0.0.0.0");
app.start(7070);
MessageHandler messageHandler = new MessageHandler(System.getProperty("janus_address", "localhost:8188"));
app.ws("/signaling", ws -> {
ws.onConnect(ctx -> {
String username = randomString();
userUsernameMap.put(ctx, username);
messageHandler.createSession(username, ctx);
ctx.send("{\"type\":\"status\",\"status\":\"connected\"}");
logger.info("{} joined", username);
});
ws.onClose(ctx -> {
String username = userUsernameMap.get(ctx);
userUsernameMap.remove(ctx);
| messageHandler.destroySession(username); |
logger.info("{} left ", username);
});
ws.onMessage(ctx -> {
String username = userUsernameMap.get(ctx);
logger.info("{} send {}", username, ctx.message());
messageHandler.handleMessage(userUsernameMap.get(ctx), ctx);
});
});
}
private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
private static final Random random = new Random();
public static String randomString() {
int length = 20; // the desired length of the random string
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++) {
int index = random.nextInt(CHARACTERS.length());
sb.append(CHARACTERS.charAt(index));
}
return sb.toString();
}
}
| signaling/src/main/java/net/edulive/janus/signaling_server/WebRTCSignalingApp.java | vudangngoc-janus-java-client-b9f0b37 | [
{
"filename": "signaling/src/main/java/net/edulive/janus/signaling_server/MessageHandler.java",
"retrieved_chunk": " .thenAccept(sessionId -> {\n Long handleId = videoRoomAdaptor.attachToVideoRoom(sessionId);\n sessionToHandle.put(sessionId, handleId);\n });\n }\n public void destroySession(String userId) {\n Long janusSessionId = userToJanus.remove(userId);\n userContexts.remove(userId);\n if (janusSessionId != null) {\n janusToUserMap.remove(janusSessionId);",
"score": 0.7872519493103027
},
{
"filename": "signaling/src/main/java/net/edulive/janus/signaling_server/MessageHandler.java",
"retrieved_chunk": " }\n }\n public void createSession(String userId, WsConnectContext ctx) {\n CompletableFuture.supplyAsync(janusClient::createSession)\n .thenApply(sessionId -> {\n janusToUserMap.put(sessionId, userId);\n userToJanus.put(userId, sessionId);\n userContexts.put(userId, ctx);\n return sessionId;\n })",
"score": 0.7805604934692383
},
{
"filename": "signaling/src/main/java/net/edulive/janus/signaling_server/MessageHandler.java",
"retrieved_chunk": " break;\n case \"unpublish\":\n videoRoomAdaptor.stopPublishStream(janusSessionId, sessionToHandle.get(janusSessionId));\n break;\n case \"leave_room\":\n Long handleId = sessionToHandle.remove(janusSessionId);\n if (handleId != null) {\n videoRoomAdaptor.leaveRoom(janusSessionId, handleId);\n }\n context.closeSession();",
"score": 0.7545638680458069
},
{
"filename": "signaling/src/main/java/net/edulive/janus/signaling_server/MessageHandler.java",
"retrieved_chunk": " break;\n case \"room_info\":\n context.send(\n videoRoomAdaptor.getAllRooms(janusSessionId, sessionToHandle.get(janusSessionId)\n ).put(\"type\", \"room_info_result\").toString());\n break;\n case \"leave_room_subscriber\":\n Long subscriberSession = publisherSessionToSubscriberSession.remove(janusSessionId);\n if (subscriberSession != null)\n videoRoomAdaptor.leaveRoom(subscriberSession, sessionToHandle.remove(subscriberSession));",
"score": 0.7391963005065918
},
{
"filename": "signaling/src/main/java/net/edulive/janus/signaling_server/MessageHandler.java",
"retrieved_chunk": " }\n Long janusSessionId = userToJanus.get(user);\n switch (json.getString(\"type\")) {\n case \"join_room\":\n handleJoinRoom(user, context, json, janusSessionId);\n break;\n case \"create_room\":\n long roomName = videoRoomAdaptor.createRoom(janusSessionId, sessionToHandle.get(janusSessionId));\n context.send(new JSONObject().put(\"type\", \"create_room_result\").put(\"room_name\", roomName).toString());\n break;",
"score": 0.7379488945007324
}
] | java | messageHandler.destroySession(username); |
package com.projeto.workshopmongo.config;
import com.projeto.workshopmongo.domain.Post;
import com.projeto.workshopmongo.domain.User;
import com.projeto.workshopmongo.dto.AuthorDTO;
import com.projeto.workshopmongo.dto.CommentDTO;
import com.projeto.workshopmongo.repository.PostRepository;
import com.projeto.workshopmongo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.TimeZone;
@Configuration
public class Instanciation implements CommandLineRunner {
@Autowired
private UserRepository userRepository;
@Autowired
PostRepository postRepository;
@Override
public void run(String... args) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
userRepository.deleteAll();
postRepository.deleteAll();
User maria = new User(null, "Maria Brown", "[email protected]");
User alex = new User(null, "Alex Green", "[email protected]");
User bob = new User(null, "Bob Grey", "[email protected]");
userRepository.saveAll(Arrays.asList(maria,alex,bob));
Post post1 = new Post (null, sdf.parse("21/03/2018"), "Partiu viagem","Vou viajar para SP abraços", new AuthorDTO(maria));
Post post2 = new Post(null, sdf.parse("18/04/2023"),"Workshop muito bom!","Estou aprendendo bastante sobre Spring!", new AuthorDTO(bob));
CommentDTO c1 = new CommentDTO("Boa viagem mano!", sdf.parse("21/02/2018"),new AuthorDTO(alex));
CommentDTO c2 = new CommentDTO("Aproveite", sdf.parse("22/02/2018"),new AuthorDTO(bob));
CommentDTO c3 = new CommentDTO("Tenha um ótimo dia!", sdf.parse("23/02/2018"),new AuthorDTO(alex));
post1.getCommentsList().addAll(Arrays.asList(c1,c2));
post2.getCommentsList().addAll(Arrays.asList(c3));
postRepository.saveAll(Arrays.asList(post1, post2));
| maria.getPosts().addAll(Arrays.asList(post1,post2)); |
userRepository.save(maria);
}
}
| src/main/java/com/projeto/workshopmongo/config/Instanciation.java | wesleyfsousa01-workshop-spring-boot-mongoDB-2ed3895 | [
{
"filename": "src/main/java/com/projeto/workshopmongo/services/UserService.java",
"retrieved_chunk": " return repository.save(newObj);\n }\n private void updateData(User newObj, User obj){\n newObj.setId(obj.getId());\n newObj.setName(obj.getName());\n newObj.setEmail(obj.getEmail());\n }\n public User fromDTO (UserDTO objDTO){\n return new User(objDTO.getId(), objDTO.getName(), objDTO.getEmail());\n }",
"score": 0.6322029829025269
},
{
"filename": "src/main/java/com/projeto/workshopmongo/resources/PostResource.java",
"retrieved_chunk": " text = URL.decodeParam(text);\n Date min = URL.convertDate(minDate, new Date(0L));\n Date max = URL.convertDate(maxDate, new Date());\n List<Post> list = postService.fullSearch(text, min ,max);\n return ResponseEntity.ok().body(list);\n }\n}",
"score": 0.5680642127990723
},
{
"filename": "src/main/java/com/projeto/workshopmongo/resources/UseResource.java",
"retrieved_chunk": " public ResponseEntity<List<UserDTO>> findAll(){\n List<User>lista = service.findAll();\n List<UserDTO> listaDTO = lista.stream().map(x -> new UserDTO(x)).collect(Collectors.toList());\n return ResponseEntity.ok().body(listaDTO);\n }\n @GetMapping(value =\"/{id}\")\n public ResponseEntity<UserDTO> findById(@PathVariable String id){\n User obj = service.findById(id);\n return ResponseEntity.ok(new UserDTO(obj));\n }",
"score": 0.5629644989967346
},
{
"filename": "src/main/java/com/projeto/workshopmongo/services/UserService.java",
"retrieved_chunk": " public User insert(User obj){\n return repository.insert(obj);\n }\n public void deleteById(String id){\n findById(id);\n repository.deleteById(id);\n }\n public User update(User obj){\n User newObj = findById(obj.getId()) ;\n updateData(newObj,obj);",
"score": 0.5494044423103333
},
{
"filename": "src/main/java/com/projeto/workshopmongo/repository/PostRepository.java",
"retrieved_chunk": "package com.projeto.workshopmongo.repository;\nimport com.projeto.workshopmongo.domain.Post;\nimport org.springframework.data.mongodb.repository.MongoRepository;\nimport org.springframework.data.mongodb.repository.Query;\nimport org.springframework.stereotype.Repository;\nimport java.util.Date;\nimport java.util.List;\n@Repository\npublic interface PostRepository extends MongoRepository<Post, String> {\n @Query(\"{ 'title': { $regex: ?0, $options: 'i' } }\")",
"score": 0.5176267027854919
}
] | java | maria.getPosts().addAll(Arrays.asList(post1,post2)); |
package filter.statistics;
class MethodStatistics {
private final long total;
private final Modifiers modifiers;
MethodStatistics(
final long total,
final Modifier... modifier
) {
this(total, new Modifiers(modifier));
}
MethodStatistics(
final long total,
final Modifiers modifiers
) {
this.total = total;
this.modifiers = modifiers;
}
long total() {
return this.total;
}
boolean isInstancePrivate() {
return this.modifiers.isInstancePrivate();
}
boolean isInstancePackagePrivate() {
return this.modifiers.isInstancePackage();
}
boolean isInstancePublicOverridden() {
| return this.modifiers.isInstanceOverridden(); |
}
boolean isInstancePublic() {
return this.modifiers.isInstancePublic();
}
boolean isStaticPackagePrivate() {
return this.modifiers.isStaticPackagePrivate();
}
boolean isStaticPublic() {
return this.modifiers.isStaticPublic();
}
boolean isStaticPrivate() {
return this.modifiers.isStaticPrivate();
}
boolean isConstructor() {
return this.modifiers.isConstructor();
}
public boolean isNotFound() {
return this.modifiers.isNotFound();
}
}
| src/main/java/filter/statistics/MethodStatistics.java | volodya-lombrozo-oop-statistics-filter-c298155 | [
{
"filename": "src/main/java/filter/statistics/Modifiers.java",
"retrieved_chunk": " }\n public boolean isStatic() {\n return this.modifiers.contains(Modifier.STATIC);\n }\n boolean isInstancePrivate() {\n return this.modifiers.contains(Modifier.PRIVATE)\n && this.modifiers.contains(Modifier.INSTANCE);\n }\n boolean isInstancePackage() {\n return this.modifiers.contains(Modifier.PACKAGE_PRIVATE)",
"score": 0.9249098300933838
},
{
"filename": "src/main/java/filter/statistics/Modifiers.java",
"retrieved_chunk": " }\n boolean isStaticPackagePrivate() {\n return this.modifiers.contains(Modifier.PACKAGE_PRIVATE)\n && this.modifiers.contains(Modifier.STATIC);\n }\n boolean isStaticPublic() {\n return this.modifiers.contains(Modifier.PUBLIC)\n && this.modifiers.contains(Modifier.STATIC);\n }\n boolean isStaticPrivate() {",
"score": 0.8965691924095154
},
{
"filename": "src/main/java/filter/statistics/Modifiers.java",
"retrieved_chunk": " && this.modifiers.contains(Modifier.INSTANCE);\n }\n boolean isInstanceOverridden() {\n return this.modifiers.contains(Modifier.OVERRIDDEN)\n && this.modifiers.contains(Modifier.INSTANCE);\n }\n boolean isInstancePublic() {\n return this.modifiers.contains(Modifier.PUBLIC)\n && this.modifiers.contains(Modifier.INSTANCE)\n && !this.modifiers.contains(Modifier.OVERRIDDEN);",
"score": 0.8907192349433899
},
{
"filename": "src/main/java/filter/statistics/Modifiers.java",
"retrieved_chunk": " return this.modifiers.contains(Modifier.PRIVATE)\n && this.modifiers.contains(Modifier.STATIC);\n }\n boolean isConstructor() {\n return this.modifiers.contains(Modifier.CONSTRUCTOR);\n }\n boolean isNotFound() {\n return this.modifiers.contains(Modifier.NOT_FOUND);\n }\n}",
"score": 0.8454619646072388
},
{
"filename": "src/main/java/filter/statistics/ParsedMethod.java",
"retrieved_chunk": " }\n if (this.method.isPublic()) {\n modifiers.add(Modifier.PUBLIC);\n } else if (this.method.isPrivate()) {\n modifiers.add(Modifier.PRIVATE);\n } else {\n modifiers.add(Modifier.PACKAGE_PRIVATE);\n }\n return new Modifiers(modifiers);\n }",
"score": 0.8365625143051147
}
] | java | return this.modifiers.isInstanceOverridden(); |
package filter.statistics;
import filter.CSV;
import filter.StatisticsCase;
import filter.csv.CSVCell;
import filter.csv.CSVRows;
import filter.csv.ParsedCSVRow;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import lombok.ToString;
@ToString
public class StatisticsCaseWithoutSources implements StatisticsCase {
private static final String[] EMPTY = {};
private final String title;
private final CSV csv;
private final String[] excluded;
StatisticsCaseWithoutSources(
final String title,
final CSV csv,
final String... excluded
) {
this.title = title;
this.csv = csv;
this.excluded = excluded;
}
@Override
public List<CSVCell> cells() {
return Stream.concat(
Stream.of(new CSVCell("Application", this.title)),
this.statistics().cells().stream()
).collect(Collectors.toList());
}
StatisticsWithoutSources statistics() {
final Set<ParsedCSVRow> rows = new CSVRows(this.csv, StatisticsCaseWithoutSources.EMPTY,
this.excluded
).toSet();
final StatisticsWithoutSources stat = new StatisticsWithoutSources();
for (final ParsedCSVRow row : rows) {
if (row.isConstructor()) {
stat.add(new MethodStatistics(row.getCount(), Modifier.CONSTRUCTOR));
} else {
stat.add(new | MethodStatistics(row.getCount())); |
}
}
return stat;
}
}
| src/main/java/filter/statistics/StatisticsCaseWithoutSources.java | volodya-lombrozo-oop-statistics-filter-c298155 | [
{
"filename": "src/main/java/filter/statistics/StatisticsCaseWithModifiers.java",
"retrieved_chunk": " ).collect(Collectors.toList());\n }\n StatisticsWithModifiers statistics() {\n final Set<ParsedCSVRow> csvRows = new CSVRows(this.csv, this.filters).toSet();\n final Map<String, Modifiers> methods = this.methods();\n StatisticsWithModifiers stats = new StatisticsWithModifiers();\n for (final ParsedCSVRow row : csvRows) {\n final long total = row.getCount();\n if (row.isConstructor()) {\n stats.add(new MethodStatistics(total, Modifier.CONSTRUCTOR));",
"score": 0.939943790435791
},
{
"filename": "src/main/java/filter/statistics/StatisticsWithModifiers.java",
"retrieved_chunk": " this(new ArrayList<>());\n }\n private StatisticsWithModifiers(final Collection<MethodStatistics> rows) {\n this.rows = rows;\n }\n @Override\n public List<CSVCell> cells() {\n return Arrays.asList(\n new CSVCell(\"Total\", this.total()),\n new CSVCell(\"Instance Private Methods\", this.instancePrivate()),",
"score": 0.8285678625106812
},
{
"filename": "src/main/java/filter/statistics/StatisticsWithModifiers.java",
"retrieved_chunk": " this.constructorsPercent(),\n };\n }\n StatisticsWithModifiers add(final MethodStatistics statistics) {\n this.rows.add(statistics);\n return this;\n }\n private long total() {\n return this.rows.stream().mapToLong(MethodStatistics::total).sum();\n }",
"score": 0.8266029953956604
},
{
"filename": "src/main/java/filter/statistics/StatisticsWithoutSources.java",
"retrieved_chunk": " new CSVCell(\"Library Total\", this.total()),\n new CSVCell(\"Library Methods\", this.methods()),\n new CSVCell(\"Library Constructors\", this.constructors())\n );\n }\n void add(final MethodStatistics methodStatistics) {\n this.statistics.add(methodStatistics);\n }\n private long total() {\n return this.statistics.stream().mapToLong(MethodStatistics::total).sum();",
"score": 0.8260812759399414
},
{
"filename": "src/main/java/filter/statistics/StatisticCaseApplications.java",
"retrieved_chunk": " Stream.of(new CSVCell(\"Application\", this.title)),\n this.statistics().cells().stream()\n ).collect(Collectors.toList());\n }\n private Statistics statistics() {\n return new StatisticsComposite(\n new StatisticsCaseWithModifiers(\n this.title,\n this.csv,\n this.project,",
"score": 0.8247257471084595
}
] | java | MethodStatistics(row.getCount())); |
package filter.statistics;
import filter.CSV;
import filter.StatisticsCase;
import filter.csv.CSVCell;
import filter.csv.CSVRows;
import filter.csv.ParsedCSVRow;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import lombok.ToString;
@ToString
public class StatisticsCaseWithoutSources implements StatisticsCase {
private static final String[] EMPTY = {};
private final String title;
private final CSV csv;
private final String[] excluded;
StatisticsCaseWithoutSources(
final String title,
final CSV csv,
final String... excluded
) {
this.title = title;
this.csv = csv;
this.excluded = excluded;
}
@Override
public List<CSVCell> cells() {
return Stream.concat(
Stream.of(new CSVCell("Application", this.title)),
this.statistics().cells().stream()
).collect(Collectors.toList());
}
StatisticsWithoutSources statistics() {
final Set<ParsedCSVRow> rows = new CSVRows(this.csv, StatisticsCaseWithoutSources.EMPTY,
this.excluded
).toSet();
final StatisticsWithoutSources stat = new StatisticsWithoutSources();
for (final ParsedCSVRow row : rows) {
if (row.isConstructor()) {
stat.add(new MethodStatistics( | row.getCount(), Modifier.CONSTRUCTOR)); |
} else {
stat.add(new MethodStatistics(row.getCount()));
}
}
return stat;
}
}
| src/main/java/filter/statistics/StatisticsCaseWithoutSources.java | volodya-lombrozo-oop-statistics-filter-c298155 | [
{
"filename": "src/main/java/filter/statistics/StatisticsCaseWithModifiers.java",
"retrieved_chunk": " ).collect(Collectors.toList());\n }\n StatisticsWithModifiers statistics() {\n final Set<ParsedCSVRow> csvRows = new CSVRows(this.csv, this.filters).toSet();\n final Map<String, Modifiers> methods = this.methods();\n StatisticsWithModifiers stats = new StatisticsWithModifiers();\n for (final ParsedCSVRow row : csvRows) {\n final long total = row.getCount();\n if (row.isConstructor()) {\n stats.add(new MethodStatistics(total, Modifier.CONSTRUCTOR));",
"score": 0.9488521218299866
},
{
"filename": "src/main/java/filter/statistics/StatisticCaseApplications.java",
"retrieved_chunk": " Stream.of(new CSVCell(\"Application\", this.title)),\n this.statistics().cells().stream()\n ).collect(Collectors.toList());\n }\n private Statistics statistics() {\n return new StatisticsComposite(\n new StatisticsCaseWithModifiers(\n this.title,\n this.csv,\n this.project,",
"score": 0.8265769481658936
},
{
"filename": "src/main/java/filter/statistics/StatisticsWithoutSources.java",
"retrieved_chunk": " private final Collection<MethodStatistics> statistics;\n StatisticsWithoutSources() {\n this(new ArrayList<>(0));\n }\n private StatisticsWithoutSources(final Collection<MethodStatistics> statistics) {\n this.statistics = statistics;\n }\n @Override\n public List<CSVCell> cells() {\n return Arrays.asList(",
"score": 0.8264671564102173
},
{
"filename": "src/main/java/filter/statistics/StatisticsWithModifiers.java",
"retrieved_chunk": " this(new ArrayList<>());\n }\n private StatisticsWithModifiers(final Collection<MethodStatistics> rows) {\n this.rows = rows;\n }\n @Override\n public List<CSVCell> cells() {\n return Arrays.asList(\n new CSVCell(\"Total\", this.total()),\n new CSVCell(\"Instance Private Methods\", this.instancePrivate()),",
"score": 0.8236290216445923
},
{
"filename": "src/main/java/filter/statistics/StatisticsWithModifiers.java",
"retrieved_chunk": " this.constructorsPercent(),\n };\n }\n StatisticsWithModifiers add(final MethodStatistics statistics) {\n this.rows.add(statistics);\n return this;\n }\n private long total() {\n return this.rows.stream().mapToLong(MethodStatistics::total).sum();\n }",
"score": 0.8115168809890747
}
] | java | row.getCount(), Modifier.CONSTRUCTOR)); |
package filter.statistics;
import filter.Application;
import filter.CSV;
import filter.StatisticsCase;
import filter.csv.CSVCell;
import java.util.List;
import lombok.ToString;
@ToString
public class StatisticsCaseLibrary implements StatisticsCase {
private final String title;
private final CSV csv;
private final Application project;
private final String[] filters;
public StatisticsCaseLibrary(
final String title,
final CSV csv,
final Application project,
final String... filters
) {
this.title = title;
this.csv = csv;
this.project = project;
this.filters = filters;
}
@Override
public List<CSVCell> cells() {
return new StatisticsComposite(
new StatisticsCaseWithModifiers(title, csv, project, filters),
| new GitHubMetrics(this.project.githubUrl())
).cells(); |
}
}
| src/main/java/filter/statistics/StatisticsCaseLibrary.java | volodya-lombrozo-oop-statistics-filter-c298155 | [
{
"filename": "src/main/java/filter/statistics/StatisticCaseApplications.java",
"retrieved_chunk": " final String... filters\n ) {\n this.title = title;\n this.csv = csv;\n this.project = project;\n this.filters = filters;\n }\n @Override\n public List<CSVCell> cells() {\n return Stream.concat(",
"score": 0.899992823600769
},
{
"filename": "src/main/java/filter/statistics/StatisticsCaseWithModifiers.java",
"retrieved_chunk": " this.title = title;\n this.csv = csv;\n this.project = project;\n this.filters = filters;\n }\n @Override\n public List<CSVCell> cells() {\n return Stream.concat(\n Stream.of(new CSVCell(\"Application\", this.title)),\n this.statistics().cells().stream()",
"score": 0.8954513669013977
},
{
"filename": "src/main/java/filter/statistics/StatisticCaseApplications.java",
"retrieved_chunk": " Stream.of(new CSVCell(\"Application\", this.title)),\n this.statistics().cells().stream()\n ).collect(Collectors.toList());\n }\n private Statistics statistics() {\n return new StatisticsComposite(\n new StatisticsCaseWithModifiers(\n this.title,\n this.csv,\n this.project,",
"score": 0.8888060450553894
},
{
"filename": "src/main/java/filter/statistics/StatisticsCaseWithoutSources.java",
"retrieved_chunk": " final String... excluded\n ) {\n this.title = title;\n this.csv = csv;\n this.excluded = excluded;\n }\n @Override\n public List<CSVCell> cells() {\n return Stream.concat(\n Stream.of(new CSVCell(\"Application\", this.title)),",
"score": 0.8581931591033936
},
{
"filename": "src/main/java/filter/statistics/StatisticsWithModifiers.java",
"retrieved_chunk": " this(new ArrayList<>());\n }\n private StatisticsWithModifiers(final Collection<MethodStatistics> rows) {\n this.rows = rows;\n }\n @Override\n public List<CSVCell> cells() {\n return Arrays.asList(\n new CSVCell(\"Total\", this.total()),\n new CSVCell(\"Instance Private Methods\", this.instancePrivate()),",
"score": 0.8383365869522095
}
] | java | new GitHubMetrics(this.project.githubUrl())
).cells(); |
package filter.statistics;
import filter.Statistics;
import filter.csv.CSVCell;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import lombok.ToString;
@ToString
public class StatisticsWithoutSources implements Statistics {
private final Collection<MethodStatistics> statistics;
StatisticsWithoutSources() {
this(new ArrayList<>(0));
}
private StatisticsWithoutSources(final Collection<MethodStatistics> statistics) {
this.statistics = statistics;
}
@Override
public List<CSVCell> cells() {
return Arrays.asList(
new CSVCell("Library Total", this.total()),
new CSVCell("Library Methods", this.methods()),
new CSVCell("Library Constructors", this.constructors())
);
}
void add(final MethodStatistics methodStatistics) {
this.statistics.add(methodStatistics);
}
private long total() {
return this.statistics.stream().mapToLong(MethodStatistics::total).sum();
}
private long methods() {
return this.statistics.stream()
.filter( | method -> !method.isConstructor())
.mapToLong(MethodStatistics::total)
.sum(); |
}
private long constructors() {
return this.statistics.stream()
.filter(MethodStatistics::isConstructor)
.mapToLong(MethodStatistics::total)
.sum();
}
}
| src/main/java/filter/statistics/StatisticsWithoutSources.java | volodya-lombrozo-oop-statistics-filter-c298155 | [
{
"filename": "src/main/java/filter/statistics/StatisticsWithModifiers.java",
"retrieved_chunk": " private long staticPublic() {\n return this.rows.stream()\n .filter(MethodStatistics::isStaticPublic)\n .mapToLong(MethodStatistics::total)\n .sum();\n }\n private long constructors() {\n return this.rows.stream()\n .filter(MethodStatistics::isConstructor)\n .mapToLong(MethodStatistics::total)",
"score": 0.9457470178604126
},
{
"filename": "src/main/java/filter/statistics/StatisticsWithModifiers.java",
"retrieved_chunk": " private long notFound() {\n return this.rows.stream()\n .filter(MethodStatistics::isNotFound)\n .mapToLong(MethodStatistics::total).sum();\n }\n private long instancePrivate() {\n return this.rows.stream()\n .filter(MethodStatistics::isInstancePrivate)\n .mapToLong(MethodStatistics::total).sum();\n }",
"score": 0.9252544045448303
},
{
"filename": "src/main/java/filter/statistics/StatisticsWithModifiers.java",
"retrieved_chunk": " private long instancePackagePrivate() {\n return this.rows.stream()\n .filter(MethodStatistics::isInstancePackagePrivate)\n .mapToLong(MethodStatistics::total)\n .sum();\n }\n private long instancePublicOverridden() {\n return this.rows.stream()\n .filter(MethodStatistics::isInstancePublicOverridden)\n .mapToLong(MethodStatistics::total)",
"score": 0.923538863658905
},
{
"filename": "src/main/java/filter/statistics/StatisticsWithModifiers.java",
"retrieved_chunk": " .sum();\n }\n private long instancePublic() {\n return this.rows.stream()\n .filter(MethodStatistics::isInstancePublic)\n .mapToLong(MethodStatistics::total)\n .sum();\n }\n private long staticPrivate() {\n return this.rows.stream()",
"score": 0.9219820499420166
},
{
"filename": "src/main/java/filter/statistics/StatisticsWithModifiers.java",
"retrieved_chunk": " .filter(MethodStatistics::isStaticPrivate)\n .mapToLong(MethodStatistics::total)\n .sum();\n }\n private long staticPackagePrivate() {\n return this.rows.stream()\n .filter(MethodStatistics::isStaticPackagePrivate)\n .mapToLong(MethodStatistics::total)\n .sum();\n }",
"score": 0.9133021831512451
}
] | java | method -> !method.isConstructor())
.mapToLong(MethodStatistics::total)
.sum(); |
package com.projeto.workshopmongo.resources;
import com.projeto.workshopmongo.domain.Post;
import com.projeto.workshopmongo.domain.User;
import com.projeto.workshopmongo.dto.UserDTO;
import com.projeto.workshopmongo.resources.util.URL;
import com.projeto.workshopmongo.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.net.URI;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
@RestController
@RequestMapping(value="/users")
public class UseResource {
@Autowired
private UserService service;
@GetMapping
public ResponseEntity<List<UserDTO>> findAll(){
List<User>lista = service.findAll();
List<UserDTO> listaDTO = lista.stream().map(x -> new UserDTO(x)).collect(Collectors.toList());
return ResponseEntity.ok().body(listaDTO);
}
@GetMapping(value ="/{id}")
public ResponseEntity<UserDTO> findById(@PathVariable String id){
User obj = service.findById(id);
return ResponseEntity.ok(new UserDTO(obj));
}
@PostMapping
public ResponseEntity<Void> insert(@RequestBody UserDTO objDTO){
User obj = service.fromDTO(objDTO);
obj = service.insert(obj);
URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(obj.getId()).toUri();
return ResponseEntity.created(uri).build();
}
@PutMapping(value = "/{id}")
public ResponseEntity<Void> update(@RequestBody UserDTO objDto, @PathVariable String id){
User obj = service.fromDTO(objDto);
| obj.setId(id); |
obj = service.update(obj);
return ResponseEntity.noContent().build();
}
@GetMapping(value = "{id}/posts")
ResponseEntity<List<Post>> findPost(@PathVariable String id){
User obj = service.findById(id);
return ResponseEntity.ok().body(obj.getPosts());
}
@DeleteMapping(value = "/{id}")
public ResponseEntity<Void> deleteById(@PathVariable String id){
service.deleteById(id);
return ResponseEntity.noContent().build();
}
}
| src/main/java/com/projeto/workshopmongo/resources/UseResource.java | wesleyfsousa01-workshop-spring-boot-mongoDB-2ed3895 | [
{
"filename": "src/main/java/com/projeto/workshopmongo/resources/PostResource.java",
"retrieved_chunk": "@RequestMapping(value = \"/posts\")\npublic class PostResource {\n @Autowired\n private PostService postService;\n @GetMapping(value = \"/{id}\")\n public ResponseEntity<Post> findById(@PathVariable String id){\n Post obj = postService.findById(id);\n return ResponseEntity.ok().body(obj);\n }\n @GetMapping(value = \"/titlesearch\")",
"score": 0.7610954642295837
},
{
"filename": "src/main/java/com/projeto/workshopmongo/services/UserService.java",
"retrieved_chunk": " public User insert(User obj){\n return repository.insert(obj);\n }\n public void deleteById(String id){\n findById(id);\n repository.deleteById(id);\n }\n public User update(User obj){\n User newObj = findById(obj.getId()) ;\n updateData(newObj,obj);",
"score": 0.7228633165359497
},
{
"filename": "src/main/java/com/projeto/workshopmongo/services/UserService.java",
"retrieved_chunk": " return repository.save(newObj);\n }\n private void updateData(User newObj, User obj){\n newObj.setId(obj.getId());\n newObj.setName(obj.getName());\n newObj.setEmail(obj.getEmail());\n }\n public User fromDTO (UserDTO objDTO){\n return new User(objDTO.getId(), objDTO.getName(), objDTO.getEmail());\n }",
"score": 0.6966248750686646
},
{
"filename": "src/main/java/com/projeto/workshopmongo/resources/PostResource.java",
"retrieved_chunk": " public ResponseEntity<List<Post>> findByTitle(@RequestParam(value = \"text\", defaultValue = \"\") String text){\n String decodingText = URL.decodeParam(text);\n List<Post> list = postService.findByTitle(decodingText);\n return ResponseEntity.ok().body(list);\n }\n @GetMapping(\"/fullsearch\")\n public ResponseEntity<List<Post>> fullSearch(\n @RequestParam(value = \"text\", defaultValue = \"\") String text,\n @RequestParam(value = \"minDate\", defaultValue = \"\") String minDate,\n @RequestParam(value = \"maxDate\", defaultValue = \"\") String maxDate) {",
"score": 0.6739544868469238
},
{
"filename": "src/main/java/com/projeto/workshopmongo/services/UserService.java",
"retrieved_chunk": "public class UserService {\n @Autowired\n private UserRepository repository;\n public List<User> findAll(){\n return repository.findAll();\n }\n public User findById(String id){\n Optional<User> obj= repository.findById(id);\n return obj.orElseThrow(() -> new ObjectNotFoundException(\"Objeto não encontrado\"));\n }",
"score": 0.634134829044342
}
] | java | obj.setId(id); |
package filter.statistics;
class MethodStatistics {
private final long total;
private final Modifiers modifiers;
MethodStatistics(
final long total,
final Modifier... modifier
) {
this(total, new Modifiers(modifier));
}
MethodStatistics(
final long total,
final Modifiers modifiers
) {
this.total = total;
this.modifiers = modifiers;
}
long total() {
return this.total;
}
boolean isInstancePrivate() {
return this.modifiers.isInstancePrivate();
}
boolean isInstancePackagePrivate() {
return this.modifiers.isInstancePackage();
}
boolean isInstancePublicOverridden() {
return this.modifiers.isInstanceOverridden();
}
boolean isInstancePublic() {
return this.modifiers.isInstancePublic();
}
boolean isStaticPackagePrivate() {
return this | .modifiers.isStaticPackagePrivate(); |
}
boolean isStaticPublic() {
return this.modifiers.isStaticPublic();
}
boolean isStaticPrivate() {
return this.modifiers.isStaticPrivate();
}
boolean isConstructor() {
return this.modifiers.isConstructor();
}
public boolean isNotFound() {
return this.modifiers.isNotFound();
}
}
| src/main/java/filter/statistics/MethodStatistics.java | volodya-lombrozo-oop-statistics-filter-c298155 | [
{
"filename": "src/main/java/filter/statistics/Modifiers.java",
"retrieved_chunk": " }\n public boolean isStatic() {\n return this.modifiers.contains(Modifier.STATIC);\n }\n boolean isInstancePrivate() {\n return this.modifiers.contains(Modifier.PRIVATE)\n && this.modifiers.contains(Modifier.INSTANCE);\n }\n boolean isInstancePackage() {\n return this.modifiers.contains(Modifier.PACKAGE_PRIVATE)",
"score": 0.9334875345230103
},
{
"filename": "src/main/java/filter/statistics/Modifiers.java",
"retrieved_chunk": " }\n boolean isStaticPackagePrivate() {\n return this.modifiers.contains(Modifier.PACKAGE_PRIVATE)\n && this.modifiers.contains(Modifier.STATIC);\n }\n boolean isStaticPublic() {\n return this.modifiers.contains(Modifier.PUBLIC)\n && this.modifiers.contains(Modifier.STATIC);\n }\n boolean isStaticPrivate() {",
"score": 0.9252961874008179
},
{
"filename": "src/main/java/filter/statistics/Modifiers.java",
"retrieved_chunk": " && this.modifiers.contains(Modifier.INSTANCE);\n }\n boolean isInstanceOverridden() {\n return this.modifiers.contains(Modifier.OVERRIDDEN)\n && this.modifiers.contains(Modifier.INSTANCE);\n }\n boolean isInstancePublic() {\n return this.modifiers.contains(Modifier.PUBLIC)\n && this.modifiers.contains(Modifier.INSTANCE)\n && !this.modifiers.contains(Modifier.OVERRIDDEN);",
"score": 0.9066005349159241
},
{
"filename": "src/main/java/filter/statistics/Modifiers.java",
"retrieved_chunk": " return this.modifiers.contains(Modifier.PRIVATE)\n && this.modifiers.contains(Modifier.STATIC);\n }\n boolean isConstructor() {\n return this.modifiers.contains(Modifier.CONSTRUCTOR);\n }\n boolean isNotFound() {\n return this.modifiers.contains(Modifier.NOT_FOUND);\n }\n}",
"score": 0.8445795178413391
},
{
"filename": "src/main/java/filter/statistics/ParsedMethod.java",
"retrieved_chunk": " }\n Modifiers modifiers() {\n final Set<Modifier> modifiers = new HashSet<>();\n if (this.method.isStatic()) {\n modifiers.add(Modifier.STATIC);\n } else {\n modifiers.add(Modifier.INSTANCE);\n }\n if (this.method.getAnnotationByClass(Override.class).isPresent()) {\n modifiers.add(Modifier.OVERRIDDEN);",
"score": 0.8423516154289246
}
] | java | .modifiers.isStaticPackagePrivate(); |
package filter.statistics;
import filter.Application;
import filter.CSV;
import filter.StatisticsCase;
import filter.csv.CSVCell;
import filter.csv.CSVRows;
import filter.csv.ParsedCSVRow;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import lombok.ToString;
@ToString
public final class StatisticsCaseWithModifiers implements StatisticsCase {
private final String title;
private final CSV csv;
private final Application project;
private final String[] filters;
public StatisticsCaseWithModifiers(
final String title,
final CSV csv,
final Application project,
final String... filters
) {
this.title = title;
this.csv = csv;
this.project = project;
this.filters = filters;
}
@Override
public List<CSVCell> cells() {
return Stream.concat(
Stream.of(new CSVCell("Application", this.title)),
this.statistics().cells().stream()
).collect(Collectors.toList());
}
StatisticsWithModifiers statistics() {
final Set<ParsedCSVRow> csvRows = new CSVRows(this.csv, this.filters).toSet();
final Map<String, Modifiers> methods = this.methods();
StatisticsWithModifiers stats = new StatisticsWithModifiers();
for (final ParsedCSVRow row : csvRows) {
final long total = row.getCount();
if (row.isConstructor()) {
stats.add(new MethodStatistics(total, Modifier.CONSTRUCTOR));
} else if (!methods.containsKey(row.shortMethodName())) {
final String alternative = row.shortMethodNameWithoutFQNForParameters();
if (methods.containsKey(alternative)) {
stats.add(new MethodStatistics(total, methods.get(alternative)));
} else {
Logger.getLogger("PARSER")
.warning(
() -> String.format("Method not found: %s", row.fullMethodName())
);
stats.add(new MethodStatistics(total, Modifier.NOT_FOUND));
}
} else if (methods.containsKey(row.shortMethodName())) {
stats.add(new MethodStatistics(total, methods.get(row.shortMethodName())));
}
}
return stats;
}
/**
* Parses methods from entire project.
* @return Map of methods.
*/
private Map<String, Modifiers> methods() {
return this.parseClasses().values()
.stream()
.flatMap(parsed -> parsed.methods().stream())
.collect(Collectors.toMap(ParsedMethod::name, ParsedMethod::modifiers, (a, b) -> a));
}
private Map<String, ParsedClass> parseClasses() {
try (final Stream<Path> files = Files.walk | (this.project.path())) { |
return files
.filter(Files::exists)
.filter(Files::isRegularFile)
.parallel()
.filter(path -> path.toString().endsWith(".java"))
.flatMap(ParsedClass::parse)
.collect(
Collectors.toMap(
ParsedClass::name,
parsed -> parsed,
ParsedClass::add
)
);
} catch (final IOException exception) {
throw new IllegalStateException(exception);
}
}
}
| src/main/java/filter/statistics/StatisticsCaseWithModifiers.java | volodya-lombrozo-oop-statistics-filter-c298155 | [
{
"filename": "src/main/java/filter/statistics/ParsedClass.java",
"retrieved_chunk": " }\n String name() {\n return this.name;\n }\n Collection<ParsedMethod> methods() {\n return this.unit.stream()\n .flatMap(u -> u.getMethods().stream())\n .map(method -> new ParsedMethod(method, this))\n .collect(Collectors.toSet());\n }",
"score": 0.8931530714035034
},
{
"filename": "src/main/java/filter/statistics/StatisticsWithoutSources.java",
"retrieved_chunk": " }\n private long methods() {\n return this.statistics.stream()\n .filter(method -> !method.isConstructor())\n .mapToLong(MethodStatistics::total)\n .sum();\n }\n private long constructors() {\n return this.statistics.stream()\n .filter(MethodStatistics::isConstructor)",
"score": 0.8386057615280151
},
{
"filename": "src/main/java/filter/statistics/StatisticsWithModifiers.java",
"retrieved_chunk": " private long instancePackagePrivate() {\n return this.rows.stream()\n .filter(MethodStatistics::isInstancePackagePrivate)\n .mapToLong(MethodStatistics::total)\n .sum();\n }\n private long instancePublicOverridden() {\n return this.rows.stream()\n .filter(MethodStatistics::isInstancePublicOverridden)\n .mapToLong(MethodStatistics::total)",
"score": 0.8140480518341064
},
{
"filename": "src/main/java/filter/Report.java",
"retrieved_chunk": " () -> new IllegalStateException(String.format(\"No data found in table %s\", table))\n ).stream()\n .map(CSVCell::header)\n .collect(Collectors.toList());\n }\n private static List<Object> values(List<? extends CSVCell> cells) {\n return cells.stream()\n .map(CSVCell::value)\n .collect(Collectors.toList());\n }",
"score": 0.8113034963607788
},
{
"filename": "src/main/java/filter/statistics/StatisticsWithModifiers.java",
"retrieved_chunk": " private long staticPublic() {\n return this.rows.stream()\n .filter(MethodStatistics::isStaticPublic)\n .mapToLong(MethodStatistics::total)\n .sum();\n }\n private long constructors() {\n return this.rows.stream()\n .filter(MethodStatistics::isConstructor)\n .mapToLong(MethodStatistics::total)",
"score": 0.8088049292564392
}
] | java | (this.project.path())) { |
package com.github.wandererex.wormhole.proxy;
import com.github.wandererex.wormhole.serialize.Frame;
import com.github.wandererex.wormhole.serialize.ProxyServiceConfig;
import com.github.wandererex.wormhole.serialize.Task;
import com.github.wandererex.wormhole.serialize.TaskExecutor;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
@Slf4j
public class ProxyHandler extends SimpleChannelInboundHandler<Frame> {
private ProxyServiceConfig config;
private ConcurrentMap<String, Channel> map = new ConcurrentHashMap<>();
private ProxyClient proxyClient;
public ProxyHandler(ProxyClient proxyClient, ProxyServiceConfig config) {
this.config = config;
this.proxyClient = proxyClient;
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, Frame msg) throws Exception {
int opCode = msg.getOpCode();
String serviceKey = msg.getServiceKey();
byte[] payload = msg.getPayload();
if (opCode == 0x9) {
ProxyServiceConfig.ServiceConfig serviceConfig = config.getServiceConfig(serviceKey);
ProxyClient proxyClient = new ProxyClient(null);
proxyClient.setChannel1(ctx.channel());
proxyClient.setServiceKey(serviceKey);
try {
Channel channel = proxyClient.connect(serviceConfig.getIp(), serviceConfig.getPort());
map.put(serviceKey, channel);
Frame frame = new Frame(0x91, serviceKey, null);
ctx.writeAndFlush(frame);
} catch (Exception e) {
Frame frame = new Frame(0x90, serviceKey, null);
ctx.writeAndFlush(frame);
}
} else if (opCode == 0x3) {
Channel channel = map.get(serviceKey);
if (channel == null) {
Frame frame = new Frame(0x40, serviceKey, null);
ctx.writeAndFlush(frame);
} else {
log.info("proxy send to service data {}", payload);
TaskExecutor.get().addTask(new Task(channel, Unpooled.copiedBuffer(payload)));
Frame frame = new Frame(0x41, serviceKey, null);
ctx.writeAndFlush(frame);
}
} else if (opCode == 0x10) {
log.error("proxy connect server error");
close();
} else if (opCode == 0x11) {
log.info("proxy connect server success");
| proxyClient.authSuccess(); |
} else if (opCode == 0x6) {
log.info("proxy update heatbeat time");
proxyClient.updateHeatbeatTime();
} else if (opCode == 0x81) {
log.info("proxy offline success");
close();
} else if (opCode == 0x80) {
log.error("proxy offline error");
} else if (opCode == 0x7) {
log.info("server offline");
Frame frame = new Frame(0x81, null, null);
proxyClient.send(frame);
close();
} else if (opCode == 0xA) {
log.info("server offline");
Channel channel = map.get(serviceKey);
if (channel != null) {
channel.close();
}
}
}
private void close() throws Exception {
proxyClient.shutdown();
for (Channel channel : map.values()) {
channel.close();
}
}
}
| proxy/src/main/java/com/github/wandererex/wormhole/proxy/ProxyHandler.java | wandererex-wormhole-a724af4 | [
{
"filename": "server/src/main/java/com/github/wandererex/wormhole/server/ProxyServerHandler.java",
"retrieved_chunk": " ProxyServer proxyServer = proxyServerMap.get(msg.getServiceKey());\n if (proxyServer != null) {\n proxyServer.send(msg.getPayload());\n }\n Frame frame = new Frame(0x41, null, null);\n ctx.writeAndFlush(frame);\n System.out.println(\"write: \" + frame);\n }\n if (msg.getOpCode() == 0x40) {\n System.out.println(\"write data error\");",
"score": 0.9013975262641907
},
{
"filename": "server/src/main/java/com/github/wandererex/wormhole/server/ProxyServerHandler.java",
"retrieved_chunk": " buildForwardServer(proxyServiceConfig, ctx.channel());\n msg.setOpCode(0x11);\n ctx.writeAndFlush(msg);\n System.out.println(\"write: \" + msg);\n }\n if (msg.getOpCode() == 0x5) {\n Frame frame = new Frame(0x6, null, null);\n ctx.writeAndFlush(frame);\n System.out.println(\"write: \" + frame);\n }",
"score": 0.8886253833770752
},
{
"filename": "server/src/main/java/com/github/wandererex/wormhole/server/ProxyServerHandler.java",
"retrieved_chunk": " }\n if (msg.getOpCode() == 0x41) {\n System.out.println(\"write data success\");\n }\n if (msg.getOpCode() == 0xB) {\n log.info(\"server offline\");\n ProxyServer proxyServer = proxyServerMap.get(msg.getServiceKey());\n if (proxyServer != null) {\n proxyServer.close();\n }",
"score": 0.8519089221954346
},
{
"filename": "proxy/src/test/java/com/github/wandererex/wormhole/proxy/ProxyServer.java",
"retrieved_chunk": " @Override\n protected void channelRead0(ChannelHandlerContext ctx, Frame msg) throws Exception {\n System.out.println(\"read: \" + msg);\n if (msg.getOpCode() == 0x1) {\n msg.setOpCode(0x11);\n ctx.writeAndFlush(msg);\n System.out.println(\"write: \" + msg);\n }\n if (msg.getOpCode() == 0x5) {\n Frame frame = new Frame(0x6, null, null);",
"score": 0.8505887985229492
},
{
"filename": "server/src/main/java/com/github/wandererex/wormhole/server/ProxyServer.java",
"retrieved_chunk": " attr.set(latch);\n proxyChannel.writeAndFlush(frame);\n }\n @Override\n public void channelInactive(ChannelHandlerContext ctx) throws Exception {\n Frame frame = new Frame(0xA, serviceKey, null);\n proxyChannel.writeAndFlush(frame);\n ctx.fireChannelInactive();\n }\n });",
"score": 0.8490058779716492
}
] | java | proxyClient.authSuccess(); |
package filter.statistics;
class MethodStatistics {
private final long total;
private final Modifiers modifiers;
MethodStatistics(
final long total,
final Modifier... modifier
) {
this(total, new Modifiers(modifier));
}
MethodStatistics(
final long total,
final Modifiers modifiers
) {
this.total = total;
this.modifiers = modifiers;
}
long total() {
return this.total;
}
boolean isInstancePrivate() {
return this.modifiers.isInstancePrivate();
}
boolean isInstancePackagePrivate() {
return this. | modifiers.isInstancePackage(); |
}
boolean isInstancePublicOverridden() {
return this.modifiers.isInstanceOverridden();
}
boolean isInstancePublic() {
return this.modifiers.isInstancePublic();
}
boolean isStaticPackagePrivate() {
return this.modifiers.isStaticPackagePrivate();
}
boolean isStaticPublic() {
return this.modifiers.isStaticPublic();
}
boolean isStaticPrivate() {
return this.modifiers.isStaticPrivate();
}
boolean isConstructor() {
return this.modifiers.isConstructor();
}
public boolean isNotFound() {
return this.modifiers.isNotFound();
}
}
| src/main/java/filter/statistics/MethodStatistics.java | volodya-lombrozo-oop-statistics-filter-c298155 | [
{
"filename": "src/main/java/filter/statistics/Modifiers.java",
"retrieved_chunk": " }\n public boolean isStatic() {\n return this.modifiers.contains(Modifier.STATIC);\n }\n boolean isInstancePrivate() {\n return this.modifiers.contains(Modifier.PRIVATE)\n && this.modifiers.contains(Modifier.INSTANCE);\n }\n boolean isInstancePackage() {\n return this.modifiers.contains(Modifier.PACKAGE_PRIVATE)",
"score": 0.9333839416503906
},
{
"filename": "src/main/java/filter/statistics/Modifiers.java",
"retrieved_chunk": " }\n boolean isStaticPackagePrivate() {\n return this.modifiers.contains(Modifier.PACKAGE_PRIVATE)\n && this.modifiers.contains(Modifier.STATIC);\n }\n boolean isStaticPublic() {\n return this.modifiers.contains(Modifier.PUBLIC)\n && this.modifiers.contains(Modifier.STATIC);\n }\n boolean isStaticPrivate() {",
"score": 0.9085418581962585
},
{
"filename": "src/main/java/filter/statistics/Modifiers.java",
"retrieved_chunk": " && this.modifiers.contains(Modifier.INSTANCE);\n }\n boolean isInstanceOverridden() {\n return this.modifiers.contains(Modifier.OVERRIDDEN)\n && this.modifiers.contains(Modifier.INSTANCE);\n }\n boolean isInstancePublic() {\n return this.modifiers.contains(Modifier.PUBLIC)\n && this.modifiers.contains(Modifier.INSTANCE)\n && !this.modifiers.contains(Modifier.OVERRIDDEN);",
"score": 0.8727463483810425
},
{
"filename": "src/main/java/filter/statistics/Modifiers.java",
"retrieved_chunk": " return this.modifiers.contains(Modifier.PRIVATE)\n && this.modifiers.contains(Modifier.STATIC);\n }\n boolean isConstructor() {\n return this.modifiers.contains(Modifier.CONSTRUCTOR);\n }\n boolean isNotFound() {\n return this.modifiers.contains(Modifier.NOT_FOUND);\n }\n}",
"score": 0.8314681053161621
},
{
"filename": "src/main/java/filter/statistics/ParsedMethod.java",
"retrieved_chunk": " }\n if (this.method.isPublic()) {\n modifiers.add(Modifier.PUBLIC);\n } else if (this.method.isPrivate()) {\n modifiers.add(Modifier.PRIVATE);\n } else {\n modifiers.add(Modifier.PACKAGE_PRIVATE);\n }\n return new Modifiers(modifiers);\n }",
"score": 0.8301001191139221
}
] | java | modifiers.isInstancePackage(); |
package com.github.wandererex.wormhole.proxy;
import com.github.wandererex.wormhole.serialize.Frame;
import com.github.wandererex.wormhole.serialize.ProxyServiceConfig;
import com.github.wandererex.wormhole.serialize.Task;
import com.github.wandererex.wormhole.serialize.TaskExecutor;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
@Slf4j
public class ProxyHandler extends SimpleChannelInboundHandler<Frame> {
private ProxyServiceConfig config;
private ConcurrentMap<String, Channel> map = new ConcurrentHashMap<>();
private ProxyClient proxyClient;
public ProxyHandler(ProxyClient proxyClient, ProxyServiceConfig config) {
this.config = config;
this.proxyClient = proxyClient;
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, Frame msg) throws Exception {
int opCode = msg.getOpCode();
String serviceKey = msg.getServiceKey();
byte[] payload = msg.getPayload();
if (opCode == 0x9) {
ProxyServiceConfig.ServiceConfig serviceConfig = config.getServiceConfig(serviceKey);
ProxyClient proxyClient = new ProxyClient(null);
proxyClient.setChannel1(ctx.channel());
proxyClient.setServiceKey(serviceKey);
try {
Channel channel = proxyClient.connect(serviceConfig.getIp(), serviceConfig.getPort());
map.put(serviceKey, channel);
Frame frame = new Frame(0x91, serviceKey, null);
ctx.writeAndFlush(frame);
} catch (Exception e) {
Frame frame = new Frame(0x90, serviceKey, null);
ctx.writeAndFlush(frame);
}
} else if (opCode == 0x3) {
Channel channel = map.get(serviceKey);
if (channel == null) {
Frame frame = new Frame(0x40, serviceKey, null);
ctx.writeAndFlush(frame);
} else {
log.info("proxy send to service data {}", payload);
TaskExecutor.get().addTask(new Task(channel, Unpooled.copiedBuffer(payload)));
Frame frame = new Frame(0x41, serviceKey, null);
ctx.writeAndFlush(frame);
}
} else if (opCode == 0x10) {
log.error("proxy connect server error");
close();
} else if (opCode == 0x11) {
log.info("proxy connect server success");
proxyClient.authSuccess();
} else if (opCode == 0x6) {
log.info("proxy update heatbeat time");
proxyClient.updateHeatbeatTime();
} else if (opCode == 0x81) {
log.info("proxy offline success");
close();
} else if (opCode == 0x80) {
log.error("proxy offline error");
} else if (opCode == 0x7) {
log.info("server offline");
Frame frame = new Frame(0x81, null, null);
proxyClient.send(frame);
close();
} else if (opCode == 0xA) {
log.info("server offline");
Channel channel = map.get(serviceKey);
if (channel != null) {
channel.close();
}
}
}
private void close() throws Exception {
| proxyClient.shutdown(); |
for (Channel channel : map.values()) {
channel.close();
}
}
}
| proxy/src/main/java/com/github/wandererex/wormhole/proxy/ProxyHandler.java | wandererex-wormhole-a724af4 | [
{
"filename": "server/src/main/java/com/github/wandererex/wormhole/server/ProxyServerHandler.java",
"retrieved_chunk": " }\n if (msg.getOpCode() == 0x41) {\n System.out.println(\"write data success\");\n }\n if (msg.getOpCode() == 0xB) {\n log.info(\"server offline\");\n ProxyServer proxyServer = proxyServerMap.get(msg.getServiceKey());\n if (proxyServer != null) {\n proxyServer.close();\n }",
"score": 0.8826403021812439
},
{
"filename": "proxy/src/test/java/com/github/wandererex/wormhole/proxy/ProxyServer.java",
"retrieved_chunk": " worker.shutdownGracefully().syncUninterruptibly();\n }));\n }\n public void close() {\n if (channelFuture != null) {\n channelFuture.channel().close();\n }\n }\n public static void main(String[] args) {\n new ProxyServer(8090).open();",
"score": 0.8777071237564087
},
{
"filename": "server/src/main/java/com/github/wandererex/wormhole/server/ProxyServer.java",
"retrieved_chunk": " public void close() {\n if (channel == null) {\n return;\n }\n channel.close();\n }\n}",
"score": 0.8740919828414917
},
{
"filename": "proxy/src/main/java/com/github/wandererex/wormhole/proxy/ProxyClient.java",
"retrieved_chunk": " if (future.isSuccess()) {\n return future.channel();\n }\n Thread.sleep(5000);\n }\n throw new RuntimeException(\"connect business server fail, client \" + NetworkUtil.getLocalHost() + \", server \" + ip + \":\" + port);\n }\n public void disconnect() throws Exception {\n if (!connectSuccess) {\n log.error(\"no connect!\");",
"score": 0.852494478225708
},
{
"filename": "proxy/src/main/java/com/github/wandererex/wormhole/proxy/ProxyClient.java",
"retrieved_chunk": " }\n public void authSuccess() {\n this.authSuccess = true;\n channelPromise.setSuccess();\n }\n public void shutdown() throws Exception {\n disconnect();\n clientGroup.shutdownGracefully().syncUninterruptibly();\n Proxy.latch.countDown();\n }",
"score": 0.850232720375061
}
] | java | proxyClient.shutdown(); |
package com.github.wandererex.wormhole.proxy;
import com.github.wandererex.wormhole.serialize.Frame;
import com.github.wandererex.wormhole.serialize.ProxyServiceConfig;
import com.github.wandererex.wormhole.serialize.Task;
import com.github.wandererex.wormhole.serialize.TaskExecutor;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
@Slf4j
public class ProxyHandler extends SimpleChannelInboundHandler<Frame> {
private ProxyServiceConfig config;
private ConcurrentMap<String, Channel> map = new ConcurrentHashMap<>();
private ProxyClient proxyClient;
public ProxyHandler(ProxyClient proxyClient, ProxyServiceConfig config) {
this.config = config;
this.proxyClient = proxyClient;
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, Frame msg) throws Exception {
int opCode = msg.getOpCode();
String serviceKey = msg.getServiceKey();
byte[] payload = msg.getPayload();
if (opCode == 0x9) {
ProxyServiceConfig.ServiceConfig serviceConfig = config.getServiceConfig(serviceKey);
ProxyClient proxyClient = new ProxyClient(null);
proxyClient.setChannel1(ctx.channel());
proxyClient.setServiceKey(serviceKey);
try {
Channel channel = proxyClient.connect(serviceConfig.getIp(), serviceConfig.getPort());
map.put(serviceKey, channel);
Frame frame = new Frame(0x91, serviceKey, null);
ctx.writeAndFlush(frame);
} catch (Exception e) {
Frame frame = new Frame(0x90, serviceKey, null);
ctx.writeAndFlush(frame);
}
} else if (opCode == 0x3) {
Channel channel = map.get(serviceKey);
if (channel == null) {
Frame frame = new Frame(0x40, serviceKey, null);
ctx.writeAndFlush(frame);
} else {
log.info("proxy send to service data {}", payload);
TaskExecutor.get().addTask(new Task(channel, Unpooled.copiedBuffer(payload)));
Frame frame = new Frame(0x41, serviceKey, null);
ctx.writeAndFlush(frame);
}
} else if (opCode == 0x10) {
log.error("proxy connect server error");
close();
} else if (opCode == 0x11) {
log.info("proxy connect server success");
proxyClient.authSuccess();
} else if (opCode == 0x6) {
log.info("proxy update heatbeat time");
| proxyClient.updateHeatbeatTime(); |
} else if (opCode == 0x81) {
log.info("proxy offline success");
close();
} else if (opCode == 0x80) {
log.error("proxy offline error");
} else if (opCode == 0x7) {
log.info("server offline");
Frame frame = new Frame(0x81, null, null);
proxyClient.send(frame);
close();
} else if (opCode == 0xA) {
log.info("server offline");
Channel channel = map.get(serviceKey);
if (channel != null) {
channel.close();
}
}
}
private void close() throws Exception {
proxyClient.shutdown();
for (Channel channel : map.values()) {
channel.close();
}
}
}
| proxy/src/main/java/com/github/wandererex/wormhole/proxy/ProxyHandler.java | wandererex-wormhole-a724af4 | [
{
"filename": "server/src/main/java/com/github/wandererex/wormhole/server/ProxyServerHandler.java",
"retrieved_chunk": " }\n if (msg.getOpCode() == 0x41) {\n System.out.println(\"write data success\");\n }\n if (msg.getOpCode() == 0xB) {\n log.info(\"server offline\");\n ProxyServer proxyServer = proxyServerMap.get(msg.getServiceKey());\n if (proxyServer != null) {\n proxyServer.close();\n }",
"score": 0.864500880241394
},
{
"filename": "server/src/main/java/com/github/wandererex/wormhole/server/ProxyServerHandler.java",
"retrieved_chunk": " ProxyServer proxyServer = proxyServerMap.get(msg.getServiceKey());\n if (proxyServer != null) {\n proxyServer.send(msg.getPayload());\n }\n Frame frame = new Frame(0x41, null, null);\n ctx.writeAndFlush(frame);\n System.out.println(\"write: \" + frame);\n }\n if (msg.getOpCode() == 0x40) {\n System.out.println(\"write data error\");",
"score": 0.8063981533050537
},
{
"filename": "proxy/src/main/java/com/github/wandererex/wormhole/proxy/ProxyClient.java",
"retrieved_chunk": " if (future.isSuccess()) {\n return future.channel();\n }\n Thread.sleep(5000);\n }\n throw new RuntimeException(\"connect business server fail, client \" + NetworkUtil.getLocalHost() + \", server \" + ip + \":\" + port);\n }\n public void disconnect() throws Exception {\n if (!connectSuccess) {\n log.error(\"no connect!\");",
"score": 0.7915096879005432
},
{
"filename": "server/src/main/java/com/github/wandererex/wormhole/server/ProxyServerHandler.java",
"retrieved_chunk": " buildForwardServer(proxyServiceConfig, ctx.channel());\n msg.setOpCode(0x11);\n ctx.writeAndFlush(msg);\n System.out.println(\"write: \" + msg);\n }\n if (msg.getOpCode() == 0x5) {\n Frame frame = new Frame(0x6, null, null);\n ctx.writeAndFlush(frame);\n System.out.println(\"write: \" + frame);\n }",
"score": 0.7653311491012573
},
{
"filename": "proxy/src/main/java/com/github/wandererex/wormhole/proxy/ProxyClient.java",
"retrieved_chunk": " return;\n }\n channel.close().sync();\n connectSuccess = false;\n }\n public void send(Frame frame) throws Exception {\n if (!connectSuccess) {\n throw new RuntimeException(\"no connect!\");\n }\n channel.writeAndFlush(frame).sync();",
"score": 0.7573673725128174
}
] | java | proxyClient.updateHeatbeatTime(); |
package com.github.wandererex.wormhole.server;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.wandererex.wormhole.serialize.Frame;
import com.github.wandererex.wormhole.serialize.ProxyServiceConfig;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
@Slf4j
public class ProxyServerHandler extends SimpleChannelInboundHandler<Frame> {
private Map<String, ProxyServer> proxyServerMap = new HashMap<>();
@Override
protected void channelRead0(ChannelHandlerContext ctx, Frame msg) throws Exception {
System.out.println("read: " + msg);
if (msg.getOpCode() == 0x1) {
byte[] payload = msg.getPayload();
String s = new String(payload, StandardCharsets.UTF_8);
JSONObject jsonObject = JSON.parseObject(s);
ProxyServiceConfig proxyServiceConfig = new ProxyServiceConfig();
for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
proxyServiceConfig.addConfig(entry.getKey(), JSON.parseObject((String) entry.getValue()).toJavaObject(ProxyServiceConfig.ServiceConfig.class));
}
buildForwardServer(proxyServiceConfig, ctx.channel());
msg.setOpCode(0x11);
ctx.writeAndFlush(msg);
System.out.println("write: " + msg);
}
if (msg.getOpCode() == 0x5) {
Frame frame = new Frame(0x6, null, null);
ctx.writeAndFlush(frame);
System.out.println("write: " + frame);
}
if (msg.getOpCode() == 0x91) {
AttributeKey<CountDownLatch> attributeKey = AttributeKey.valueOf(msg.getServiceKey());
Attribute<CountDownLatch> attr = ctx.attr(attributeKey);
CountDownLatch latch = attr.get();
if (latch != null) {
latch.countDown();
}
}
if (msg.getOpCode() == 0x3) {
log.info("server read from proxy data {}", msg);
ProxyServer proxyServer = proxyServerMap.get(msg.getServiceKey());
if (proxyServer != null) {
proxyServer.send(msg.getPayload());
}
Frame frame = new Frame(0x41, null, null);
ctx.writeAndFlush(frame);
System.out.println("write: " + frame);
}
if (msg.getOpCode() == 0x40) {
System.out.println("write data error");
}
if (msg.getOpCode() == 0x41) {
System.out.println("write data success");
}
if (msg.getOpCode() == 0xB) {
log.info("server offline");
ProxyServer proxyServer = proxyServerMap.get(msg.getServiceKey());
if (proxyServer != null) {
proxyServer.close();
}
}
}
private void buildForwardServer(ProxyServiceConfig config, Channel channel) {
Map<String, ProxyServiceConfig.ServiceConfig> serviceConfigMap = config.getServiceConfigMap();
for (Map.Entry<String, ProxyServiceConfig.ServiceConfig> config1 : serviceConfigMap.entrySet()) {
ProxyServer proxyServer = new ProxyServer(config1.getKey(), config1.getValue().getMappingPort(), channel);
proxyServerMap.put(config1.getKey(), proxyServer);
| proxyServer.open(); |
log.info("port mapping open {} {} {}", config1.getKey(), config1.getValue().getPort(), config1.getValue().getMappingPort());
}
}
}
| server/src/main/java/com/github/wandererex/wormhole/server/ProxyServerHandler.java | wandererex-wormhole-a724af4 | [
{
"filename": "serialize/src/main/java/com/github/wandererex/wormhole/serialize/ProxyServiceConfig.java",
"retrieved_chunk": " private Integer mappingPort;\n }\n private Map<String, ServiceConfig> map = new HashMap<>();\n private String serverHost;\n private Integer serverPort;\n public ServiceConfig getServiceConfig(String serviceKey) {\n return map.get(serviceKey);\n }\n public Map<String, ServiceConfig> getServiceConfigMap() {\n return new HashMap<>(map);",
"score": 0.8131487965583801
},
{
"filename": "proxy/src/main/java/com/github/wandererex/wormhole/proxy/Proxy.java",
"retrieved_chunk": " }\n private void online(Channel channel) {\n JSONObject jsonObject = new JSONObject();\n for (Map.Entry<String, ProxyServiceConfig.ServiceConfig> entry : config.getServiceConfigMap().entrySet()){\n jsonObject.put(entry.getKey(), JSON.toJSONString(entry.getValue()));\n }\n String string = jsonObject.toJSONString();\n Frame frame = new Frame(0x1, null, string.getBytes(StandardCharsets.UTF_8));\n channel.writeAndFlush(frame);\n }",
"score": 0.8070870041847229
},
{
"filename": "server/src/main/java/com/github/wandererex/wormhole/server/ProxyServer.java",
"retrieved_chunk": " this.serviceKey = serviceKey;\n this.mappingPort = mappingPort;\n this.proxyChannel = proxyChannel;\n this.forwardHandler = new ForwardHandler(serviceKey, proxyChannel);\n }\n public void send(byte[] buf) {\n if (channel == null) {\n return;\n }\n TaskExecutor.get().addTask(new Task(channel, Unpooled.copiedBuffer(buf)));",
"score": 0.7878609895706177
},
{
"filename": "proxy/src/main/java/com/github/wandererex/wormhole/proxy/ProxyHandler.java",
"retrieved_chunk": " ProxyClient proxyClient = new ProxyClient(null);\n proxyClient.setChannel1(ctx.channel());\n proxyClient.setServiceKey(serviceKey);\n try {\n Channel channel = proxyClient.connect(serviceConfig.getIp(), serviceConfig.getPort());\n map.put(serviceKey, channel);\n Frame frame = new Frame(0x91, serviceKey, null);\n ctx.writeAndFlush(frame);\n } catch (Exception e) {\n Frame frame = new Frame(0x90, serviceKey, null);",
"score": 0.7860400676727295
},
{
"filename": "server/src/main/java/com/github/wandererex/wormhole/server/ForwardHandler.java",
"retrieved_chunk": " private Channel proxyChannel;\n private Channel channel;\n public ForwardHandler(String serviceKey, Channel proxyChannel) {\n this.serviceKey = serviceKey;\n this.proxyChannel = proxyChannel;\n }\n public void setChannel(Channel channel) {\n this.channel = channel;\n }\n @Override",
"score": 0.7711632251739502
}
] | java | proxyServer.open(); |
package com.vsantos1.legacy.core.response;
import com.vsantos1.legacy.core.enums.HttpStatus;
import com.vsantos1.legacy.core.parser.Json;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
public class ResponseEntity<T> {
private final HttpStatus status;
private static final String CHARSET_ENCODING = "UTF-8";
private final T body;
protected Json json;
ResponseEntity(HttpStatus status, T body) {
this.status = status;
this.body = body;
}
public void build(HttpServletResponse response) {
try {
this.execute(response);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected void execute(HttpServletResponse response) throws IOException {
response.setStatus(this.status.getValue());
response.setCharacterEncoding(CHARSET_ENCODING);
if (this.status == HttpStatus.NO_CONTENT || this.body == null) {
return;
}
if (this.body instanceof byte[]) {
response.getOutputStream().write((byte[]) this.body);
response.getOutputStream().close();
return;
}
response.getWriter | ().write(Json.parseToJson(this.body)); |
response.getWriter().close();
}
} | src/main/java/com/vsantos1/legacy/core/response/ResponseEntity.java | vsantos1-java-microframework-web-a4674ab | [
{
"filename": "src/main/java/com/vsantos1/legacy/core/upload/FileUpload.java",
"retrieved_chunk": " response.setHeader(\"Content-Disposition\", \"attachment; filename=\\\"\" + fileName + \"\\\"\");\n try (InputStream in = Files.newInputStream(file)) {\n byte[] buffer = new byte[4096];\n int bytesRead;\n while ((bytesRead = in.read(buffer)) != -1) {\n response.getOutputStream().write(buffer, 0, bytesRead);\n }\n }\n } else {\n response.sendError(HttpServletResponse.SC_NOT_FOUND, \"File not found\");",
"score": 0.762903094291687
},
{
"filename": "src/main/java/com/vsantos1/legacy/core/response/StatusBuilder.java",
"retrieved_chunk": " }\n public void build(HttpServletResponse response) {\n new ResponseEntity<>(status, response).build(response);\n }\n}",
"score": 0.761001467704773
},
{
"filename": "src/main/java/com/vsantos1/legacy/core/upload/FileUpload.java",
"retrieved_chunk": " this.isSizeAllowed(part, maxFileSize);\n // Do the magic\n this.execute(folderName, fileName, part, unique);\n }\n public void downloadFileFromDisk(String fileName, HttpServletResponse response) throws IOException {\n String filePath = this.uploadDir + File.separator + \"uploads\" + File.separator + fileName;\n Path file = Paths.get(filePath);\n if (Files.exists(file)) {\n response.setContentType(\"application/octet-stream\");\n response.setStatus(HttpStatus.OK.getValue());",
"score": 0.7393391132354736
},
{
"filename": "src/main/java/com/vsantos1/legacy/core/router/Controller.java",
"retrieved_chunk": " }\n }\n handlerMethod.invoke(this, args);\n }\n private void ErrorBuilder(HttpServletRequest request, HttpServletResponse response, String message, HttpStatus status) {\n Response.status(status).body(new Error(message, status.getValue(), request.getRequestURI(), new Date())).build(response);\n }\n}",
"score": 0.7317085266113281
},
{
"filename": "src/main/java/com/vsantos1/legacy/core/router/Controller.java",
"retrieved_chunk": " handleRequest(handlerMethod, request, response, mapping.contentType());\n } catch (IllegalAccessException | InvocationTargetException e) {\n this.ErrorBuilder(request, response, \"Internal Server Error\", HttpStatus.INTERNAL_SERVER_ERROR);\n }\n return;\n }\n }\n this.ErrorBuilder(request, response, \"Not found\", HttpStatus.NOT_FOUND);\n }\n private void handleRequest(Method handlerMethod, HttpServletRequest request, HttpServletResponse response, ContentType contentType)",
"score": 0.716676652431488
}
] | java | ().write(Json.parseToJson(this.body)); |
package com.vsantos1.legacy.core.router;
import com.vsantos1.legacy.core.annotations.RequestMapping;
import com.vsantos1.legacy.core.enums.ContentType;
import com.vsantos1.legacy.core.enums.HttpStatus;
import com.vsantos1.legacy.core.response.Error;
import com.vsantos1.legacy.core.response.Response;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class Controller extends HttpServlet {
private Map<String, Method> handlerMethods;
@Override
public void init() throws ServletException {
super.init();
handlerMethods = new HashMap<>();
Method[] methods = this.getClass().getDeclaredMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(RequestMapping.class)) {
RequestMapping mapping = method.getAnnotation(RequestMapping.class);
String path = mapping.value();
handlerMethods.put(path, method);
}
}
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) {
String path = request.getPathInfo();
String method = request.getMethod();
Method handlerMethod = handlerMethods.get(path);
if (handlerMethod != null) {
RequestMapping mapping = handlerMethod.getAnnotation(RequestMapping.class);
if (mapping.method().name().equalsIgnoreCase(method)) {
try {
handleRequest(handlerMethod, request, response, mapping.contentType());
} catch (IllegalAccessException | InvocationTargetException e) {
this.ErrorBuilder(request, response, "Internal Server Error", HttpStatus.INTERNAL_SERVER_ERROR);
}
return;
}
}
this.ErrorBuilder(request, response, "Not found", HttpStatus.NOT_FOUND);
}
private void handleRequest(Method handlerMethod, HttpServletRequest request, HttpServletResponse response, ContentType contentType)
throws IllegalAccessException, InvocationTargetException {
response.setContentType(ContentType.TEXT_PLAIN.getValue());
Class<?>[] parameterTypes = handlerMethod.getParameterTypes();
Object[] args = new Object[parameterTypes.length];
for (int i = 0; i < parameterTypes.length; i++) {
if (parameterTypes[i].equals(HttpServletRequest.class)) {
args[i] = request;
}
if (parameterTypes[i].equals(HttpServletResponse.class)) {
args[i] = response;
}
}
handlerMethod.invoke(this, args);
}
private void ErrorBuilder(HttpServletRequest request, HttpServletResponse response, String message, HttpStatus status) {
Response.status(status).body(new Error( | message, status.getValue(), request.getRequestURI(), new Date())).build(response); |
}
}
| src/main/java/com/vsantos1/legacy/core/router/Controller.java | vsantos1-java-microframework-web-a4674ab | [
{
"filename": "src/main/java/com/vsantos1/legacy/core/response/StatusBuilder.java",
"retrieved_chunk": " }\n public void build(HttpServletResponse response) {\n new ResponseEntity<>(status, response).build(response);\n }\n}",
"score": 0.8690907955169678
},
{
"filename": "src/main/java/com/vsantos1/legacy/core/response/ResponseEntity.java",
"retrieved_chunk": " ResponseEntity(HttpStatus status, T body) {\n this.status = status;\n this.body = body;\n }\n public void build(HttpServletResponse response) {\n try {\n this.execute(response);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }",
"score": 0.853158712387085
},
{
"filename": "src/main/java/com/vsantos1/legacy/web/servlets/FilesServlet.java",
"retrieved_chunk": " Response.status(HttpStatus.OK).body(file.getFileFromDisk(fileName)).build(resp, ContentType.IMAGE_JPEG);\n }\n @Override\n protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {\n super.doPost(req, resp);\n }\n}",
"score": 0.8139557838439941
},
{
"filename": "src/main/java/com/vsantos1/legacy/core/response/ResponseEntity.java",
"retrieved_chunk": " }\n protected void execute(HttpServletResponse response) throws IOException {\n response.setStatus(this.status.getValue());\n response.setCharacterEncoding(CHARSET_ENCODING);\n if (this.status == HttpStatus.NO_CONTENT || this.body == null) {\n return;\n }\n if (this.body instanceof byte[]) {\n response.getOutputStream().write((byte[]) this.body);\n response.getOutputStream().close();",
"score": 0.7870191335678101
},
{
"filename": "src/main/java/com/vsantos1/legacy/core/response/Response.java",
"retrieved_chunk": "package com.vsantos1.legacy.core.response;\nimport com.vsantos1.legacy.core.enums.HttpStatus;\npublic class Response<T> {\n private final HttpStatus status;\n private final T body;\n Response(HttpStatus status, T body) {\n this.status = status;\n this.body = body;\n }\n public static <T> StatusBuilder<T> status(HttpStatus status) {",
"score": 0.779507040977478
}
] | java | message, status.getValue(), request.getRequestURI(), new Date())).build(response); |
package com.projeto.workshopmongo.resources;
import com.projeto.workshopmongo.domain.Post;
import com.projeto.workshopmongo.domain.User;
import com.projeto.workshopmongo.dto.UserDTO;
import com.projeto.workshopmongo.resources.util.URL;
import com.projeto.workshopmongo.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.net.URI;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
@RestController
@RequestMapping(value="/users")
public class UseResource {
@Autowired
private UserService service;
@GetMapping
public ResponseEntity<List<UserDTO>> findAll(){
List<User>lista = service.findAll();
List<UserDTO> listaDTO = lista.stream().map(x -> new UserDTO(x)).collect(Collectors.toList());
return ResponseEntity.ok().body(listaDTO);
}
@GetMapping(value ="/{id}")
public ResponseEntity<UserDTO> findById(@PathVariable String id){
User obj = service.findById(id);
return ResponseEntity.ok(new UserDTO(obj));
}
@PostMapping
public ResponseEntity<Void> insert(@RequestBody UserDTO objDTO){
User obj = service.fromDTO(objDTO);
obj = service.insert(obj);
URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(obj.getId()).toUri();
return ResponseEntity.created(uri).build();
}
@PutMapping(value = "/{id}")
public ResponseEntity<Void> update(@RequestBody UserDTO objDto, @PathVariable String id){
User obj = service.fromDTO(objDto);
obj.setId(id);
obj = service.update(obj);
return ResponseEntity.noContent().build();
}
@GetMapping(value = "{id}/posts")
ResponseEntity<List<Post>> findPost(@PathVariable String id){
User obj = service.findById(id);
return | ResponseEntity.ok().body(obj.getPosts()); |
}
@DeleteMapping(value = "/{id}")
public ResponseEntity<Void> deleteById(@PathVariable String id){
service.deleteById(id);
return ResponseEntity.noContent().build();
}
}
| src/main/java/com/projeto/workshopmongo/resources/UseResource.java | wesleyfsousa01-workshop-spring-boot-mongoDB-2ed3895 | [
{
"filename": "src/main/java/com/projeto/workshopmongo/resources/PostResource.java",
"retrieved_chunk": "@RequestMapping(value = \"/posts\")\npublic class PostResource {\n @Autowired\n private PostService postService;\n @GetMapping(value = \"/{id}\")\n public ResponseEntity<Post> findById(@PathVariable String id){\n Post obj = postService.findById(id);\n return ResponseEntity.ok().body(obj);\n }\n @GetMapping(value = \"/titlesearch\")",
"score": 0.844719648361206
},
{
"filename": "src/main/java/com/projeto/workshopmongo/services/UserService.java",
"retrieved_chunk": " public User insert(User obj){\n return repository.insert(obj);\n }\n public void deleteById(String id){\n findById(id);\n repository.deleteById(id);\n }\n public User update(User obj){\n User newObj = findById(obj.getId()) ;\n updateData(newObj,obj);",
"score": 0.7258363962173462
},
{
"filename": "src/main/java/com/projeto/workshopmongo/resources/PostResource.java",
"retrieved_chunk": " text = URL.decodeParam(text);\n Date min = URL.convertDate(minDate, new Date(0L));\n Date max = URL.convertDate(maxDate, new Date());\n List<Post> list = postService.fullSearch(text, min ,max);\n return ResponseEntity.ok().body(list);\n }\n}",
"score": 0.7126629948616028
},
{
"filename": "src/main/java/com/projeto/workshopmongo/services/PostService.java",
"retrieved_chunk": "public class PostService {\n @Autowired\n private PostRepository postRepository;\n public Post findById(String id){\n Optional<Post> obj = postRepository.findById(id);\n return obj.orElseThrow(() -> new ObjectNotFoundException(\"Objeto não encontrado\"));\n }\n public List<Post> findByTitle(String text){\n return postRepository.searchTitle(text);\n }",
"score": 0.6911959648132324
},
{
"filename": "src/main/java/com/projeto/workshopmongo/resources/PostResource.java",
"retrieved_chunk": " public ResponseEntity<List<Post>> findByTitle(@RequestParam(value = \"text\", defaultValue = \"\") String text){\n String decodingText = URL.decodeParam(text);\n List<Post> list = postService.findByTitle(decodingText);\n return ResponseEntity.ok().body(list);\n }\n @GetMapping(\"/fullsearch\")\n public ResponseEntity<List<Post>> fullSearch(\n @RequestParam(value = \"text\", defaultValue = \"\") String text,\n @RequestParam(value = \"minDate\", defaultValue = \"\") String minDate,\n @RequestParam(value = \"maxDate\", defaultValue = \"\") String maxDate) {",
"score": 0.6784054040908813
}
] | java | ResponseEntity.ok().body(obj.getPosts()); |
package com.github.wenqiglantz.service.tenantadmin.service;
import com.github.wenqiglantz.service.tenantadmin.domain.entity.IsolationType;
import com.github.wenqiglantz.service.tenantadmin.util.EncryptionService;
import com.github.wenqiglantz.service.tenantadmin.domain.entity.Tenant;
import com.github.wenqiglantz.service.tenantadmin.repository.TenantRepository;
import liquibase.exception.LiquibaseException;
import liquibase.integration.spring.SpringLiquibase;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.core.io.ResourceLoader;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.StatementCallback;
import org.springframework.jdbc.datasource.SingleConnectionDataSource;
import org.springframework.stereotype.Service;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
@Slf4j
@Service
@EnableConfigurationProperties(LiquibaseProperties.class)
public class TenantAdminService {
private static final String VALID_DB_SCHEMA_NAME_REGEXP = "[A-Za-z0-9_]*";
private final EncryptionService encryptionService;
private final DataSource dataSource;
private final JdbcTemplate jdbcTemplate;
private final LiquibaseProperties tenantLiquibaseProperties;
private final LiquibaseProperties liquibaseProperties;
private final ResourceLoader resourceLoader;
private final TenantRepository tenantRepository;
private final String databaseName;
private final String urlPrefix;
private final String liquibaseChangeLog;
private final String liquibaseContexts;
private final String secret;
private final String salt;
@Autowired
public TenantAdminService(EncryptionService encryptionService,
DataSource dataSource,
JdbcTemplate jdbcTemplate,
@Qualifier("masterLiquibaseProperties")
LiquibaseProperties liquibaseProperties,
@Qualifier("tenantLiquibaseProperties")
LiquibaseProperties tenantLiquibaseProperties,
ResourceLoader resourceLoader,
TenantRepository tenantRepository,
@Value("${databaseName:}") String databaseName,
@Value("${multitenancy.tenant.datasource.url-prefix}") String urlPrefix,
@Value("${multitenancy.tenant.liquibase.changeLog}") String liquibaseChangeLog,
@Value("${multitenancy.tenant.liquibase.contexts:#{null}") String liquibaseContexts,
@Value("${encryption.secret}") String secret,
@Value("${encryption.salt}") String salt
) {
this.encryptionService = encryptionService;
this.dataSource = dataSource;
this.jdbcTemplate = jdbcTemplate;
this.liquibaseProperties = liquibaseProperties;
this.tenantLiquibaseProperties = tenantLiquibaseProperties;
this.resourceLoader = resourceLoader;
this.tenantRepository = tenantRepository;
this.databaseName = databaseName;
this.urlPrefix = urlPrefix;
this.liquibaseChangeLog = liquibaseChangeLog;
this.liquibaseContexts = liquibaseContexts;
this.secret = secret;
this.salt = salt;
}
public void createTenant(String tenantId, IsolationType isolationType, String dbOrSchema, String userName, String password) {
// Verify db or schema string to prevent SQL injection
if (!dbOrSchema.matches(VALID_DB_SCHEMA_NAME_REGEXP)) {
throw new TenantCreationException("Invalid database or schema name: " + dbOrSchema);
}
String url = null;
| String encryptedPassword = encryptionService.encrypt(password, secret, salt); |
switch (isolationType) {
case DATABASE:
url = urlPrefix + dbOrSchema;
try {
createDatabase(dbOrSchema, password);
} catch (DataAccessException e) {
throw new TenantCreationException("Error when creating db: " + dbOrSchema, e);
}
try (Connection connection = DriverManager.getConnection(url, dbOrSchema, password)) {
DataSource tenantDataSource = new SingleConnectionDataSource(connection, false);
runLiquibase(tenantDataSource);
} catch (SQLException | LiquibaseException e) {
throw new TenantCreationException("Error when populating db: ", e);
}
break;
case SCHEMA:
url = urlPrefix + databaseName + "?currentSchema=" + dbOrSchema;
try {
createSchema(dbOrSchema, password);
runLiquibase(dataSource, dbOrSchema);
} catch (DataAccessException e) {
throw new TenantCreationException("Error when creating schema: " + dbOrSchema, e);
} catch (LiquibaseException e) {
throw new TenantCreationException("Error when populating schema: ", e);
}
break;
case DISCRIMINATOR:
url = urlPrefix + databaseName;
try {
runLiquibase(dataSource);
} catch (DataAccessException e) {
throw new TenantCreationException("Error when creating schema: " + dbOrSchema, e);
} catch (LiquibaseException e) {
throw new TenantCreationException("Error when populating schema: ", e);
}
break;
}
Tenant tenant = Tenant.builder()
.tenantId(tenantId)
.isolationType(isolationType)
.dbOrSchema(dbOrSchema)
.url(url)
.username(userName)
.password(encryptedPassword)
.build();
tenantRepository.save(tenant);
}
private void createDatabase(String db, String password) {
jdbcTemplate.execute((StatementCallback<Boolean>) stmt -> stmt.execute("CREATE DATABASE " + db));
jdbcTemplate.execute((StatementCallback<Boolean>) stmt -> stmt.execute("CREATE USER " + db + " WITH ENCRYPTED PASSWORD '" + password + "'"));
jdbcTemplate.execute((StatementCallback<Boolean>) stmt -> stmt.execute("GRANT ALL PRIVILEGES ON DATABASE " + db + " TO " + db));
}
private void runLiquibase(DataSource dataSource) throws LiquibaseException {
SpringLiquibase liquibase = getSpringLiquibase(dataSource);
liquibase.afterPropertiesSet();
}
private void createSchema(String schema, String password) {
jdbcTemplate.execute((StatementCallback<Boolean>) stmt -> stmt.execute("CREATE USER " + schema+ " WITH ENCRYPTED PASSWORD '" + password + "'"));
jdbcTemplate.execute((StatementCallback<Boolean>) stmt -> stmt.execute("GRANT CONNECT ON DATABASE " + databaseName + " TO " + schema));
jdbcTemplate.execute((StatementCallback<Boolean>) stmt -> stmt.execute("CREATE SCHEMA " + schema + " AUTHORIZATION " + schema));
jdbcTemplate.execute((StatementCallback<Boolean>) stmt -> stmt.execute("ALTER DEFAULT PRIVILEGES IN SCHEMA " + schema + " GRANT ALL PRIVILEGES ON TABLES TO " + schema));
jdbcTemplate.execute((StatementCallback<Boolean>) stmt -> stmt.execute("ALTER DEFAULT PRIVILEGES IN SCHEMA " + schema + " GRANT USAGE ON SEQUENCES TO " + schema));
jdbcTemplate.execute((StatementCallback<Boolean>) stmt -> stmt.execute("ALTER DEFAULT PRIVILEGES IN SCHEMA " + schema + " GRANT EXECUTE ON FUNCTIONS TO " + schema));
}
private void runLiquibase(DataSource dataSource, String schema) throws LiquibaseException {
SpringLiquibase liquibase = getSpringLiquibase(dataSource, schema);
liquibase.afterPropertiesSet();
}
protected SpringLiquibase getSpringLiquibase(DataSource dataSource) {
SpringLiquibase liquibase = new SpringLiquibase();
liquibase.setResourceLoader(resourceLoader);
liquibase.setDataSource(dataSource);
liquibase.setChangeLog(tenantLiquibaseProperties.getChangeLog());
liquibase.setContexts(tenantLiquibaseProperties.getContexts());
liquibase.setDefaultSchema(tenantLiquibaseProperties.getDefaultSchema());
liquibase.setLiquibaseSchema(tenantLiquibaseProperties.getLiquibaseSchema());
liquibase.setLiquibaseTablespace(tenantLiquibaseProperties.getLiquibaseTablespace());
liquibase.setDatabaseChangeLogTable(tenantLiquibaseProperties.getDatabaseChangeLogTable());
liquibase.setDatabaseChangeLogLockTable(tenantLiquibaseProperties.getDatabaseChangeLogLockTable());
liquibase.setDropFirst(tenantLiquibaseProperties.isDropFirst());
liquibase.setShouldRun(tenantLiquibaseProperties.isEnabled());
liquibase.setLabels(tenantLiquibaseProperties.getLabels());
liquibase.setChangeLogParameters(tenantLiquibaseProperties.getParameters());
liquibase.setRollbackFile(tenantLiquibaseProperties.getRollbackFile());
liquibase.setTestRollbackOnUpdate(tenantLiquibaseProperties.isTestRollbackOnUpdate());
return liquibase;
}
protected SpringLiquibase getSpringLiquibase(DataSource dataSource, String schema) {
SpringLiquibase liquibase = new SpringLiquibase();
liquibase.setResourceLoader(resourceLoader);
liquibase.setDataSource(dataSource);
liquibase.setDefaultSchema(schema);
liquibase.setChangeLog(liquibaseChangeLog);
liquibase.setContexts(liquibaseContexts);
liquibase.setDropFirst(liquibaseProperties.isDropFirst());
liquibase.setShouldRun(liquibaseProperties.isEnabled());
return liquibase;
}
}
| hybrid-multitenancy-admin-service/src/main/java/com/github/wenqiglantz/service/tenantadmin/service/TenantAdminService.java | wenqiglantz-rds-hybrid-multitenancy-ad04a23 | [
{
"filename": "hybrid-multitenancy-customer-service/src/main/java/com/github/wenqiglantz/service/customer/multitenancy/config/tenant/TenantHibernateConfig.java",
"retrieved_chunk": " properties.put(AvailableSettings.BEAN_CONTAINER, new SpringBeanContainer(this.beanFactory));\n String tenant = TenantContext.getTenantId();\n if (null == tenant) {\n properties.remove(AvailableSettings.DEFAULT_SCHEMA);\n } else {\n //TODO\n Tenant dbTenant = tenantRepository.findByTenantId(tenant).get();\n switch (dbTenant.getIsolationType()) {\n case DATABASE:\n break;",
"score": 0.8394556045532227
},
{
"filename": "hybrid-multitenancy-customer-service/src/main/java/com/github/wenqiglantz/service/customer/multitenancy/config/tenant/liquibase/HybridMultiTenantSpringLiquibase.java",
"retrieved_chunk": " log.info(\"Hybrid multitenancy enabled\");\n this.runOnAllTenants(masterTenantRepository.findAll());\n }\n protected void runOnAllTenants(Collection<Tenant> tenants) throws LiquibaseException {\n for(Tenant tenant : tenants) {\n String decryptedPassword = encryptionService.decrypt(tenant.getPassword(), secret, salt);\n log.info(\"Initializing Liquibase for tenant \" + tenant.getTenantId() + \" and password \" + decryptedPassword);\n switch (tenant.getIsolationType()) {\n case DATABASE:\n try (Connection connection = DriverManager.getConnection(urlPrefix + tenant.getDbOrSchema(),",
"score": 0.8305935263633728
},
{
"filename": "hybrid-multitenancy-customer-service/src/main/java/com/github/wenqiglantz/service/customer/multitenancy/config/tenant/CurrentTenantIdentifierResolverImpl.java",
"retrieved_chunk": " }\n @Override\n public String resolveCurrentTenantIdentifier() {\n String tenantId = TenantContext.getTenantId();\n log.info(\">>> tenantId in resolveCurrentTenantIdentifier \", tenantId);\n if (!Strings.isEmpty(tenantId)) {\n return tenantId;\n } else if (!Strings.isEmpty(this.defaultTenant)) {\n return this.defaultTenant;\n } else {",
"score": 0.828365683555603
},
{
"filename": "hybrid-multitenancy-admin-service/src/main/java/com/github/wenqiglantz/service/tenantadmin/controller/TenantAdminController.java",
"retrieved_chunk": " @RequestParam String password) {\n tenantAdminService.createTenant(tenantId, isolationType, dbOrSchema, userName, password);\n return new ResponseEntity<>(HttpStatus.CREATED);\n }\n}",
"score": 0.8166092038154602
},
{
"filename": "hybrid-multitenancy-customer-service/src/main/java/com/github/wenqiglantz/service/customer/multitenancy/config/tenant/hibernate/HybridMultiTenantConnectionProvider.java",
"retrieved_chunk": " }\n @Override\n protected DataSource selectAnyDataSource() {\n return masterDataSource;\n }\n @Override\n protected DataSource selectDataSource(String tenantIdentifier) {\n try {\n return tenantDataSources.get(tenantIdentifier);\n } catch (ExecutionException e) {",
"score": 0.8093308210372925
}
] | java | String encryptedPassword = encryptionService.encrypt(password, secret, salt); |
package com.github.wenqiglantz.service.customer.multitenancy.config.tenant.hibernate;
import com.github.wenqiglantz.service.customer.multitenancy.Tenant;
import com.github.wenqiglantz.service.customer.multitenancy.TenantRepository;
import com.github.wenqiglantz.service.customer.util.EncryptionService;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.cache.RemovalListener;
import com.zaxxer.hikari.HikariDataSource;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.engine.jdbc.connections.spi.AbstractDataSourceBasedMultiTenantConnectionProviderImpl;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
@RequiredArgsConstructor
@Slf4j
@Component("hybridMultiTenantConnectionProvider")
public class HybridMultiTenantConnectionProvider
extends AbstractDataSourceBasedMultiTenantConnectionProviderImpl {
private static final String TENANT_POOL_NAME_SUFFIX = "DataSource";
private final EncryptionService encryptionService;
@Qualifier("masterDataSource")
private final DataSource masterDataSource;
@Qualifier("masterDataSourceProperties")
private final DataSourceProperties dataSourceProperties;
private final TenantRepository masterTenantRepository;
@Value("${multitenancy.tenant.datasource.url-prefix}")
private String urlPrefix;
@Value("${multitenancy.datasource-cache.maximumSize:100}")
private Long maximumSize;
@Value("${multitenancy.datasource-cache.expireAfterAccess:10}")
private Integer expireAfterAccess;
@Value("${encryption.secret}")
private String secret;
@Value("${encryption.salt}")
private String salt;
private LoadingCache<String, DataSource> tenantDataSources;
@PostConstruct
private void createCache() {
tenantDataSources = CacheBuilder.newBuilder()
.maximumSize(maximumSize)
.expireAfterAccess(expireAfterAccess, TimeUnit.MINUTES)
.removalListener((RemovalListener<String, DataSource>) removal -> {
HikariDataSource ds = (HikariDataSource) removal.getValue();
ds.close(); // tear down properly
log.info("Closed datasource: {}", ds.getPoolName());
})
.build(new CacheLoader<String, DataSource>() {
public DataSource load(String key) {
Tenant tenant | = masterTenantRepository.findByTenantId(key)
.orElseThrow(() -> new RuntimeException("No such tenant: " + key)); |
return createAndConfigureDataSource(tenant);
}
});
}
@Override
protected DataSource selectAnyDataSource() {
return masterDataSource;
}
@Override
protected DataSource selectDataSource(String tenantIdentifier) {
try {
return tenantDataSources.get(tenantIdentifier);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}
private DataSource createAndConfigureDataSource(Tenant tenant) {
String decryptedPassword = encryptionService.decrypt(tenant.getPassword(), secret, salt);
HikariDataSource ds = dataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
ds.setUsername(tenant.getUserName());
ds.setPassword(decryptedPassword);
ds.setJdbcUrl(tenant.getUrl());
ds.setPoolName(tenant.getTenantId() + TENANT_POOL_NAME_SUFFIX);
log.info("Configured datasource: {}", ds.getPoolName());
log.info("ds url " + ds.getJdbcUrl() + ", user " + ds.getUsername() + ", isolation " + tenant.getIsolationType());
return ds;
}
} | hybrid-multitenancy-customer-service/src/main/java/com/github/wenqiglantz/service/customer/multitenancy/config/tenant/hibernate/HybridMultiTenantConnectionProvider.java | wenqiglantz-rds-hybrid-multitenancy-ad04a23 | [
{
"filename": "hybrid-multitenancy-customer-service/src/main/java/com/github/wenqiglantz/service/customer/multitenancy/config/tenant/liquibase/HybridMultiTenantSpringLiquibase.java",
"retrieved_chunk": " tenant.getDbOrSchema(), decryptedPassword)) {\n DataSource tenantDataSource = new SingleConnectionDataSource(connection, false);\n SpringLiquibase liquibase = this.getSpringLiquibase(tenantDataSource);\n liquibase.afterPropertiesSet();\n } catch (SQLException | LiquibaseException e) {\n log.error(\"Failed to run Liquibase for tenant \" + tenant.getTenantId(), e);\n }\n break;\n case SCHEMA:\n try (Connection connection = DriverManager.getConnection(tenant.getUrl(), tenant.getDbOrSchema(),",
"score": 0.8110818862915039
},
{
"filename": "hybrid-multitenancy-customer-service/src/main/java/com/github/wenqiglantz/service/customer/multitenancy/config/tenant/liquibase/HybridMultiTenantSpringLiquibase.java",
"retrieved_chunk": " log.info(\"Hybrid multitenancy enabled\");\n this.runOnAllTenants(masterTenantRepository.findAll());\n }\n protected void runOnAllTenants(Collection<Tenant> tenants) throws LiquibaseException {\n for(Tenant tenant : tenants) {\n String decryptedPassword = encryptionService.decrypt(tenant.getPassword(), secret, salt);\n log.info(\"Initializing Liquibase for tenant \" + tenant.getTenantId() + \" and password \" + decryptedPassword);\n switch (tenant.getIsolationType()) {\n case DATABASE:\n try (Connection connection = DriverManager.getConnection(urlPrefix + tenant.getDbOrSchema(),",
"score": 0.8060764074325562
},
{
"filename": "hybrid-multitenancy-admin-service/src/main/java/com/github/wenqiglantz/service/tenantadmin/service/TenantAdminService.java",
"retrieved_chunk": " case DATABASE:\n url = urlPrefix + dbOrSchema;\n try {\n createDatabase(dbOrSchema, password);\n } catch (DataAccessException e) {\n throw new TenantCreationException(\"Error when creating db: \" + dbOrSchema, e);\n }\n try (Connection connection = DriverManager.getConnection(url, dbOrSchema, password)) {\n DataSource tenantDataSource = new SingleConnectionDataSource(connection, false);\n runLiquibase(tenantDataSource);",
"score": 0.7988971471786499
},
{
"filename": "hybrid-multitenancy-admin-service/src/main/java/com/github/wenqiglantz/service/tenantadmin/config/DataSourceConfiguration.java",
"retrieved_chunk": " public DataSource masterDataSource() {\n HikariDataSource dataSource = masterDataSourceProperties()\n .initializeDataSourceBuilder()\n .type(HikariDataSource.class)\n .build();\n dataSource.setPoolName(\"masterDataSource\");\n return dataSource;\n }\n}",
"score": 0.7971271872520447
},
{
"filename": "hybrid-multitenancy-customer-service/src/main/java/com/github/wenqiglantz/service/customer/multitenancy/TenantService.java",
"retrieved_chunk": " public Tenant findByTenantId(String tenantId) {\n return tenantRepository.findByTenantId(tenantId)\n .orElseThrow(() -> new RuntimeException(\"No such tenant: \" + tenantId));\n }\n}",
"score": 0.7929978966712952
}
] | java | = masterTenantRepository.findByTenantId(key)
.orElseThrow(() -> new RuntimeException("No such tenant: " + key)); |
package com.github.wenqiglantz.service.customer.multitenancy.config.tenant;
import com.github.wenqiglantz.service.customer.multitenancy.Tenant;
import com.github.wenqiglantz.service.customer.multitenancy.TenantRepository;
import com.github.wenqiglantz.service.customer.multitenancy.TenantContext;
import jakarta.persistence.EntityManagerFactory;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.context.spi.CurrentTenantIdentifierResolver;
import org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.hibernate5.SpringBeanContainer;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@Configuration
@EnableJpaRepositories(
basePackages = {"${multitenancy.tenant.repository.packages}" },
entityManagerFactoryRef = "tenantEntityManagerFactory",
transactionManagerRef = "tenantTransactionManager"
)
@EnableConfigurationProperties(JpaProperties.class)
public class TenantHibernateConfig {
private final ConfigurableListableBeanFactory beanFactory;
private final JpaProperties jpaProperties;
private final TenantRepository tenantRepository;
@Value("${multitenancy.tenant.entityManager.packages}")
private String entityPackages;
@Autowired
public TenantHibernateConfig(
ConfigurableListableBeanFactory beanFactory,
JpaProperties jpaProperties, TenantRepository tenantRepository) {
this.beanFactory = beanFactory;
this.jpaProperties = jpaProperties;
this.tenantRepository = tenantRepository;
}
@Primary
@Bean("tenantEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean tenantEntityManagerFactory(
@Qualifier("hybridMultiTenantConnectionProvider")
MultiTenantConnectionProvider connectionProvider,
@Qualifier("currentTenantIdentifierResolver") CurrentTenantIdentifierResolver tenantResolver) {
LocalContainerEntityManagerFactoryBean emfBean = new LocalContainerEntityManagerFactoryBean();
emfBean.setPersistenceUnitName("tenantdb-persistence-unit");
emfBean.setPackagesToScan(entityPackages);
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
emfBean.setJpaVendorAdapter(vendorAdapter);
Map<String, Object> properties = new HashMap<>(this.jpaProperties.getProperties());
properties.put(AvailableSettings.BEAN_CONTAINER, new SpringBeanContainer(this.beanFactory));
String tenant = TenantContext.getTenantId();
if (null == tenant) {
properties.remove(AvailableSettings.DEFAULT_SCHEMA);
} else {
//TODO
Tenant dbTenant | = tenantRepository.findByTenantId(tenant).get(); |
switch (dbTenant.getIsolationType()) {
case DATABASE:
break;
case SCHEMA:
properties.remove(AvailableSettings.DEFAULT_SCHEMA);
break;
}
}
properties.put(AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER, connectionProvider);
properties.put(AvailableSettings.MULTI_TENANT_IDENTIFIER_RESOLVER, tenantResolver);
emfBean.setJpaPropertyMap(properties);
log.info("tenantEntityManagerFactory set up successfully!");
return emfBean;
}
@Primary
@Bean("tenantTransactionManager")
public JpaTransactionManager tenantTransactionManager(
@Qualifier("tenantEntityManagerFactory") EntityManagerFactory emf) {
JpaTransactionManager tenantTransactionManager = new JpaTransactionManager();
tenantTransactionManager.setEntityManagerFactory(emf);
return tenantTransactionManager;
}
}
| hybrid-multitenancy-customer-service/src/main/java/com/github/wenqiglantz/service/customer/multitenancy/config/tenant/TenantHibernateConfig.java | wenqiglantz-rds-hybrid-multitenancy-ad04a23 | [
{
"filename": "hybrid-multitenancy-customer-service/src/main/java/com/github/wenqiglantz/service/customer/multitenancy/TenantInterceptor.java",
"retrieved_chunk": " if (request.getHeader(TenantConstants.X_TENANT_ID) != null) {\n tenantId = request.getHeader(TenantConstants.X_TENANT_ID);\n } else if (this.defaultTenant != null) {\n tenantId = this.defaultTenant;\n } else {\n tenantId = ((ServletWebRequest)request).getRequest().getServerName().split(\"\\\\.\")[0];\n }\n TenantContext.setTenantId(tenantId);\n }\n @Override",
"score": 0.8339735865592957
},
{
"filename": "hybrid-multitenancy-customer-service/src/main/java/com/github/wenqiglantz/service/customer/multitenancy/config/master/MasterHibernateConfig.java",
"retrieved_chunk": " @Qualifier(\"masterDataSource\") DataSource dataSource) {\n LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();\n em.setPersistenceUnitName(\"master-persistence-unit\");\n em.setPackagesToScan(entityPackages);\n em.setDataSource(dataSource);\n JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();\n em.setJpaVendorAdapter(vendorAdapter);\n Map<String, Object> properties = new HashMap<>(this.jpaProperties.getProperties());\n properties.put(AvailableSettings.BEAN_CONTAINER, new SpringBeanContainer(this.beanFactory));\n em.setJpaPropertyMap(properties);",
"score": 0.8285088539123535
},
{
"filename": "hybrid-multitenancy-customer-service/src/main/java/com/github/wenqiglantz/service/customer/multitenancy/config/tenant/CurrentTenantIdentifierResolverImpl.java",
"retrieved_chunk": " }\n @Override\n public String resolveCurrentTenantIdentifier() {\n String tenantId = TenantContext.getTenantId();\n log.info(\">>> tenantId in resolveCurrentTenantIdentifier \", tenantId);\n if (!Strings.isEmpty(tenantId)) {\n return tenantId;\n } else if (!Strings.isEmpty(this.defaultTenant)) {\n return this.defaultTenant;\n } else {",
"score": 0.8232091665267944
},
{
"filename": "hybrid-multitenancy-customer-service/src/main/java/com/github/wenqiglantz/service/customer/multitenancy/config/tenant/liquibase/HybridMultiTenantSpringLiquibase.java",
"retrieved_chunk": " log.info(\"Hybrid multitenancy enabled\");\n this.runOnAllTenants(masterTenantRepository.findAll());\n }\n protected void runOnAllTenants(Collection<Tenant> tenants) throws LiquibaseException {\n for(Tenant tenant : tenants) {\n String decryptedPassword = encryptionService.decrypt(tenant.getPassword(), secret, salt);\n log.info(\"Initializing Liquibase for tenant \" + tenant.getTenantId() + \" and password \" + decryptedPassword);\n switch (tenant.getIsolationType()) {\n case DATABASE:\n try (Connection connection = DriverManager.getConnection(urlPrefix + tenant.getDbOrSchema(),",
"score": 0.8150209188461304
},
{
"filename": "hybrid-multitenancy-customer-service/src/main/java/com/github/wenqiglantz/service/customer/multitenancy/config/tenant/hibernate/HybridMultiTenantConnectionProvider.java",
"retrieved_chunk": " throw new RuntimeException(e);\n }\n }\n private DataSource createAndConfigureDataSource(Tenant tenant) {\n String decryptedPassword = encryptionService.decrypt(tenant.getPassword(), secret, salt);\n HikariDataSource ds = dataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build();\n ds.setUsername(tenant.getUserName());\n ds.setPassword(decryptedPassword);\n ds.setJdbcUrl(tenant.getUrl());\n ds.setPoolName(tenant.getTenantId() + TENANT_POOL_NAME_SUFFIX);",
"score": 0.8083480000495911
}
] | java | = tenantRepository.findByTenantId(tenant).get(); |
package com.github.wenqiglantz.service.customer.multitenancy.config.tenant;
import com.github.wenqiglantz.service.customer.multitenancy.Tenant;
import com.github.wenqiglantz.service.customer.multitenancy.TenantRepository;
import com.github.wenqiglantz.service.customer.multitenancy.TenantContext;
import jakarta.persistence.EntityManagerFactory;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.context.spi.CurrentTenantIdentifierResolver;
import org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.hibernate5.SpringBeanContainer;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@Configuration
@EnableJpaRepositories(
basePackages = {"${multitenancy.tenant.repository.packages}" },
entityManagerFactoryRef = "tenantEntityManagerFactory",
transactionManagerRef = "tenantTransactionManager"
)
@EnableConfigurationProperties(JpaProperties.class)
public class TenantHibernateConfig {
private final ConfigurableListableBeanFactory beanFactory;
private final JpaProperties jpaProperties;
private final TenantRepository tenantRepository;
@Value("${multitenancy.tenant.entityManager.packages}")
private String entityPackages;
@Autowired
public TenantHibernateConfig(
ConfigurableListableBeanFactory beanFactory,
JpaProperties jpaProperties, TenantRepository tenantRepository) {
this.beanFactory = beanFactory;
this.jpaProperties = jpaProperties;
this.tenantRepository = tenantRepository;
}
@Primary
@Bean("tenantEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean tenantEntityManagerFactory(
@Qualifier("hybridMultiTenantConnectionProvider")
MultiTenantConnectionProvider connectionProvider,
@Qualifier("currentTenantIdentifierResolver") CurrentTenantIdentifierResolver tenantResolver) {
LocalContainerEntityManagerFactoryBean emfBean = new LocalContainerEntityManagerFactoryBean();
emfBean.setPersistenceUnitName("tenantdb-persistence-unit");
emfBean.setPackagesToScan(entityPackages);
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
emfBean.setJpaVendorAdapter(vendorAdapter);
Map<String, Object> properties = new HashMap<>(this.jpaProperties.getProperties());
properties.put(AvailableSettings.BEAN_CONTAINER, new SpringBeanContainer(this.beanFactory));
| String tenant = TenantContext.getTenantId(); |
if (null == tenant) {
properties.remove(AvailableSettings.DEFAULT_SCHEMA);
} else {
//TODO
Tenant dbTenant = tenantRepository.findByTenantId(tenant).get();
switch (dbTenant.getIsolationType()) {
case DATABASE:
break;
case SCHEMA:
properties.remove(AvailableSettings.DEFAULT_SCHEMA);
break;
}
}
properties.put(AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER, connectionProvider);
properties.put(AvailableSettings.MULTI_TENANT_IDENTIFIER_RESOLVER, tenantResolver);
emfBean.setJpaPropertyMap(properties);
log.info("tenantEntityManagerFactory set up successfully!");
return emfBean;
}
@Primary
@Bean("tenantTransactionManager")
public JpaTransactionManager tenantTransactionManager(
@Qualifier("tenantEntityManagerFactory") EntityManagerFactory emf) {
JpaTransactionManager tenantTransactionManager = new JpaTransactionManager();
tenantTransactionManager.setEntityManagerFactory(emf);
return tenantTransactionManager;
}
}
| hybrid-multitenancy-customer-service/src/main/java/com/github/wenqiglantz/service/customer/multitenancy/config/tenant/TenantHibernateConfig.java | wenqiglantz-rds-hybrid-multitenancy-ad04a23 | [
{
"filename": "hybrid-multitenancy-customer-service/src/main/java/com/github/wenqiglantz/service/customer/multitenancy/config/master/MasterHibernateConfig.java",
"retrieved_chunk": " @Qualifier(\"masterDataSource\") DataSource dataSource) {\n LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();\n em.setPersistenceUnitName(\"master-persistence-unit\");\n em.setPackagesToScan(entityPackages);\n em.setDataSource(dataSource);\n JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();\n em.setJpaVendorAdapter(vendorAdapter);\n Map<String, Object> properties = new HashMap<>(this.jpaProperties.getProperties());\n properties.put(AvailableSettings.BEAN_CONTAINER, new SpringBeanContainer(this.beanFactory));\n em.setJpaPropertyMap(properties);",
"score": 0.9517114758491516
},
{
"filename": "hybrid-multitenancy-customer-service/src/main/java/com/github/wenqiglantz/service/customer/multitenancy/config/master/MasterHibernateConfig.java",
"retrieved_chunk": " @Value(\"${multitenancy.master.entityManager.packages}\")\n\tprivate String entityPackages;\n\t@Autowired\n public MasterHibernateConfig(ConfigurableListableBeanFactory beanFactory,\n JpaProperties jpaProperties) {\n this.beanFactory = beanFactory;\n this.jpaProperties = jpaProperties;\n }\n @Bean(name = \"masterEntityManagerFactory\")\n public LocalContainerEntityManagerFactoryBean masterEntityManagerFactory(",
"score": 0.8465009927749634
},
{
"filename": "hybrid-multitenancy-customer-service/src/main/java/com/github/wenqiglantz/service/customer/multitenancy/config/master/MasterHibernateConfig.java",
"retrieved_chunk": " return em;\n }\n @Bean(name = \"masterTransactionManager\")\n public JpaTransactionManager masterTransactionManager(\n @Qualifier(\"masterEntityManagerFactory\") EntityManagerFactory emf) {\n JpaTransactionManager transactionManager = new JpaTransactionManager();\n transactionManager.setEntityManagerFactory(emf);\n return transactionManager;\n }\n}",
"score": 0.8212636113166809
},
{
"filename": "hybrid-multitenancy-customer-service/src/main/java/com/github/wenqiglantz/service/customer/multitenancy/config/master/MasterHibernateConfig.java",
"retrieved_chunk": "@Configuration\n@EnableJpaRepositories(\n basePackages = { \"${multitenancy.master.repository.packages}\" },\n entityManagerFactoryRef = \"masterEntityManagerFactory\",\n transactionManagerRef = \"masterTransactionManager\"\n)\n@EnableConfigurationProperties(JpaProperties.class)\npublic class MasterHibernateConfig {\n private final ConfigurableListableBeanFactory beanFactory;\n private final JpaProperties jpaProperties;",
"score": 0.7859437465667725
},
{
"filename": "hybrid-multitenancy-customer-service/src/main/java/com/github/wenqiglantz/service/customer/multitenancy/config/tenant/hibernate/HybridMultiTenantConnectionProvider.java",
"retrieved_chunk": " throw new RuntimeException(e);\n }\n }\n private DataSource createAndConfigureDataSource(Tenant tenant) {\n String decryptedPassword = encryptionService.decrypt(tenant.getPassword(), secret, salt);\n HikariDataSource ds = dataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build();\n ds.setUsername(tenant.getUserName());\n ds.setPassword(decryptedPassword);\n ds.setJdbcUrl(tenant.getUrl());\n ds.setPoolName(tenant.getTenantId() + TENANT_POOL_NAME_SUFFIX);",
"score": 0.7742873430252075
}
] | java | String tenant = TenantContext.getTenantId(); |
package com.juziml.read.business.read.view;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewParent;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.juziml.read.business.read.anim.AnimHelper;
import com.juziml.read.business.read.anim.CoverAnimationEffecter;
import com.juziml.read.business.read.anim.IAnimationEffecter;
import com.juziml.read.business.read.anim.SimulationAnimationEffecter;
/**
* 此View的作用就像幕后一样,负责接受事件并传递到动画,Effecter
* create by zhusw on 2020-08-14 17:37
*/
public class PuppetView extends View implements EventProxy, AnimParentView {
IAnimationEffecter animationEffecter;
AnimParentView parentView;
private Bitmap previousViewBitmap;
private Bitmap currentViewBitmap;
private Bitmap nextViewBitmap;
boolean performDrawCurlTexture = false;
private int vWidth, vHeight;
public PuppetView(@NonNull Context context) {
this(context, null);
}
public PuppetView(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public PuppetView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
/*
view 可以单独关,但是不能单独打开硬件加速
关闭硬件加速 卡到爆炸
开启硬件加速,诱发 OpenGLRenderer: Path too large to be rendered into a texture
setLayerType(LAYER_TYPE_SOFTWARE,null);
*/
}
public boolean animRunningOrTouching() {
boolean animRunningOrTouching = false;
if (null != animationEffecter) {
animRunningOrTouching = animRunning();
}
return animRunningOrTouching;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
ViewParent viewParent = getParent();
parentView = (AnimParentView) viewParent;
if (null != animationEffecter) {
animationEffecter.onViewAttachedToWindow();
}
}
public void setAnimMode(int animMode) {
//重置某些属性 与变量
animationEffecter = null;
if (animMode == BookLayoutManager.BookFlipMode.MODE_COVER) {
animationEffecter = new CoverAnimationEffecter(this);
} else if (animMode == BookLayoutManager.BookFlipMode.MODE_CURL) {
animationEffecter = new SimulationAnimationEffecter(this);
}
if (null != animationEffecter) {
animationEffecter.onViewSizeChanged(vWidth, vHeight);
}
}
@Override
public void draw(Canvas canvas) {
if (performDrawCurlTexture && null != animationEffecter) {
animationEffecter.draw(canvas);
} else {
super.draw(canvas);
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (null != animationEffecter) {
animationEffecter.onViewDetachedFromWindow();
}
}
/**
* 这个会被调用多次,最终宽度为实际测量宽度-2px
* 这样在 layoutmanager 进行布局时 才可以同时保持3个item被显示
*
* @param widthMeasureSpec
* @param heightMeasureSpec
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int height = measureSize(5, heightMeasureSpec);
int width = measureSize(5, widthMeasureSpec) - 2;
setMeasuredDimension(width - 2, height);
vWidth = width;
vHeight = height;
if (null != animationEffecter) {
animationEffecter.onViewSizeChanged(vWidth, vHeight);
}
}
private int measureSize(int defaultSize, int measureSpec) {
int result = defaultSize;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
result = specSize;
} else if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
return result;
}
public void buildBitmap(int slideDirection) {
performDrawCurlTexture = false;
if (slideDirection == AnimHelper.SLID_DIRECTION_LEFT) {
currentViewBitmap = parentView.getCurrentBitmap();
nextViewBitmap = parentView.getNextBitmap();
} else if (slideDirection == AnimHelper.SLID_DIRECTION_RIGHT) {
previousViewBitmap = parentView.getPreviousBitmap();
}
performDrawCurlTexture = true;
}
@Override
public boolean onItemViewTouchEvent(MotionEvent event) {
if (null != animationEffecter) {
animationEffecter.handlerEvent(event);
}
return true;
}
@Override
public boolean animRunning() {
if (null != animationEffecter) {
return animationEffecter.animInEffect();
}
return false;
}
@Override
public void computeScroll() {
if (null != animationEffecter) {
| animationEffecter.onScroll(); |
}
}
@Override
public void onExpectNext() {
parentView.onExpectNext();
}
@Override
public void onExpectPrevious() {
parentView.onExpectPrevious();
}
@Override
public Bitmap getPreviousBitmap() {
return previousViewBitmap;
}
@Override
public Bitmap getCurrentBitmap() {
return currentViewBitmap;
}
@Override
public Bitmap getNextBitmap() {
return nextViewBitmap;
}
@Override
public int getBackgroundColor() {
return parentView.getBackgroundColor();
}
@Override
public AnimHelper getAnimHelper() {
return parentView.getAnimHelper();
}
@Override
public void onClickMenuArea() {
parentView.onClickMenuArea();
}
@Override
public void onClickNextArea() {
parentView.onClickNextArea();
}
@Override
public void onClickPreviousArea() {
parentView.onClickPreviousArea();
}
public void reset() {
previousViewBitmap = null;
nextViewBitmap = null;
currentViewBitmap = null;
performDrawCurlTexture = false;
}
}
| app/src/main/java/com/juziml/read/business/read/view/PuppetView.java | Western-parotia-BookViewProject-1727e80 | [
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookLayoutManager.java",
"retrieved_chunk": " horizontalOffset += (long) distance;\n requestLayout();\n if (null != onForceLayoutCompleted) {\n onForceLayoutCompleted.onLayoutCompleted(position);\n }\n }\n }\n public void cancelAnimator() {\n if (selectAnimator != null && (selectAnimator.isStarted() || selectAnimator.isRunning())) {\n selectAnimator.cancel();",
"score": 0.8468371033668518
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookRecyclerView.java",
"retrieved_chunk": " return false;\n }\n @Override\n public void onClickMenu() {\n animParentView.onClickMenuArea();\n }\n private class ItemOnScrollStop implements BookLayoutManager.OnStopScroller {\n @Override\n public void onStop(boolean autoLeftScroll, int curPos) {\n boolean arriveNext = currentPosition < curPos;",
"score": 0.8466946482658386
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/PaperLayout.java",
"retrieved_chunk": " }\n @Override\n public boolean isScrollContainer() {\n return false;\n }\n private float interceptDownX;\n @Override\n public boolean onInterceptTouchEvent(MotionEvent ev) {\n //动画执行期间 子view 也不可获取事件\n if (bookRecyclerView.animRunning()) return true;",
"score": 0.8421756625175476
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookRecyclerView.java",
"retrieved_chunk": " readLayoutManger.onRecyclerViewSizeChange();\n }\n private final List<Float> moveSampling = new LinkedList<>();\n private final int MAX_COUNT = 5;\n @Override\n public boolean isScrollContainer() {\n if (allowInterceptTouchEvent) {\n return super.isScrollContainer();\n } else {\n return false;",
"score": 0.8381864428520203
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookRecyclerView.java",
"retrieved_chunk": " } else {\n scrollToPosition(nextPos);\n }\n }\n }\n @Override\n public void onExpectPrevious(boolean smooth) {\n if (currentPosition - 1 >= 0) {\n if (smooth) {\n smoothScrollToPosition(currentPosition - 1);",
"score": 0.8379620313644409
}
] | java | animationEffecter.onScroll(); |
package com.juziml.content.gpu_test;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Region;
import android.util.AttributeSet;
import android.view.View;
import androidx.annotation.Nullable;
/**
* create by zhusw on 2020-07-29 10:54
*/
public class GpuTestCurlAnimView extends View {
Paint pointPaint;
FPoint a, f, g, e, h, c, j, b, k, d, i;
int width;
int height;
//图形
Paint pathAPaint;
Path pathA;
Bitmap holderBitmap;
Canvas bitmapCanvas = new Canvas();
Paint pathCPaint;
Path pathC;
Paint pathBPaint;
Path pathB;
PorterDuffXfermode xfDST_ATOP = new PorterDuffXfermode(PorterDuff.Mode.DST_ATOP);
public GpuTestCurlAnimView(Context context) {
this(context, null);
}
public GpuTestCurlAnimView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
width = w;
height = h;
a.setXY(-1, -1);
holderBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
}
public GpuTestCurlAnimView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
pointPaint = new Paint();
pointPaint.setColor(Color.RED);
pointPaint.setTextSize(25);
a = new FPoint();
f = new FPoint();
g = new FPoint();
e = new FPoint();
h = new FPoint();
c = new FPoint();
j = new FPoint();
b = new FPoint();
k = new FPoint();
d = new FPoint();
i = new FPoint();
pathAPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
pathAPaint.setColor(Color.GREEN);
pathA = new Path();
pathCPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
pathCPaint.setColor(Color.YELLOW);
pathCPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_ATOP));//消除c区 与a区重叠部分,原文注释:丢弃原图想覆盖目标图像的区域
pathC = new Path();
pathBPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
pathBPaint.setColor(Color.BLUE);
pathB = new Path();
}
public void flipPrepare(float x, float y) {
if (y < height / 2) {
f.setXY(width, 0);
} else {
| f.setXY(width, height); |
}
}
public void flipSetToDefault() {
a.setXY(-1, -1);
f.setXY(0, 0);
calculatePointXY(a, f);
postInvalidate();
}
public void flipCurl(float x, float y) {
a.x = x;
a.y = y;
calculatePointXY(a, f);
//修正c点范围 不可小于0
if (calculateCxRange(a.x, a.y, f) < 0) {
calcPointAByTouchPoint();
calculatePointXY(a, f);
}
postInvalidate();
}
private float calculateCxRange(float ax, float ay, FPoint f) {
float gx = (ax + f.x) / 2;
float gy = (ay + f.y) / 2;
float ex = gx - (f.y - gy) * (f.y - gy) / (f.x - gx);
return ex - (f.x - ex) / 2;
}
/**
* 如果c点x坐标小于0,根据触摸点重新测量a点坐标
*/
private void calcPointAByTouchPoint() {
float w0 = width - c.x;
float w1 = Math.abs(f.x - a.x);
float w2 = width * w1 / w0;
a.x = Math.abs(f.x - w2);
float h1 = Math.abs(f.y - a.y);
float h2 = w2 * h1 / w1;
a.y = Math.abs(f.y - h2);
}
@Override
public void onDrawForeground(Canvas canvas) {
super.onDrawForeground(canvas);
//把点绘制在前景上 方便观察
drawPoint(canvas);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (a.x == -1 && a.y == -1) {
canvas.drawPath(getDefaultPath(), pathAPaint);
} else {
Path pathA = getPathAFromRightTop();
if (f.x == width && f.y == height) {
pathA = getPathAFromRightBottom();
}
Path pathC = getPathC();
canvas.drawPath(pathC, pathCPaint);//先给C区画上底色
canvas.drawPath(pathA, pathAPaint);//先给A区画上底色
canvas.save();//扣出B区
canvas.clipPath(pathC, Region.Op.DIFFERENCE);
canvas.clipPath(pathA, Region.Op.DIFFERENCE);
canvas.drawPath(getPathB(), pathBPaint);
canvas.restore();
}
}
public Path getDefaultPath() {
pathA.reset();
pathA.lineTo(0, height);
pathA.lineTo(width, height);
pathA.lineTo(width, 0);
pathA.close();
return pathA;
}
/**
* 以右下角为触发起点
*
* @return
*/
private Path getPathAFromRightBottom() {
pathA.reset();
//划线从 0,0开始
pathA.lineTo(0, height);//划线到左下角
pathA.lineTo(c.x, c.y);//划线到c点
pathA.quadTo(e.x, e.y, b.x, b.y);//以c为起点,b为终点,e为动点 画曲线
pathA.lineTo(a.x, a.y);
pathA.lineTo(k.x, k.y);
pathA.quadTo(h.x, h.y, j.x, j.y);//以k为起点,j为终点 h为动点 画曲线
pathA.lineTo(width, 0);
pathA.close();
return pathA;
}
private Path getPathAFromRightTop() {
pathA.reset();
pathA.lineTo(c.x, c.y);//划线到c
pathA.quadTo(e.x, e.y, b.x, b.y);//c-b的曲线
pathA.lineTo(a.x, a.y);//划线到a
pathA.lineTo(k.x, k.y);//划线到k
pathA.quadTo(h.x, h.y, j.x, j.y);//k-j的曲线
pathA.lineTo(width, height);
pathA.lineTo(0, height);
pathA.close();
return pathA;
}
private Path getPathC() {
pathC.reset();
pathC.moveTo(d.x, d.y);
pathC.lineTo(b.x, b.y);
pathC.lineTo(a.x, a.y);
pathC.lineTo(k.x, k.y);
pathC.lineTo(i.x, i.y);
pathC.close();
return pathC;
}
private Path getPathB() {
pathB.reset();
pathB.lineTo(0, height);
pathB.lineTo(width, height);
pathB.lineTo(width, 0);
pathB.close();
return pathB;
}
private void drawPoint(Canvas canvas) {
canvas.drawText("a", a.x, a.y, pointPaint);
canvas.drawText("f", f.x, f.y, pointPaint);
canvas.drawText("g", g.x, g.y, pointPaint);
canvas.drawText("e", e.x, e.y, pointPaint);
canvas.drawText("h", h.x, h.y, pointPaint);
canvas.drawText("c", c.x, c.y, pointPaint);
canvas.drawText("j", j.x, j.y, pointPaint);
canvas.drawText("b", b.x, b.y, pointPaint);
canvas.drawText("k", k.x, k.y, pointPaint);
canvas.drawText("d", d.x, d.y, pointPaint);
canvas.drawText("i", i.x, i.y, pointPaint);
}
/**
* 计算切点坐标,这里就没有推导公式了,直接拿来用了
*
* @param lineOne_My_pointOne
* @param lineOne_My_pointTwo
* @param lineTwo_My_pointOne
* @param lineTwo_My_pointTwo
* @return
*/
private FPoint getIntersectionPoint(FPoint lineOne_My_pointOne,
FPoint lineOne_My_pointTwo,
FPoint lineTwo_My_pointOne,
FPoint lineTwo_My_pointTwo) {
float x1, y1, x2, y2, x3, y3, x4, y4;
x1 = lineOne_My_pointOne.x;
y1 = lineOne_My_pointOne.y;
x2 = lineOne_My_pointTwo.x;
y2 = lineOne_My_pointTwo.y;
x3 = lineTwo_My_pointOne.x;
y3 = lineTwo_My_pointOne.y;
x4 = lineTwo_My_pointTwo.x;
y4 = lineTwo_My_pointTwo.y;
float pointX = ((x1 - x2) * (x3 * y4 - x4 * y3)
- (x3 - x4) * (x1 * y2 - x2 * y1)) / ((x3 - x4)
* (y1 - y2) - (x1 - x2) * (y3 - y4));
float pointY = ((y1 - y2) * (x3 * y4 - x4 * y3)
- (x1 * y2 - x2 * y1) * (y3 - y4)) / ((y1 - y2)
* (x3 - x4) - (x1 - x2) * (y3 - y4));
return new FPoint(pointX, pointY);
}
/**
* 计算各点坐标
*/
private void calculatePointXY(FPoint a, FPoint f) {
g.x = (a.x + f.x) / 2;
g.y = (a.y + f.y) / 2;
e.x = g.x - (f.y - g.y) * (f.y - g.y) / (f.x - g.x);
e.y = f.y;
h.x = f.x;
h.y = g.y - (f.x - g.x) * (f.x - g.x) / (f.y - g.y);
c.x = e.x - (f.x - e.x) / 2;
c.y = f.y;
j.x = f.x;
j.y = h.y - (f.y - h.y) / 2;
b = getIntersectionPoint(a, e, c, j);
k = getIntersectionPoint(a, h, c, j);
d.x = (c.x + 2 * e.x + b.x) / 4;
d.y = (2 * e.y + c.y + b.y) / 4;
i.x = (j.x + 2 * h.x + k.x) / 4;
i.y = (2 * h.y + j.y + k.y) / 4;
}
}
| gpu_test/src/main/java/com/juziml/content/gpu_test/GpuTestCurlAnimView.java | Western-parotia-BookViewProject-1727e80 | [
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/CoverAnimationEffecter.java",
"retrieved_chunk": " canvas.drawBitmap(readAnimView.getCurrentBitmap(), -offset, 0, paint);\n canvas.restore();\n canvas.save();\n canvas.clipPath(getPathB());\n canvas.drawBitmap(readAnimView.getNextBitmap(), 0, 0, paint);\n canvas.restore();\n drawShadow((int) (vWidth - offset), canvas);\n } else {\n float leftOffset = vWidth - currentX;\n canvas.save();",
"score": 0.8446362018585205
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " g2 = new FPoint();\n e2 = new FPoint();\n pathPaint = new Paint(Paint.ANTI_ALIAS_FLAG);\n bitmapPaint = new Paint(Paint.ANTI_ALIAS_FLAG);\n pathA = new Path();\n pathC = new Path();\n pathRightShadow = new Path();\n pathLeftShadow = new Path();\n ColorMatrix cm = new ColorMatrix();//设置颜色数组\n float[] array = {1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0};",
"score": 0.844111979007721
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/CoverAnimationEffecter.java",
"retrieved_chunk": " }\n private Path getPathB() {\n pathB.reset();\n float x = vWidth - (downX - currentX);\n x = Math.min(vWidth, x);\n pathB.moveTo(x, 0);\n pathB.lineTo(vWidth, 0);\n pathB.lineTo(vWidth, vHeight);\n pathB.lineTo(x, vHeight);\n pathB.close();",
"score": 0.8433800339698792
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/CoverAnimationEffecter.java",
"retrieved_chunk": " canvas.clipPath(getPathAToRight());\n canvas.drawBitmap(readAnimView.getPreviousBitmap(), -leftOffset, 0, paint);\n canvas.restore();\n drawShadow((int) currentX, canvas);\n }\n }\n private void drawShadow(int left, Canvas canvas) {\n GradientDrawable drawable = readAnimView.getAnimHelper().getCoverGradientDrawable();\n drawable.setBounds(left, 0, left + shadowWidth, vHeight);\n drawable.draw(canvas);",
"score": 0.827875554561615
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/CoverAnimationEffecter.java",
"retrieved_chunk": " }\n private Path getPathAToLeft() {\n pathA.reset();\n float x = vWidth - (downX - currentX);\n x = Math.min(vWidth, x);\n pathA.lineTo(x, 0);\n pathA.lineTo(x, vHeight);\n pathA.lineTo(0, vHeight);\n pathA.close();\n return pathA;",
"score": 0.8231055736541748
}
] | java | f.setXY(width, height); |
package com.juziml.content.gpu_test;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.juziml.content.R;
/**
* create by zhusw on 2020-07-29 10:55
*/
public class GpuTestAct extends AppCompatActivity {
GpuTestCurlAnimView gpuTestCurlAnimView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_gputest);
gpuTestCurlAnimView = findViewById(R.id.curlView);
gpuTestCurlAnimView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
gpuTestCurlAnimView.flipPrepare(event.getRawX(), event.getRawY());
break;
case MotionEvent.ACTION_MOVE:
gpuTestCurlAnimView.flipCurl(event.getRawX(), event.getRawY());
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
| gpuTestCurlAnimView.flipSetToDefault(); |
break;
default:
break;
}
return true;
}
});
}
}
| gpu_test/src/main/java/com/juziml/content/gpu_test/GpuTestAct.java | Western-parotia-BookViewProject-1727e80 | [
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/PaperLayout.java",
"retrieved_chunk": " downY = ev.getRawY();\n } else if (ev.getAction() == MotionEvent.ACTION_MOVE) {\n if (receiveDownX == -1) {\n ev.setAction(MotionEvent.ACTION_DOWN);\n receiveDownX = ev.getRawX();\n }\n } else if (ev.getAction() == MotionEvent.ACTION_UP\n || ev.getAction() == MotionEvent.ACTION_CANCEL) {\n receiveDownX = -1;\n }",
"score": 0.8441991806030273
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookRecyclerView.java",
"retrieved_chunk": " }\n break;\n case MotionEvent.ACTION_UP:\n case MotionEvent.ACTION_CANCEL:\n if (moveSampling.size() > 0) {\n float lastMoveX = moveSampling.get(moveSampling.size() - 1);\n float firstMoveX = moveSampling.get(0);\n float finallyMoveX = lastMoveX - firstMoveX;\n if (lastMoveX - downX < 0) {//左滑\n readLayoutManger.setAutoLeftScroll(finallyMoveX < 10);",
"score": 0.7966902256011963
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/PaperLayout.java",
"retrieved_chunk": " if (ev.getAction() == MotionEvent.ACTION_DOWN) {\n interceptDownX = ev.getRawX();\n } else if (ev.getAction() == MotionEvent.ACTION_MOVE) {\n float currentX = ev.getRawX();\n float distance = Math.abs(currentX - interceptDownX);\n if (distance > 1F) {\n return true;\n }\n }\n return super.onInterceptTouchEvent(ev);",
"score": 0.789046049118042
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " switch (event.getAction()) {\n case MotionEvent.ACTION_DOWN:\n isTouching = true;\n drawCurlAnimBefore = false;\n moveSampling.clear();\n downX = x;\n curlSlideDirection = AnimHelper.SLID_DIRECTION_UNKNOWN;\n if (x < menuBounds.left) {\n downArea = DOWN_AREA_LEFT;\n } else if (x > menuBounds.left && y < menuBounds.top) {",
"score": 0.776403546333313
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " case MotionEvent.ACTION_UP://需要对最后手势进行采样,判断是 取消还是自动翻页\n if (drawCurlAnimBefore) {\n if (moveSampling.size() > 0) {\n float lastMoveX = moveSampling.get(moveSampling.size() - 1);\n float firstMoveX = moveSampling.get(0);\n float finallyMoveX = lastMoveX - firstMoveX;\n if (curlSlideDirection == AnimHelper.SLID_DIRECTION_LEFT) {\n boolean lastFingerLeftSlop = finallyMoveX < 10;\n touchUp(lastFingerLeftSlop);\n } else if (curlSlideDirection == AnimHelper.SLID_DIRECTION_RIGHT) {",
"score": 0.7741315364837646
}
] | java | gpuTestCurlAnimView.flipSetToDefault(); |
package com.juziml.read.business.read.view;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewParent;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.juziml.read.business.read.anim.AnimHelper;
import com.juziml.read.business.read.anim.CoverAnimationEffecter;
import com.juziml.read.business.read.anim.IAnimationEffecter;
import com.juziml.read.business.read.anim.SimulationAnimationEffecter;
/**
* 此View的作用就像幕后一样,负责接受事件并传递到动画,Effecter
* create by zhusw on 2020-08-14 17:37
*/
public class PuppetView extends View implements EventProxy, AnimParentView {
IAnimationEffecter animationEffecter;
AnimParentView parentView;
private Bitmap previousViewBitmap;
private Bitmap currentViewBitmap;
private Bitmap nextViewBitmap;
boolean performDrawCurlTexture = false;
private int vWidth, vHeight;
public PuppetView(@NonNull Context context) {
this(context, null);
}
public PuppetView(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public PuppetView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
/*
view 可以单独关,但是不能单独打开硬件加速
关闭硬件加速 卡到爆炸
开启硬件加速,诱发 OpenGLRenderer: Path too large to be rendered into a texture
setLayerType(LAYER_TYPE_SOFTWARE,null);
*/
}
public boolean animRunningOrTouching() {
boolean animRunningOrTouching = false;
if (null != animationEffecter) {
animRunningOrTouching = animRunning();
}
return animRunningOrTouching;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
ViewParent viewParent = getParent();
parentView = (AnimParentView) viewParent;
if (null != animationEffecter) {
animationEffecter.onViewAttachedToWindow();
}
}
public void setAnimMode(int animMode) {
//重置某些属性 与变量
animationEffecter = null;
if (animMode == BookLayoutManager.BookFlipMode.MODE_COVER) {
animationEffecter = new CoverAnimationEffecter(this);
} else if (animMode == BookLayoutManager.BookFlipMode.MODE_CURL) {
animationEffecter = new SimulationAnimationEffecter(this);
}
if (null != animationEffecter) {
animationEffecter.onViewSizeChanged(vWidth, vHeight);
}
}
@Override
public void draw(Canvas canvas) {
if (performDrawCurlTexture && null != animationEffecter) {
animationEffecter.draw(canvas);
} else {
super.draw(canvas);
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (null != animationEffecter) {
animationEffecter.onViewDetachedFromWindow();
}
}
/**
* 这个会被调用多次,最终宽度为实际测量宽度-2px
* 这样在 layoutmanager 进行布局时 才可以同时保持3个item被显示
*
* @param widthMeasureSpec
* @param heightMeasureSpec
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int height = measureSize(5, heightMeasureSpec);
int width = measureSize(5, widthMeasureSpec) - 2;
setMeasuredDimension(width - 2, height);
vWidth = width;
vHeight = height;
if (null != animationEffecter) {
animationEffecter.onViewSizeChanged(vWidth, vHeight);
}
}
private int measureSize(int defaultSize, int measureSpec) {
int result = defaultSize;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
result = specSize;
} else if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
return result;
}
public void buildBitmap(int slideDirection) {
performDrawCurlTexture = false;
if (slideDirection == AnimHelper.SLID_DIRECTION_LEFT) {
currentViewBitmap = parentView.getCurrentBitmap();
nextViewBitmap = parentView.getNextBitmap();
} else if (slideDirection == AnimHelper.SLID_DIRECTION_RIGHT) {
previousViewBitmap = parentView.getPreviousBitmap();
}
performDrawCurlTexture = true;
}
@Override
public boolean onItemViewTouchEvent(MotionEvent event) {
if (null != animationEffecter) {
animationEffecter.handlerEvent(event);
}
return true;
}
@Override
public boolean animRunning() {
if (null != animationEffecter) {
| return animationEffecter.animInEffect(); |
}
return false;
}
@Override
public void computeScroll() {
if (null != animationEffecter) {
animationEffecter.onScroll();
}
}
@Override
public void onExpectNext() {
parentView.onExpectNext();
}
@Override
public void onExpectPrevious() {
parentView.onExpectPrevious();
}
@Override
public Bitmap getPreviousBitmap() {
return previousViewBitmap;
}
@Override
public Bitmap getCurrentBitmap() {
return currentViewBitmap;
}
@Override
public Bitmap getNextBitmap() {
return nextViewBitmap;
}
@Override
public int getBackgroundColor() {
return parentView.getBackgroundColor();
}
@Override
public AnimHelper getAnimHelper() {
return parentView.getAnimHelper();
}
@Override
public void onClickMenuArea() {
parentView.onClickMenuArea();
}
@Override
public void onClickNextArea() {
parentView.onClickNextArea();
}
@Override
public void onClickPreviousArea() {
parentView.onClickPreviousArea();
}
public void reset() {
previousViewBitmap = null;
nextViewBitmap = null;
currentViewBitmap = null;
performDrawCurlTexture = false;
}
}
| app/src/main/java/com/juziml/read/business/read/view/PuppetView.java | Western-parotia-BookViewProject-1727e80 | [
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookRecyclerView.java",
"retrieved_chunk": " public void onItemViewTouchEvent(MotionEvent event) {\n if (null != eventProxyWeakReference && null != eventProxyWeakReference.get()) {\n eventProxyWeakReference.get().onItemViewTouchEvent(event);\n }\n }\n @Override\n public boolean animRunning() {\n if (null != eventProxyWeakReference && null != eventProxyWeakReference.get()) {\n eventProxyWeakReference.get().animRunning();\n }",
"score": 0.8645972013473511
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookLayoutManager.java",
"retrieved_chunk": " horizontalOffset += (long) distance;\n requestLayout();\n if (null != onForceLayoutCompleted) {\n onForceLayoutCompleted.onLayoutCompleted(position);\n }\n }\n }\n public void cancelAnimator() {\n if (selectAnimator != null && (selectAnimator.isStarted() || selectAnimator.isRunning())) {\n selectAnimator.cancel();",
"score": 0.8510615229606628
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/PaperLayout.java",
"retrieved_chunk": " }\n @Override\n public boolean isScrollContainer() {\n return false;\n }\n private float interceptDownX;\n @Override\n public boolean onInterceptTouchEvent(MotionEvent ev) {\n //动画执行期间 子view 也不可获取事件\n if (bookRecyclerView.animRunning()) return true;",
"score": 0.8501614332199097
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookRecyclerView.java",
"retrieved_chunk": " return false;\n }\n @Override\n public void onClickMenu() {\n animParentView.onClickMenuArea();\n }\n private class ItemOnScrollStop implements BookLayoutManager.OnStopScroller {\n @Override\n public void onStop(boolean autoLeftScroll, int curPos) {\n boolean arriveNext = currentPosition < curPos;",
"score": 0.8415930271148682
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookLayoutManager.java",
"retrieved_chunk": " }\n }\n public boolean animIsRunning() {\n return selectAnimator != null && (selectAnimator.isStarted() || selectAnimator.isRunning());\n }\n private int horizontalLayout(RecyclerView.Recycler recycler, int dx) {\n //-----------------------1 边界检测---------------\n //已达左边界\n if (dx < 0) {\n if (horizontalOffset < 0) {",
"score": 0.8346633911132812
}
] | java | return animationEffecter.animInEffect(); |
package com.juziml.content.gpu_test;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Region;
import android.util.AttributeSet;
import android.view.View;
import androidx.annotation.Nullable;
/**
* create by zhusw on 2020-07-29 10:54
*/
public class GpuTestCurlAnimView extends View {
Paint pointPaint;
FPoint a, f, g, e, h, c, j, b, k, d, i;
int width;
int height;
//图形
Paint pathAPaint;
Path pathA;
Bitmap holderBitmap;
Canvas bitmapCanvas = new Canvas();
Paint pathCPaint;
Path pathC;
Paint pathBPaint;
Path pathB;
PorterDuffXfermode xfDST_ATOP = new PorterDuffXfermode(PorterDuff.Mode.DST_ATOP);
public GpuTestCurlAnimView(Context context) {
this(context, null);
}
public GpuTestCurlAnimView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
width = w;
height = h;
a.setXY(-1, -1);
holderBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
}
public GpuTestCurlAnimView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
pointPaint = new Paint();
pointPaint.setColor(Color.RED);
pointPaint.setTextSize(25);
a = new FPoint();
f = new FPoint();
g = new FPoint();
e = new FPoint();
h = new FPoint();
c = new FPoint();
j = new FPoint();
b = new FPoint();
k = new FPoint();
d = new FPoint();
i = new FPoint();
pathAPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
pathAPaint.setColor(Color.GREEN);
pathA = new Path();
pathCPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
pathCPaint.setColor(Color.YELLOW);
pathCPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_ATOP));//消除c区 与a区重叠部分,原文注释:丢弃原图想覆盖目标图像的区域
pathC = new Path();
pathBPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
pathBPaint.setColor(Color.BLUE);
pathB = new Path();
}
public void flipPrepare(float x, float y) {
if (y < height / 2) {
f.setXY(width, 0);
} else {
f.setXY(width, height);
}
}
public void flipSetToDefault() {
a.setXY(-1, -1);
| f.setXY(0, 0); |
calculatePointXY(a, f);
postInvalidate();
}
public void flipCurl(float x, float y) {
a.x = x;
a.y = y;
calculatePointXY(a, f);
//修正c点范围 不可小于0
if (calculateCxRange(a.x, a.y, f) < 0) {
calcPointAByTouchPoint();
calculatePointXY(a, f);
}
postInvalidate();
}
private float calculateCxRange(float ax, float ay, FPoint f) {
float gx = (ax + f.x) / 2;
float gy = (ay + f.y) / 2;
float ex = gx - (f.y - gy) * (f.y - gy) / (f.x - gx);
return ex - (f.x - ex) / 2;
}
/**
* 如果c点x坐标小于0,根据触摸点重新测量a点坐标
*/
private void calcPointAByTouchPoint() {
float w0 = width - c.x;
float w1 = Math.abs(f.x - a.x);
float w2 = width * w1 / w0;
a.x = Math.abs(f.x - w2);
float h1 = Math.abs(f.y - a.y);
float h2 = w2 * h1 / w1;
a.y = Math.abs(f.y - h2);
}
@Override
public void onDrawForeground(Canvas canvas) {
super.onDrawForeground(canvas);
//把点绘制在前景上 方便观察
drawPoint(canvas);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (a.x == -1 && a.y == -1) {
canvas.drawPath(getDefaultPath(), pathAPaint);
} else {
Path pathA = getPathAFromRightTop();
if (f.x == width && f.y == height) {
pathA = getPathAFromRightBottom();
}
Path pathC = getPathC();
canvas.drawPath(pathC, pathCPaint);//先给C区画上底色
canvas.drawPath(pathA, pathAPaint);//先给A区画上底色
canvas.save();//扣出B区
canvas.clipPath(pathC, Region.Op.DIFFERENCE);
canvas.clipPath(pathA, Region.Op.DIFFERENCE);
canvas.drawPath(getPathB(), pathBPaint);
canvas.restore();
}
}
public Path getDefaultPath() {
pathA.reset();
pathA.lineTo(0, height);
pathA.lineTo(width, height);
pathA.lineTo(width, 0);
pathA.close();
return pathA;
}
/**
* 以右下角为触发起点
*
* @return
*/
private Path getPathAFromRightBottom() {
pathA.reset();
//划线从 0,0开始
pathA.lineTo(0, height);//划线到左下角
pathA.lineTo(c.x, c.y);//划线到c点
pathA.quadTo(e.x, e.y, b.x, b.y);//以c为起点,b为终点,e为动点 画曲线
pathA.lineTo(a.x, a.y);
pathA.lineTo(k.x, k.y);
pathA.quadTo(h.x, h.y, j.x, j.y);//以k为起点,j为终点 h为动点 画曲线
pathA.lineTo(width, 0);
pathA.close();
return pathA;
}
private Path getPathAFromRightTop() {
pathA.reset();
pathA.lineTo(c.x, c.y);//划线到c
pathA.quadTo(e.x, e.y, b.x, b.y);//c-b的曲线
pathA.lineTo(a.x, a.y);//划线到a
pathA.lineTo(k.x, k.y);//划线到k
pathA.quadTo(h.x, h.y, j.x, j.y);//k-j的曲线
pathA.lineTo(width, height);
pathA.lineTo(0, height);
pathA.close();
return pathA;
}
private Path getPathC() {
pathC.reset();
pathC.moveTo(d.x, d.y);
pathC.lineTo(b.x, b.y);
pathC.lineTo(a.x, a.y);
pathC.lineTo(k.x, k.y);
pathC.lineTo(i.x, i.y);
pathC.close();
return pathC;
}
private Path getPathB() {
pathB.reset();
pathB.lineTo(0, height);
pathB.lineTo(width, height);
pathB.lineTo(width, 0);
pathB.close();
return pathB;
}
private void drawPoint(Canvas canvas) {
canvas.drawText("a", a.x, a.y, pointPaint);
canvas.drawText("f", f.x, f.y, pointPaint);
canvas.drawText("g", g.x, g.y, pointPaint);
canvas.drawText("e", e.x, e.y, pointPaint);
canvas.drawText("h", h.x, h.y, pointPaint);
canvas.drawText("c", c.x, c.y, pointPaint);
canvas.drawText("j", j.x, j.y, pointPaint);
canvas.drawText("b", b.x, b.y, pointPaint);
canvas.drawText("k", k.x, k.y, pointPaint);
canvas.drawText("d", d.x, d.y, pointPaint);
canvas.drawText("i", i.x, i.y, pointPaint);
}
/**
* 计算切点坐标,这里就没有推导公式了,直接拿来用了
*
* @param lineOne_My_pointOne
* @param lineOne_My_pointTwo
* @param lineTwo_My_pointOne
* @param lineTwo_My_pointTwo
* @return
*/
private FPoint getIntersectionPoint(FPoint lineOne_My_pointOne,
FPoint lineOne_My_pointTwo,
FPoint lineTwo_My_pointOne,
FPoint lineTwo_My_pointTwo) {
float x1, y1, x2, y2, x3, y3, x4, y4;
x1 = lineOne_My_pointOne.x;
y1 = lineOne_My_pointOne.y;
x2 = lineOne_My_pointTwo.x;
y2 = lineOne_My_pointTwo.y;
x3 = lineTwo_My_pointOne.x;
y3 = lineTwo_My_pointOne.y;
x4 = lineTwo_My_pointTwo.x;
y4 = lineTwo_My_pointTwo.y;
float pointX = ((x1 - x2) * (x3 * y4 - x4 * y3)
- (x3 - x4) * (x1 * y2 - x2 * y1)) / ((x3 - x4)
* (y1 - y2) - (x1 - x2) * (y3 - y4));
float pointY = ((y1 - y2) * (x3 * y4 - x4 * y3)
- (x1 * y2 - x2 * y1) * (y3 - y4)) / ((y1 - y2)
* (x3 - x4) - (x1 - x2) * (y3 - y4));
return new FPoint(pointX, pointY);
}
/**
* 计算各点坐标
*/
private void calculatePointXY(FPoint a, FPoint f) {
g.x = (a.x + f.x) / 2;
g.y = (a.y + f.y) / 2;
e.x = g.x - (f.y - g.y) * (f.y - g.y) / (f.x - g.x);
e.y = f.y;
h.x = f.x;
h.y = g.y - (f.x - g.x) * (f.x - g.x) / (f.y - g.y);
c.x = e.x - (f.x - e.x) / 2;
c.y = f.y;
j.x = f.x;
j.y = h.y - (f.y - h.y) / 2;
b = getIntersectionPoint(a, e, c, j);
k = getIntersectionPoint(a, h, c, j);
d.x = (c.x + 2 * e.x + b.x) / 4;
d.y = (2 * e.y + c.y + b.y) / 4;
i.x = (j.x + 2 * h.x + k.x) / 4;
i.y = (2 * h.y + j.y + k.y) / 4;
}
}
| gpu_test/src/main/java/com/juziml/content/gpu_test/GpuTestCurlAnimView.java | Western-parotia-BookViewProject-1727e80 | [
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " a.x = -1;\n a.y = -1;\n menuBounds.left = vWidth / 3F;\n menuBounds.top = vHeight / 3F;\n menuBounds.right = vWidth * 2 / 3F;\n menuBounds.bottom = vHeight * 2 / 3F;\n }\n @Override\n public void onViewAttachedToWindow() {\n }",
"score": 0.8411927819252014
},
{
"filename": "gpu_test/src/main/java/com/juziml/content/gpu_test/FPoint.java",
"retrieved_chunk": " this.y = y;\n }\n public void setXY(float x, float y) {\n this.x = x;\n this.y = y;\n }\n}",
"score": 0.8104087114334106
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/FPoint.java",
"retrieved_chunk": " this.y = y;\n }\n public void setXY(float x, float y) {\n this.x = x;\n this.y = y;\n }\n}",
"score": 0.8104087114334106
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/PaperLayout.java",
"retrieved_chunk": " || bookRecyclerView.getFlipMode() == BookLayoutManager.BookFlipMode.MODE_COVER) {\n requestDisallowInterceptTouchEvent(true);\n } else {\n requestDisallowInterceptTouchEvent(false);\n }\n menuBounds.left = getWidth() / 3F;\n menuBounds.top = getHeight() / 3F;\n menuBounds.right = getWidth() * 2 / 3F;\n menuBounds.bottom = getHeight() * 2 / 3F;\n }",
"score": 0.8037834167480469
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/CoverAnimationEffecter.java",
"retrieved_chunk": " dx = vWidth - (int) currentX;\n }\n scroller.startScroll(startX, startY, dx, dy, duration);\n invalidate();\n }\n @Override\n public void draw(Canvas canvas) {\n if (currentX == -1) {\n DLog.log(\"CoverAnimationEffect draw 1\");\n return;",
"score": 0.7924326062202454
}
] | java | f.setXY(0, 0); |
package com.juziml.read.business.read.anim;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.drawable.GradientDrawable;
import android.view.MotionEvent;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.Scroller;
import com.juziml.read.business.read.view.PuppetView;
import com.juziml.read.utils.DLog;
import java.util.LinkedList;
import java.util.List;
/**
* create by zhusw on 2020-08-24 14:06
*/
public class CoverAnimationEffecter implements IAnimationEffecter {
private final static int DOWN_AREA_NONE = -1;
private final static int DOWN_AREA_MENU = 1;
private final static int DOWN_AREA_LEFT = 2;
private final static int DOWN_AREA_RIGHT = 3;
int vWidth = 1;
int vHeight = 1;
private final PuppetView readAnimView;
private boolean isCancelFlip = false;
private boolean coverAnimationRunning = false;
private boolean isTouching = false;
private final Scroller scroller;
private final ScrollRunnable scrollRunnable;
private final RectF menuBounds;
private final Path pathA;
private final Path pathB;
private final Paint paint;
private final int shadowWidth;
public CoverAnimationEffecter(PuppetView readAnimView) {
this.readAnimView = readAnimView;
scroller = new Scroller(readAnimView.getContext(), new AccelerateDecelerateInterpolator());
scrollRunnable = new ScrollRunnable();
menuBounds = new RectF();
pathA = new Path();
pathB = new Path();
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
shadowWidth = 20;
}
private int downArea = DOWN_AREA_NONE;
private float downX = 0F;
private int coverSlideDirection = AnimHelper.SLID_DIRECTION_UNKNOWN;
private final List<Float> moveSampling = new LinkedList<>();
private final int MAX_COUNT = 5;
private boolean prepareDrawCoverAnimEffect = false;
private float currentX = -1;
@Override
public void handlerEvent(MotionEvent event) {
if (coverAnimationRunning) return;
float x = event.getRawX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
moveSampling.clear();
downX = x;
prepareDrawCoverAnimEffect = false;
isTouching = true;
currentX = -1;
downArea = DOWN_AREA_NONE;
coverSlideDirection = AnimHelper.SLID_DIRECTION_UNKNOWN;
if (x > menuBounds.left && y > menuBounds.top
&& x < menuBounds.right && y < menuBounds.bottom) {
downArea = DOWN_AREA_MENU;
} else if (x < vWidth / 2F) {
downArea = DOWN_AREA_LEFT;
} else {
downArea = DOWN_AREA_RIGHT;
}
break;
case MotionEvent.ACTION_MOVE:
isTouching = true;
float curDistance = x - downX;
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_UNKNOWN && checkDownArea(downArea)) {
if (curDistance > 0) {
coverSlideDirection = AnimHelper.SLID_DIRECTION_RIGHT;
} else {
coverSlideDirection = AnimHelper.SLID_DIRECTION_LEFT;
}
| readAnimView.buildBitmap(coverSlideDirection); |
prepareDrawCoverAnimEffect = checkAnimCondition(coverSlideDirection);
}
if (prepareDrawCoverAnimEffect) {
if (moveSampling.size() == 0
|| x != moveSampling.get(moveSampling.size() - 1)) {
moveSampling.add(x);
}
if (moveSampling.size() > MAX_COUNT) {
moveSampling.remove(0);
}
currentX = x;
invalidate();
}
break;
case MotionEvent.ACTION_CANCEL:
isTouching = false;
break;
case MotionEvent.ACTION_UP:
currentX = x;
if (prepareDrawCoverAnimEffect) {
if (moveSampling.size() > 0) {
float lastMoveX = moveSampling.get(moveSampling.size() - 1);
float firstMoveX = moveSampling.get(0);
float finallyMoveX = lastMoveX - firstMoveX;
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT) {
boolean lastFingerLeftSlop = finallyMoveX < 10;
touchUp(lastFingerLeftSlop);
} else if (coverSlideDirection == AnimHelper.SLID_DIRECTION_RIGHT) {
finallyMoveX = lastMoveX - firstMoveX;
touchUp(finallyMoveX < 0);
}
} else {
touchUp(false);
}
} else if (downArea == DOWN_AREA_MENU) {
if (x > menuBounds.left && x < menuBounds.right
&& y > menuBounds.top && y < menuBounds.bottom) {
readAnimView.onClickMenuArea();
}
} else if (downArea != DOWN_AREA_NONE) {
if (x == downX && downX >= vWidth / 2F) {//下一页
coverSlideDirection = AnimHelper.SLID_DIRECTION_LEFT;
readAnimView.buildBitmap(coverSlideDirection);
if (checkAnimCondition(coverSlideDirection)) {
touchUp(true);
}
} else if (x == downX && downX < vWidth / 2F) {//上一页
coverSlideDirection = AnimHelper.SLID_DIRECTION_RIGHT;
readAnimView.buildBitmap(coverSlideDirection);
if (checkAnimCondition(coverSlideDirection)) {
touchUp(false);
}
}
}
moveSampling.clear();
isTouching = false;
break;
default:
break;
}
}
private void touchUp(boolean lastFingerLeftSlop) {
DLog.log("touchUp coverAnimationRunning=%s", coverAnimationRunning);
coverAnimationRunning = true;
isCancelFlip = (coverSlideDirection == AnimHelper.SLID_DIRECTION_RIGHT && lastFingerLeftSlop)
|| (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT && !lastFingerLeftSlop);
int duration = isCancelFlip ? AnimHelper.CANCEL_ANIM_DURATION : AnimHelper.RELAY_ANIM_DURATION;
duration = (int) (duration * 0.7F);//cover动画时间减少一点
// duration = 1000;//cover动画时间减少一点
int startX = (int) currentX;
int startY = 0;
int dy = 0;
int dx;
if (lastFingerLeftSlop) {
dx = (int) -(vWidth - (downX - currentX));
} else {
dx = vWidth - (int) currentX;
}
scroller.startScroll(startX, startY, dx, dy, duration);
invalidate();
}
@Override
public void draw(Canvas canvas) {
if (currentX == -1) {
DLog.log("CoverAnimationEffect draw 1");
return;
}
if (coverSlideDirection != AnimHelper.SLID_DIRECTION_LEFT && coverSlideDirection != AnimHelper.SLID_DIRECTION_RIGHT) {
DLog.log("CoverAnimationEffect draw 2");
return;
}
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT
&& (null == readAnimView.getCurrentBitmap() || null == readAnimView.getNextBitmap())) {
DLog.log("CoverAnimationEffect draw 3");
return;
}
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_RIGHT && null == readAnimView.getPreviousBitmap()) {
DLog.log("CoverAnimationEffect draw 4");
return;
}
DLog.log("CoverAnimationEffect draw 5");
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT) {
float offset = downX - currentX;
offset = Math.max(0, offset);
canvas.save();
canvas.clipPath(getPathAToLeft());
canvas.drawBitmap(readAnimView.getCurrentBitmap(), -offset, 0, paint);
canvas.restore();
canvas.save();
canvas.clipPath(getPathB());
canvas.drawBitmap(readAnimView.getNextBitmap(), 0, 0, paint);
canvas.restore();
drawShadow((int) (vWidth - offset), canvas);
} else {
float leftOffset = vWidth - currentX;
canvas.save();
canvas.clipPath(getPathAToRight());
canvas.drawBitmap(readAnimView.getPreviousBitmap(), -leftOffset, 0, paint);
canvas.restore();
drawShadow((int) currentX, canvas);
}
}
private void drawShadow(int left, Canvas canvas) {
GradientDrawable drawable = readAnimView.getAnimHelper().getCoverGradientDrawable();
drawable.setBounds(left, 0, left + shadowWidth, vHeight);
drawable.draw(canvas);
}
private Path getPathAToLeft() {
pathA.reset();
float x = vWidth - (downX - currentX);
x = Math.min(vWidth, x);
pathA.lineTo(x, 0);
pathA.lineTo(x, vHeight);
pathA.lineTo(0, vHeight);
pathA.close();
return pathA;
}
private Path getPathB() {
pathB.reset();
float x = vWidth - (downX - currentX);
x = Math.min(vWidth, x);
pathB.moveTo(x, 0);
pathB.lineTo(vWidth, 0);
pathB.lineTo(vWidth, vHeight);
pathB.lineTo(x, vHeight);
pathB.close();
return pathB;
}
private Path getPathAToRight() {
pathA.reset();
pathA.lineTo(currentX, 0);
pathA.lineTo(currentX, vHeight);
pathA.lineTo(0, vHeight);
pathA.close();
return pathA;
}
private boolean checkDownArea(int downArea) {
return downArea != DOWN_AREA_MENU && downArea != DOWN_AREA_NONE;
}
private boolean checkAnimCondition(int slideDirection) {
if (slideDirection == AnimHelper.SLID_DIRECTION_LEFT && (null != readAnimView.getNextBitmap() && null != readAnimView.getCurrentBitmap())) {
return true;
} else if (slideDirection == AnimHelper.SLID_DIRECTION_RIGHT && null != readAnimView.getPreviousBitmap()) {
return true;
}
return false;
}
@Override
public boolean animInEffect() {
return isTouching || coverAnimationRunning;
}
@Override
public void onViewSizeChanged(int vWidth, int vHeight) {
this.vWidth = vWidth;
this.vHeight = vHeight;
menuBounds.left = vWidth / 3F;
menuBounds.top = vHeight / 3F;
menuBounds.right = vWidth * 2 / 3F;
menuBounds.bottom = vHeight * 2 / 3F;
}
@Override
public void onViewAttachedToWindow() {
}
@Override
public void onViewDetachedFromWindow() {
readAnimView.removeCallbacks(scrollRunnable);
}
private void invalidate() {
readAnimView.postInvalidate();
}
@Override
public void onScroll() {
if (scroller.computeScrollOffset()) {
int x = scroller.getCurrX();
int y = scroller.getCurrY();
if (x == scroller.getFinalX() && y == scroller.getFinalY()) {
scroller.forceFinished(true);
//补一点时间,避免动画太快结束,提供两次动画触发间隔
DLog.log("coverAnimationRunning coverAnimationRunning=%s 结束,延时开启 状态重置", coverAnimationRunning);
readAnimView.post(scrollRunnable);
} else {
currentX = x;
invalidate();
}
}
}
protected class ScrollRunnable implements Runnable {
@Override
public void run() {
readAnimView.reset();
coverAnimationRunning = false;
if (!isCancelFlip) {
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT) {
readAnimView.onExpectNext();
} else if (coverSlideDirection == AnimHelper.SLID_DIRECTION_RIGHT) {
readAnimView.onExpectPrevious();
}
}
invalidate();
}
}
}
| app/src/main/java/com/juziml/read/business/read/anim/CoverAnimationEffecter.java | Western-parotia-BookViewProject-1727e80 | [
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " }\n } else if (downArea != DOWN_AREA_NONE) {\n if (x == downX && downX >= vWidth / 2F) {//下一页\n curlSlideDirection = AnimHelper.SLID_DIRECTION_LEFT;\n touchDown(downArea, curlSlideDirection);\n readAnimView.buildBitmap(curlSlideDirection);\n if (checkAnimCondition(curlSlideDirection, downArea)) {\n touchMove(x, y, curlSlideDirection, true, false);\n touchUp(true);\n }",
"score": 0.9089508652687073
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " if (curlSlideDirection == AnimHelper.SLID_DIRECTION_LEFT && (null != readAnimView.getNextBitmap() && null != readAnimView.getCurrentBitmap())) {\n return true;\n } else if (curlSlideDirection == AnimHelper.SLID_DIRECTION_RIGHT && null != readAnimView.getPreviousBitmap()) {\n return true;\n }\n return false;\n }\n public void touchDown(int downArea, int curlSlideDirection) {\n //判断触摸起始点位置,确定f点\n if (downArea == DOWN_AREA_TOP_RIGHT && curlSlideDirection == AnimHelper.SLID_DIRECTION_LEFT) {",
"score": 0.9002807140350342
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " switch (event.getAction()) {\n case MotionEvent.ACTION_DOWN:\n isTouching = true;\n drawCurlAnimBefore = false;\n moveSampling.clear();\n downX = x;\n curlSlideDirection = AnimHelper.SLID_DIRECTION_UNKNOWN;\n if (x < menuBounds.left) {\n downArea = DOWN_AREA_LEFT;\n } else if (x > menuBounds.left && y < menuBounds.top) {",
"score": 0.8938589096069336
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " int finalY = scroller.getFinalY();\n if (x == finalX && y == finalY) {\n if (!isCancelFlip) {\n if (curlSlideDirection == AnimHelper.SLID_DIRECTION_LEFT) {\n readAnimView.onExpectNext();\n } else if (curlSlideDirection == AnimHelper.SLID_DIRECTION_RIGHT) {\n readAnimView.onExpectPrevious();\n }\n }\n readAnimView.post(scrollRunnable);",
"score": 0.8892752528190613
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " } else if (x == downX && downX < vWidth / 2F) {//上一页\n curlSlideDirection = AnimHelper.SLID_DIRECTION_RIGHT;\n touchDown(downArea, curlSlideDirection);\n readAnimView.buildBitmap(curlSlideDirection);\n if (checkAnimCondition(curlSlideDirection, downArea)) {\n touchMove(x, y, curlSlideDirection, true, false);\n touchUp(false);\n }\n }\n }",
"score": 0.8859456181526184
}
] | java | readAnimView.buildBitmap(coverSlideDirection); |
package com.juziml.read.business.read.view;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewParent;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.juziml.read.business.read.anim.AnimHelper;
import com.juziml.read.business.read.anim.CoverAnimationEffecter;
import com.juziml.read.business.read.anim.IAnimationEffecter;
import com.juziml.read.business.read.anim.SimulationAnimationEffecter;
/**
* 此View的作用就像幕后一样,负责接受事件并传递到动画,Effecter
* create by zhusw on 2020-08-14 17:37
*/
public class PuppetView extends View implements EventProxy, AnimParentView {
IAnimationEffecter animationEffecter;
AnimParentView parentView;
private Bitmap previousViewBitmap;
private Bitmap currentViewBitmap;
private Bitmap nextViewBitmap;
boolean performDrawCurlTexture = false;
private int vWidth, vHeight;
public PuppetView(@NonNull Context context) {
this(context, null);
}
public PuppetView(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public PuppetView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
/*
view 可以单独关,但是不能单独打开硬件加速
关闭硬件加速 卡到爆炸
开启硬件加速,诱发 OpenGLRenderer: Path too large to be rendered into a texture
setLayerType(LAYER_TYPE_SOFTWARE,null);
*/
}
public boolean animRunningOrTouching() {
boolean animRunningOrTouching = false;
if (null != animationEffecter) {
animRunningOrTouching = animRunning();
}
return animRunningOrTouching;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
ViewParent viewParent = getParent();
parentView = (AnimParentView) viewParent;
if (null != animationEffecter) {
| animationEffecter.onViewAttachedToWindow(); |
}
}
public void setAnimMode(int animMode) {
//重置某些属性 与变量
animationEffecter = null;
if (animMode == BookLayoutManager.BookFlipMode.MODE_COVER) {
animationEffecter = new CoverAnimationEffecter(this);
} else if (animMode == BookLayoutManager.BookFlipMode.MODE_CURL) {
animationEffecter = new SimulationAnimationEffecter(this);
}
if (null != animationEffecter) {
animationEffecter.onViewSizeChanged(vWidth, vHeight);
}
}
@Override
public void draw(Canvas canvas) {
if (performDrawCurlTexture && null != animationEffecter) {
animationEffecter.draw(canvas);
} else {
super.draw(canvas);
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (null != animationEffecter) {
animationEffecter.onViewDetachedFromWindow();
}
}
/**
* 这个会被调用多次,最终宽度为实际测量宽度-2px
* 这样在 layoutmanager 进行布局时 才可以同时保持3个item被显示
*
* @param widthMeasureSpec
* @param heightMeasureSpec
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int height = measureSize(5, heightMeasureSpec);
int width = measureSize(5, widthMeasureSpec) - 2;
setMeasuredDimension(width - 2, height);
vWidth = width;
vHeight = height;
if (null != animationEffecter) {
animationEffecter.onViewSizeChanged(vWidth, vHeight);
}
}
private int measureSize(int defaultSize, int measureSpec) {
int result = defaultSize;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
result = specSize;
} else if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
return result;
}
public void buildBitmap(int slideDirection) {
performDrawCurlTexture = false;
if (slideDirection == AnimHelper.SLID_DIRECTION_LEFT) {
currentViewBitmap = parentView.getCurrentBitmap();
nextViewBitmap = parentView.getNextBitmap();
} else if (slideDirection == AnimHelper.SLID_DIRECTION_RIGHT) {
previousViewBitmap = parentView.getPreviousBitmap();
}
performDrawCurlTexture = true;
}
@Override
public boolean onItemViewTouchEvent(MotionEvent event) {
if (null != animationEffecter) {
animationEffecter.handlerEvent(event);
}
return true;
}
@Override
public boolean animRunning() {
if (null != animationEffecter) {
return animationEffecter.animInEffect();
}
return false;
}
@Override
public void computeScroll() {
if (null != animationEffecter) {
animationEffecter.onScroll();
}
}
@Override
public void onExpectNext() {
parentView.onExpectNext();
}
@Override
public void onExpectPrevious() {
parentView.onExpectPrevious();
}
@Override
public Bitmap getPreviousBitmap() {
return previousViewBitmap;
}
@Override
public Bitmap getCurrentBitmap() {
return currentViewBitmap;
}
@Override
public Bitmap getNextBitmap() {
return nextViewBitmap;
}
@Override
public int getBackgroundColor() {
return parentView.getBackgroundColor();
}
@Override
public AnimHelper getAnimHelper() {
return parentView.getAnimHelper();
}
@Override
public void onClickMenuArea() {
parentView.onClickMenuArea();
}
@Override
public void onClickNextArea() {
parentView.onClickNextArea();
}
@Override
public void onClickPreviousArea() {
parentView.onClickPreviousArea();
}
public void reset() {
previousViewBitmap = null;
nextViewBitmap = null;
currentViewBitmap = null;
performDrawCurlTexture = false;
}
}
| app/src/main/java/com/juziml/read/business/read/view/PuppetView.java | Western-parotia-BookViewProject-1727e80 | [
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookRecyclerView.java",
"retrieved_chunk": " super(context, attrs, defStyle);\n readLayoutManger = new BookLayoutManager(context);\n setLayoutManager(readLayoutManger);\n readLayoutManger.setOnForceLayoutCompleted(new ItemOnForceLayoutCompleted());\n readLayoutManger.setonStopScroller(new ItemOnScrollStop());\n }\n @Override\n protected void onAttachedToWindow() {\n super.onAttachedToWindow();\n animParentView = (AnimParentView) getParent();",
"score": 0.8540802001953125
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookView.java",
"retrieved_chunk": " protected void onDetachedFromWindow() {\n super.onDetachedFromWindow();\n if (null != dataPendIntentTask) {\n bookRecyclerView.removeCallbacks(dataPendIntentTask);\n }\n }\n @Override\n public void onExpectNext() {\n bookRecyclerView.onExpectNext(false);\n if (null != dataPendIntentTask) {",
"score": 0.8301171064376831
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/CoverAnimationEffecter.java",
"retrieved_chunk": " }\n @Override\n public boolean animInEffect() {\n return isTouching || coverAnimationRunning;\n }\n @Override\n public void onViewSizeChanged(int vWidth, int vHeight) {\n this.vWidth = vWidth;\n this.vHeight = vHeight;\n menuBounds.left = vWidth / 3F;",
"score": 0.8070418238639832
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookLayoutManager.java",
"retrieved_chunk": " horizontalOffset += (long) distance;\n requestLayout();\n if (null != onForceLayoutCompleted) {\n onForceLayoutCompleted.onLayoutCompleted(position);\n }\n }\n }\n public void cancelAnimator() {\n if (selectAnimator != null && (selectAnimator.isStarted() || selectAnimator.isRunning())) {\n selectAnimator.cancel();",
"score": 0.8062392473220825
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookRecyclerView.java",
"retrieved_chunk": " }\n @Override\n protected void onDetachedFromWindow() {\n super.onDetachedFromWindow();\n eventProxyWeakReference.clear();\n }\n protected void bindReadCurlAnimProxy(EventProxy ic) {\n if (null != eventProxyWeakReference) {\n eventProxyWeakReference.clear();\n }",
"score": 0.8049911260604858
}
] | java | animationEffecter.onViewAttachedToWindow(); |
/*
* Copyright 2017 JessYan
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.foundation.service.urlmanager.retrofiturlmanager.parser;
import android.text.TextUtils;
import com.foundation.service.urlmanager.retrofiturlmanager.RetrofitUrlManager;
import com.foundation.service.urlmanager.retrofiturlmanager.cache.Cache;
import com.foundation.service.urlmanager.retrofiturlmanager.cache.LruCache;
import java.util.ArrayList;
import java.util.List;
import okhttp3.HttpUrl;
/**
* ================================================
* 高级解析器, 当 BaseUrl 中有除了域名以外的其他 Path 时, 可使用此解析器
* <p>
* 比如:
* 1.
* 旧 URL 地址为 https://www.github.com/wiki/part, 您在 App 初始化时传入 {@link RetrofitUrlManager#startAdvancedModel(String)}
* 的 BaseUrl 为 https://www.github.com/wiki
* 您调用 {@link RetrofitUrlManager#putDomain(String, String)} 方法传入的 URL 地址是 https://www.google.com/api
* 经过本解析器解析后生成的新 URL 地址为 http://www.google.com/api/part
* <p>
* 2.
* 旧 URL 地址为 https://www.github.com/wiki/part, 您在 App 初始化时传入 {@link RetrofitUrlManager#startAdvancedModel(String)}
* 的 BaseUrl 为 https://www.github.com/wiki
* 您调用 {@link RetrofitUrlManager#putDomain(String, String)} 方法传入的 URL 地址是 https://www.google.com
* 经过本解析器解析后生成的新 URL 地址为 http://www.google.com/part
* <p>
* 3.
* 旧 URL 地址为 https://www.github.com/wiki/part, 您在 App 初始化时传入 {@link RetrofitUrlManager#startAdvancedModel(String)}
* 的 BaseUrl 为 https://www.github.com
* 您调用 {@link RetrofitUrlManager#putDomain(String, String)} 方法传入的 URL 地址是 https://www.google.com/api
* 经过本解析器解析后生成的新 URL 地址为 http://www.google.com/api/wiki/part
* <p>
* 解析器会将 BaseUrl 全部替换成您传入的 Url 地址
*
* @see UrlParser
* Created by JessYan on 09/06/2018 16:00
* <a href="mailto:[email protected]">Contact me</a>
* <a href="https://github.com/JessYanCoding">Follow me</a>
* ================================================
*/
public class AdvancedUrlParser implements UrlParser {
private RetrofitUrlManager mRetrofitUrlManager;
private Cache<String, String> mCache;
@Override
public void init(RetrofitUrlManager retrofitUrlManager) {
this.mRetrofitUrlManager = retrofitUrlManager;
this.mCache = new LruCache<>(100);
}
@Override
public HttpUrl parseUrl(HttpUrl domainUrl, HttpUrl url) {
if (null == domainUrl) return url;
HttpUrl.Builder builder = url.newBuilder();
if (TextUtils.isEmpty(mCache.get(getKey(domainUrl, url)))) {
for (int i = 0; i < url.pathSize(); i++) {
//当删除了上一个 index, PathSegment 的 item 会自动前进一位, 所以 remove(0) 就好
builder.removePathSegment(0);
}
List<String> newPathSegments = new ArrayList<>();
newPathSegments.addAll(domainUrl.encodedPathSegments());
if (url.pathSize() > mRetrofitUrlManager.getPathSize()) {
List<String> encodedPathSegments = url.encodedPathSegments();
for ( | int i = mRetrofitUrlManager.getPathSize(); | i < encodedPathSegments.size(); i++) {
newPathSegments.add(encodedPathSegments.get(i));
}
} else if (url.pathSize() < mRetrofitUrlManager.getPathSize()) {
throw new IllegalArgumentException(String.format("Your final path is %s, but the baseUrl of your RetrofitUrlManager#startAdvancedModel is %s",
url.scheme() + "://" + url.host() + url.encodedPath(),
mRetrofitUrlManager.getBaseUrl().scheme() + "://"
+ mRetrofitUrlManager.getBaseUrl().host()
+ mRetrofitUrlManager.getBaseUrl().encodedPath()));
}
for (String PathSegment : newPathSegments) {
builder.addEncodedPathSegment(PathSegment);
}
} else {
builder.encodedPath(mCache.get(getKey(domainUrl, url)));
}
HttpUrl httpUrl = builder
.scheme(domainUrl.scheme())
.host(domainUrl.host())
.port(domainUrl.port())
.build();
if (TextUtils.isEmpty(mCache.get(getKey(domainUrl, url)))) {
mCache.put(getKey(domainUrl, url), httpUrl.encodedPath());
}
return httpUrl;
}
private String getKey(HttpUrl domainUrl, HttpUrl url) {
return domainUrl.encodedPath() + url.encodedPath()
+ mRetrofitUrlManager.getPathSize();
}
}
| net/src/main/java/com/foundation/service/urlmanager/retrofiturlmanager/parser/AdvancedUrlParser.java | Western-parotia-Net-accd348 | [
{
"filename": "net/src/main/java/com/foundation/service/urlmanager/retrofiturlmanager/parser/SuperUrlParser.java",
"retrieved_chunk": " //当删除了上一个 index, PathSegment 的 item 会自动前进一位, 所以 remove(0) 就好\n builder.removePathSegment(0);\n }\n List<String> newPathSegments = new ArrayList<>();\n newPathSegments.addAll(domainUrl.encodedPathSegments());\n if (url.pathSize() > pathSize) {\n List<String> encodedPathSegments = url.encodedPathSegments();\n for (int i = pathSize; i < encodedPathSegments.size(); i++) {\n newPathSegments.add(encodedPathSegments.get(i));\n }",
"score": 0.9576508402824402
},
{
"filename": "net/src/main/java/com/foundation/service/urlmanager/retrofiturlmanager/parser/DomainUrlParser.java",
"retrieved_chunk": " List<String> newPathSegments = new ArrayList<>();\n newPathSegments.addAll(domainUrl.encodedPathSegments());\n newPathSegments.addAll(url.encodedPathSegments());\n for (String PathSegment : newPathSegments) {\n builder.addEncodedPathSegment(PathSegment);\n }\n } else {\n builder.encodedPath(mCache.get(getKey(domainUrl, url)));\n }\n HttpUrl httpUrl = builder",
"score": 0.8664981126785278
},
{
"filename": "net/src/main/java/com/foundation/service/urlmanager/retrofiturlmanager/parser/SuperUrlParser.java",
"retrieved_chunk": " } else if (url.pathSize() < pathSize) {\n throw new IllegalArgumentException(String.format(\n \"Your final path is %s, the pathSize = %d, but the #baseurl_path_size = %d, #baseurl_path_size must be less than or equal to pathSize of the final path\",\n url.scheme() + \"://\" + url.host() + url.encodedPath(), url.pathSize(), pathSize));\n }\n for (String PathSegment : newPathSegments) {\n builder.addEncodedPathSegment(PathSegment);\n }\n } else {\n builder.encodedPath(mCache.get(getKey(domainUrl, url, pathSize)));",
"score": 0.8140456080436707
},
{
"filename": "net/src/main/java/com/foundation/service/urlmanager/retrofiturlmanager/parser/SuperUrlParser.java",
"retrieved_chunk": " }\n private String getKey(HttpUrl domainUrl, HttpUrl url, int PathSize) {\n return domainUrl.encodedPath() + url.encodedPath()\n + PathSize;\n }\n private int resolvePathSize(HttpUrl httpUrl, HttpUrl.Builder builder) {\n String fragment = httpUrl.fragment();\n int pathSize = 0;\n StringBuffer newFragment = new StringBuffer();\n if (fragment.indexOf(\"#\") == -1) {",
"score": 0.8085986375808716
},
{
"filename": "net/src/main/java/com/foundation/service/urlmanager/retrofiturlmanager/parser/SuperUrlParser.java",
"retrieved_chunk": " this.mRetrofitUrlManager = retrofitUrlManager;\n this.mCache = new LruCache<>(100);\n }\n @Override\n public HttpUrl parseUrl(HttpUrl domainUrl, HttpUrl url) {\n if (null == domainUrl) return url;\n HttpUrl.Builder builder = url.newBuilder();\n int pathSize = resolvePathSize(url, builder);\n if (TextUtils.isEmpty(mCache.get(getKey(domainUrl, url, pathSize)))) {\n for (int i = 0; i < url.pathSize(); i++) {",
"score": 0.8074430823326111
}
] | java | int i = mRetrofitUrlManager.getPathSize(); |
package com.juziml.content.gpu_test;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Region;
import android.util.AttributeSet;
import android.view.View;
import androidx.annotation.Nullable;
/**
* create by zhusw on 2020-07-29 10:54
*/
public class GpuTestCurlAnimView extends View {
Paint pointPaint;
FPoint a, f, g, e, h, c, j, b, k, d, i;
int width;
int height;
//图形
Paint pathAPaint;
Path pathA;
Bitmap holderBitmap;
Canvas bitmapCanvas = new Canvas();
Paint pathCPaint;
Path pathC;
Paint pathBPaint;
Path pathB;
PorterDuffXfermode xfDST_ATOP = new PorterDuffXfermode(PorterDuff.Mode.DST_ATOP);
public GpuTestCurlAnimView(Context context) {
this(context, null);
}
public GpuTestCurlAnimView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
width = w;
height = h;
| a.setXY(-1, -1); |
holderBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
}
public GpuTestCurlAnimView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
pointPaint = new Paint();
pointPaint.setColor(Color.RED);
pointPaint.setTextSize(25);
a = new FPoint();
f = new FPoint();
g = new FPoint();
e = new FPoint();
h = new FPoint();
c = new FPoint();
j = new FPoint();
b = new FPoint();
k = new FPoint();
d = new FPoint();
i = new FPoint();
pathAPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
pathAPaint.setColor(Color.GREEN);
pathA = new Path();
pathCPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
pathCPaint.setColor(Color.YELLOW);
pathCPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_ATOP));//消除c区 与a区重叠部分,原文注释:丢弃原图想覆盖目标图像的区域
pathC = new Path();
pathBPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
pathBPaint.setColor(Color.BLUE);
pathB = new Path();
}
public void flipPrepare(float x, float y) {
if (y < height / 2) {
f.setXY(width, 0);
} else {
f.setXY(width, height);
}
}
public void flipSetToDefault() {
a.setXY(-1, -1);
f.setXY(0, 0);
calculatePointXY(a, f);
postInvalidate();
}
public void flipCurl(float x, float y) {
a.x = x;
a.y = y;
calculatePointXY(a, f);
//修正c点范围 不可小于0
if (calculateCxRange(a.x, a.y, f) < 0) {
calcPointAByTouchPoint();
calculatePointXY(a, f);
}
postInvalidate();
}
private float calculateCxRange(float ax, float ay, FPoint f) {
float gx = (ax + f.x) / 2;
float gy = (ay + f.y) / 2;
float ex = gx - (f.y - gy) * (f.y - gy) / (f.x - gx);
return ex - (f.x - ex) / 2;
}
/**
* 如果c点x坐标小于0,根据触摸点重新测量a点坐标
*/
private void calcPointAByTouchPoint() {
float w0 = width - c.x;
float w1 = Math.abs(f.x - a.x);
float w2 = width * w1 / w0;
a.x = Math.abs(f.x - w2);
float h1 = Math.abs(f.y - a.y);
float h2 = w2 * h1 / w1;
a.y = Math.abs(f.y - h2);
}
@Override
public void onDrawForeground(Canvas canvas) {
super.onDrawForeground(canvas);
//把点绘制在前景上 方便观察
drawPoint(canvas);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (a.x == -1 && a.y == -1) {
canvas.drawPath(getDefaultPath(), pathAPaint);
} else {
Path pathA = getPathAFromRightTop();
if (f.x == width && f.y == height) {
pathA = getPathAFromRightBottom();
}
Path pathC = getPathC();
canvas.drawPath(pathC, pathCPaint);//先给C区画上底色
canvas.drawPath(pathA, pathAPaint);//先给A区画上底色
canvas.save();//扣出B区
canvas.clipPath(pathC, Region.Op.DIFFERENCE);
canvas.clipPath(pathA, Region.Op.DIFFERENCE);
canvas.drawPath(getPathB(), pathBPaint);
canvas.restore();
}
}
public Path getDefaultPath() {
pathA.reset();
pathA.lineTo(0, height);
pathA.lineTo(width, height);
pathA.lineTo(width, 0);
pathA.close();
return pathA;
}
/**
* 以右下角为触发起点
*
* @return
*/
private Path getPathAFromRightBottom() {
pathA.reset();
//划线从 0,0开始
pathA.lineTo(0, height);//划线到左下角
pathA.lineTo(c.x, c.y);//划线到c点
pathA.quadTo(e.x, e.y, b.x, b.y);//以c为起点,b为终点,e为动点 画曲线
pathA.lineTo(a.x, a.y);
pathA.lineTo(k.x, k.y);
pathA.quadTo(h.x, h.y, j.x, j.y);//以k为起点,j为终点 h为动点 画曲线
pathA.lineTo(width, 0);
pathA.close();
return pathA;
}
private Path getPathAFromRightTop() {
pathA.reset();
pathA.lineTo(c.x, c.y);//划线到c
pathA.quadTo(e.x, e.y, b.x, b.y);//c-b的曲线
pathA.lineTo(a.x, a.y);//划线到a
pathA.lineTo(k.x, k.y);//划线到k
pathA.quadTo(h.x, h.y, j.x, j.y);//k-j的曲线
pathA.lineTo(width, height);
pathA.lineTo(0, height);
pathA.close();
return pathA;
}
private Path getPathC() {
pathC.reset();
pathC.moveTo(d.x, d.y);
pathC.lineTo(b.x, b.y);
pathC.lineTo(a.x, a.y);
pathC.lineTo(k.x, k.y);
pathC.lineTo(i.x, i.y);
pathC.close();
return pathC;
}
private Path getPathB() {
pathB.reset();
pathB.lineTo(0, height);
pathB.lineTo(width, height);
pathB.lineTo(width, 0);
pathB.close();
return pathB;
}
private void drawPoint(Canvas canvas) {
canvas.drawText("a", a.x, a.y, pointPaint);
canvas.drawText("f", f.x, f.y, pointPaint);
canvas.drawText("g", g.x, g.y, pointPaint);
canvas.drawText("e", e.x, e.y, pointPaint);
canvas.drawText("h", h.x, h.y, pointPaint);
canvas.drawText("c", c.x, c.y, pointPaint);
canvas.drawText("j", j.x, j.y, pointPaint);
canvas.drawText("b", b.x, b.y, pointPaint);
canvas.drawText("k", k.x, k.y, pointPaint);
canvas.drawText("d", d.x, d.y, pointPaint);
canvas.drawText("i", i.x, i.y, pointPaint);
}
/**
* 计算切点坐标,这里就没有推导公式了,直接拿来用了
*
* @param lineOne_My_pointOne
* @param lineOne_My_pointTwo
* @param lineTwo_My_pointOne
* @param lineTwo_My_pointTwo
* @return
*/
private FPoint getIntersectionPoint(FPoint lineOne_My_pointOne,
FPoint lineOne_My_pointTwo,
FPoint lineTwo_My_pointOne,
FPoint lineTwo_My_pointTwo) {
float x1, y1, x2, y2, x3, y3, x4, y4;
x1 = lineOne_My_pointOne.x;
y1 = lineOne_My_pointOne.y;
x2 = lineOne_My_pointTwo.x;
y2 = lineOne_My_pointTwo.y;
x3 = lineTwo_My_pointOne.x;
y3 = lineTwo_My_pointOne.y;
x4 = lineTwo_My_pointTwo.x;
y4 = lineTwo_My_pointTwo.y;
float pointX = ((x1 - x2) * (x3 * y4 - x4 * y3)
- (x3 - x4) * (x1 * y2 - x2 * y1)) / ((x3 - x4)
* (y1 - y2) - (x1 - x2) * (y3 - y4));
float pointY = ((y1 - y2) * (x3 * y4 - x4 * y3)
- (x1 * y2 - x2 * y1) * (y3 - y4)) / ((y1 - y2)
* (x3 - x4) - (x1 - x2) * (y3 - y4));
return new FPoint(pointX, pointY);
}
/**
* 计算各点坐标
*/
private void calculatePointXY(FPoint a, FPoint f) {
g.x = (a.x + f.x) / 2;
g.y = (a.y + f.y) / 2;
e.x = g.x - (f.y - g.y) * (f.y - g.y) / (f.x - g.x);
e.y = f.y;
h.x = f.x;
h.y = g.y - (f.x - g.x) * (f.x - g.x) / (f.y - g.y);
c.x = e.x - (f.x - e.x) / 2;
c.y = f.y;
j.x = f.x;
j.y = h.y - (f.y - h.y) / 2;
b = getIntersectionPoint(a, e, c, j);
k = getIntersectionPoint(a, h, c, j);
d.x = (c.x + 2 * e.x + b.x) / 4;
d.y = (2 * e.y + c.y + b.y) / 4;
i.x = (j.x + 2 * h.x + k.x) / 4;
i.y = (2 * h.y + j.y + k.y) / 4;
}
}
| gpu_test/src/main/java/com/juziml/content/gpu_test/GpuTestCurlAnimView.java | Western-parotia-BookViewProject-1727e80 | [
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookRecyclerView.java",
"retrieved_chunk": " public void scrollToPosition(int position) {\n readLayoutManger.forceScrollToPosition(position);\n }\n @Override\n public void smoothScrollToPosition(int position) {\n readLayoutManger.smoothScrollToPosition(position);\n }\n @Override\n protected void onSizeChanged(int w, int h, int oldw, int oldh) {\n super.onSizeChanged(w, h, oldw, oldh);",
"score": 0.889145016670227
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " isTouching = false;\n downX = 0F;\n drawCurlAnimBefore = false;\n break;\n }\n }\n @Override\n public void onViewSizeChanged(int vWidth, int vHeight) {\n this.vWidth = vWidth;\n this.vHeight = vHeight;",
"score": 0.8877056241035461
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookView.java",
"retrieved_chunk": " params.gravity = Gravity.CENTER;\n addView(bookRecyclerView, params);\n LayoutParams params2 = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);\n params2.gravity = Gravity.CENTER;\n addView(puppetView, params2);\n }\n @Override\n protected void onSizeChanged(int w, int h, int oldw, int oldh) {\n super.onSizeChanged(w, h, oldw, oldh);\n bookRecyclerView.bindReadCurlAnimProxy(puppetView);",
"score": 0.8835606575012207
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/CoverAnimationEffecter.java",
"retrieved_chunk": " }\n @Override\n public boolean animInEffect() {\n return isTouching || coverAnimationRunning;\n }\n @Override\n public void onViewSizeChanged(int vWidth, int vHeight) {\n this.vWidth = vWidth;\n this.vHeight = vHeight;\n menuBounds.left = vWidth / 3F;",
"score": 0.8621042370796204
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/PaperLayout.java",
"retrieved_chunk": " }\n @Override\n protected void onAttachedToWindow() {\n super.onAttachedToWindow();\n bookRecyclerView = (BookRecyclerView) getParent();\n }\n @Override\n protected void onSizeChanged(int w, int h, int oldw, int oldh) {\n super.onSizeChanged(w, h, oldw, oldh);\n if (bookRecyclerView.getFlipMode() == BookLayoutManager.BookFlipMode.MODE_CURL",
"score": 0.8588523864746094
}
] | java | a.setXY(-1, -1); |
package com.juziml.content.gpu_test;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Region;
import android.util.AttributeSet;
import android.view.View;
import androidx.annotation.Nullable;
/**
* create by zhusw on 2020-07-29 10:54
*/
public class GpuTestCurlAnimView extends View {
Paint pointPaint;
FPoint a, f, g, e, h, c, j, b, k, d, i;
int width;
int height;
//图形
Paint pathAPaint;
Path pathA;
Bitmap holderBitmap;
Canvas bitmapCanvas = new Canvas();
Paint pathCPaint;
Path pathC;
Paint pathBPaint;
Path pathB;
PorterDuffXfermode xfDST_ATOP = new PorterDuffXfermode(PorterDuff.Mode.DST_ATOP);
public GpuTestCurlAnimView(Context context) {
this(context, null);
}
public GpuTestCurlAnimView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
width = w;
height = h;
a.setXY(-1, -1);
holderBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
}
public GpuTestCurlAnimView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
pointPaint = new Paint();
pointPaint.setColor(Color.RED);
pointPaint.setTextSize(25);
a = new FPoint();
f = new FPoint();
g = new FPoint();
e = new FPoint();
h = new FPoint();
c = new FPoint();
j = new FPoint();
b = new FPoint();
k = new FPoint();
d = new FPoint();
i = new FPoint();
pathAPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
pathAPaint.setColor(Color.GREEN);
pathA = new Path();
pathCPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
pathCPaint.setColor(Color.YELLOW);
pathCPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_ATOP));//消除c区 与a区重叠部分,原文注释:丢弃原图想覆盖目标图像的区域
pathC = new Path();
pathBPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
pathBPaint.setColor(Color.BLUE);
pathB = new Path();
}
public void flipPrepare(float x, float y) {
if (y < height / 2) {
| f.setXY(width, 0); |
} else {
f.setXY(width, height);
}
}
public void flipSetToDefault() {
a.setXY(-1, -1);
f.setXY(0, 0);
calculatePointXY(a, f);
postInvalidate();
}
public void flipCurl(float x, float y) {
a.x = x;
a.y = y;
calculatePointXY(a, f);
//修正c点范围 不可小于0
if (calculateCxRange(a.x, a.y, f) < 0) {
calcPointAByTouchPoint();
calculatePointXY(a, f);
}
postInvalidate();
}
private float calculateCxRange(float ax, float ay, FPoint f) {
float gx = (ax + f.x) / 2;
float gy = (ay + f.y) / 2;
float ex = gx - (f.y - gy) * (f.y - gy) / (f.x - gx);
return ex - (f.x - ex) / 2;
}
/**
* 如果c点x坐标小于0,根据触摸点重新测量a点坐标
*/
private void calcPointAByTouchPoint() {
float w0 = width - c.x;
float w1 = Math.abs(f.x - a.x);
float w2 = width * w1 / w0;
a.x = Math.abs(f.x - w2);
float h1 = Math.abs(f.y - a.y);
float h2 = w2 * h1 / w1;
a.y = Math.abs(f.y - h2);
}
@Override
public void onDrawForeground(Canvas canvas) {
super.onDrawForeground(canvas);
//把点绘制在前景上 方便观察
drawPoint(canvas);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (a.x == -1 && a.y == -1) {
canvas.drawPath(getDefaultPath(), pathAPaint);
} else {
Path pathA = getPathAFromRightTop();
if (f.x == width && f.y == height) {
pathA = getPathAFromRightBottom();
}
Path pathC = getPathC();
canvas.drawPath(pathC, pathCPaint);//先给C区画上底色
canvas.drawPath(pathA, pathAPaint);//先给A区画上底色
canvas.save();//扣出B区
canvas.clipPath(pathC, Region.Op.DIFFERENCE);
canvas.clipPath(pathA, Region.Op.DIFFERENCE);
canvas.drawPath(getPathB(), pathBPaint);
canvas.restore();
}
}
public Path getDefaultPath() {
pathA.reset();
pathA.lineTo(0, height);
pathA.lineTo(width, height);
pathA.lineTo(width, 0);
pathA.close();
return pathA;
}
/**
* 以右下角为触发起点
*
* @return
*/
private Path getPathAFromRightBottom() {
pathA.reset();
//划线从 0,0开始
pathA.lineTo(0, height);//划线到左下角
pathA.lineTo(c.x, c.y);//划线到c点
pathA.quadTo(e.x, e.y, b.x, b.y);//以c为起点,b为终点,e为动点 画曲线
pathA.lineTo(a.x, a.y);
pathA.lineTo(k.x, k.y);
pathA.quadTo(h.x, h.y, j.x, j.y);//以k为起点,j为终点 h为动点 画曲线
pathA.lineTo(width, 0);
pathA.close();
return pathA;
}
private Path getPathAFromRightTop() {
pathA.reset();
pathA.lineTo(c.x, c.y);//划线到c
pathA.quadTo(e.x, e.y, b.x, b.y);//c-b的曲线
pathA.lineTo(a.x, a.y);//划线到a
pathA.lineTo(k.x, k.y);//划线到k
pathA.quadTo(h.x, h.y, j.x, j.y);//k-j的曲线
pathA.lineTo(width, height);
pathA.lineTo(0, height);
pathA.close();
return pathA;
}
private Path getPathC() {
pathC.reset();
pathC.moveTo(d.x, d.y);
pathC.lineTo(b.x, b.y);
pathC.lineTo(a.x, a.y);
pathC.lineTo(k.x, k.y);
pathC.lineTo(i.x, i.y);
pathC.close();
return pathC;
}
private Path getPathB() {
pathB.reset();
pathB.lineTo(0, height);
pathB.lineTo(width, height);
pathB.lineTo(width, 0);
pathB.close();
return pathB;
}
private void drawPoint(Canvas canvas) {
canvas.drawText("a", a.x, a.y, pointPaint);
canvas.drawText("f", f.x, f.y, pointPaint);
canvas.drawText("g", g.x, g.y, pointPaint);
canvas.drawText("e", e.x, e.y, pointPaint);
canvas.drawText("h", h.x, h.y, pointPaint);
canvas.drawText("c", c.x, c.y, pointPaint);
canvas.drawText("j", j.x, j.y, pointPaint);
canvas.drawText("b", b.x, b.y, pointPaint);
canvas.drawText("k", k.x, k.y, pointPaint);
canvas.drawText("d", d.x, d.y, pointPaint);
canvas.drawText("i", i.x, i.y, pointPaint);
}
/**
* 计算切点坐标,这里就没有推导公式了,直接拿来用了
*
* @param lineOne_My_pointOne
* @param lineOne_My_pointTwo
* @param lineTwo_My_pointOne
* @param lineTwo_My_pointTwo
* @return
*/
private FPoint getIntersectionPoint(FPoint lineOne_My_pointOne,
FPoint lineOne_My_pointTwo,
FPoint lineTwo_My_pointOne,
FPoint lineTwo_My_pointTwo) {
float x1, y1, x2, y2, x3, y3, x4, y4;
x1 = lineOne_My_pointOne.x;
y1 = lineOne_My_pointOne.y;
x2 = lineOne_My_pointTwo.x;
y2 = lineOne_My_pointTwo.y;
x3 = lineTwo_My_pointOne.x;
y3 = lineTwo_My_pointOne.y;
x4 = lineTwo_My_pointTwo.x;
y4 = lineTwo_My_pointTwo.y;
float pointX = ((x1 - x2) * (x3 * y4 - x4 * y3)
- (x3 - x4) * (x1 * y2 - x2 * y1)) / ((x3 - x4)
* (y1 - y2) - (x1 - x2) * (y3 - y4));
float pointY = ((y1 - y2) * (x3 * y4 - x4 * y3)
- (x1 * y2 - x2 * y1) * (y3 - y4)) / ((y1 - y2)
* (x3 - x4) - (x1 - x2) * (y3 - y4));
return new FPoint(pointX, pointY);
}
/**
* 计算各点坐标
*/
private void calculatePointXY(FPoint a, FPoint f) {
g.x = (a.x + f.x) / 2;
g.y = (a.y + f.y) / 2;
e.x = g.x - (f.y - g.y) * (f.y - g.y) / (f.x - g.x);
e.y = f.y;
h.x = f.x;
h.y = g.y - (f.x - g.x) * (f.x - g.x) / (f.y - g.y);
c.x = e.x - (f.x - e.x) / 2;
c.y = f.y;
j.x = f.x;
j.y = h.y - (f.y - h.y) / 2;
b = getIntersectionPoint(a, e, c, j);
k = getIntersectionPoint(a, h, c, j);
d.x = (c.x + 2 * e.x + b.x) / 4;
d.y = (2 * e.y + c.y + b.y) / 4;
i.x = (j.x + 2 * h.x + k.x) / 4;
i.y = (2 * h.y + j.y + k.y) / 4;
}
}
| gpu_test/src/main/java/com/juziml/content/gpu_test/GpuTestCurlAnimView.java | Western-parotia-BookViewProject-1727e80 | [
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " //转换成含有透明度的颜色\n int tempColor = Color.argb(200, red, green, blue);\n canvas.save();\n canvas.clipPath(pathC);\n canvas.clipPath(pathA, Region.Op.DIFFERENCE);\n canvas.drawColor(readAnimView.getBackgroundColor());\n bitmapPaint.setColorFilter(colorMatrixColorFilter);\n canvas.drawBitmap(curBitmap, matrix, bitmapPaint);//绘制背面到C区\n canvas.drawColor(tempColor);//叠加背景\n bitmapPaint.setColorFilter(null);",
"score": 0.8580518960952759
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " canvas.restore();\n canvas.save();\n canvas.clipPath(pathC, Region.Op.DIFFERENCE);\n canvas.clipPath(pathA, Region.Op.DIFFERENCE);\n canvas.drawBitmap(nextBitmap, 0, 0, bitmapPaint);//绘制B区\n canvas.restore();\n } else {\n //对Bitmap进行取色\n int color = preBitmap.getPixel(1, 1);\n //获取对应的三色",
"score": 0.8418012261390686
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " int red = (color & 0xff0000) >> 16;\n int green = (color & 0x00ff00) >> 8;\n int blue = (color & 0x0000ff);\n //转换成含有透明度的颜色\n int tempColor = Color.argb(200, red, green, blue);\n bitmapPaint.setColorFilter(colorMatrixColorFilter);\n canvas.save();\n canvas.clipPath(pathC);\n canvas.clipPath(pathA, Region.Op.DIFFERENCE);\n bitmapPaint.setColorFilter(colorMatrixColorFilter);",
"score": 0.8350837230682373
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " } else {\n //从右向左线性渐变\n gradientDrawable = readAnimView.getAnimHelper().getBottomBGradientDrawable();\n left = (int) (c.x - aTof / 4 - lightOffset);//c点位于左下角\n right = (int) (c.x + deepOffset);\n }\n gradientDrawable.setBounds(left, top, right, bottom);//设置阴影矩形\n canvas.save();\n canvas.clipPath(pathA, Region.Op.DIFFERENCE);\n canvas.clipPath(pathC, Region.Op.DIFFERENCE);//留出b区",
"score": 0.8315839767456055
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " g2 = new FPoint();\n e2 = new FPoint();\n pathPaint = new Paint(Paint.ANTI_ALIAS_FLAG);\n bitmapPaint = new Paint(Paint.ANTI_ALIAS_FLAG);\n pathA = new Path();\n pathC = new Path();\n pathRightShadow = new Path();\n pathLeftShadow = new Path();\n ColorMatrix cm = new ColorMatrix();//设置颜色数组\n float[] array = {1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0};",
"score": 0.8222399950027466
}
] | java | f.setXY(width, 0); |
/*
* Copyright 2017 JessYan
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.foundation.service.urlmanager.retrofiturlmanager.parser;
import android.text.TextUtils;
import com.foundation.service.urlmanager.retrofiturlmanager.RetrofitUrlManager;
import com.foundation.service.urlmanager.retrofiturlmanager.cache.Cache;
import com.foundation.service.urlmanager.retrofiturlmanager.cache.LruCache;
import java.util.ArrayList;
import java.util.List;
import okhttp3.HttpUrl;
/**
* ================================================
* 高级解析器, 当 BaseUrl 中有除了域名以外的其他 Path 时, 可使用此解析器
* <p>
* 比如:
* 1.
* 旧 URL 地址为 https://www.github.com/wiki/part, 您在 App 初始化时传入 {@link RetrofitUrlManager#startAdvancedModel(String)}
* 的 BaseUrl 为 https://www.github.com/wiki
* 您调用 {@link RetrofitUrlManager#putDomain(String, String)} 方法传入的 URL 地址是 https://www.google.com/api
* 经过本解析器解析后生成的新 URL 地址为 http://www.google.com/api/part
* <p>
* 2.
* 旧 URL 地址为 https://www.github.com/wiki/part, 您在 App 初始化时传入 {@link RetrofitUrlManager#startAdvancedModel(String)}
* 的 BaseUrl 为 https://www.github.com/wiki
* 您调用 {@link RetrofitUrlManager#putDomain(String, String)} 方法传入的 URL 地址是 https://www.google.com
* 经过本解析器解析后生成的新 URL 地址为 http://www.google.com/part
* <p>
* 3.
* 旧 URL 地址为 https://www.github.com/wiki/part, 您在 App 初始化时传入 {@link RetrofitUrlManager#startAdvancedModel(String)}
* 的 BaseUrl 为 https://www.github.com
* 您调用 {@link RetrofitUrlManager#putDomain(String, String)} 方法传入的 URL 地址是 https://www.google.com/api
* 经过本解析器解析后生成的新 URL 地址为 http://www.google.com/api/wiki/part
* <p>
* 解析器会将 BaseUrl 全部替换成您传入的 Url 地址
*
* @see UrlParser
* Created by JessYan on 09/06/2018 16:00
* <a href="mailto:[email protected]">Contact me</a>
* <a href="https://github.com/JessYanCoding">Follow me</a>
* ================================================
*/
public class AdvancedUrlParser implements UrlParser {
private RetrofitUrlManager mRetrofitUrlManager;
private Cache<String, String> mCache;
@Override
public void init(RetrofitUrlManager retrofitUrlManager) {
this.mRetrofitUrlManager = retrofitUrlManager;
this.mCache = new LruCache<>(100);
}
@Override
public HttpUrl parseUrl(HttpUrl domainUrl, HttpUrl url) {
if (null == domainUrl) return url;
HttpUrl.Builder builder = url.newBuilder();
if (TextUtils.isEmpty(mCache.get(getKey(domainUrl, url)))) {
for (int i = 0; i < url.pathSize(); i++) {
//当删除了上一个 index, PathSegment 的 item 会自动前进一位, 所以 remove(0) 就好
builder.removePathSegment(0);
}
List<String> newPathSegments = new ArrayList<>();
newPathSegments.addAll(domainUrl.encodedPathSegments());
if (url.pathSize() > mRetrofitUrlManager.getPathSize()) {
List<String> encodedPathSegments = url.encodedPathSegments();
for (int i = mRetrofitUrlManager.getPathSize(); i < encodedPathSegments.size(); i++) {
newPathSegments.add(encodedPathSegments.get(i));
}
} else if (url.pathSize() < mRetrofitUrlManager.getPathSize()) {
throw new IllegalArgumentException(String.format("Your final path is %s, but the baseUrl of your RetrofitUrlManager#startAdvancedModel is %s",
url.scheme() + "://" + url.host() + url.encodedPath(),
mRetrofitUrlManager.getBaseUrl().scheme() + "://"
+ mRetrofitUrlManager.getBaseUrl().host()
+ mRetrofitUrlManager.getBaseUrl().encodedPath()));
}
for (String PathSegment : newPathSegments) {
builder.addEncodedPathSegment(PathSegment);
}
} else {
builder.encodedPath(mCache.get(getKey(domainUrl, url)));
}
HttpUrl httpUrl = builder
.scheme(domainUrl.scheme())
.host(domainUrl.host())
.port(domainUrl.port())
.build();
if (TextUtils.isEmpty(mCache.get(getKey(domainUrl, url)))) {
mCache.put(getKey(domainUrl, url), httpUrl.encodedPath());
}
return httpUrl;
}
private String getKey(HttpUrl domainUrl, HttpUrl url) {
return domainUrl.encodedPath() + url.encodedPath()
| + mRetrofitUrlManager.getPathSize(); |
}
}
| net/src/main/java/com/foundation/service/urlmanager/retrofiturlmanager/parser/AdvancedUrlParser.java | Western-parotia-Net-accd348 | [
{
"filename": "net/src/main/java/com/foundation/service/urlmanager/retrofiturlmanager/parser/DomainUrlParser.java",
"retrieved_chunk": " .scheme(domainUrl.scheme())\n .host(domainUrl.host())\n .port(domainUrl.port())\n .build();\n if (TextUtils.isEmpty(mCache.get(getKey(domainUrl, url)))) {\n mCache.put(getKey(domainUrl, url), httpUrl.encodedPath());\n }\n return httpUrl;\n }\n private String getKey(HttpUrl domainUrl, HttpUrl url) {",
"score": 0.9667561054229736
},
{
"filename": "net/src/main/java/com/foundation/service/urlmanager/retrofiturlmanager/parser/SuperUrlParser.java",
"retrieved_chunk": " }\n HttpUrl httpUrl = builder\n .scheme(domainUrl.scheme())\n .host(domainUrl.host())\n .port(domainUrl.port())\n .build();\n if (TextUtils.isEmpty(mCache.get(getKey(domainUrl, url, pathSize)))) {\n mCache.put(getKey(domainUrl, url, pathSize), httpUrl.encodedPath());\n }\n return httpUrl;",
"score": 0.9314137101173401
},
{
"filename": "net/src/main/java/com/foundation/service/urlmanager/retrofiturlmanager/parser/SuperUrlParser.java",
"retrieved_chunk": " this.mRetrofitUrlManager = retrofitUrlManager;\n this.mCache = new LruCache<>(100);\n }\n @Override\n public HttpUrl parseUrl(HttpUrl domainUrl, HttpUrl url) {\n if (null == domainUrl) return url;\n HttpUrl.Builder builder = url.newBuilder();\n int pathSize = resolvePathSize(url, builder);\n if (TextUtils.isEmpty(mCache.get(getKey(domainUrl, url, pathSize)))) {\n for (int i = 0; i < url.pathSize(); i++) {",
"score": 0.8868750929832458
},
{
"filename": "net/src/main/java/com/foundation/service/urlmanager/retrofiturlmanager/parser/DefaultUrlParser.java",
"retrieved_chunk": " this.mRetrofitUrlManager = retrofitUrlManager;\n this.mDomainUrlParser = new DomainUrlParser();\n this.mDomainUrlParser.init(retrofitUrlManager);\n }\n @Override\n public HttpUrl parseUrl(HttpUrl domainUrl, HttpUrl url) {\n if (null == domainUrl) return url;\n if (url.toString().contains(IDENTIFICATION_PATH_SIZE)) {\n if (mSuperUrlParser == null) {\n synchronized (this) {",
"score": 0.8471425771713257
},
{
"filename": "net/src/main/java/com/foundation/service/urlmanager/retrofiturlmanager/parser/SuperUrlParser.java",
"retrieved_chunk": " }\n private String getKey(HttpUrl domainUrl, HttpUrl url, int PathSize) {\n return domainUrl.encodedPath() + url.encodedPath()\n + PathSize;\n }\n private int resolvePathSize(HttpUrl httpUrl, HttpUrl.Builder builder) {\n String fragment = httpUrl.fragment();\n int pathSize = 0;\n StringBuffer newFragment = new StringBuffer();\n if (fragment.indexOf(\"#\") == -1) {",
"score": 0.8468631505966187
}
] | java | + mRetrofitUrlManager.getPathSize(); |
package com.juziml.read.business.read.view;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewParent;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.juziml.read.business.read.anim.AnimHelper;
import com.juziml.read.business.read.anim.CoverAnimationEffecter;
import com.juziml.read.business.read.anim.IAnimationEffecter;
import com.juziml.read.business.read.anim.SimulationAnimationEffecter;
/**
* 此View的作用就像幕后一样,负责接受事件并传递到动画,Effecter
* create by zhusw on 2020-08-14 17:37
*/
public class PuppetView extends View implements EventProxy, AnimParentView {
IAnimationEffecter animationEffecter;
AnimParentView parentView;
private Bitmap previousViewBitmap;
private Bitmap currentViewBitmap;
private Bitmap nextViewBitmap;
boolean performDrawCurlTexture = false;
private int vWidth, vHeight;
public PuppetView(@NonNull Context context) {
this(context, null);
}
public PuppetView(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public PuppetView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
/*
view 可以单独关,但是不能单独打开硬件加速
关闭硬件加速 卡到爆炸
开启硬件加速,诱发 OpenGLRenderer: Path too large to be rendered into a texture
setLayerType(LAYER_TYPE_SOFTWARE,null);
*/
}
public boolean animRunningOrTouching() {
boolean animRunningOrTouching = false;
if (null != animationEffecter) {
animRunningOrTouching = animRunning();
}
return animRunningOrTouching;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
ViewParent viewParent = getParent();
parentView = (AnimParentView) viewParent;
if (null != animationEffecter) {
animationEffecter.onViewAttachedToWindow();
}
}
public void setAnimMode(int animMode) {
//重置某些属性 与变量
animationEffecter = null;
if (animMode == BookLayoutManager.BookFlipMode.MODE_COVER) {
animationEffecter = new CoverAnimationEffecter(this);
} else if (animMode == BookLayoutManager.BookFlipMode.MODE_CURL) {
animationEffecter = new SimulationAnimationEffecter(this);
}
if (null != animationEffecter) {
| animationEffecter.onViewSizeChanged(vWidth, vHeight); |
}
}
@Override
public void draw(Canvas canvas) {
if (performDrawCurlTexture && null != animationEffecter) {
animationEffecter.draw(canvas);
} else {
super.draw(canvas);
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (null != animationEffecter) {
animationEffecter.onViewDetachedFromWindow();
}
}
/**
* 这个会被调用多次,最终宽度为实际测量宽度-2px
* 这样在 layoutmanager 进行布局时 才可以同时保持3个item被显示
*
* @param widthMeasureSpec
* @param heightMeasureSpec
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int height = measureSize(5, heightMeasureSpec);
int width = measureSize(5, widthMeasureSpec) - 2;
setMeasuredDimension(width - 2, height);
vWidth = width;
vHeight = height;
if (null != animationEffecter) {
animationEffecter.onViewSizeChanged(vWidth, vHeight);
}
}
private int measureSize(int defaultSize, int measureSpec) {
int result = defaultSize;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
result = specSize;
} else if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
return result;
}
public void buildBitmap(int slideDirection) {
performDrawCurlTexture = false;
if (slideDirection == AnimHelper.SLID_DIRECTION_LEFT) {
currentViewBitmap = parentView.getCurrentBitmap();
nextViewBitmap = parentView.getNextBitmap();
} else if (slideDirection == AnimHelper.SLID_DIRECTION_RIGHT) {
previousViewBitmap = parentView.getPreviousBitmap();
}
performDrawCurlTexture = true;
}
@Override
public boolean onItemViewTouchEvent(MotionEvent event) {
if (null != animationEffecter) {
animationEffecter.handlerEvent(event);
}
return true;
}
@Override
public boolean animRunning() {
if (null != animationEffecter) {
return animationEffecter.animInEffect();
}
return false;
}
@Override
public void computeScroll() {
if (null != animationEffecter) {
animationEffecter.onScroll();
}
}
@Override
public void onExpectNext() {
parentView.onExpectNext();
}
@Override
public void onExpectPrevious() {
parentView.onExpectPrevious();
}
@Override
public Bitmap getPreviousBitmap() {
return previousViewBitmap;
}
@Override
public Bitmap getCurrentBitmap() {
return currentViewBitmap;
}
@Override
public Bitmap getNextBitmap() {
return nextViewBitmap;
}
@Override
public int getBackgroundColor() {
return parentView.getBackgroundColor();
}
@Override
public AnimHelper getAnimHelper() {
return parentView.getAnimHelper();
}
@Override
public void onClickMenuArea() {
parentView.onClickMenuArea();
}
@Override
public void onClickNextArea() {
parentView.onClickNextArea();
}
@Override
public void onClickPreviousArea() {
parentView.onClickPreviousArea();
}
public void reset() {
previousViewBitmap = null;
nextViewBitmap = null;
currentViewBitmap = null;
performDrawCurlTexture = false;
}
}
| app/src/main/java/com/juziml/read/business/read/view/PuppetView.java | Western-parotia-BookViewProject-1727e80 | [
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookView.java",
"retrieved_chunk": " || flipMode == BookLayoutManager.BookFlipMode.MODE_COVER) {\n puppetView.setVisibility(View.VISIBLE);\n } else {\n puppetView.setVisibility(View.INVISIBLE);//不可以设置为gone,避免animView 无法获取尺寸\n }\n bookRecyclerView.setFlipMode(flipMode);\n puppetView.setAnimMode(flipMode);\n }\n @Override\n public AnimHelper getAnimHelper() {",
"score": 0.847142219543457
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookRecyclerView.java",
"retrieved_chunk": " } else {\n scrollToPosition(currentPosition - 1);\n }\n }\n }\n protected void setFlipMode(int flipMode) {\n readLayoutManger.setBookFlipMode(flipMode);\n if (flipMode == BookLayoutManager.BookFlipMode.MODE_CURL\n || flipMode == BookLayoutManager.BookFlipMode.MODE_COVER) {\n allowInterceptTouchEvent = false;",
"score": 0.8333473205566406
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/CoverAnimationEffecter.java",
"retrieved_chunk": " protected class ScrollRunnable implements Runnable {\n @Override\n public void run() {\n readAnimView.reset();\n coverAnimationRunning = false;\n if (!isCancelFlip) {\n if (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT) {\n readAnimView.onExpectNext();\n } else if (coverSlideDirection == AnimHelper.SLID_DIRECTION_RIGHT) {\n readAnimView.onExpectPrevious();",
"score": 0.8137820363044739
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookView.java",
"retrieved_chunk": " animHelper = new AnimHelper();\n init();\n }\n private void init() {\n removeAllViews();\n bookRecyclerView = new BookRecyclerView(getContext());\n puppetView = new PuppetView(getContext());\n puppetView.setAnimMode(bookRecyclerView.getFlipMode());\n bookRecyclerView.bindReadCurlAnimProxy(puppetView);\n LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);",
"score": 0.8021456003189087
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/CoverAnimationEffecter.java",
"retrieved_chunk": " }\n if (coverSlideDirection != AnimHelper.SLID_DIRECTION_LEFT && coverSlideDirection != AnimHelper.SLID_DIRECTION_RIGHT) {\n DLog.log(\"CoverAnimationEffect draw 2\");\n return;\n }\n if (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT\n && (null == readAnimView.getCurrentBitmap() || null == readAnimView.getNextBitmap())) {\n DLog.log(\"CoverAnimationEffect draw 3\");\n return;\n }",
"score": 0.7996642589569092
}
] | java | animationEffecter.onViewSizeChanged(vWidth, vHeight); |
package com.juziml.read.business.read.anim;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.drawable.GradientDrawable;
import android.view.MotionEvent;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.Scroller;
import com.juziml.read.business.read.view.PuppetView;
import com.juziml.read.utils.DLog;
import java.util.LinkedList;
import java.util.List;
/**
* create by zhusw on 2020-08-24 14:06
*/
public class CoverAnimationEffecter implements IAnimationEffecter {
private final static int DOWN_AREA_NONE = -1;
private final static int DOWN_AREA_MENU = 1;
private final static int DOWN_AREA_LEFT = 2;
private final static int DOWN_AREA_RIGHT = 3;
int vWidth = 1;
int vHeight = 1;
private final PuppetView readAnimView;
private boolean isCancelFlip = false;
private boolean coverAnimationRunning = false;
private boolean isTouching = false;
private final Scroller scroller;
private final ScrollRunnable scrollRunnable;
private final RectF menuBounds;
private final Path pathA;
private final Path pathB;
private final Paint paint;
private final int shadowWidth;
public CoverAnimationEffecter(PuppetView readAnimView) {
this.readAnimView = readAnimView;
scroller = new Scroller(readAnimView.getContext(), new AccelerateDecelerateInterpolator());
scrollRunnable = new ScrollRunnable();
menuBounds = new RectF();
pathA = new Path();
pathB = new Path();
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
shadowWidth = 20;
}
private int downArea = DOWN_AREA_NONE;
private float downX = 0F;
private int coverSlideDirection = AnimHelper.SLID_DIRECTION_UNKNOWN;
private final List<Float> moveSampling = new LinkedList<>();
private final int MAX_COUNT = 5;
private boolean prepareDrawCoverAnimEffect = false;
private float currentX = -1;
@Override
public void handlerEvent(MotionEvent event) {
if (coverAnimationRunning) return;
float x = event.getRawX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
moveSampling.clear();
downX = x;
prepareDrawCoverAnimEffect = false;
isTouching = true;
currentX = -1;
downArea = DOWN_AREA_NONE;
coverSlideDirection = AnimHelper.SLID_DIRECTION_UNKNOWN;
if (x > menuBounds.left && y > menuBounds.top
&& x < menuBounds.right && y < menuBounds.bottom) {
downArea = DOWN_AREA_MENU;
} else if (x < vWidth / 2F) {
downArea = DOWN_AREA_LEFT;
} else {
downArea = DOWN_AREA_RIGHT;
}
break;
case MotionEvent.ACTION_MOVE:
isTouching = true;
float curDistance = x - downX;
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_UNKNOWN && checkDownArea(downArea)) {
if (curDistance > 0) {
coverSlideDirection = AnimHelper.SLID_DIRECTION_RIGHT;
} else {
coverSlideDirection = AnimHelper.SLID_DIRECTION_LEFT;
}
readAnimView.buildBitmap(coverSlideDirection);
prepareDrawCoverAnimEffect = checkAnimCondition(coverSlideDirection);
}
if (prepareDrawCoverAnimEffect) {
if (moveSampling.size() == 0
|| x != moveSampling.get(moveSampling.size() - 1)) {
moveSampling.add(x);
}
if (moveSampling.size() > MAX_COUNT) {
moveSampling.remove(0);
}
currentX = x;
invalidate();
}
break;
case MotionEvent.ACTION_CANCEL:
isTouching = false;
break;
case MotionEvent.ACTION_UP:
currentX = x;
if (prepareDrawCoverAnimEffect) {
if (moveSampling.size() > 0) {
float lastMoveX = moveSampling.get(moveSampling.size() - 1);
float firstMoveX = moveSampling.get(0);
float finallyMoveX = lastMoveX - firstMoveX;
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT) {
boolean lastFingerLeftSlop = finallyMoveX < 10;
touchUp(lastFingerLeftSlop);
} else if (coverSlideDirection == AnimHelper.SLID_DIRECTION_RIGHT) {
finallyMoveX = lastMoveX - firstMoveX;
touchUp(finallyMoveX < 0);
}
} else {
touchUp(false);
}
} else if (downArea == DOWN_AREA_MENU) {
if (x > menuBounds.left && x < menuBounds.right
&& y > menuBounds.top && y < menuBounds.bottom) {
readAnimView.onClickMenuArea();
}
} else if (downArea != DOWN_AREA_NONE) {
if (x == downX && downX >= vWidth / 2F) {//下一页
coverSlideDirection = AnimHelper.SLID_DIRECTION_LEFT;
readAnimView.buildBitmap(coverSlideDirection);
if (checkAnimCondition(coverSlideDirection)) {
touchUp(true);
}
} else if (x == downX && downX < vWidth / 2F) {//上一页
coverSlideDirection = AnimHelper.SLID_DIRECTION_RIGHT;
readAnimView.buildBitmap(coverSlideDirection);
if (checkAnimCondition(coverSlideDirection)) {
touchUp(false);
}
}
}
moveSampling.clear();
isTouching = false;
break;
default:
break;
}
}
private void touchUp(boolean lastFingerLeftSlop) {
DLog.log("touchUp coverAnimationRunning=%s", coverAnimationRunning);
coverAnimationRunning = true;
isCancelFlip = (coverSlideDirection == AnimHelper.SLID_DIRECTION_RIGHT && lastFingerLeftSlop)
|| (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT && !lastFingerLeftSlop);
int duration = isCancelFlip ? AnimHelper.CANCEL_ANIM_DURATION : AnimHelper.RELAY_ANIM_DURATION;
duration = (int) (duration * 0.7F);//cover动画时间减少一点
// duration = 1000;//cover动画时间减少一点
int startX = (int) currentX;
int startY = 0;
int dy = 0;
int dx;
if (lastFingerLeftSlop) {
dx = (int) -(vWidth - (downX - currentX));
} else {
dx = vWidth - (int) currentX;
}
scroller.startScroll(startX, startY, dx, dy, duration);
invalidate();
}
@Override
public void draw(Canvas canvas) {
if (currentX == -1) {
DLog.log("CoverAnimationEffect draw 1");
return;
}
if (coverSlideDirection != AnimHelper.SLID_DIRECTION_LEFT && coverSlideDirection != AnimHelper.SLID_DIRECTION_RIGHT) {
DLog.log("CoverAnimationEffect draw 2");
return;
}
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT
&& (null == readAnimView.getCurrentBitmap() || null == readAnimView.getNextBitmap())) {
DLog.log("CoverAnimationEffect draw 3");
return;
}
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_RIGHT && null == readAnimView.getPreviousBitmap()) {
DLog.log("CoverAnimationEffect draw 4");
return;
}
DLog.log("CoverAnimationEffect draw 5");
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT) {
float offset = downX - currentX;
offset = Math.max(0, offset);
canvas.save();
canvas.clipPath(getPathAToLeft());
canvas.drawBitmap(readAnimView.getCurrentBitmap(), -offset, 0, paint);
canvas.restore();
canvas.save();
canvas.clipPath(getPathB());
canvas.drawBitmap(readAnimView.getNextBitmap(), 0, 0, paint);
canvas.restore();
drawShadow((int) (vWidth - offset), canvas);
} else {
float leftOffset = vWidth - currentX;
canvas.save();
canvas.clipPath(getPathAToRight());
canvas.drawBitmap | (readAnimView.getPreviousBitmap(), -leftOffset, 0, paint); |
canvas.restore();
drawShadow((int) currentX, canvas);
}
}
private void drawShadow(int left, Canvas canvas) {
GradientDrawable drawable = readAnimView.getAnimHelper().getCoverGradientDrawable();
drawable.setBounds(left, 0, left + shadowWidth, vHeight);
drawable.draw(canvas);
}
private Path getPathAToLeft() {
pathA.reset();
float x = vWidth - (downX - currentX);
x = Math.min(vWidth, x);
pathA.lineTo(x, 0);
pathA.lineTo(x, vHeight);
pathA.lineTo(0, vHeight);
pathA.close();
return pathA;
}
private Path getPathB() {
pathB.reset();
float x = vWidth - (downX - currentX);
x = Math.min(vWidth, x);
pathB.moveTo(x, 0);
pathB.lineTo(vWidth, 0);
pathB.lineTo(vWidth, vHeight);
pathB.lineTo(x, vHeight);
pathB.close();
return pathB;
}
private Path getPathAToRight() {
pathA.reset();
pathA.lineTo(currentX, 0);
pathA.lineTo(currentX, vHeight);
pathA.lineTo(0, vHeight);
pathA.close();
return pathA;
}
private boolean checkDownArea(int downArea) {
return downArea != DOWN_AREA_MENU && downArea != DOWN_AREA_NONE;
}
private boolean checkAnimCondition(int slideDirection) {
if (slideDirection == AnimHelper.SLID_DIRECTION_LEFT && (null != readAnimView.getNextBitmap() && null != readAnimView.getCurrentBitmap())) {
return true;
} else if (slideDirection == AnimHelper.SLID_DIRECTION_RIGHT && null != readAnimView.getPreviousBitmap()) {
return true;
}
return false;
}
@Override
public boolean animInEffect() {
return isTouching || coverAnimationRunning;
}
@Override
public void onViewSizeChanged(int vWidth, int vHeight) {
this.vWidth = vWidth;
this.vHeight = vHeight;
menuBounds.left = vWidth / 3F;
menuBounds.top = vHeight / 3F;
menuBounds.right = vWidth * 2 / 3F;
menuBounds.bottom = vHeight * 2 / 3F;
}
@Override
public void onViewAttachedToWindow() {
}
@Override
public void onViewDetachedFromWindow() {
readAnimView.removeCallbacks(scrollRunnable);
}
private void invalidate() {
readAnimView.postInvalidate();
}
@Override
public void onScroll() {
if (scroller.computeScrollOffset()) {
int x = scroller.getCurrX();
int y = scroller.getCurrY();
if (x == scroller.getFinalX() && y == scroller.getFinalY()) {
scroller.forceFinished(true);
//补一点时间,避免动画太快结束,提供两次动画触发间隔
DLog.log("coverAnimationRunning coverAnimationRunning=%s 结束,延时开启 状态重置", coverAnimationRunning);
readAnimView.post(scrollRunnable);
} else {
currentX = x;
invalidate();
}
}
}
protected class ScrollRunnable implements Runnable {
@Override
public void run() {
readAnimView.reset();
coverAnimationRunning = false;
if (!isCancelFlip) {
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT) {
readAnimView.onExpectNext();
} else if (coverSlideDirection == AnimHelper.SLID_DIRECTION_RIGHT) {
readAnimView.onExpectPrevious();
}
}
invalidate();
}
}
}
| app/src/main/java/com/juziml/read/business/read/anim/CoverAnimationEffecter.java | Western-parotia-BookViewProject-1727e80 | [
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " canvas.restore();\n canvas.save();\n canvas.clipPath(pathC, Region.Op.DIFFERENCE);\n canvas.clipPath(pathA, Region.Op.DIFFERENCE);\n canvas.drawBitmap(nextBitmap, 0, 0, bitmapPaint);//绘制B区\n canvas.restore();\n } else {\n //对Bitmap进行取色\n int color = preBitmap.getPixel(1, 1);\n //获取对应的三色",
"score": 0.8519843816757202
},
{
"filename": "gpu_test/src/main/java/com/juziml/content/gpu_test/GpuTestCurlAnimView.java",
"retrieved_chunk": " @Override\n protected void onDraw(Canvas canvas) {\n super.onDraw(canvas);\n if (a.x == -1 && a.y == -1) {\n canvas.drawPath(getDefaultPath(), pathAPaint);\n } else {\n Path pathA = getPathAFromRightTop();\n if (f.x == width && f.y == height) {\n pathA = getPathAFromRightBottom();\n }",
"score": 0.8445627689361572
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " private void touchMoveAndInvalidate(float x, float y, int curlSlideDirection, boolean offset) {\n touchMove(x, y, curlSlideDirection, offset, true);\n }\n private void drawShaDow(Canvas canvas, Path pathA, Path pathC) {\n drawPathARightShadow(canvas, pathA);\n drawPathALeftShadow(canvas, pathA);\n drawPathBShadow(canvas, pathA, pathC);\n drawPathCShadow(canvas, pathA);\n }\n private void drawContent(Canvas canvas, Path pathA, Path pathC, Bitmap curBitmap, Bitmap nextBitmap, Bitmap preBitmap) {",
"score": 0.8405647277832031
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " pathA = getPathAFromRightTop();\n } else {\n pathA = getPathAFromRightBottom();\n }\n Path pathC = getPathC();\n drawContent(canvas, pathA, pathC, readAnimView.getCurrentBitmap(), readAnimView.getNextBitmap(), readAnimView.getPreviousBitmap());\n drawShaDow(canvas, pathA, pathC);\n }\n @Override\n public boolean animInEffect() {",
"score": 0.8395871520042419
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " GradientDrawable gradientDrawable;\n if (downArea == DOWN_AREA_TOP_RIGHT && curlSlideDirection == AnimHelper.SLID_DIRECTION_LEFT) {\n gradientDrawable = readAnimView.getAnimHelper().getTopLeftGradientDrawable();\n left = (int) (e.x - lPathAShadowDis / 2);\n right = (int) (e.x);\n } else {\n gradientDrawable = readAnimView.getAnimHelper().getBottomLeftGradientDrawable();\n left = (int) (e.x);\n right = (int) (e.x + lPathAShadowDis / 2);\n }",
"score": 0.8263347148895264
}
] | java | (readAnimView.getPreviousBitmap(), -leftOffset, 0, paint); |
package com.juziml.read.business.read.anim;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.drawable.GradientDrawable;
import android.view.MotionEvent;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.Scroller;
import com.juziml.read.business.read.view.PuppetView;
import com.juziml.read.utils.DLog;
import java.util.LinkedList;
import java.util.List;
/**
* create by zhusw on 2020-08-24 14:06
*/
public class CoverAnimationEffecter implements IAnimationEffecter {
private final static int DOWN_AREA_NONE = -1;
private final static int DOWN_AREA_MENU = 1;
private final static int DOWN_AREA_LEFT = 2;
private final static int DOWN_AREA_RIGHT = 3;
int vWidth = 1;
int vHeight = 1;
private final PuppetView readAnimView;
private boolean isCancelFlip = false;
private boolean coverAnimationRunning = false;
private boolean isTouching = false;
private final Scroller scroller;
private final ScrollRunnable scrollRunnable;
private final RectF menuBounds;
private final Path pathA;
private final Path pathB;
private final Paint paint;
private final int shadowWidth;
public CoverAnimationEffecter(PuppetView readAnimView) {
this.readAnimView = readAnimView;
scroller = new Scroller(readAnimView.getContext(), new AccelerateDecelerateInterpolator());
scrollRunnable = new ScrollRunnable();
menuBounds = new RectF();
pathA = new Path();
pathB = new Path();
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
shadowWidth = 20;
}
private int downArea = DOWN_AREA_NONE;
private float downX = 0F;
private int coverSlideDirection = AnimHelper.SLID_DIRECTION_UNKNOWN;
private final List<Float> moveSampling = new LinkedList<>();
private final int MAX_COUNT = 5;
private boolean prepareDrawCoverAnimEffect = false;
private float currentX = -1;
@Override
public void handlerEvent(MotionEvent event) {
if (coverAnimationRunning) return;
float x = event.getRawX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
moveSampling.clear();
downX = x;
prepareDrawCoverAnimEffect = false;
isTouching = true;
currentX = -1;
downArea = DOWN_AREA_NONE;
coverSlideDirection = AnimHelper.SLID_DIRECTION_UNKNOWN;
if (x > menuBounds.left && y > menuBounds.top
&& x < menuBounds.right && y < menuBounds.bottom) {
downArea = DOWN_AREA_MENU;
} else if (x < vWidth / 2F) {
downArea = DOWN_AREA_LEFT;
} else {
downArea = DOWN_AREA_RIGHT;
}
break;
case MotionEvent.ACTION_MOVE:
isTouching = true;
float curDistance = x - downX;
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_UNKNOWN && checkDownArea(downArea)) {
if (curDistance > 0) {
coverSlideDirection = AnimHelper.SLID_DIRECTION_RIGHT;
} else {
coverSlideDirection = AnimHelper.SLID_DIRECTION_LEFT;
}
readAnimView.buildBitmap(coverSlideDirection);
prepareDrawCoverAnimEffect = checkAnimCondition(coverSlideDirection);
}
if (prepareDrawCoverAnimEffect) {
if (moveSampling.size() == 0
|| x != moveSampling.get(moveSampling.size() - 1)) {
moveSampling.add(x);
}
if (moveSampling.size() > MAX_COUNT) {
moveSampling.remove(0);
}
currentX = x;
invalidate();
}
break;
case MotionEvent.ACTION_CANCEL:
isTouching = false;
break;
case MotionEvent.ACTION_UP:
currentX = x;
if (prepareDrawCoverAnimEffect) {
if (moveSampling.size() > 0) {
float lastMoveX = moveSampling.get(moveSampling.size() - 1);
float firstMoveX = moveSampling.get(0);
float finallyMoveX = lastMoveX - firstMoveX;
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT) {
boolean lastFingerLeftSlop = finallyMoveX < 10;
touchUp(lastFingerLeftSlop);
} else if (coverSlideDirection == AnimHelper.SLID_DIRECTION_RIGHT) {
finallyMoveX = lastMoveX - firstMoveX;
touchUp(finallyMoveX < 0);
}
} else {
touchUp(false);
}
} else if (downArea == DOWN_AREA_MENU) {
if (x > menuBounds.left && x < menuBounds.right
&& y > menuBounds.top && y < menuBounds.bottom) {
readAnimView.onClickMenuArea();
}
} else if (downArea != DOWN_AREA_NONE) {
if (x == downX && downX >= vWidth / 2F) {//下一页
coverSlideDirection = AnimHelper.SLID_DIRECTION_LEFT;
readAnimView.buildBitmap(coverSlideDirection);
if (checkAnimCondition(coverSlideDirection)) {
touchUp(true);
}
} else if (x == downX && downX < vWidth / 2F) {//上一页
coverSlideDirection = AnimHelper.SLID_DIRECTION_RIGHT;
readAnimView.buildBitmap(coverSlideDirection);
if (checkAnimCondition(coverSlideDirection)) {
touchUp(false);
}
}
}
moveSampling.clear();
isTouching = false;
break;
default:
break;
}
}
private void touchUp(boolean lastFingerLeftSlop) {
DLog.log("touchUp coverAnimationRunning=%s", coverAnimationRunning);
coverAnimationRunning = true;
isCancelFlip = (coverSlideDirection == AnimHelper.SLID_DIRECTION_RIGHT && lastFingerLeftSlop)
|| (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT && !lastFingerLeftSlop);
int duration = isCancelFlip ? AnimHelper.CANCEL_ANIM_DURATION : AnimHelper.RELAY_ANIM_DURATION;
duration = (int) (duration * 0.7F);//cover动画时间减少一点
// duration = 1000;//cover动画时间减少一点
int startX = (int) currentX;
int startY = 0;
int dy = 0;
int dx;
if (lastFingerLeftSlop) {
dx = (int) -(vWidth - (downX - currentX));
} else {
dx = vWidth - (int) currentX;
}
scroller.startScroll(startX, startY, dx, dy, duration);
invalidate();
}
@Override
public void draw(Canvas canvas) {
if (currentX == -1) {
DLog.log("CoverAnimationEffect draw 1");
return;
}
if (coverSlideDirection != AnimHelper.SLID_DIRECTION_LEFT && coverSlideDirection != AnimHelper.SLID_DIRECTION_RIGHT) {
DLog.log("CoverAnimationEffect draw 2");
return;
}
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT
&& (null == readAnimView.getCurrentBitmap() || null == readAnimView.getNextBitmap())) {
DLog.log("CoverAnimationEffect draw 3");
return;
}
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_RIGHT && null == readAnimView.getPreviousBitmap()) {
DLog.log("CoverAnimationEffect draw 4");
return;
}
DLog.log("CoverAnimationEffect draw 5");
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT) {
float offset = downX - currentX;
offset = Math.max(0, offset);
canvas.save();
canvas.clipPath(getPathAToLeft());
canvas.drawBitmap(readAnimView.getCurrentBitmap(), -offset, 0, paint);
canvas.restore();
canvas.save();
canvas.clipPath(getPathB());
canvas.drawBitmap(readAnimView.getNextBitmap(), 0, 0, paint);
canvas.restore();
drawShadow((int) (vWidth - offset), canvas);
} else {
float leftOffset = vWidth - currentX;
canvas.save();
canvas.clipPath(getPathAToRight());
canvas.drawBitmap(readAnimView.getPreviousBitmap(), -leftOffset, 0, paint);
canvas.restore();
drawShadow((int) currentX, canvas);
}
}
private void drawShadow(int left, Canvas canvas) {
GradientDrawable drawable = readAnimView.getAnimHelper().getCoverGradientDrawable();
drawable.setBounds(left, 0, left + shadowWidth, vHeight);
drawable.draw(canvas);
}
private Path getPathAToLeft() {
pathA.reset();
float x = vWidth - (downX - currentX);
x = Math.min(vWidth, x);
pathA.lineTo(x, 0);
pathA.lineTo(x, vHeight);
pathA.lineTo(0, vHeight);
pathA.close();
return pathA;
}
private Path getPathB() {
pathB.reset();
float x = vWidth - (downX - currentX);
x = Math.min(vWidth, x);
pathB.moveTo(x, 0);
pathB.lineTo(vWidth, 0);
pathB.lineTo(vWidth, vHeight);
pathB.lineTo(x, vHeight);
pathB.close();
return pathB;
}
private Path getPathAToRight() {
pathA.reset();
pathA.lineTo(currentX, 0);
pathA.lineTo(currentX, vHeight);
pathA.lineTo(0, vHeight);
pathA.close();
return pathA;
}
private boolean checkDownArea(int downArea) {
return downArea != DOWN_AREA_MENU && downArea != DOWN_AREA_NONE;
}
private boolean checkAnimCondition(int slideDirection) {
if | (slideDirection == AnimHelper.SLID_DIRECTION_LEFT && (null != readAnimView.getNextBitmap() && null != readAnimView.getCurrentBitmap())) { |
return true;
} else if (slideDirection == AnimHelper.SLID_DIRECTION_RIGHT && null != readAnimView.getPreviousBitmap()) {
return true;
}
return false;
}
@Override
public boolean animInEffect() {
return isTouching || coverAnimationRunning;
}
@Override
public void onViewSizeChanged(int vWidth, int vHeight) {
this.vWidth = vWidth;
this.vHeight = vHeight;
menuBounds.left = vWidth / 3F;
menuBounds.top = vHeight / 3F;
menuBounds.right = vWidth * 2 / 3F;
menuBounds.bottom = vHeight * 2 / 3F;
}
@Override
public void onViewAttachedToWindow() {
}
@Override
public void onViewDetachedFromWindow() {
readAnimView.removeCallbacks(scrollRunnable);
}
private void invalidate() {
readAnimView.postInvalidate();
}
@Override
public void onScroll() {
if (scroller.computeScrollOffset()) {
int x = scroller.getCurrX();
int y = scroller.getCurrY();
if (x == scroller.getFinalX() && y == scroller.getFinalY()) {
scroller.forceFinished(true);
//补一点时间,避免动画太快结束,提供两次动画触发间隔
DLog.log("coverAnimationRunning coverAnimationRunning=%s 结束,延时开启 状态重置", coverAnimationRunning);
readAnimView.post(scrollRunnable);
} else {
currentX = x;
invalidate();
}
}
}
protected class ScrollRunnable implements Runnable {
@Override
public void run() {
readAnimView.reset();
coverAnimationRunning = false;
if (!isCancelFlip) {
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT) {
readAnimView.onExpectNext();
} else if (coverSlideDirection == AnimHelper.SLID_DIRECTION_RIGHT) {
readAnimView.onExpectPrevious();
}
}
invalidate();
}
}
}
| app/src/main/java/com/juziml/read/business/read/anim/CoverAnimationEffecter.java | Western-parotia-BookViewProject-1727e80 | [
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " if (curlSlideDirection == AnimHelper.SLID_DIRECTION_LEFT && (null != readAnimView.getNextBitmap() && null != readAnimView.getCurrentBitmap())) {\n return true;\n } else if (curlSlideDirection == AnimHelper.SLID_DIRECTION_RIGHT && null != readAnimView.getPreviousBitmap()) {\n return true;\n }\n return false;\n }\n public void touchDown(int downArea, int curlSlideDirection) {\n //判断触摸起始点位置,确定f点\n if (downArea == DOWN_AREA_TOP_RIGHT && curlSlideDirection == AnimHelper.SLID_DIRECTION_LEFT) {",
"score": 0.9222801327705383
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " return;\n }\n if (curlSlideDirection == AnimHelper.SLID_DIRECTION_LEFT && (null == readAnimView.getCurrentBitmap() || null == readAnimView.getNextBitmap())) {\n return;\n }\n if (curlSlideDirection == AnimHelper.SLID_DIRECTION_RIGHT && null == readAnimView.getPreviousBitmap()) {\n return;\n }\n Path pathA;\n if (f.x == vWidth && f.y == 0) {",
"score": 0.9107262492179871
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " private int curlSlideDirection = AnimHelper.SLID_DIRECTION_UNKNOWN;\n private final List<Float> moveSampling = new LinkedList<>();\n private final int MAX_COUNT = 5;\n private boolean drawCurlAnimBefore = false;\n private boolean checkDownArea(int downArea) {\n return downArea != DOWN_AREA_MENU && downArea != DOWN_AREA_NONE;\n }\n private boolean checkAnimCondition(int curlSlideDirection, int downArea) {\n boolean notAtSlideArea = !checkDownArea(downArea);\n if (curlAnimationRunning || notAtSlideArea) return false;",
"score": 0.8940922021865845
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/PuppetView.java",
"retrieved_chunk": " result = Math.min(result, specSize);\n }\n return result;\n }\n public void buildBitmap(int slideDirection) {\n performDrawCurlTexture = false;\n if (slideDirection == AnimHelper.SLID_DIRECTION_LEFT) {\n currentViewBitmap = parentView.getCurrentBitmap();\n nextViewBitmap = parentView.getNextBitmap();\n } else if (slideDirection == AnimHelper.SLID_DIRECTION_RIGHT) {",
"score": 0.8839154243469238
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " }\n } else if (downArea != DOWN_AREA_NONE) {\n if (x == downX && downX >= vWidth / 2F) {//下一页\n curlSlideDirection = AnimHelper.SLID_DIRECTION_LEFT;\n touchDown(downArea, curlSlideDirection);\n readAnimView.buildBitmap(curlSlideDirection);\n if (checkAnimCondition(curlSlideDirection, downArea)) {\n touchMove(x, y, curlSlideDirection, true, false);\n touchUp(true);\n }",
"score": 0.8728382587432861
}
] | java | (slideDirection == AnimHelper.SLID_DIRECTION_LEFT && (null != readAnimView.getNextBitmap() && null != readAnimView.getCurrentBitmap())) { |
/*
* Copyright 2017 JessYan
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.foundation.service.urlmanager.retrofiturlmanager.parser;
import android.text.TextUtils;
import com.foundation.service.urlmanager.retrofiturlmanager.RetrofitUrlManager;
import com.foundation.service.urlmanager.retrofiturlmanager.cache.Cache;
import com.foundation.service.urlmanager.retrofiturlmanager.cache.LruCache;
import java.util.ArrayList;
import java.util.List;
import okhttp3.HttpUrl;
/**
* ================================================
* 高级解析器, 当 BaseUrl 中有除了域名以外的其他 Path 时, 可使用此解析器
* <p>
* 比如:
* 1.
* 旧 URL 地址为 https://www.github.com/wiki/part, 您在 App 初始化时传入 {@link RetrofitUrlManager#startAdvancedModel(String)}
* 的 BaseUrl 为 https://www.github.com/wiki
* 您调用 {@link RetrofitUrlManager#putDomain(String, String)} 方法传入的 URL 地址是 https://www.google.com/api
* 经过本解析器解析后生成的新 URL 地址为 http://www.google.com/api/part
* <p>
* 2.
* 旧 URL 地址为 https://www.github.com/wiki/part, 您在 App 初始化时传入 {@link RetrofitUrlManager#startAdvancedModel(String)}
* 的 BaseUrl 为 https://www.github.com/wiki
* 您调用 {@link RetrofitUrlManager#putDomain(String, String)} 方法传入的 URL 地址是 https://www.google.com
* 经过本解析器解析后生成的新 URL 地址为 http://www.google.com/part
* <p>
* 3.
* 旧 URL 地址为 https://www.github.com/wiki/part, 您在 App 初始化时传入 {@link RetrofitUrlManager#startAdvancedModel(String)}
* 的 BaseUrl 为 https://www.github.com
* 您调用 {@link RetrofitUrlManager#putDomain(String, String)} 方法传入的 URL 地址是 https://www.google.com/api
* 经过本解析器解析后生成的新 URL 地址为 http://www.google.com/api/wiki/part
* <p>
* 解析器会将 BaseUrl 全部替换成您传入的 Url 地址
*
* @see UrlParser
* Created by JessYan on 09/06/2018 16:00
* <a href="mailto:[email protected]">Contact me</a>
* <a href="https://github.com/JessYanCoding">Follow me</a>
* ================================================
*/
public class AdvancedUrlParser implements UrlParser {
private RetrofitUrlManager mRetrofitUrlManager;
private Cache<String, String> mCache;
@Override
public void init(RetrofitUrlManager retrofitUrlManager) {
this.mRetrofitUrlManager = retrofitUrlManager;
this.mCache = new LruCache<>(100);
}
@Override
public HttpUrl parseUrl(HttpUrl domainUrl, HttpUrl url) {
if (null == domainUrl) return url;
HttpUrl.Builder builder = url.newBuilder();
if (TextUtils.isEmpty(mCache.get(getKey(domainUrl, url)))) {
for (int i = 0; i < url.pathSize(); i++) {
//当删除了上一个 index, PathSegment 的 item 会自动前进一位, 所以 remove(0) 就好
builder.removePathSegment(0);
}
List<String> newPathSegments = new ArrayList<>();
newPathSegments.addAll(domainUrl.encodedPathSegments());
if (url.pathSize() > mRetrofitUrlManager.getPathSize()) {
List<String> encodedPathSegments = url.encodedPathSegments();
for (int i = mRetrofitUrlManager.getPathSize(); i < encodedPathSegments.size(); i++) {
newPathSegments.add(encodedPathSegments.get(i));
}
} else if (url.pathSize() < mRetrofitUrlManager.getPathSize()) {
throw new IllegalArgumentException(String.format("Your final path is %s, but the baseUrl of your RetrofitUrlManager#startAdvancedModel is %s",
url.scheme() + "://" + url.host() + url.encodedPath(),
mRetrofitUrlManager.getBaseUrl().scheme() + "://"
| + mRetrofitUrlManager.getBaseUrl().host()
+ mRetrofitUrlManager.getBaseUrl().encodedPath())); |
}
for (String PathSegment : newPathSegments) {
builder.addEncodedPathSegment(PathSegment);
}
} else {
builder.encodedPath(mCache.get(getKey(domainUrl, url)));
}
HttpUrl httpUrl = builder
.scheme(domainUrl.scheme())
.host(domainUrl.host())
.port(domainUrl.port())
.build();
if (TextUtils.isEmpty(mCache.get(getKey(domainUrl, url)))) {
mCache.put(getKey(domainUrl, url), httpUrl.encodedPath());
}
return httpUrl;
}
private String getKey(HttpUrl domainUrl, HttpUrl url) {
return domainUrl.encodedPath() + url.encodedPath()
+ mRetrofitUrlManager.getPathSize();
}
}
| net/src/main/java/com/foundation/service/urlmanager/retrofiturlmanager/parser/AdvancedUrlParser.java | Western-parotia-Net-accd348 | [
{
"filename": "net/src/main/java/com/foundation/service/urlmanager/retrofiturlmanager/parser/SuperUrlParser.java",
"retrieved_chunk": " } else if (url.pathSize() < pathSize) {\n throw new IllegalArgumentException(String.format(\n \"Your final path is %s, the pathSize = %d, but the #baseurl_path_size = %d, #baseurl_path_size must be less than or equal to pathSize of the final path\",\n url.scheme() + \"://\" + url.host() + url.encodedPath(), url.pathSize(), pathSize));\n }\n for (String PathSegment : newPathSegments) {\n builder.addEncodedPathSegment(PathSegment);\n }\n } else {\n builder.encodedPath(mCache.get(getKey(domainUrl, url, pathSize)));",
"score": 0.831122636795044
},
{
"filename": "net/src/main/java/com/foundation/service/urlmanager/retrofiturlmanager/parser/DomainUrlParser.java",
"retrieved_chunk": " List<String> newPathSegments = new ArrayList<>();\n newPathSegments.addAll(domainUrl.encodedPathSegments());\n newPathSegments.addAll(url.encodedPathSegments());\n for (String PathSegment : newPathSegments) {\n builder.addEncodedPathSegment(PathSegment);\n }\n } else {\n builder.encodedPath(mCache.get(getKey(domainUrl, url)));\n }\n HttpUrl httpUrl = builder",
"score": 0.8215035200119019
},
{
"filename": "net/src/main/java/com/foundation/service/urlmanager/retrofiturlmanager/parser/SuperUrlParser.java",
"retrieved_chunk": " //当删除了上一个 index, PathSegment 的 item 会自动前进一位, 所以 remove(0) 就好\n builder.removePathSegment(0);\n }\n List<String> newPathSegments = new ArrayList<>();\n newPathSegments.addAll(domainUrl.encodedPathSegments());\n if (url.pathSize() > pathSize) {\n List<String> encodedPathSegments = url.encodedPathSegments();\n for (int i = pathSize; i < encodedPathSegments.size(); i++) {\n newPathSegments.add(encodedPathSegments.get(i));\n }",
"score": 0.8041986227035522
},
{
"filename": "net/src/main/java/com/foundation/service/urlmanager/retrofiturlmanager/parser/SuperUrlParser.java",
"retrieved_chunk": " }\n HttpUrl httpUrl = builder\n .scheme(domainUrl.scheme())\n .host(domainUrl.host())\n .port(domainUrl.port())\n .build();\n if (TextUtils.isEmpty(mCache.get(getKey(domainUrl, url, pathSize)))) {\n mCache.put(getKey(domainUrl, url, pathSize), httpUrl.encodedPath());\n }\n return httpUrl;",
"score": 0.7999269962310791
},
{
"filename": "net/src/main/java/com/foundation/service/urlmanager/retrofiturlmanager/parser/DomainUrlParser.java",
"retrieved_chunk": " .scheme(domainUrl.scheme())\n .host(domainUrl.host())\n .port(domainUrl.port())\n .build();\n if (TextUtils.isEmpty(mCache.get(getKey(domainUrl, url)))) {\n mCache.put(getKey(domainUrl, url), httpUrl.encodedPath());\n }\n return httpUrl;\n }\n private String getKey(HttpUrl domainUrl, HttpUrl url) {",
"score": 0.7909090518951416
}
] | java | + mRetrofitUrlManager.getBaseUrl().host()
+ mRetrofitUrlManager.getBaseUrl().encodedPath())); |
/*
* Copyright 2017 JessYan
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.foundation.service.urlmanager.retrofiturlmanager.parser;
import android.text.TextUtils;
import com.foundation.service.urlmanager.retrofiturlmanager.RetrofitUrlManager;
import com.foundation.service.urlmanager.retrofiturlmanager.cache.Cache;
import com.foundation.service.urlmanager.retrofiturlmanager.cache.LruCache;
import java.util.ArrayList;
import java.util.List;
import okhttp3.HttpUrl;
/**
* ================================================
* 高级解析器, 当 BaseUrl 中有除了域名以外的其他 Path 时, 可使用此解析器
* <p>
* 比如:
* 1.
* 旧 URL 地址为 https://www.github.com/wiki/part, 您在 App 初始化时传入 {@link RetrofitUrlManager#startAdvancedModel(String)}
* 的 BaseUrl 为 https://www.github.com/wiki
* 您调用 {@link RetrofitUrlManager#putDomain(String, String)} 方法传入的 URL 地址是 https://www.google.com/api
* 经过本解析器解析后生成的新 URL 地址为 http://www.google.com/api/part
* <p>
* 2.
* 旧 URL 地址为 https://www.github.com/wiki/part, 您在 App 初始化时传入 {@link RetrofitUrlManager#startAdvancedModel(String)}
* 的 BaseUrl 为 https://www.github.com/wiki
* 您调用 {@link RetrofitUrlManager#putDomain(String, String)} 方法传入的 URL 地址是 https://www.google.com
* 经过本解析器解析后生成的新 URL 地址为 http://www.google.com/part
* <p>
* 3.
* 旧 URL 地址为 https://www.github.com/wiki/part, 您在 App 初始化时传入 {@link RetrofitUrlManager#startAdvancedModel(String)}
* 的 BaseUrl 为 https://www.github.com
* 您调用 {@link RetrofitUrlManager#putDomain(String, String)} 方法传入的 URL 地址是 https://www.google.com/api
* 经过本解析器解析后生成的新 URL 地址为 http://www.google.com/api/wiki/part
* <p>
* 解析器会将 BaseUrl 全部替换成您传入的 Url 地址
*
* @see UrlParser
* Created by JessYan on 09/06/2018 16:00
* <a href="mailto:[email protected]">Contact me</a>
* <a href="https://github.com/JessYanCoding">Follow me</a>
* ================================================
*/
public class AdvancedUrlParser implements UrlParser {
private RetrofitUrlManager mRetrofitUrlManager;
private Cache<String, String> mCache;
@Override
public void init(RetrofitUrlManager retrofitUrlManager) {
this.mRetrofitUrlManager = retrofitUrlManager;
this.mCache = new LruCache<>(100);
}
@Override
public HttpUrl parseUrl(HttpUrl domainUrl, HttpUrl url) {
if (null == domainUrl) return url;
HttpUrl.Builder builder = url.newBuilder();
if (TextUtils.isEmpty(mCache.get(getKey(domainUrl, url)))) {
for (int i = 0; i < url.pathSize(); i++) {
//当删除了上一个 index, PathSegment 的 item 会自动前进一位, 所以 remove(0) 就好
builder.removePathSegment(0);
}
List<String> newPathSegments = new ArrayList<>();
newPathSegments.addAll(domainUrl.encodedPathSegments());
if (url.pathSize | () > mRetrofitUrlManager.getPathSize()) { |
List<String> encodedPathSegments = url.encodedPathSegments();
for (int i = mRetrofitUrlManager.getPathSize(); i < encodedPathSegments.size(); i++) {
newPathSegments.add(encodedPathSegments.get(i));
}
} else if (url.pathSize() < mRetrofitUrlManager.getPathSize()) {
throw new IllegalArgumentException(String.format("Your final path is %s, but the baseUrl of your RetrofitUrlManager#startAdvancedModel is %s",
url.scheme() + "://" + url.host() + url.encodedPath(),
mRetrofitUrlManager.getBaseUrl().scheme() + "://"
+ mRetrofitUrlManager.getBaseUrl().host()
+ mRetrofitUrlManager.getBaseUrl().encodedPath()));
}
for (String PathSegment : newPathSegments) {
builder.addEncodedPathSegment(PathSegment);
}
} else {
builder.encodedPath(mCache.get(getKey(domainUrl, url)));
}
HttpUrl httpUrl = builder
.scheme(domainUrl.scheme())
.host(domainUrl.host())
.port(domainUrl.port())
.build();
if (TextUtils.isEmpty(mCache.get(getKey(domainUrl, url)))) {
mCache.put(getKey(domainUrl, url), httpUrl.encodedPath());
}
return httpUrl;
}
private String getKey(HttpUrl domainUrl, HttpUrl url) {
return domainUrl.encodedPath() + url.encodedPath()
+ mRetrofitUrlManager.getPathSize();
}
}
| net/src/main/java/com/foundation/service/urlmanager/retrofiturlmanager/parser/AdvancedUrlParser.java | Western-parotia-Net-accd348 | [
{
"filename": "net/src/main/java/com/foundation/service/urlmanager/retrofiturlmanager/parser/SuperUrlParser.java",
"retrieved_chunk": " //当删除了上一个 index, PathSegment 的 item 会自动前进一位, 所以 remove(0) 就好\n builder.removePathSegment(0);\n }\n List<String> newPathSegments = new ArrayList<>();\n newPathSegments.addAll(domainUrl.encodedPathSegments());\n if (url.pathSize() > pathSize) {\n List<String> encodedPathSegments = url.encodedPathSegments();\n for (int i = pathSize; i < encodedPathSegments.size(); i++) {\n newPathSegments.add(encodedPathSegments.get(i));\n }",
"score": 0.9198039770126343
},
{
"filename": "net/src/main/java/com/foundation/service/urlmanager/retrofiturlmanager/parser/SuperUrlParser.java",
"retrieved_chunk": " this.mRetrofitUrlManager = retrofitUrlManager;\n this.mCache = new LruCache<>(100);\n }\n @Override\n public HttpUrl parseUrl(HttpUrl domainUrl, HttpUrl url) {\n if (null == domainUrl) return url;\n HttpUrl.Builder builder = url.newBuilder();\n int pathSize = resolvePathSize(url, builder);\n if (TextUtils.isEmpty(mCache.get(getKey(domainUrl, url, pathSize)))) {\n for (int i = 0; i < url.pathSize(); i++) {",
"score": 0.8610703945159912
},
{
"filename": "net/src/main/java/com/foundation/service/urlmanager/retrofiturlmanager/parser/DomainUrlParser.java",
"retrieved_chunk": " List<String> newPathSegments = new ArrayList<>();\n newPathSegments.addAll(domainUrl.encodedPathSegments());\n newPathSegments.addAll(url.encodedPathSegments());\n for (String PathSegment : newPathSegments) {\n builder.addEncodedPathSegment(PathSegment);\n }\n } else {\n builder.encodedPath(mCache.get(getKey(domainUrl, url)));\n }\n HttpUrl httpUrl = builder",
"score": 0.8514898419380188
},
{
"filename": "net/src/main/java/com/foundation/service/urlmanager/retrofiturlmanager/parser/DomainUrlParser.java",
"retrieved_chunk": " // 如果 HttpUrl.parse(url); 解析为 null 说明,url 格式不正确,正确的格式为 \"https://github.com:443\"\n // http 默认端口 80, https 默认端口 443, 如果端口号是默认端口号就可以将 \":443\" 去掉\n // 只支持 http 和 https\n if (null == domainUrl) return url;\n HttpUrl.Builder builder = url.newBuilder();\n if (TextUtils.isEmpty(mCache.get(getKey(domainUrl, url)))) {\n for (int i = 0; i < url.pathSize(); i++) {\n //当删除了上一个 index, PathSegment 的 item 会自动前进一位, 所以 remove(0) 就好\n builder.removePathSegment(0);\n }",
"score": 0.8328583240509033
},
{
"filename": "net/src/main/java/com/foundation/service/urlmanager/retrofiturlmanager/parser/SuperUrlParser.java",
"retrieved_chunk": " } else if (url.pathSize() < pathSize) {\n throw new IllegalArgumentException(String.format(\n \"Your final path is %s, the pathSize = %d, but the #baseurl_path_size = %d, #baseurl_path_size must be less than or equal to pathSize of the final path\",\n url.scheme() + \"://\" + url.host() + url.encodedPath(), url.pathSize(), pathSize));\n }\n for (String PathSegment : newPathSegments) {\n builder.addEncodedPathSegment(PathSegment);\n }\n } else {\n builder.encodedPath(mCache.get(getKey(domainUrl, url, pathSize)));",
"score": 0.8159909844398499
}
] | java | () > mRetrofitUrlManager.getPathSize()) { |
package com.juziml.read.business.read.anim;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.drawable.GradientDrawable;
import android.view.MotionEvent;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.Scroller;
import com.juziml.read.business.read.view.PuppetView;
import com.juziml.read.utils.DLog;
import java.util.LinkedList;
import java.util.List;
/**
* create by zhusw on 2020-08-24 14:06
*/
public class CoverAnimationEffecter implements IAnimationEffecter {
private final static int DOWN_AREA_NONE = -1;
private final static int DOWN_AREA_MENU = 1;
private final static int DOWN_AREA_LEFT = 2;
private final static int DOWN_AREA_RIGHT = 3;
int vWidth = 1;
int vHeight = 1;
private final PuppetView readAnimView;
private boolean isCancelFlip = false;
private boolean coverAnimationRunning = false;
private boolean isTouching = false;
private final Scroller scroller;
private final ScrollRunnable scrollRunnable;
private final RectF menuBounds;
private final Path pathA;
private final Path pathB;
private final Paint paint;
private final int shadowWidth;
public CoverAnimationEffecter(PuppetView readAnimView) {
this.readAnimView = readAnimView;
scroller = new Scroller(readAnimView.getContext(), new AccelerateDecelerateInterpolator());
scrollRunnable = new ScrollRunnable();
menuBounds = new RectF();
pathA = new Path();
pathB = new Path();
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
shadowWidth = 20;
}
private int downArea = DOWN_AREA_NONE;
private float downX = 0F;
private int coverSlideDirection = AnimHelper.SLID_DIRECTION_UNKNOWN;
private final List<Float> moveSampling = new LinkedList<>();
private final int MAX_COUNT = 5;
private boolean prepareDrawCoverAnimEffect = false;
private float currentX = -1;
@Override
public void handlerEvent(MotionEvent event) {
if (coverAnimationRunning) return;
float x = event.getRawX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
moveSampling.clear();
downX = x;
prepareDrawCoverAnimEffect = false;
isTouching = true;
currentX = -1;
downArea = DOWN_AREA_NONE;
coverSlideDirection = AnimHelper.SLID_DIRECTION_UNKNOWN;
if (x > menuBounds.left && y > menuBounds.top
&& x < menuBounds.right && y < menuBounds.bottom) {
downArea = DOWN_AREA_MENU;
} else if (x < vWidth / 2F) {
downArea = DOWN_AREA_LEFT;
} else {
downArea = DOWN_AREA_RIGHT;
}
break;
case MotionEvent.ACTION_MOVE:
isTouching = true;
float curDistance = x - downX;
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_UNKNOWN && checkDownArea(downArea)) {
if (curDistance > 0) {
coverSlideDirection = AnimHelper.SLID_DIRECTION_RIGHT;
} else {
coverSlideDirection = AnimHelper.SLID_DIRECTION_LEFT;
}
readAnimView.buildBitmap(coverSlideDirection);
prepareDrawCoverAnimEffect = checkAnimCondition(coverSlideDirection);
}
if (prepareDrawCoverAnimEffect) {
if (moveSampling.size() == 0
|| x != moveSampling.get(moveSampling.size() - 1)) {
moveSampling.add(x);
}
if (moveSampling.size() > MAX_COUNT) {
moveSampling.remove(0);
}
currentX = x;
invalidate();
}
break;
case MotionEvent.ACTION_CANCEL:
isTouching = false;
break;
case MotionEvent.ACTION_UP:
currentX = x;
if (prepareDrawCoverAnimEffect) {
if (moveSampling.size() > 0) {
float lastMoveX = moveSampling.get(moveSampling.size() - 1);
float firstMoveX = moveSampling.get(0);
float finallyMoveX = lastMoveX - firstMoveX;
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT) {
boolean lastFingerLeftSlop = finallyMoveX < 10;
touchUp(lastFingerLeftSlop);
} else if (coverSlideDirection == AnimHelper.SLID_DIRECTION_RIGHT) {
finallyMoveX = lastMoveX - firstMoveX;
touchUp(finallyMoveX < 0);
}
} else {
touchUp(false);
}
} else if (downArea == DOWN_AREA_MENU) {
if (x > menuBounds.left && x < menuBounds.right
&& y > menuBounds.top && y < menuBounds.bottom) {
readAnimView.onClickMenuArea();
}
} else if (downArea != DOWN_AREA_NONE) {
if (x == downX && downX >= vWidth / 2F) {//下一页
coverSlideDirection = AnimHelper.SLID_DIRECTION_LEFT;
readAnimView.buildBitmap(coverSlideDirection);
if (checkAnimCondition(coverSlideDirection)) {
touchUp(true);
}
} else if (x == downX && downX < vWidth / 2F) {//上一页
coverSlideDirection = AnimHelper.SLID_DIRECTION_RIGHT;
readAnimView.buildBitmap(coverSlideDirection);
if (checkAnimCondition(coverSlideDirection)) {
touchUp(false);
}
}
}
moveSampling.clear();
isTouching = false;
break;
default:
break;
}
}
private void touchUp(boolean lastFingerLeftSlop) {
DLog.log("touchUp coverAnimationRunning=%s", coverAnimationRunning);
coverAnimationRunning = true;
isCancelFlip = (coverSlideDirection == AnimHelper.SLID_DIRECTION_RIGHT && lastFingerLeftSlop)
|| (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT && !lastFingerLeftSlop);
int duration = isCancelFlip ? AnimHelper.CANCEL_ANIM_DURATION : AnimHelper.RELAY_ANIM_DURATION;
duration = (int) (duration * 0.7F);//cover动画时间减少一点
// duration = 1000;//cover动画时间减少一点
int startX = (int) currentX;
int startY = 0;
int dy = 0;
int dx;
if (lastFingerLeftSlop) {
dx = (int) -(vWidth - (downX - currentX));
} else {
dx = vWidth - (int) currentX;
}
scroller.startScroll(startX, startY, dx, dy, duration);
invalidate();
}
@Override
public void draw(Canvas canvas) {
if (currentX == -1) {
DLog.log("CoverAnimationEffect draw 1");
return;
}
if (coverSlideDirection != AnimHelper.SLID_DIRECTION_LEFT && coverSlideDirection != AnimHelper.SLID_DIRECTION_RIGHT) {
DLog.log("CoverAnimationEffect draw 2");
return;
}
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT
&& (null == readAnimView.getCurrentBitmap() || null == readAnimView.getNextBitmap())) {
DLog.log("CoverAnimationEffect draw 3");
return;
}
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_RIGHT && null == readAnimView.getPreviousBitmap()) {
DLog.log("CoverAnimationEffect draw 4");
return;
}
DLog.log("CoverAnimationEffect draw 5");
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT) {
float offset = downX - currentX;
offset = Math.max(0, offset);
canvas.save();
canvas.clipPath(getPathAToLeft());
canvas.drawBitmap(readAnimView.getCurrentBitmap(), -offset, 0, paint);
canvas.restore();
canvas.save();
canvas.clipPath(getPathB());
canvas.drawBitmap(readAnimView.getNextBitmap(), 0, 0, paint);
canvas.restore();
drawShadow((int) (vWidth - offset), canvas);
} else {
float leftOffset = vWidth - currentX;
canvas.save();
canvas.clipPath(getPathAToRight());
canvas.drawBitmap(readAnimView.getPreviousBitmap(), -leftOffset, 0, paint);
canvas.restore();
drawShadow((int) currentX, canvas);
}
}
private void drawShadow(int left, Canvas canvas) {
GradientDrawable | drawable = readAnimView.getAnimHelper().getCoverGradientDrawable(); |
drawable.setBounds(left, 0, left + shadowWidth, vHeight);
drawable.draw(canvas);
}
private Path getPathAToLeft() {
pathA.reset();
float x = vWidth - (downX - currentX);
x = Math.min(vWidth, x);
pathA.lineTo(x, 0);
pathA.lineTo(x, vHeight);
pathA.lineTo(0, vHeight);
pathA.close();
return pathA;
}
private Path getPathB() {
pathB.reset();
float x = vWidth - (downX - currentX);
x = Math.min(vWidth, x);
pathB.moveTo(x, 0);
pathB.lineTo(vWidth, 0);
pathB.lineTo(vWidth, vHeight);
pathB.lineTo(x, vHeight);
pathB.close();
return pathB;
}
private Path getPathAToRight() {
pathA.reset();
pathA.lineTo(currentX, 0);
pathA.lineTo(currentX, vHeight);
pathA.lineTo(0, vHeight);
pathA.close();
return pathA;
}
private boolean checkDownArea(int downArea) {
return downArea != DOWN_AREA_MENU && downArea != DOWN_AREA_NONE;
}
private boolean checkAnimCondition(int slideDirection) {
if (slideDirection == AnimHelper.SLID_DIRECTION_LEFT && (null != readAnimView.getNextBitmap() && null != readAnimView.getCurrentBitmap())) {
return true;
} else if (slideDirection == AnimHelper.SLID_DIRECTION_RIGHT && null != readAnimView.getPreviousBitmap()) {
return true;
}
return false;
}
@Override
public boolean animInEffect() {
return isTouching || coverAnimationRunning;
}
@Override
public void onViewSizeChanged(int vWidth, int vHeight) {
this.vWidth = vWidth;
this.vHeight = vHeight;
menuBounds.left = vWidth / 3F;
menuBounds.top = vHeight / 3F;
menuBounds.right = vWidth * 2 / 3F;
menuBounds.bottom = vHeight * 2 / 3F;
}
@Override
public void onViewAttachedToWindow() {
}
@Override
public void onViewDetachedFromWindow() {
readAnimView.removeCallbacks(scrollRunnable);
}
private void invalidate() {
readAnimView.postInvalidate();
}
@Override
public void onScroll() {
if (scroller.computeScrollOffset()) {
int x = scroller.getCurrX();
int y = scroller.getCurrY();
if (x == scroller.getFinalX() && y == scroller.getFinalY()) {
scroller.forceFinished(true);
//补一点时间,避免动画太快结束,提供两次动画触发间隔
DLog.log("coverAnimationRunning coverAnimationRunning=%s 结束,延时开启 状态重置", coverAnimationRunning);
readAnimView.post(scrollRunnable);
} else {
currentX = x;
invalidate();
}
}
}
protected class ScrollRunnable implements Runnable {
@Override
public void run() {
readAnimView.reset();
coverAnimationRunning = false;
if (!isCancelFlip) {
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT) {
readAnimView.onExpectNext();
} else if (coverSlideDirection == AnimHelper.SLID_DIRECTION_RIGHT) {
readAnimView.onExpectPrevious();
}
}
invalidate();
}
}
}
| app/src/main/java/com/juziml/read/business/read/anim/CoverAnimationEffecter.java | Western-parotia-BookViewProject-1727e80 | [
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " pathA = getPathAFromRightTop();\n } else {\n pathA = getPathAFromRightBottom();\n }\n Path pathC = getPathC();\n drawContent(canvas, pathA, pathC, readAnimView.getCurrentBitmap(), readAnimView.getNextBitmap(), readAnimView.getPreviousBitmap());\n drawShaDow(canvas, pathA, pathC);\n }\n @Override\n public boolean animInEffect() {",
"score": 0.849885106086731
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " //转换成含有透明度的颜色\n int tempColor = Color.argb(200, red, green, blue);\n canvas.save();\n canvas.clipPath(pathC);\n canvas.clipPath(pathA, Region.Op.DIFFERENCE);\n canvas.drawColor(readAnimView.getBackgroundColor());\n bitmapPaint.setColorFilter(colorMatrixColorFilter);\n canvas.drawBitmap(curBitmap, matrix, bitmapPaint);//绘制背面到C区\n canvas.drawColor(tempColor);//叠加背景\n bitmapPaint.setColorFilter(null);",
"score": 0.8377548456192017
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " canvas.restore();\n canvas.save();\n canvas.clipPath(pathC, Region.Op.DIFFERENCE);\n canvas.clipPath(pathA, Region.Op.DIFFERENCE);\n canvas.drawBitmap(nextBitmap, 0, 0, bitmapPaint);//绘制B区\n canvas.restore();\n } else {\n //对Bitmap进行取色\n int color = preBitmap.getPixel(1, 1);\n //获取对应的三色",
"score": 0.837067723274231
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " gradientDrawable = readAnimView.getAnimHelper().getTopRightGradientDrawable();\n top = (int) (h.y - rPathAShadowDis / 2) + offset;\n bottom = (int) h.y;\n } else {\n gradientDrawable = readAnimView.getAnimHelper().getBottomRightGradientDrawable();\n top = (int) h.y;\n bottom = (int) (h.y + rPathAShadowDis / 2);\n }\n gradientDrawable.setBounds(left, top, right, bottom);\n //裁剪出我们需要的区域",
"score": 0.8340978622436523
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " } else {\n //从右向左线性渐变\n gradientDrawable = readAnimView.getAnimHelper().getBottomBGradientDrawable();\n left = (int) (c.x - aTof / 4 - lightOffset);//c点位于左下角\n right = (int) (c.x + deepOffset);\n }\n gradientDrawable.setBounds(left, top, right, bottom);//设置阴影矩形\n canvas.save();\n canvas.clipPath(pathA, Region.Op.DIFFERENCE);\n canvas.clipPath(pathC, Region.Op.DIFFERENCE);//留出b区",
"score": 0.8278508186340332
}
] | java | drawable = readAnimView.getAnimHelper().getCoverGradientDrawable(); |
package com.juziml.read.business.read.view;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.List;
/**
* 关闭了抛投效果
* create by zhusw on 2020-03-30 11:51
*/
public class BookRecyclerView extends RecyclerView implements RVInnerItemFunction, RVOuterFunction {
private final BookLayoutManager readLayoutManger;
private boolean allowInterceptTouchEvent = true;
private int currentPosition = 0;
private WeakReference<EventProxy> eventProxyWeakReference;
private AnimParentView animParentView;
private BookView.OnPositionChangedListener onPositionChangedListener;
public BookRecyclerView(Context context) {
this(context, null);
}
public BookRecyclerView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public BookRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
readLayoutManger = new BookLayoutManager(context);
setLayoutManager(readLayoutManger);
readLayoutManger.setOnForceLayoutCompleted(new ItemOnForceLayoutCompleted());
readLayoutManger.setonStopScroller(new ItemOnScrollStop());
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
animParentView = (AnimParentView) getParent();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
eventProxyWeakReference.clear();
}
protected void bindReadCurlAnimProxy(EventProxy ic) {
if (null != eventProxyWeakReference) {
eventProxyWeakReference.clear();
}
eventProxyWeakReference = new WeakReference<>(ic);
}
protected void setOnPositionChangedListener(BookView.OnPositionChangedListener onPositionChangedListener) {
this.onPositionChangedListener = onPositionChangedListener;
}
@Override
public boolean fling(int velocityX, int velocityY) {
return false;
}
@Override
public void scrollToPosition(int position) {
readLayoutManger.forceScrollToPosition(position);
}
@Override
public void smoothScrollToPosition(int position) {
readLayoutManger.smoothScrollToPosition(position);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
readLayoutManger.onRecyclerViewSizeChange();
}
private final List<Float> moveSampling = new LinkedList<>();
private final int MAX_COUNT = 5;
@Override
public boolean isScrollContainer() {
if (allowInterceptTouchEvent) {
return super.isScrollContainer();
} else {
return false;
}
}
private float downX = 0F;
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouchEvent(MotionEvent e) {
if (!allowInterceptTouchEvent) return false;//[偶现 动画期间 产生了item滑动,这里最后杀手锏再屏蔽下]
switch (e.getAction()) {
case MotionEvent.ACTION_DOWN:
moveSampling.clear();
downX = e.getRawX();
break;
case MotionEvent.ACTION_MOVE:
float mx = e.getRawX();
if (moveSampling.size() == 0
|| mx != moveSampling.get(moveSampling.size() - 1)) {
moveSampling.add(mx);
}
if (moveSampling.size() > MAX_COUNT) {
moveSampling.remove(0);
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
if (moveSampling.size() > 0) {
float lastMoveX = moveSampling.get(moveSampling.size() - 1);
float firstMoveX = moveSampling.get(0);
float finallyMoveX = lastMoveX - firstMoveX;
if (lastMoveX - downX < 0) {//左滑
| readLayoutManger.setAutoLeftScroll(finallyMoveX < 10); |
} else {
readLayoutManger.setAutoLeftScroll(finallyMoveX < 0);
}
moveSampling.clear();
} else {
readLayoutManger.setAutoLeftScroll(false);
}
break;
default:
break;
}
return super.onTouchEvent(e);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent e) {
//交由父类处理滑动,flip = BookFlipMode.MODE_NORMAL,
if (allowInterceptTouchEvent) {
return super.onInterceptTouchEvent(e);
}
//交由子View自行处理,flip = BookFlipMode.MODE_COVER| BookFlipMode.MODE_CURL
return false;
}
@Override
public void onExpectNext(boolean smooth) {
Adapter adapter = getAdapter();
final int dataCount = adapter.getItemCount();
final int nextPos = currentPosition + 1;
if (nextPos < dataCount) {
if (smooth) {
smoothScrollToPosition(nextPos);
} else {
scrollToPosition(nextPos);
}
}
}
@Override
public void onExpectPrevious(boolean smooth) {
if (currentPosition - 1 >= 0) {
if (smooth) {
smoothScrollToPosition(currentPosition - 1);
} else {
scrollToPosition(currentPosition - 1);
}
}
}
protected void setFlipMode(int flipMode) {
readLayoutManger.setBookFlipMode(flipMode);
if (flipMode == BookLayoutManager.BookFlipMode.MODE_CURL
|| flipMode == BookLayoutManager.BookFlipMode.MODE_COVER) {
allowInterceptTouchEvent = false;
} else {
allowInterceptTouchEvent = true;
}
readLayoutManger.requestLayout();
}
@Override
public int getFlipMode() {
return readLayoutManger.getBookFlipMode();
}
@Override
public void onItemViewTouchEvent(MotionEvent event) {
if (null != eventProxyWeakReference && null != eventProxyWeakReference.get()) {
eventProxyWeakReference.get().onItemViewTouchEvent(event);
}
}
@Override
public boolean animRunning() {
if (null != eventProxyWeakReference && null != eventProxyWeakReference.get()) {
eventProxyWeakReference.get().animRunning();
}
return false;
}
@Override
public void onClickMenu() {
animParentView.onClickMenuArea();
}
private class ItemOnScrollStop implements BookLayoutManager.OnStopScroller {
@Override
public void onStop(boolean autoLeftScroll, int curPos) {
boolean arriveNext = currentPosition < curPos;
currentPosition = curPos;
if (null != onPositionChangedListener) {
onPositionChangedListener.onChanged(arriveNext, curPos);
}
}
}
private class ItemOnForceLayoutCompleted implements BookLayoutManager.OnForceLayoutCompleted {
@Override
public void onLayoutCompleted(final int curPos) {
boolean arriveNext = currentPosition < curPos;
currentPosition = curPos;
if (null != onPositionChangedListener) {
onPositionChangedListener.onChanged(arriveNext, curPos);
}
}
}
@Override
public Bitmap getPreviousBitmap() {
int prePos = currentPosition - 1;
Bitmap pb = null;
if (prePos >= 0) {
pb = printViewToBitmap(prePos);
}
return pb;
}
@Override
public Bitmap getCurrentBitmap() {
return printViewToBitmap(currentPosition);
}
@Override
public Bitmap getNextBitmap() {
final int dataCount = getAdapter().getItemCount();
int nextPos = currentPosition + 1;
Bitmap nb = null;
if (nextPos < dataCount) {
nb = printViewToBitmap(nextPos);
}
return nb;
}
/**
* 将view渲染结果 打印到一个bitmap上
*
* @param pos
* @return
*/
private Bitmap printViewToBitmap(int pos) {
View view = readLayoutManger.findViewByPosition(pos);
if (null != view) {
if (view instanceof PaperLayout) {
PaperLayout pageView = (PaperLayout) view;
Bitmap bitmapTarget = Bitmap.createBitmap(pageView.getWidth(), pageView.getHeight(), Bitmap.Config.ARGB_4444);
pageView.drawViewScreenShotToBitmap(bitmapTarget);
return bitmapTarget;
} else {
throw new IllegalArgumentException("item 根View必须使用 PaperLayout");
}
}
return null;
}
}
| app/src/main/java/com/juziml/read/business/read/view/BookRecyclerView.java | Western-parotia-BookViewProject-1727e80 | [
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/CoverAnimationEffecter.java",
"retrieved_chunk": " break;\n case MotionEvent.ACTION_UP:\n currentX = x;\n if (prepareDrawCoverAnimEffect) {\n if (moveSampling.size() > 0) {\n float lastMoveX = moveSampling.get(moveSampling.size() - 1);\n float firstMoveX = moveSampling.get(0);\n float finallyMoveX = lastMoveX - firstMoveX;\n if (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT) {\n boolean lastFingerLeftSlop = finallyMoveX < 10;",
"score": 0.9438119530677795
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " case MotionEvent.ACTION_UP://需要对最后手势进行采样,判断是 取消还是自动翻页\n if (drawCurlAnimBefore) {\n if (moveSampling.size() > 0) {\n float lastMoveX = moveSampling.get(moveSampling.size() - 1);\n float firstMoveX = moveSampling.get(0);\n float finallyMoveX = lastMoveX - firstMoveX;\n if (curlSlideDirection == AnimHelper.SLID_DIRECTION_LEFT) {\n boolean lastFingerLeftSlop = finallyMoveX < 10;\n touchUp(lastFingerLeftSlop);\n } else if (curlSlideDirection == AnimHelper.SLID_DIRECTION_RIGHT) {",
"score": 0.9130125045776367
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/PaperLayout.java",
"retrieved_chunk": " if (ev.getAction() == MotionEvent.ACTION_DOWN) {\n interceptDownX = ev.getRawX();\n } else if (ev.getAction() == MotionEvent.ACTION_MOVE) {\n float currentX = ev.getRawX();\n float distance = Math.abs(currentX - interceptDownX);\n if (distance > 1F) {\n return true;\n }\n }\n return super.onInterceptTouchEvent(ev);",
"score": 0.8484748601913452
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " switch (event.getAction()) {\n case MotionEvent.ACTION_DOWN:\n isTouching = true;\n drawCurlAnimBefore = false;\n moveSampling.clear();\n downX = x;\n curlSlideDirection = AnimHelper.SLID_DIRECTION_UNKNOWN;\n if (x < menuBounds.left) {\n downArea = DOWN_AREA_LEFT;\n } else if (x > menuBounds.left && y < menuBounds.top) {",
"score": 0.8473213911056519
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/CoverAnimationEffecter.java",
"retrieved_chunk": " }\n if (moveSampling.size() > MAX_COUNT) {\n moveSampling.remove(0);\n }\n currentX = x;\n invalidate();\n }\n break;\n case MotionEvent.ACTION_CANCEL:\n isTouching = false;",
"score": 0.8444778919219971
}
] | java | readLayoutManger.setAutoLeftScroll(finallyMoveX < 10); |
package com.juziml.read.business.read.view;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.List;
/**
* 关闭了抛投效果
* create by zhusw on 2020-03-30 11:51
*/
public class BookRecyclerView extends RecyclerView implements RVInnerItemFunction, RVOuterFunction {
private final BookLayoutManager readLayoutManger;
private boolean allowInterceptTouchEvent = true;
private int currentPosition = 0;
private WeakReference<EventProxy> eventProxyWeakReference;
private AnimParentView animParentView;
private BookView.OnPositionChangedListener onPositionChangedListener;
public BookRecyclerView(Context context) {
this(context, null);
}
public BookRecyclerView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public BookRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
readLayoutManger = new BookLayoutManager(context);
setLayoutManager(readLayoutManger);
readLayoutManger.setOnForceLayoutCompleted(new ItemOnForceLayoutCompleted());
readLayoutManger.setonStopScroller(new ItemOnScrollStop());
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
animParentView = (AnimParentView) getParent();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
eventProxyWeakReference.clear();
}
protected void bindReadCurlAnimProxy(EventProxy ic) {
if (null != eventProxyWeakReference) {
eventProxyWeakReference.clear();
}
eventProxyWeakReference = new WeakReference<>(ic);
}
protected void setOnPositionChangedListener(BookView.OnPositionChangedListener onPositionChangedListener) {
this.onPositionChangedListener = onPositionChangedListener;
}
@Override
public boolean fling(int velocityX, int velocityY) {
return false;
}
@Override
public void scrollToPosition(int position) {
readLayoutManger.forceScrollToPosition(position);
}
@Override
public void smoothScrollToPosition(int position) {
readLayoutManger.smoothScrollToPosition(position);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
| readLayoutManger.onRecyclerViewSizeChange(); |
}
private final List<Float> moveSampling = new LinkedList<>();
private final int MAX_COUNT = 5;
@Override
public boolean isScrollContainer() {
if (allowInterceptTouchEvent) {
return super.isScrollContainer();
} else {
return false;
}
}
private float downX = 0F;
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouchEvent(MotionEvent e) {
if (!allowInterceptTouchEvent) return false;//[偶现 动画期间 产生了item滑动,这里最后杀手锏再屏蔽下]
switch (e.getAction()) {
case MotionEvent.ACTION_DOWN:
moveSampling.clear();
downX = e.getRawX();
break;
case MotionEvent.ACTION_MOVE:
float mx = e.getRawX();
if (moveSampling.size() == 0
|| mx != moveSampling.get(moveSampling.size() - 1)) {
moveSampling.add(mx);
}
if (moveSampling.size() > MAX_COUNT) {
moveSampling.remove(0);
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
if (moveSampling.size() > 0) {
float lastMoveX = moveSampling.get(moveSampling.size() - 1);
float firstMoveX = moveSampling.get(0);
float finallyMoveX = lastMoveX - firstMoveX;
if (lastMoveX - downX < 0) {//左滑
readLayoutManger.setAutoLeftScroll(finallyMoveX < 10);
} else {
readLayoutManger.setAutoLeftScroll(finallyMoveX < 0);
}
moveSampling.clear();
} else {
readLayoutManger.setAutoLeftScroll(false);
}
break;
default:
break;
}
return super.onTouchEvent(e);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent e) {
//交由父类处理滑动,flip = BookFlipMode.MODE_NORMAL,
if (allowInterceptTouchEvent) {
return super.onInterceptTouchEvent(e);
}
//交由子View自行处理,flip = BookFlipMode.MODE_COVER| BookFlipMode.MODE_CURL
return false;
}
@Override
public void onExpectNext(boolean smooth) {
Adapter adapter = getAdapter();
final int dataCount = adapter.getItemCount();
final int nextPos = currentPosition + 1;
if (nextPos < dataCount) {
if (smooth) {
smoothScrollToPosition(nextPos);
} else {
scrollToPosition(nextPos);
}
}
}
@Override
public void onExpectPrevious(boolean smooth) {
if (currentPosition - 1 >= 0) {
if (smooth) {
smoothScrollToPosition(currentPosition - 1);
} else {
scrollToPosition(currentPosition - 1);
}
}
}
protected void setFlipMode(int flipMode) {
readLayoutManger.setBookFlipMode(flipMode);
if (flipMode == BookLayoutManager.BookFlipMode.MODE_CURL
|| flipMode == BookLayoutManager.BookFlipMode.MODE_COVER) {
allowInterceptTouchEvent = false;
} else {
allowInterceptTouchEvent = true;
}
readLayoutManger.requestLayout();
}
@Override
public int getFlipMode() {
return readLayoutManger.getBookFlipMode();
}
@Override
public void onItemViewTouchEvent(MotionEvent event) {
if (null != eventProxyWeakReference && null != eventProxyWeakReference.get()) {
eventProxyWeakReference.get().onItemViewTouchEvent(event);
}
}
@Override
public boolean animRunning() {
if (null != eventProxyWeakReference && null != eventProxyWeakReference.get()) {
eventProxyWeakReference.get().animRunning();
}
return false;
}
@Override
public void onClickMenu() {
animParentView.onClickMenuArea();
}
private class ItemOnScrollStop implements BookLayoutManager.OnStopScroller {
@Override
public void onStop(boolean autoLeftScroll, int curPos) {
boolean arriveNext = currentPosition < curPos;
currentPosition = curPos;
if (null != onPositionChangedListener) {
onPositionChangedListener.onChanged(arriveNext, curPos);
}
}
}
private class ItemOnForceLayoutCompleted implements BookLayoutManager.OnForceLayoutCompleted {
@Override
public void onLayoutCompleted(final int curPos) {
boolean arriveNext = currentPosition < curPos;
currentPosition = curPos;
if (null != onPositionChangedListener) {
onPositionChangedListener.onChanged(arriveNext, curPos);
}
}
}
@Override
public Bitmap getPreviousBitmap() {
int prePos = currentPosition - 1;
Bitmap pb = null;
if (prePos >= 0) {
pb = printViewToBitmap(prePos);
}
return pb;
}
@Override
public Bitmap getCurrentBitmap() {
return printViewToBitmap(currentPosition);
}
@Override
public Bitmap getNextBitmap() {
final int dataCount = getAdapter().getItemCount();
int nextPos = currentPosition + 1;
Bitmap nb = null;
if (nextPos < dataCount) {
nb = printViewToBitmap(nextPos);
}
return nb;
}
/**
* 将view渲染结果 打印到一个bitmap上
*
* @param pos
* @return
*/
private Bitmap printViewToBitmap(int pos) {
View view = readLayoutManger.findViewByPosition(pos);
if (null != view) {
if (view instanceof PaperLayout) {
PaperLayout pageView = (PaperLayout) view;
Bitmap bitmapTarget = Bitmap.createBitmap(pageView.getWidth(), pageView.getHeight(), Bitmap.Config.ARGB_4444);
pageView.drawViewScreenShotToBitmap(bitmapTarget);
return bitmapTarget;
} else {
throw new IllegalArgumentException("item 根View必须使用 PaperLayout");
}
}
return null;
}
}
| app/src/main/java/com/juziml/read/business/read/view/BookRecyclerView.java | Western-parotia-BookViewProject-1727e80 | [
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/PaperLayout.java",
"retrieved_chunk": " }\n @Override\n protected void onAttachedToWindow() {\n super.onAttachedToWindow();\n bookRecyclerView = (BookRecyclerView) getParent();\n }\n @Override\n protected void onSizeChanged(int w, int h, int oldw, int oldh) {\n super.onSizeChanged(w, h, oldw, oldh);\n if (bookRecyclerView.getFlipMode() == BookLayoutManager.BookFlipMode.MODE_CURL",
"score": 0.9208739399909973
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookView.java",
"retrieved_chunk": " params.gravity = Gravity.CENTER;\n addView(bookRecyclerView, params);\n LayoutParams params2 = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);\n params2.gravity = Gravity.CENTER;\n addView(puppetView, params2);\n }\n @Override\n protected void onSizeChanged(int w, int h, int oldw, int oldh) {\n super.onSizeChanged(w, h, oldw, oldh);\n bookRecyclerView.bindReadCurlAnimProxy(puppetView);",
"score": 0.888520359992981
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/CoverAnimationEffecter.java",
"retrieved_chunk": " }\n @Override\n public boolean animInEffect() {\n return isTouching || coverAnimationRunning;\n }\n @Override\n public void onViewSizeChanged(int vWidth, int vHeight) {\n this.vWidth = vWidth;\n this.vHeight = vHeight;\n menuBounds.left = vWidth / 3F;",
"score": 0.8745822906494141
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " isTouching = false;\n downX = 0F;\n drawCurlAnimBefore = false;\n break;\n }\n }\n @Override\n public void onViewSizeChanged(int vWidth, int vHeight) {\n this.vWidth = vWidth;\n this.vHeight = vHeight;",
"score": 0.8585351705551147
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookView.java",
"retrieved_chunk": " public void smoothScrollToPosition(int position) {\n bookRecyclerView.smoothScrollToPosition(position);\n }\n public void setAdapter(RecyclerView.Adapter adapter) {\n bookRecyclerView.setAdapter(adapter);\n }\n public void setItemViewBackgroundColor(int itemViewBackgroundColor) {\n this.itemViewBackgroundColor = itemViewBackgroundColor;\n }\n @Override",
"score": 0.8548860549926758
}
] | java | readLayoutManger.onRecyclerViewSizeChange(); |
package com.juziml.read.business.read.view;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.List;
/**
* 关闭了抛投效果
* create by zhusw on 2020-03-30 11:51
*/
public class BookRecyclerView extends RecyclerView implements RVInnerItemFunction, RVOuterFunction {
private final BookLayoutManager readLayoutManger;
private boolean allowInterceptTouchEvent = true;
private int currentPosition = 0;
private WeakReference<EventProxy> eventProxyWeakReference;
private AnimParentView animParentView;
private BookView.OnPositionChangedListener onPositionChangedListener;
public BookRecyclerView(Context context) {
this(context, null);
}
public BookRecyclerView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public BookRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
readLayoutManger = new BookLayoutManager(context);
setLayoutManager(readLayoutManger);
readLayoutManger.setOnForceLayoutCompleted(new ItemOnForceLayoutCompleted());
readLayoutManger.setonStopScroller(new ItemOnScrollStop());
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
animParentView = (AnimParentView) getParent();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
eventProxyWeakReference.clear();
}
protected void bindReadCurlAnimProxy(EventProxy ic) {
if (null != eventProxyWeakReference) {
eventProxyWeakReference.clear();
}
eventProxyWeakReference = new WeakReference<>(ic);
}
protected void setOnPositionChangedListener(BookView.OnPositionChangedListener onPositionChangedListener) {
this.onPositionChangedListener = onPositionChangedListener;
}
@Override
public boolean fling(int velocityX, int velocityY) {
return false;
}
@Override
public void scrollToPosition(int position) {
readLayoutManger.forceScrollToPosition(position);
}
@Override
public void smoothScrollToPosition(int position) {
readLayoutManger.smoothScrollToPosition(position);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
readLayoutManger.onRecyclerViewSizeChange();
}
private final List<Float> moveSampling = new LinkedList<>();
private final int MAX_COUNT = 5;
@Override
public boolean isScrollContainer() {
if (allowInterceptTouchEvent) {
return super.isScrollContainer();
} else {
return false;
}
}
private float downX = 0F;
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouchEvent(MotionEvent e) {
if (!allowInterceptTouchEvent) return false;//[偶现 动画期间 产生了item滑动,这里最后杀手锏再屏蔽下]
switch (e.getAction()) {
case MotionEvent.ACTION_DOWN:
moveSampling.clear();
downX = e.getRawX();
break;
case MotionEvent.ACTION_MOVE:
float mx = e.getRawX();
if (moveSampling.size() == 0
|| mx != moveSampling.get(moveSampling.size() - 1)) {
moveSampling.add(mx);
}
if (moveSampling.size() > MAX_COUNT) {
moveSampling.remove(0);
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
if (moveSampling.size() > 0) {
float lastMoveX = moveSampling.get(moveSampling.size() - 1);
float firstMoveX = moveSampling.get(0);
float finallyMoveX = lastMoveX - firstMoveX;
if (lastMoveX - downX < 0) {//左滑
readLayoutManger.setAutoLeftScroll(finallyMoveX < 10);
} else {
readLayoutManger.setAutoLeftScroll(finallyMoveX < 0);
}
moveSampling.clear();
} else {
readLayoutManger.setAutoLeftScroll(false);
}
break;
default:
break;
}
return super.onTouchEvent(e);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent e) {
//交由父类处理滑动,flip = BookFlipMode.MODE_NORMAL,
if (allowInterceptTouchEvent) {
return super.onInterceptTouchEvent(e);
}
//交由子View自行处理,flip = BookFlipMode.MODE_COVER| BookFlipMode.MODE_CURL
return false;
}
@Override
public void onExpectNext(boolean smooth) {
Adapter adapter = getAdapter();
final int dataCount = adapter.getItemCount();
final int nextPos = currentPosition + 1;
if (nextPos < dataCount) {
if (smooth) {
smoothScrollToPosition(nextPos);
} else {
scrollToPosition(nextPos);
}
}
}
@Override
public void onExpectPrevious(boolean smooth) {
if (currentPosition - 1 >= 0) {
if (smooth) {
smoothScrollToPosition(currentPosition - 1);
} else {
scrollToPosition(currentPosition - 1);
}
}
}
protected void setFlipMode(int flipMode) {
readLayoutManger.setBookFlipMode(flipMode);
if (flipMode == BookLayoutManager.BookFlipMode.MODE_CURL
|| flipMode == BookLayoutManager.BookFlipMode.MODE_COVER) {
allowInterceptTouchEvent = false;
} else {
allowInterceptTouchEvent = true;
}
readLayoutManger.requestLayout();
}
@Override
public int getFlipMode() {
return | readLayoutManger.getBookFlipMode(); |
}
@Override
public void onItemViewTouchEvent(MotionEvent event) {
if (null != eventProxyWeakReference && null != eventProxyWeakReference.get()) {
eventProxyWeakReference.get().onItemViewTouchEvent(event);
}
}
@Override
public boolean animRunning() {
if (null != eventProxyWeakReference && null != eventProxyWeakReference.get()) {
eventProxyWeakReference.get().animRunning();
}
return false;
}
@Override
public void onClickMenu() {
animParentView.onClickMenuArea();
}
private class ItemOnScrollStop implements BookLayoutManager.OnStopScroller {
@Override
public void onStop(boolean autoLeftScroll, int curPos) {
boolean arriveNext = currentPosition < curPos;
currentPosition = curPos;
if (null != onPositionChangedListener) {
onPositionChangedListener.onChanged(arriveNext, curPos);
}
}
}
private class ItemOnForceLayoutCompleted implements BookLayoutManager.OnForceLayoutCompleted {
@Override
public void onLayoutCompleted(final int curPos) {
boolean arriveNext = currentPosition < curPos;
currentPosition = curPos;
if (null != onPositionChangedListener) {
onPositionChangedListener.onChanged(arriveNext, curPos);
}
}
}
@Override
public Bitmap getPreviousBitmap() {
int prePos = currentPosition - 1;
Bitmap pb = null;
if (prePos >= 0) {
pb = printViewToBitmap(prePos);
}
return pb;
}
@Override
public Bitmap getCurrentBitmap() {
return printViewToBitmap(currentPosition);
}
@Override
public Bitmap getNextBitmap() {
final int dataCount = getAdapter().getItemCount();
int nextPos = currentPosition + 1;
Bitmap nb = null;
if (nextPos < dataCount) {
nb = printViewToBitmap(nextPos);
}
return nb;
}
/**
* 将view渲染结果 打印到一个bitmap上
*
* @param pos
* @return
*/
private Bitmap printViewToBitmap(int pos) {
View view = readLayoutManger.findViewByPosition(pos);
if (null != view) {
if (view instanceof PaperLayout) {
PaperLayout pageView = (PaperLayout) view;
Bitmap bitmapTarget = Bitmap.createBitmap(pageView.getWidth(), pageView.getHeight(), Bitmap.Config.ARGB_4444);
pageView.drawViewScreenShotToBitmap(bitmapTarget);
return bitmapTarget;
} else {
throw new IllegalArgumentException("item 根View必须使用 PaperLayout");
}
}
return null;
}
}
| app/src/main/java/com/juziml/read/business/read/view/BookRecyclerView.java | Western-parotia-BookViewProject-1727e80 | [
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/PaperLayout.java",
"retrieved_chunk": " }\n @Override\n public boolean isScrollContainer() {\n return false;\n }\n private float interceptDownX;\n @Override\n public boolean onInterceptTouchEvent(MotionEvent ev) {\n //动画执行期间 子view 也不可获取事件\n if (bookRecyclerView.animRunning()) return true;",
"score": 0.856238603591919
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookView.java",
"retrieved_chunk": " @Override\n public Bitmap getNextBitmap() {\n return bookRecyclerView.getNextBitmap();\n }\n @Override\n public int getBackgroundColor() {\n return itemViewBackgroundColor;\n }\n public void setFlipMode(int flipMode) {\n if (flipMode == BookLayoutManager.BookFlipMode.MODE_CURL",
"score": 0.852530300617218
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/PuppetView.java",
"retrieved_chunk": " if (null != animationEffecter) {\n animationEffecter.onScroll();\n }\n }\n @Override\n public void onExpectNext() {\n parentView.onExpectNext();\n }\n @Override\n public void onExpectPrevious() {",
"score": 0.8442256450653076
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookView.java",
"retrieved_chunk": " */\n @Override\n public void onClickNextArea() {\n bookRecyclerView.onExpectNext(true);\n }\n /**\n * 只在非卷曲模式下调用\n */\n @Override\n public void onClickPreviousArea() {",
"score": 0.8393131494522095
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookView.java",
"retrieved_chunk": " }\n }\n @Override\n public Bitmap getPreviousBitmap() {\n return bookRecyclerView.getPreviousBitmap();\n }\n @Override\n public Bitmap getCurrentBitmap() {\n return bookRecyclerView.getCurrentBitmap();\n }",
"score": 0.8377800583839417
}
] | java | readLayoutManger.getBookFlipMode(); |
package com.juziml.read.business.read.view;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.List;
/**
* 关闭了抛投效果
* create by zhusw on 2020-03-30 11:51
*/
public class BookRecyclerView extends RecyclerView implements RVInnerItemFunction, RVOuterFunction {
private final BookLayoutManager readLayoutManger;
private boolean allowInterceptTouchEvent = true;
private int currentPosition = 0;
private WeakReference<EventProxy> eventProxyWeakReference;
private AnimParentView animParentView;
private BookView.OnPositionChangedListener onPositionChangedListener;
public BookRecyclerView(Context context) {
this(context, null);
}
public BookRecyclerView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public BookRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
readLayoutManger = new BookLayoutManager(context);
setLayoutManager(readLayoutManger);
readLayoutManger.setOnForceLayoutCompleted(new ItemOnForceLayoutCompleted());
| readLayoutManger.setonStopScroller(new ItemOnScrollStop()); |
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
animParentView = (AnimParentView) getParent();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
eventProxyWeakReference.clear();
}
protected void bindReadCurlAnimProxy(EventProxy ic) {
if (null != eventProxyWeakReference) {
eventProxyWeakReference.clear();
}
eventProxyWeakReference = new WeakReference<>(ic);
}
protected void setOnPositionChangedListener(BookView.OnPositionChangedListener onPositionChangedListener) {
this.onPositionChangedListener = onPositionChangedListener;
}
@Override
public boolean fling(int velocityX, int velocityY) {
return false;
}
@Override
public void scrollToPosition(int position) {
readLayoutManger.forceScrollToPosition(position);
}
@Override
public void smoothScrollToPosition(int position) {
readLayoutManger.smoothScrollToPosition(position);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
readLayoutManger.onRecyclerViewSizeChange();
}
private final List<Float> moveSampling = new LinkedList<>();
private final int MAX_COUNT = 5;
@Override
public boolean isScrollContainer() {
if (allowInterceptTouchEvent) {
return super.isScrollContainer();
} else {
return false;
}
}
private float downX = 0F;
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouchEvent(MotionEvent e) {
if (!allowInterceptTouchEvent) return false;//[偶现 动画期间 产生了item滑动,这里最后杀手锏再屏蔽下]
switch (e.getAction()) {
case MotionEvent.ACTION_DOWN:
moveSampling.clear();
downX = e.getRawX();
break;
case MotionEvent.ACTION_MOVE:
float mx = e.getRawX();
if (moveSampling.size() == 0
|| mx != moveSampling.get(moveSampling.size() - 1)) {
moveSampling.add(mx);
}
if (moveSampling.size() > MAX_COUNT) {
moveSampling.remove(0);
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
if (moveSampling.size() > 0) {
float lastMoveX = moveSampling.get(moveSampling.size() - 1);
float firstMoveX = moveSampling.get(0);
float finallyMoveX = lastMoveX - firstMoveX;
if (lastMoveX - downX < 0) {//左滑
readLayoutManger.setAutoLeftScroll(finallyMoveX < 10);
} else {
readLayoutManger.setAutoLeftScroll(finallyMoveX < 0);
}
moveSampling.clear();
} else {
readLayoutManger.setAutoLeftScroll(false);
}
break;
default:
break;
}
return super.onTouchEvent(e);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent e) {
//交由父类处理滑动,flip = BookFlipMode.MODE_NORMAL,
if (allowInterceptTouchEvent) {
return super.onInterceptTouchEvent(e);
}
//交由子View自行处理,flip = BookFlipMode.MODE_COVER| BookFlipMode.MODE_CURL
return false;
}
@Override
public void onExpectNext(boolean smooth) {
Adapter adapter = getAdapter();
final int dataCount = adapter.getItemCount();
final int nextPos = currentPosition + 1;
if (nextPos < dataCount) {
if (smooth) {
smoothScrollToPosition(nextPos);
} else {
scrollToPosition(nextPos);
}
}
}
@Override
public void onExpectPrevious(boolean smooth) {
if (currentPosition - 1 >= 0) {
if (smooth) {
smoothScrollToPosition(currentPosition - 1);
} else {
scrollToPosition(currentPosition - 1);
}
}
}
protected void setFlipMode(int flipMode) {
readLayoutManger.setBookFlipMode(flipMode);
if (flipMode == BookLayoutManager.BookFlipMode.MODE_CURL
|| flipMode == BookLayoutManager.BookFlipMode.MODE_COVER) {
allowInterceptTouchEvent = false;
} else {
allowInterceptTouchEvent = true;
}
readLayoutManger.requestLayout();
}
@Override
public int getFlipMode() {
return readLayoutManger.getBookFlipMode();
}
@Override
public void onItemViewTouchEvent(MotionEvent event) {
if (null != eventProxyWeakReference && null != eventProxyWeakReference.get()) {
eventProxyWeakReference.get().onItemViewTouchEvent(event);
}
}
@Override
public boolean animRunning() {
if (null != eventProxyWeakReference && null != eventProxyWeakReference.get()) {
eventProxyWeakReference.get().animRunning();
}
return false;
}
@Override
public void onClickMenu() {
animParentView.onClickMenuArea();
}
private class ItemOnScrollStop implements BookLayoutManager.OnStopScroller {
@Override
public void onStop(boolean autoLeftScroll, int curPos) {
boolean arriveNext = currentPosition < curPos;
currentPosition = curPos;
if (null != onPositionChangedListener) {
onPositionChangedListener.onChanged(arriveNext, curPos);
}
}
}
private class ItemOnForceLayoutCompleted implements BookLayoutManager.OnForceLayoutCompleted {
@Override
public void onLayoutCompleted(final int curPos) {
boolean arriveNext = currentPosition < curPos;
currentPosition = curPos;
if (null != onPositionChangedListener) {
onPositionChangedListener.onChanged(arriveNext, curPos);
}
}
}
@Override
public Bitmap getPreviousBitmap() {
int prePos = currentPosition - 1;
Bitmap pb = null;
if (prePos >= 0) {
pb = printViewToBitmap(prePos);
}
return pb;
}
@Override
public Bitmap getCurrentBitmap() {
return printViewToBitmap(currentPosition);
}
@Override
public Bitmap getNextBitmap() {
final int dataCount = getAdapter().getItemCount();
int nextPos = currentPosition + 1;
Bitmap nb = null;
if (nextPos < dataCount) {
nb = printViewToBitmap(nextPos);
}
return nb;
}
/**
* 将view渲染结果 打印到一个bitmap上
*
* @param pos
* @return
*/
private Bitmap printViewToBitmap(int pos) {
View view = readLayoutManger.findViewByPosition(pos);
if (null != view) {
if (view instanceof PaperLayout) {
PaperLayout pageView = (PaperLayout) view;
Bitmap bitmapTarget = Bitmap.createBitmap(pageView.getWidth(), pageView.getHeight(), Bitmap.Config.ARGB_4444);
pageView.drawViewScreenShotToBitmap(bitmapTarget);
return bitmapTarget;
} else {
throw new IllegalArgumentException("item 根View必须使用 PaperLayout");
}
}
return null;
}
}
| app/src/main/java/com/juziml/read/business/read/view/BookRecyclerView.java | Western-parotia-BookViewProject-1727e80 | [
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookLayoutManager.java",
"retrieved_chunk": " this.onStopScroller = onStopScroller;\n }\n @Override\n public RecyclerView.LayoutParams generateDefaultLayoutParams() {\n return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,\n ViewGroup.LayoutParams.WRAP_CONTENT);\n }\n public void setBookFlipMode(@BookFlipMode int bookFlipMode) {\n this.bookFlipMode = bookFlipMode;\n requestLayout();",
"score": 0.8510451912879944
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookView.java",
"retrieved_chunk": " public void smoothScrollToPosition(int position) {\n bookRecyclerView.smoothScrollToPosition(position);\n }\n public void setAdapter(RecyclerView.Adapter adapter) {\n bookRecyclerView.setAdapter(adapter);\n }\n public void setItemViewBackgroundColor(int itemViewBackgroundColor) {\n this.itemViewBackgroundColor = itemViewBackgroundColor;\n }\n @Override",
"score": 0.8463790416717529
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookView.java",
"retrieved_chunk": " animHelper = new AnimHelper();\n init();\n }\n private void init() {\n removeAllViews();\n bookRecyclerView = new BookRecyclerView(getContext());\n puppetView = new PuppetView(getContext());\n puppetView.setAnimMode(bookRecyclerView.getFlipMode());\n bookRecyclerView.bindReadCurlAnimProxy(puppetView);\n LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);",
"score": 0.8452279567718506
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/PaperLayout.java",
"retrieved_chunk": " public PaperLayout(@NonNull Context context) {\n this(context, null);\n }\n public PaperLayout(@NonNull Context context, @Nullable AttributeSet attrs) {\n this(context, attrs, 0);\n }\n public PaperLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n viewScreenShotCanvas = new Canvas();\n menuBounds = new RectF();",
"score": 0.8395696878433228
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookView.java",
"retrieved_chunk": " private int itemViewBackgroundColor = Color.WHITE;\n private Runnable dataPendIntentTask;\n public BookView(@NonNull Context context) {\n this(context, null);\n }\n public BookView(@NonNull Context context, @Nullable AttributeSet attrs) {\n this(context, attrs, 0);\n }\n public BookView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);",
"score": 0.8271343111991882
}
] | java | readLayoutManger.setonStopScroller(new ItemOnScrollStop()); |
package com.juziml.read.business.read.anim;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.drawable.GradientDrawable;
import android.view.MotionEvent;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.Scroller;
import com.juziml.read.business.read.view.PuppetView;
import com.juziml.read.utils.DLog;
import java.util.LinkedList;
import java.util.List;
/**
* create by zhusw on 2020-08-24 14:06
*/
public class CoverAnimationEffecter implements IAnimationEffecter {
private final static int DOWN_AREA_NONE = -1;
private final static int DOWN_AREA_MENU = 1;
private final static int DOWN_AREA_LEFT = 2;
private final static int DOWN_AREA_RIGHT = 3;
int vWidth = 1;
int vHeight = 1;
private final PuppetView readAnimView;
private boolean isCancelFlip = false;
private boolean coverAnimationRunning = false;
private boolean isTouching = false;
private final Scroller scroller;
private final ScrollRunnable scrollRunnable;
private final RectF menuBounds;
private final Path pathA;
private final Path pathB;
private final Paint paint;
private final int shadowWidth;
public CoverAnimationEffecter(PuppetView readAnimView) {
this.readAnimView = readAnimView;
scroller = new Scroller(readAnimView.getContext(), new AccelerateDecelerateInterpolator());
scrollRunnable = new ScrollRunnable();
menuBounds = new RectF();
pathA = new Path();
pathB = new Path();
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
shadowWidth = 20;
}
private int downArea = DOWN_AREA_NONE;
private float downX = 0F;
private int coverSlideDirection = AnimHelper.SLID_DIRECTION_UNKNOWN;
private final List<Float> moveSampling = new LinkedList<>();
private final int MAX_COUNT = 5;
private boolean prepareDrawCoverAnimEffect = false;
private float currentX = -1;
@Override
public void handlerEvent(MotionEvent event) {
if (coverAnimationRunning) return;
float x = event.getRawX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
moveSampling.clear();
downX = x;
prepareDrawCoverAnimEffect = false;
isTouching = true;
currentX = -1;
downArea = DOWN_AREA_NONE;
coverSlideDirection = AnimHelper.SLID_DIRECTION_UNKNOWN;
if (x > menuBounds.left && y > menuBounds.top
&& x < menuBounds.right && y < menuBounds.bottom) {
downArea = DOWN_AREA_MENU;
} else if (x < vWidth / 2F) {
downArea = DOWN_AREA_LEFT;
} else {
downArea = DOWN_AREA_RIGHT;
}
break;
case MotionEvent.ACTION_MOVE:
isTouching = true;
float curDistance = x - downX;
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_UNKNOWN && checkDownArea(downArea)) {
if (curDistance > 0) {
coverSlideDirection = AnimHelper.SLID_DIRECTION_RIGHT;
} else {
coverSlideDirection = AnimHelper.SLID_DIRECTION_LEFT;
}
readAnimView.buildBitmap(coverSlideDirection);
prepareDrawCoverAnimEffect = checkAnimCondition(coverSlideDirection);
}
if (prepareDrawCoverAnimEffect) {
if (moveSampling.size() == 0
|| x != moveSampling.get(moveSampling.size() - 1)) {
moveSampling.add(x);
}
if (moveSampling.size() > MAX_COUNT) {
moveSampling.remove(0);
}
currentX = x;
invalidate();
}
break;
case MotionEvent.ACTION_CANCEL:
isTouching = false;
break;
case MotionEvent.ACTION_UP:
currentX = x;
if (prepareDrawCoverAnimEffect) {
if (moveSampling.size() > 0) {
float lastMoveX = moveSampling.get(moveSampling.size() - 1);
float firstMoveX = moveSampling.get(0);
float finallyMoveX = lastMoveX - firstMoveX;
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT) {
boolean lastFingerLeftSlop = finallyMoveX < 10;
touchUp(lastFingerLeftSlop);
} else if (coverSlideDirection == AnimHelper.SLID_DIRECTION_RIGHT) {
finallyMoveX = lastMoveX - firstMoveX;
touchUp(finallyMoveX < 0);
}
} else {
touchUp(false);
}
} else if (downArea == DOWN_AREA_MENU) {
if (x > menuBounds.left && x < menuBounds.right
&& y > menuBounds.top && y < menuBounds.bottom) {
readAnimView.onClickMenuArea();
}
} else if (downArea != DOWN_AREA_NONE) {
if (x == downX && downX >= vWidth / 2F) {//下一页
coverSlideDirection = AnimHelper.SLID_DIRECTION_LEFT;
readAnimView.buildBitmap(coverSlideDirection);
if (checkAnimCondition(coverSlideDirection)) {
touchUp(true);
}
} else if (x == downX && downX < vWidth / 2F) {//上一页
coverSlideDirection = AnimHelper.SLID_DIRECTION_RIGHT;
readAnimView.buildBitmap(coverSlideDirection);
if (checkAnimCondition(coverSlideDirection)) {
touchUp(false);
}
}
}
moveSampling.clear();
isTouching = false;
break;
default:
break;
}
}
private void touchUp(boolean lastFingerLeftSlop) {
| DLog.log("touchUp coverAnimationRunning=%s", coverAnimationRunning); |
coverAnimationRunning = true;
isCancelFlip = (coverSlideDirection == AnimHelper.SLID_DIRECTION_RIGHT && lastFingerLeftSlop)
|| (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT && !lastFingerLeftSlop);
int duration = isCancelFlip ? AnimHelper.CANCEL_ANIM_DURATION : AnimHelper.RELAY_ANIM_DURATION;
duration = (int) (duration * 0.7F);//cover动画时间减少一点
// duration = 1000;//cover动画时间减少一点
int startX = (int) currentX;
int startY = 0;
int dy = 0;
int dx;
if (lastFingerLeftSlop) {
dx = (int) -(vWidth - (downX - currentX));
} else {
dx = vWidth - (int) currentX;
}
scroller.startScroll(startX, startY, dx, dy, duration);
invalidate();
}
@Override
public void draw(Canvas canvas) {
if (currentX == -1) {
DLog.log("CoverAnimationEffect draw 1");
return;
}
if (coverSlideDirection != AnimHelper.SLID_DIRECTION_LEFT && coverSlideDirection != AnimHelper.SLID_DIRECTION_RIGHT) {
DLog.log("CoverAnimationEffect draw 2");
return;
}
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT
&& (null == readAnimView.getCurrentBitmap() || null == readAnimView.getNextBitmap())) {
DLog.log("CoverAnimationEffect draw 3");
return;
}
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_RIGHT && null == readAnimView.getPreviousBitmap()) {
DLog.log("CoverAnimationEffect draw 4");
return;
}
DLog.log("CoverAnimationEffect draw 5");
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT) {
float offset = downX - currentX;
offset = Math.max(0, offset);
canvas.save();
canvas.clipPath(getPathAToLeft());
canvas.drawBitmap(readAnimView.getCurrentBitmap(), -offset, 0, paint);
canvas.restore();
canvas.save();
canvas.clipPath(getPathB());
canvas.drawBitmap(readAnimView.getNextBitmap(), 0, 0, paint);
canvas.restore();
drawShadow((int) (vWidth - offset), canvas);
} else {
float leftOffset = vWidth - currentX;
canvas.save();
canvas.clipPath(getPathAToRight());
canvas.drawBitmap(readAnimView.getPreviousBitmap(), -leftOffset, 0, paint);
canvas.restore();
drawShadow((int) currentX, canvas);
}
}
private void drawShadow(int left, Canvas canvas) {
GradientDrawable drawable = readAnimView.getAnimHelper().getCoverGradientDrawable();
drawable.setBounds(left, 0, left + shadowWidth, vHeight);
drawable.draw(canvas);
}
private Path getPathAToLeft() {
pathA.reset();
float x = vWidth - (downX - currentX);
x = Math.min(vWidth, x);
pathA.lineTo(x, 0);
pathA.lineTo(x, vHeight);
pathA.lineTo(0, vHeight);
pathA.close();
return pathA;
}
private Path getPathB() {
pathB.reset();
float x = vWidth - (downX - currentX);
x = Math.min(vWidth, x);
pathB.moveTo(x, 0);
pathB.lineTo(vWidth, 0);
pathB.lineTo(vWidth, vHeight);
pathB.lineTo(x, vHeight);
pathB.close();
return pathB;
}
private Path getPathAToRight() {
pathA.reset();
pathA.lineTo(currentX, 0);
pathA.lineTo(currentX, vHeight);
pathA.lineTo(0, vHeight);
pathA.close();
return pathA;
}
private boolean checkDownArea(int downArea) {
return downArea != DOWN_AREA_MENU && downArea != DOWN_AREA_NONE;
}
private boolean checkAnimCondition(int slideDirection) {
if (slideDirection == AnimHelper.SLID_DIRECTION_LEFT && (null != readAnimView.getNextBitmap() && null != readAnimView.getCurrentBitmap())) {
return true;
} else if (slideDirection == AnimHelper.SLID_DIRECTION_RIGHT && null != readAnimView.getPreviousBitmap()) {
return true;
}
return false;
}
@Override
public boolean animInEffect() {
return isTouching || coverAnimationRunning;
}
@Override
public void onViewSizeChanged(int vWidth, int vHeight) {
this.vWidth = vWidth;
this.vHeight = vHeight;
menuBounds.left = vWidth / 3F;
menuBounds.top = vHeight / 3F;
menuBounds.right = vWidth * 2 / 3F;
menuBounds.bottom = vHeight * 2 / 3F;
}
@Override
public void onViewAttachedToWindow() {
}
@Override
public void onViewDetachedFromWindow() {
readAnimView.removeCallbacks(scrollRunnable);
}
private void invalidate() {
readAnimView.postInvalidate();
}
@Override
public void onScroll() {
if (scroller.computeScrollOffset()) {
int x = scroller.getCurrX();
int y = scroller.getCurrY();
if (x == scroller.getFinalX() && y == scroller.getFinalY()) {
scroller.forceFinished(true);
//补一点时间,避免动画太快结束,提供两次动画触发间隔
DLog.log("coverAnimationRunning coverAnimationRunning=%s 结束,延时开启 状态重置", coverAnimationRunning);
readAnimView.post(scrollRunnable);
} else {
currentX = x;
invalidate();
}
}
}
protected class ScrollRunnable implements Runnable {
@Override
public void run() {
readAnimView.reset();
coverAnimationRunning = false;
if (!isCancelFlip) {
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT) {
readAnimView.onExpectNext();
} else if (coverSlideDirection == AnimHelper.SLID_DIRECTION_RIGHT) {
readAnimView.onExpectPrevious();
}
}
invalidate();
}
}
}
| app/src/main/java/com/juziml/read/business/read/anim/CoverAnimationEffecter.java | Western-parotia-BookViewProject-1727e80 | [
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " if (moveSampling.size() > MAX_COUNT) {\n moveSampling.remove(0);\n }\n touchMoveAndInvalidate(x, y, curlSlideDirection, true);\n }\n }\n break;\n case MotionEvent.ACTION_CANCEL://[避免curl动画执行时,切换了flipMode 响应ACTION_CANCEL]\n isTouching = false;\n break;",
"score": 0.8338916301727295
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookRecyclerView.java",
"retrieved_chunk": " } else {\n readLayoutManger.setAutoLeftScroll(finallyMoveX < 0);\n }\n moveSampling.clear();\n } else {\n readLayoutManger.setAutoLeftScroll(false);\n }\n break;\n default:\n break;",
"score": 0.8298620581626892
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookRecyclerView.java",
"retrieved_chunk": " readLayoutManger.onRecyclerViewSizeChange();\n }\n private final List<Float> moveSampling = new LinkedList<>();\n private final int MAX_COUNT = 5;\n @Override\n public boolean isScrollContainer() {\n if (allowInterceptTouchEvent) {\n return super.isScrollContainer();\n } else {\n return false;",
"score": 0.8238740563392639
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " } else {\n touchMove(x, y, curlSlideDirection, false, true);\n }\n }\n }\n @Override\n public void handlerEvent(MotionEvent event) {\n if (curlAnimationRunning) return;\n float x = event.getRawX();\n float y = event.getRawY();",
"score": 0.8230323195457458
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/PaperLayout.java",
"retrieved_chunk": " }\n @Override\n public boolean isScrollContainer() {\n return false;\n }\n private float interceptDownX;\n @Override\n public boolean onInterceptTouchEvent(MotionEvent ev) {\n //动画执行期间 子view 也不可获取事件\n if (bookRecyclerView.animRunning()) return true;",
"score": 0.8076649904251099
}
] | java | DLog.log("touchUp coverAnimationRunning=%s", coverAnimationRunning); |
package com.juziml.read.business.read.view;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.List;
/**
* 关闭了抛投效果
* create by zhusw on 2020-03-30 11:51
*/
public class BookRecyclerView extends RecyclerView implements RVInnerItemFunction, RVOuterFunction {
private final BookLayoutManager readLayoutManger;
private boolean allowInterceptTouchEvent = true;
private int currentPosition = 0;
private WeakReference<EventProxy> eventProxyWeakReference;
private AnimParentView animParentView;
private BookView.OnPositionChangedListener onPositionChangedListener;
public BookRecyclerView(Context context) {
this(context, null);
}
public BookRecyclerView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public BookRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
readLayoutManger = new BookLayoutManager(context);
setLayoutManager(readLayoutManger);
readLayoutManger.setOnForceLayoutCompleted(new ItemOnForceLayoutCompleted());
readLayoutManger.setonStopScroller(new ItemOnScrollStop());
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
animParentView = (AnimParentView) getParent();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
eventProxyWeakReference.clear();
}
protected void bindReadCurlAnimProxy(EventProxy ic) {
if (null != eventProxyWeakReference) {
eventProxyWeakReference.clear();
}
eventProxyWeakReference = new WeakReference<>(ic);
}
protected void setOnPositionChangedListener(BookView.OnPositionChangedListener onPositionChangedListener) {
this.onPositionChangedListener = onPositionChangedListener;
}
@Override
public boolean fling(int velocityX, int velocityY) {
return false;
}
@Override
public void scrollToPosition(int position) {
readLayoutManger.forceScrollToPosition(position);
}
@Override
public void smoothScrollToPosition(int position) {
readLayoutManger.smoothScrollToPosition(position);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
readLayoutManger.onRecyclerViewSizeChange();
}
private final List<Float> moveSampling = new LinkedList<>();
private final int MAX_COUNT = 5;
@Override
public boolean isScrollContainer() {
if (allowInterceptTouchEvent) {
return super.isScrollContainer();
} else {
return false;
}
}
private float downX = 0F;
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouchEvent(MotionEvent e) {
if (!allowInterceptTouchEvent) return false;//[偶现 动画期间 产生了item滑动,这里最后杀手锏再屏蔽下]
switch (e.getAction()) {
case MotionEvent.ACTION_DOWN:
moveSampling.clear();
downX = e.getRawX();
break;
case MotionEvent.ACTION_MOVE:
float mx = e.getRawX();
if (moveSampling.size() == 0
|| mx != moveSampling.get(moveSampling.size() - 1)) {
moveSampling.add(mx);
}
if (moveSampling.size() > MAX_COUNT) {
moveSampling.remove(0);
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
if (moveSampling.size() > 0) {
float lastMoveX = moveSampling.get(moveSampling.size() - 1);
float firstMoveX = moveSampling.get(0);
float finallyMoveX = lastMoveX - firstMoveX;
if (lastMoveX - downX < 0) {//左滑
readLayoutManger.setAutoLeftScroll(finallyMoveX < 10);
} else {
| readLayoutManger.setAutoLeftScroll(finallyMoveX < 0); |
}
moveSampling.clear();
} else {
readLayoutManger.setAutoLeftScroll(false);
}
break;
default:
break;
}
return super.onTouchEvent(e);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent e) {
//交由父类处理滑动,flip = BookFlipMode.MODE_NORMAL,
if (allowInterceptTouchEvent) {
return super.onInterceptTouchEvent(e);
}
//交由子View自行处理,flip = BookFlipMode.MODE_COVER| BookFlipMode.MODE_CURL
return false;
}
@Override
public void onExpectNext(boolean smooth) {
Adapter adapter = getAdapter();
final int dataCount = adapter.getItemCount();
final int nextPos = currentPosition + 1;
if (nextPos < dataCount) {
if (smooth) {
smoothScrollToPosition(nextPos);
} else {
scrollToPosition(nextPos);
}
}
}
@Override
public void onExpectPrevious(boolean smooth) {
if (currentPosition - 1 >= 0) {
if (smooth) {
smoothScrollToPosition(currentPosition - 1);
} else {
scrollToPosition(currentPosition - 1);
}
}
}
protected void setFlipMode(int flipMode) {
readLayoutManger.setBookFlipMode(flipMode);
if (flipMode == BookLayoutManager.BookFlipMode.MODE_CURL
|| flipMode == BookLayoutManager.BookFlipMode.MODE_COVER) {
allowInterceptTouchEvent = false;
} else {
allowInterceptTouchEvent = true;
}
readLayoutManger.requestLayout();
}
@Override
public int getFlipMode() {
return readLayoutManger.getBookFlipMode();
}
@Override
public void onItemViewTouchEvent(MotionEvent event) {
if (null != eventProxyWeakReference && null != eventProxyWeakReference.get()) {
eventProxyWeakReference.get().onItemViewTouchEvent(event);
}
}
@Override
public boolean animRunning() {
if (null != eventProxyWeakReference && null != eventProxyWeakReference.get()) {
eventProxyWeakReference.get().animRunning();
}
return false;
}
@Override
public void onClickMenu() {
animParentView.onClickMenuArea();
}
private class ItemOnScrollStop implements BookLayoutManager.OnStopScroller {
@Override
public void onStop(boolean autoLeftScroll, int curPos) {
boolean arriveNext = currentPosition < curPos;
currentPosition = curPos;
if (null != onPositionChangedListener) {
onPositionChangedListener.onChanged(arriveNext, curPos);
}
}
}
private class ItemOnForceLayoutCompleted implements BookLayoutManager.OnForceLayoutCompleted {
@Override
public void onLayoutCompleted(final int curPos) {
boolean arriveNext = currentPosition < curPos;
currentPosition = curPos;
if (null != onPositionChangedListener) {
onPositionChangedListener.onChanged(arriveNext, curPos);
}
}
}
@Override
public Bitmap getPreviousBitmap() {
int prePos = currentPosition - 1;
Bitmap pb = null;
if (prePos >= 0) {
pb = printViewToBitmap(prePos);
}
return pb;
}
@Override
public Bitmap getCurrentBitmap() {
return printViewToBitmap(currentPosition);
}
@Override
public Bitmap getNextBitmap() {
final int dataCount = getAdapter().getItemCount();
int nextPos = currentPosition + 1;
Bitmap nb = null;
if (nextPos < dataCount) {
nb = printViewToBitmap(nextPos);
}
return nb;
}
/**
* 将view渲染结果 打印到一个bitmap上
*
* @param pos
* @return
*/
private Bitmap printViewToBitmap(int pos) {
View view = readLayoutManger.findViewByPosition(pos);
if (null != view) {
if (view instanceof PaperLayout) {
PaperLayout pageView = (PaperLayout) view;
Bitmap bitmapTarget = Bitmap.createBitmap(pageView.getWidth(), pageView.getHeight(), Bitmap.Config.ARGB_4444);
pageView.drawViewScreenShotToBitmap(bitmapTarget);
return bitmapTarget;
} else {
throw new IllegalArgumentException("item 根View必须使用 PaperLayout");
}
}
return null;
}
}
| app/src/main/java/com/juziml/read/business/read/view/BookRecyclerView.java | Western-parotia-BookViewProject-1727e80 | [
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/CoverAnimationEffecter.java",
"retrieved_chunk": " break;\n case MotionEvent.ACTION_UP:\n currentX = x;\n if (prepareDrawCoverAnimEffect) {\n if (moveSampling.size() > 0) {\n float lastMoveX = moveSampling.get(moveSampling.size() - 1);\n float firstMoveX = moveSampling.get(0);\n float finallyMoveX = lastMoveX - firstMoveX;\n if (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT) {\n boolean lastFingerLeftSlop = finallyMoveX < 10;",
"score": 0.9429739713668823
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " case MotionEvent.ACTION_UP://需要对最后手势进行采样,判断是 取消还是自动翻页\n if (drawCurlAnimBefore) {\n if (moveSampling.size() > 0) {\n float lastMoveX = moveSampling.get(moveSampling.size() - 1);\n float firstMoveX = moveSampling.get(0);\n float finallyMoveX = lastMoveX - firstMoveX;\n if (curlSlideDirection == AnimHelper.SLID_DIRECTION_LEFT) {\n boolean lastFingerLeftSlop = finallyMoveX < 10;\n touchUp(lastFingerLeftSlop);\n } else if (curlSlideDirection == AnimHelper.SLID_DIRECTION_RIGHT) {",
"score": 0.9190948009490967
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " switch (event.getAction()) {\n case MotionEvent.ACTION_DOWN:\n isTouching = true;\n drawCurlAnimBefore = false;\n moveSampling.clear();\n downX = x;\n curlSlideDirection = AnimHelper.SLID_DIRECTION_UNKNOWN;\n if (x < menuBounds.left) {\n downArea = DOWN_AREA_LEFT;\n } else if (x > menuBounds.left && y < menuBounds.top) {",
"score": 0.8474956750869751
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " finallyMoveX = lastMoveX - firstMoveX;\n touchUp(finallyMoveX < 0);\n }\n moveSampling.clear();\n } else {\n touchUp(false);\n }\n } else if (downArea == DOWN_AREA_MENU) {\n if (x > menuBounds.left && x < menuBounds.right && y > menuBounds.top && y < menuBounds.bottom) {\n readAnimView.onClickMenuArea();",
"score": 0.8465403318405151
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/CoverAnimationEffecter.java",
"retrieved_chunk": " touchUp(lastFingerLeftSlop);\n } else if (coverSlideDirection == AnimHelper.SLID_DIRECTION_RIGHT) {\n finallyMoveX = lastMoveX - firstMoveX;\n touchUp(finallyMoveX < 0);\n }\n } else {\n touchUp(false);\n }\n } else if (downArea == DOWN_AREA_MENU) {\n if (x > menuBounds.left && x < menuBounds.right",
"score": 0.8458129167556763
}
] | java | readLayoutManger.setAutoLeftScroll(finallyMoveX < 0); |
package com.juziml.read.business.read.anim;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.drawable.GradientDrawable;
import android.view.MotionEvent;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.Scroller;
import com.juziml.read.business.read.view.PuppetView;
import com.juziml.read.utils.DLog;
import java.util.LinkedList;
import java.util.List;
/**
* create by zhusw on 2020-08-24 14:06
*/
public class CoverAnimationEffecter implements IAnimationEffecter {
private final static int DOWN_AREA_NONE = -1;
private final static int DOWN_AREA_MENU = 1;
private final static int DOWN_AREA_LEFT = 2;
private final static int DOWN_AREA_RIGHT = 3;
int vWidth = 1;
int vHeight = 1;
private final PuppetView readAnimView;
private boolean isCancelFlip = false;
private boolean coverAnimationRunning = false;
private boolean isTouching = false;
private final Scroller scroller;
private final ScrollRunnable scrollRunnable;
private final RectF menuBounds;
private final Path pathA;
private final Path pathB;
private final Paint paint;
private final int shadowWidth;
public CoverAnimationEffecter(PuppetView readAnimView) {
this.readAnimView = readAnimView;
scroller = new Scroller(readAnimView.getContext(), new AccelerateDecelerateInterpolator());
scrollRunnable = new ScrollRunnable();
menuBounds = new RectF();
pathA = new Path();
pathB = new Path();
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
shadowWidth = 20;
}
private int downArea = DOWN_AREA_NONE;
private float downX = 0F;
private int coverSlideDirection = AnimHelper.SLID_DIRECTION_UNKNOWN;
private final List<Float> moveSampling = new LinkedList<>();
private final int MAX_COUNT = 5;
private boolean prepareDrawCoverAnimEffect = false;
private float currentX = -1;
@Override
public void handlerEvent(MotionEvent event) {
if (coverAnimationRunning) return;
float x = event.getRawX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
moveSampling.clear();
downX = x;
prepareDrawCoverAnimEffect = false;
isTouching = true;
currentX = -1;
downArea = DOWN_AREA_NONE;
coverSlideDirection = AnimHelper.SLID_DIRECTION_UNKNOWN;
if (x > menuBounds.left && y > menuBounds.top
&& x < menuBounds.right && y < menuBounds.bottom) {
downArea = DOWN_AREA_MENU;
} else if (x < vWidth / 2F) {
downArea = DOWN_AREA_LEFT;
} else {
downArea = DOWN_AREA_RIGHT;
}
break;
case MotionEvent.ACTION_MOVE:
isTouching = true;
float curDistance = x - downX;
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_UNKNOWN && checkDownArea(downArea)) {
if (curDistance > 0) {
coverSlideDirection = AnimHelper.SLID_DIRECTION_RIGHT;
} else {
coverSlideDirection = AnimHelper.SLID_DIRECTION_LEFT;
}
readAnimView.buildBitmap(coverSlideDirection);
prepareDrawCoverAnimEffect = checkAnimCondition(coverSlideDirection);
}
if (prepareDrawCoverAnimEffect) {
if (moveSampling.size() == 0
|| x != moveSampling.get(moveSampling.size() - 1)) {
moveSampling.add(x);
}
if (moveSampling.size() > MAX_COUNT) {
moveSampling.remove(0);
}
currentX = x;
invalidate();
}
break;
case MotionEvent.ACTION_CANCEL:
isTouching = false;
break;
case MotionEvent.ACTION_UP:
currentX = x;
if (prepareDrawCoverAnimEffect) {
if (moveSampling.size() > 0) {
float lastMoveX = moveSampling.get(moveSampling.size() - 1);
float firstMoveX = moveSampling.get(0);
float finallyMoveX = lastMoveX - firstMoveX;
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT) {
boolean lastFingerLeftSlop = finallyMoveX < 10;
touchUp(lastFingerLeftSlop);
} else if (coverSlideDirection == AnimHelper.SLID_DIRECTION_RIGHT) {
finallyMoveX = lastMoveX - firstMoveX;
touchUp(finallyMoveX < 0);
}
} else {
touchUp(false);
}
} else if (downArea == DOWN_AREA_MENU) {
if (x > menuBounds.left && x < menuBounds.right
&& y > menuBounds.top && y < menuBounds.bottom) {
readAnimView.onClickMenuArea();
}
} else if (downArea != DOWN_AREA_NONE) {
if (x == downX && downX >= vWidth / 2F) {//下一页
coverSlideDirection = AnimHelper.SLID_DIRECTION_LEFT;
readAnimView.buildBitmap(coverSlideDirection);
if (checkAnimCondition(coverSlideDirection)) {
touchUp(true);
}
} else if (x == downX && downX < vWidth / 2F) {//上一页
coverSlideDirection = AnimHelper.SLID_DIRECTION_RIGHT;
readAnimView.buildBitmap(coverSlideDirection);
if (checkAnimCondition(coverSlideDirection)) {
touchUp(false);
}
}
}
moveSampling.clear();
isTouching = false;
break;
default:
break;
}
}
private void touchUp(boolean lastFingerLeftSlop) {
DLog.log("touchUp coverAnimationRunning=%s", coverAnimationRunning);
coverAnimationRunning = true;
isCancelFlip = (coverSlideDirection == AnimHelper.SLID_DIRECTION_RIGHT && lastFingerLeftSlop)
|| (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT && !lastFingerLeftSlop);
int duration = isCancelFlip ? AnimHelper.CANCEL_ANIM_DURATION : AnimHelper.RELAY_ANIM_DURATION;
duration = (int) (duration * 0.7F);//cover动画时间减少一点
// duration = 1000;//cover动画时间减少一点
int startX = (int) currentX;
int startY = 0;
int dy = 0;
int dx;
if (lastFingerLeftSlop) {
dx = (int) -(vWidth - (downX - currentX));
} else {
dx = vWidth - (int) currentX;
}
scroller.startScroll(startX, startY, dx, dy, duration);
invalidate();
}
@Override
public void draw(Canvas canvas) {
if (currentX == -1) {
DLog.log("CoverAnimationEffect draw 1");
return;
}
if (coverSlideDirection != AnimHelper.SLID_DIRECTION_LEFT && coverSlideDirection != AnimHelper.SLID_DIRECTION_RIGHT) {
DLog.log("CoverAnimationEffect draw 2");
return;
}
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT
&& (null == readAnimView.getCurrentBitmap() || null == readAnimView.getNextBitmap())) {
DLog.log("CoverAnimationEffect draw 3");
return;
}
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_RIGHT && null == readAnimView.getPreviousBitmap()) {
DLog.log("CoverAnimationEffect draw 4");
return;
}
DLog.log("CoverAnimationEffect draw 5");
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT) {
float offset = downX - currentX;
offset = Math.max(0, offset);
canvas.save();
canvas.clipPath(getPathAToLeft());
canvas.drawBitmap(readAnimView.getCurrentBitmap(), -offset, 0, paint);
canvas.restore();
canvas.save();
canvas.clipPath(getPathB());
canvas.drawBitmap(readAnimView.getNextBitmap(), 0, 0, paint);
canvas.restore();
drawShadow((int) (vWidth - offset), canvas);
} else {
float leftOffset = vWidth - currentX;
canvas.save();
canvas.clipPath(getPathAToRight());
canvas.drawBitmap(readAnimView.getPreviousBitmap(), -leftOffset, 0, paint);
canvas.restore();
drawShadow((int) currentX, canvas);
}
}
private void drawShadow(int left, Canvas canvas) {
GradientDrawable drawable = readAnimView.getAnimHelper().getCoverGradientDrawable();
drawable.setBounds(left, 0, left + shadowWidth, vHeight);
drawable.draw(canvas);
}
private Path getPathAToLeft() {
pathA.reset();
float x = vWidth - (downX - currentX);
x = Math.min(vWidth, x);
pathA.lineTo(x, 0);
pathA.lineTo(x, vHeight);
pathA.lineTo(0, vHeight);
pathA.close();
return pathA;
}
private Path getPathB() {
pathB.reset();
float x = vWidth - (downX - currentX);
x = Math.min(vWidth, x);
pathB.moveTo(x, 0);
pathB.lineTo(vWidth, 0);
pathB.lineTo(vWidth, vHeight);
pathB.lineTo(x, vHeight);
pathB.close();
return pathB;
}
private Path getPathAToRight() {
pathA.reset();
pathA.lineTo(currentX, 0);
pathA.lineTo(currentX, vHeight);
pathA.lineTo(0, vHeight);
pathA.close();
return pathA;
}
private boolean checkDownArea(int downArea) {
return downArea != DOWN_AREA_MENU && downArea != DOWN_AREA_NONE;
}
private boolean checkAnimCondition(int slideDirection) {
if (slideDirection == AnimHelper.SLID_DIRECTION_LEFT && (null != readAnimView.getNextBitmap() && null != readAnimView.getCurrentBitmap())) {
return true;
} else if (slideDirection == AnimHelper.SLID_DIRECTION_RIGHT && null != readAnimView.getPreviousBitmap()) {
return true;
}
return false;
}
@Override
public boolean animInEffect() {
return isTouching || coverAnimationRunning;
}
@Override
public void onViewSizeChanged(int vWidth, int vHeight) {
this.vWidth = vWidth;
this.vHeight = vHeight;
menuBounds.left = vWidth / 3F;
menuBounds.top = vHeight / 3F;
menuBounds.right = vWidth * 2 / 3F;
menuBounds.bottom = vHeight * 2 / 3F;
}
@Override
public void onViewAttachedToWindow() {
}
@Override
public void onViewDetachedFromWindow() {
readAnimView.removeCallbacks(scrollRunnable);
}
private void invalidate() {
readAnimView.postInvalidate();
}
@Override
public void onScroll() {
if (scroller.computeScrollOffset()) {
int x = scroller.getCurrX();
int y = scroller.getCurrY();
if (x == scroller.getFinalX() && y == scroller.getFinalY()) {
scroller.forceFinished(true);
//补一点时间,避免动画太快结束,提供两次动画触发间隔
| DLog.log("coverAnimationRunning coverAnimationRunning=%s 结束,延时开启 状态重置", coverAnimationRunning); |
readAnimView.post(scrollRunnable);
} else {
currentX = x;
invalidate();
}
}
}
protected class ScrollRunnable implements Runnable {
@Override
public void run() {
readAnimView.reset();
coverAnimationRunning = false;
if (!isCancelFlip) {
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT) {
readAnimView.onExpectNext();
} else if (coverSlideDirection == AnimHelper.SLID_DIRECTION_RIGHT) {
readAnimView.onExpectPrevious();
}
}
invalidate();
}
}
}
| app/src/main/java/com/juziml/read/business/read/anim/CoverAnimationEffecter.java | Western-parotia-BookViewProject-1727e80 | [
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " dy = (vHeight - ay);\n }\n this.isCancelFlip = isCancelFlip;\n int duration = isCancelFlip ? AnimHelper.CANCEL_ANIM_DURATION : AnimHelper.RELAY_ANIM_DURATION;\n curlAnimationRunning = true;\n scroller.startScroll(ax, ay, dx, dy, duration);\n invalidate();//猛然想起startScroll 需要在下一帧重绘时才生效\n }\n private int downArea = DOWN_AREA_NONE;\n private float downX = 0F;",
"score": 0.8480168581008911
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookLayoutManager.java",
"retrieved_chunk": " @Override\n public void onAnimationUpdate(ValueAnimator animation) {\n float value = (float) animation.getAnimatedValue();\n horizontalOffset = (long) (startedOffset + value);\n requestLayout();\n if (value == distance) {//主动给一个滚动回调,因为不会处罚onScrollstop\n if (null != onStopScroller) {\n onStopScroller.onStop(distance > 0, position);\n }\n }",
"score": 0.8346930146217346
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " cm.set(array);\n colorMatrixColorFilter = new ColorMatrixColorFilter(cm);\n scroller = new Scroller(readAnimView.getContext(), new LinearInterpolator());\n }\n @Override\n public void onScroll() {\n if (scroller.computeScrollOffset()) {\n int x = scroller.getCurrX();\n int y = scroller.getCurrY();\n int finalX = scroller.getFinalX();",
"score": 0.8207080364227295
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " break;\n case MotionEvent.ACTION_MOVE://确定滑动方向\n isTouching = true;\n if (checkDownArea(downArea)) {\n float moveDistance = x - downX;\n //滑动距离超过5px,且单次事件周期只设置一个方向,首次滑动距离大于5px时为方向判断依据\n if (downArea != DOWN_AREA_MENU && Math.abs(moveDistance) > AnimHelper.MOVE_SLOP && curlSlideDirection == AnimHelper.SLID_DIRECTION_UNKNOWN) {\n if (moveDistance > 0) {\n curlSlideDirection = AnimHelper.SLID_DIRECTION_RIGHT;\n } else {",
"score": 0.8136756420135498
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookLayoutManager.java",
"retrieved_chunk": " }\n // 分离全部的view,加入到临时缓存,这里调用,因为在滑动过程中,可显view 可能发生改变\n detachAndScrapAttachedViews(recycler);\n //-----------------------2 计算用于 view 确定位置的参数---------------\n float layoutX = 0;\n float fraction = 0;\n View tempView = null;\n int tempPosition = -1;\n if (onceCompleteScrollLength == -1) {\n // 因为firstVisiPos在下面可能被改变,所以用tempPosition暂存一下",
"score": 0.8125666379928589
}
] | java | DLog.log("coverAnimationRunning coverAnimationRunning=%s 结束,延时开启 状态重置", coverAnimationRunning); |
package com.juziml.read.business.read.view;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.List;
/**
* 关闭了抛投效果
* create by zhusw on 2020-03-30 11:51
*/
public class BookRecyclerView extends RecyclerView implements RVInnerItemFunction, RVOuterFunction {
private final BookLayoutManager readLayoutManger;
private boolean allowInterceptTouchEvent = true;
private int currentPosition = 0;
private WeakReference<EventProxy> eventProxyWeakReference;
private AnimParentView animParentView;
private BookView.OnPositionChangedListener onPositionChangedListener;
public BookRecyclerView(Context context) {
this(context, null);
}
public BookRecyclerView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public BookRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
readLayoutManger = new BookLayoutManager(context);
setLayoutManager(readLayoutManger);
readLayoutManger.setOnForceLayoutCompleted(new ItemOnForceLayoutCompleted());
readLayoutManger.setonStopScroller(new ItemOnScrollStop());
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
animParentView = (AnimParentView) getParent();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
eventProxyWeakReference.clear();
}
protected void bindReadCurlAnimProxy(EventProxy ic) {
if (null != eventProxyWeakReference) {
eventProxyWeakReference.clear();
}
eventProxyWeakReference = new WeakReference<>(ic);
}
protected void setOnPositionChangedListener(BookView.OnPositionChangedListener onPositionChangedListener) {
this.onPositionChangedListener = onPositionChangedListener;
}
@Override
public boolean fling(int velocityX, int velocityY) {
return false;
}
@Override
public void scrollToPosition(int position) {
readLayoutManger.forceScrollToPosition(position);
}
@Override
public void smoothScrollToPosition(int position) {
readLayoutManger.smoothScrollToPosition(position);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
readLayoutManger.onRecyclerViewSizeChange();
}
private final List<Float> moveSampling = new LinkedList<>();
private final int MAX_COUNT = 5;
@Override
public boolean isScrollContainer() {
if (allowInterceptTouchEvent) {
return super.isScrollContainer();
} else {
return false;
}
}
private float downX = 0F;
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouchEvent(MotionEvent e) {
if (!allowInterceptTouchEvent) return false;//[偶现 动画期间 产生了item滑动,这里最后杀手锏再屏蔽下]
switch (e.getAction()) {
case MotionEvent.ACTION_DOWN:
moveSampling.clear();
downX = e.getRawX();
break;
case MotionEvent.ACTION_MOVE:
float mx = e.getRawX();
if (moveSampling.size() == 0
|| mx != moveSampling.get(moveSampling.size() - 1)) {
moveSampling.add(mx);
}
if (moveSampling.size() > MAX_COUNT) {
moveSampling.remove(0);
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
if (moveSampling.size() > 0) {
float lastMoveX = moveSampling.get(moveSampling.size() - 1);
float firstMoveX = moveSampling.get(0);
float finallyMoveX = lastMoveX - firstMoveX;
if (lastMoveX - downX < 0) {//左滑
readLayoutManger.setAutoLeftScroll(finallyMoveX < 10);
} else {
readLayoutManger.setAutoLeftScroll(finallyMoveX < 0);
}
moveSampling.clear();
} else {
readLayoutManger.setAutoLeftScroll(false);
}
break;
default:
break;
}
return super.onTouchEvent(e);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent e) {
//交由父类处理滑动,flip = BookFlipMode.MODE_NORMAL,
if (allowInterceptTouchEvent) {
return super.onInterceptTouchEvent(e);
}
//交由子View自行处理,flip = BookFlipMode.MODE_COVER| BookFlipMode.MODE_CURL
return false;
}
@Override
public void onExpectNext(boolean smooth) {
Adapter adapter = getAdapter();
final int dataCount = adapter.getItemCount();
final int nextPos = currentPosition + 1;
if (nextPos < dataCount) {
if (smooth) {
smoothScrollToPosition(nextPos);
} else {
scrollToPosition(nextPos);
}
}
}
@Override
public void onExpectPrevious(boolean smooth) {
if (currentPosition - 1 >= 0) {
if (smooth) {
smoothScrollToPosition(currentPosition - 1);
} else {
scrollToPosition(currentPosition - 1);
}
}
}
protected void setFlipMode(int flipMode) {
| readLayoutManger.setBookFlipMode(flipMode); |
if (flipMode == BookLayoutManager.BookFlipMode.MODE_CURL
|| flipMode == BookLayoutManager.BookFlipMode.MODE_COVER) {
allowInterceptTouchEvent = false;
} else {
allowInterceptTouchEvent = true;
}
readLayoutManger.requestLayout();
}
@Override
public int getFlipMode() {
return readLayoutManger.getBookFlipMode();
}
@Override
public void onItemViewTouchEvent(MotionEvent event) {
if (null != eventProxyWeakReference && null != eventProxyWeakReference.get()) {
eventProxyWeakReference.get().onItemViewTouchEvent(event);
}
}
@Override
public boolean animRunning() {
if (null != eventProxyWeakReference && null != eventProxyWeakReference.get()) {
eventProxyWeakReference.get().animRunning();
}
return false;
}
@Override
public void onClickMenu() {
animParentView.onClickMenuArea();
}
private class ItemOnScrollStop implements BookLayoutManager.OnStopScroller {
@Override
public void onStop(boolean autoLeftScroll, int curPos) {
boolean arriveNext = currentPosition < curPos;
currentPosition = curPos;
if (null != onPositionChangedListener) {
onPositionChangedListener.onChanged(arriveNext, curPos);
}
}
}
private class ItemOnForceLayoutCompleted implements BookLayoutManager.OnForceLayoutCompleted {
@Override
public void onLayoutCompleted(final int curPos) {
boolean arriveNext = currentPosition < curPos;
currentPosition = curPos;
if (null != onPositionChangedListener) {
onPositionChangedListener.onChanged(arriveNext, curPos);
}
}
}
@Override
public Bitmap getPreviousBitmap() {
int prePos = currentPosition - 1;
Bitmap pb = null;
if (prePos >= 0) {
pb = printViewToBitmap(prePos);
}
return pb;
}
@Override
public Bitmap getCurrentBitmap() {
return printViewToBitmap(currentPosition);
}
@Override
public Bitmap getNextBitmap() {
final int dataCount = getAdapter().getItemCount();
int nextPos = currentPosition + 1;
Bitmap nb = null;
if (nextPos < dataCount) {
nb = printViewToBitmap(nextPos);
}
return nb;
}
/**
* 将view渲染结果 打印到一个bitmap上
*
* @param pos
* @return
*/
private Bitmap printViewToBitmap(int pos) {
View view = readLayoutManger.findViewByPosition(pos);
if (null != view) {
if (view instanceof PaperLayout) {
PaperLayout pageView = (PaperLayout) view;
Bitmap bitmapTarget = Bitmap.createBitmap(pageView.getWidth(), pageView.getHeight(), Bitmap.Config.ARGB_4444);
pageView.drawViewScreenShotToBitmap(bitmapTarget);
return bitmapTarget;
} else {
throw new IllegalArgumentException("item 根View必须使用 PaperLayout");
}
}
return null;
}
}
| app/src/main/java/com/juziml/read/business/read/view/BookRecyclerView.java | Western-parotia-BookViewProject-1727e80 | [
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookLayoutManager.java",
"retrieved_chunk": " *\n * @param position 目标Item索引\n */\n public void smoothScrollToPosition(int position) {\n if (position > -1 && position < getItemCount()) {\n scrollToPosition(position, true);\n }\n }\n public int findShouldSelectPosition() {\n if (onceCompleteScrollLength == -1 || firstVisiPos == -1) {",
"score": 0.8472763299942017
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookLayoutManager.java",
"retrieved_chunk": " *\n * @param position\n */\n public void forceScrollToPosition(int position) {\n if (position > -1 && position < getItemCount()) {\n scrollToPosition(position, false);\n }\n }\n /**\n * 平滑滚动到某个位置",
"score": 0.8450433015823364
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookView.java",
"retrieved_chunk": " public void smoothScrollToPosition(int position) {\n bookRecyclerView.smoothScrollToPosition(position);\n }\n public void setAdapter(RecyclerView.Adapter adapter) {\n bookRecyclerView.setAdapter(adapter);\n }\n public void setItemViewBackgroundColor(int itemViewBackgroundColor) {\n this.itemViewBackgroundColor = itemViewBackgroundColor;\n }\n @Override",
"score": 0.8286815881729126
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookView.java",
"retrieved_chunk": " @Override\n public Bitmap getNextBitmap() {\n return bookRecyclerView.getNextBitmap();\n }\n @Override\n public int getBackgroundColor() {\n return itemViewBackgroundColor;\n }\n public void setFlipMode(int flipMode) {\n if (flipMode == BookLayoutManager.BookFlipMode.MODE_CURL",
"score": 0.8286639451980591
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/CoverAnimationEffecter.java",
"retrieved_chunk": " }\n private void invalidate() {\n readAnimView.postInvalidate();\n }\n @Override\n public void onScroll() {\n if (scroller.computeScrollOffset()) {\n int x = scroller.getCurrX();\n int y = scroller.getCurrY();\n if (x == scroller.getFinalX() && y == scroller.getFinalY()) {",
"score": 0.8233259916305542
}
] | java | readLayoutManger.setBookFlipMode(flipMode); |
package com.juziml.read.business.read.view;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.List;
/**
* 关闭了抛投效果
* create by zhusw on 2020-03-30 11:51
*/
public class BookRecyclerView extends RecyclerView implements RVInnerItemFunction, RVOuterFunction {
private final BookLayoutManager readLayoutManger;
private boolean allowInterceptTouchEvent = true;
private int currentPosition = 0;
private WeakReference<EventProxy> eventProxyWeakReference;
private AnimParentView animParentView;
private BookView.OnPositionChangedListener onPositionChangedListener;
public BookRecyclerView(Context context) {
this(context, null);
}
public BookRecyclerView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public BookRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
readLayoutManger = new BookLayoutManager(context);
setLayoutManager(readLayoutManger);
readLayoutManger.setOnForceLayoutCompleted(new ItemOnForceLayoutCompleted());
readLayoutManger.setonStopScroller(new ItemOnScrollStop());
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
animParentView = (AnimParentView) getParent();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
eventProxyWeakReference.clear();
}
protected void bindReadCurlAnimProxy(EventProxy ic) {
if (null != eventProxyWeakReference) {
eventProxyWeakReference.clear();
}
eventProxyWeakReference = new WeakReference<>(ic);
}
protected void setOnPositionChangedListener(BookView.OnPositionChangedListener onPositionChangedListener) {
this.onPositionChangedListener = onPositionChangedListener;
}
@Override
public boolean fling(int velocityX, int velocityY) {
return false;
}
@Override
public void scrollToPosition(int position) {
| readLayoutManger.forceScrollToPosition(position); |
}
@Override
public void smoothScrollToPosition(int position) {
readLayoutManger.smoothScrollToPosition(position);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
readLayoutManger.onRecyclerViewSizeChange();
}
private final List<Float> moveSampling = new LinkedList<>();
private final int MAX_COUNT = 5;
@Override
public boolean isScrollContainer() {
if (allowInterceptTouchEvent) {
return super.isScrollContainer();
} else {
return false;
}
}
private float downX = 0F;
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouchEvent(MotionEvent e) {
if (!allowInterceptTouchEvent) return false;//[偶现 动画期间 产生了item滑动,这里最后杀手锏再屏蔽下]
switch (e.getAction()) {
case MotionEvent.ACTION_DOWN:
moveSampling.clear();
downX = e.getRawX();
break;
case MotionEvent.ACTION_MOVE:
float mx = e.getRawX();
if (moveSampling.size() == 0
|| mx != moveSampling.get(moveSampling.size() - 1)) {
moveSampling.add(mx);
}
if (moveSampling.size() > MAX_COUNT) {
moveSampling.remove(0);
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
if (moveSampling.size() > 0) {
float lastMoveX = moveSampling.get(moveSampling.size() - 1);
float firstMoveX = moveSampling.get(0);
float finallyMoveX = lastMoveX - firstMoveX;
if (lastMoveX - downX < 0) {//左滑
readLayoutManger.setAutoLeftScroll(finallyMoveX < 10);
} else {
readLayoutManger.setAutoLeftScroll(finallyMoveX < 0);
}
moveSampling.clear();
} else {
readLayoutManger.setAutoLeftScroll(false);
}
break;
default:
break;
}
return super.onTouchEvent(e);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent e) {
//交由父类处理滑动,flip = BookFlipMode.MODE_NORMAL,
if (allowInterceptTouchEvent) {
return super.onInterceptTouchEvent(e);
}
//交由子View自行处理,flip = BookFlipMode.MODE_COVER| BookFlipMode.MODE_CURL
return false;
}
@Override
public void onExpectNext(boolean smooth) {
Adapter adapter = getAdapter();
final int dataCount = adapter.getItemCount();
final int nextPos = currentPosition + 1;
if (nextPos < dataCount) {
if (smooth) {
smoothScrollToPosition(nextPos);
} else {
scrollToPosition(nextPos);
}
}
}
@Override
public void onExpectPrevious(boolean smooth) {
if (currentPosition - 1 >= 0) {
if (smooth) {
smoothScrollToPosition(currentPosition - 1);
} else {
scrollToPosition(currentPosition - 1);
}
}
}
protected void setFlipMode(int flipMode) {
readLayoutManger.setBookFlipMode(flipMode);
if (flipMode == BookLayoutManager.BookFlipMode.MODE_CURL
|| flipMode == BookLayoutManager.BookFlipMode.MODE_COVER) {
allowInterceptTouchEvent = false;
} else {
allowInterceptTouchEvent = true;
}
readLayoutManger.requestLayout();
}
@Override
public int getFlipMode() {
return readLayoutManger.getBookFlipMode();
}
@Override
public void onItemViewTouchEvent(MotionEvent event) {
if (null != eventProxyWeakReference && null != eventProxyWeakReference.get()) {
eventProxyWeakReference.get().onItemViewTouchEvent(event);
}
}
@Override
public boolean animRunning() {
if (null != eventProxyWeakReference && null != eventProxyWeakReference.get()) {
eventProxyWeakReference.get().animRunning();
}
return false;
}
@Override
public void onClickMenu() {
animParentView.onClickMenuArea();
}
private class ItemOnScrollStop implements BookLayoutManager.OnStopScroller {
@Override
public void onStop(boolean autoLeftScroll, int curPos) {
boolean arriveNext = currentPosition < curPos;
currentPosition = curPos;
if (null != onPositionChangedListener) {
onPositionChangedListener.onChanged(arriveNext, curPos);
}
}
}
private class ItemOnForceLayoutCompleted implements BookLayoutManager.OnForceLayoutCompleted {
@Override
public void onLayoutCompleted(final int curPos) {
boolean arriveNext = currentPosition < curPos;
currentPosition = curPos;
if (null != onPositionChangedListener) {
onPositionChangedListener.onChanged(arriveNext, curPos);
}
}
}
@Override
public Bitmap getPreviousBitmap() {
int prePos = currentPosition - 1;
Bitmap pb = null;
if (prePos >= 0) {
pb = printViewToBitmap(prePos);
}
return pb;
}
@Override
public Bitmap getCurrentBitmap() {
return printViewToBitmap(currentPosition);
}
@Override
public Bitmap getNextBitmap() {
final int dataCount = getAdapter().getItemCount();
int nextPos = currentPosition + 1;
Bitmap nb = null;
if (nextPos < dataCount) {
nb = printViewToBitmap(nextPos);
}
return nb;
}
/**
* 将view渲染结果 打印到一个bitmap上
*
* @param pos
* @return
*/
private Bitmap printViewToBitmap(int pos) {
View view = readLayoutManger.findViewByPosition(pos);
if (null != view) {
if (view instanceof PaperLayout) {
PaperLayout pageView = (PaperLayout) view;
Bitmap bitmapTarget = Bitmap.createBitmap(pageView.getWidth(), pageView.getHeight(), Bitmap.Config.ARGB_4444);
pageView.drawViewScreenShotToBitmap(bitmapTarget);
return bitmapTarget;
} else {
throw new IllegalArgumentException("item 根View必须使用 PaperLayout");
}
}
return null;
}
}
| app/src/main/java/com/juziml/read/business/read/view/BookRecyclerView.java | Western-parotia-BookViewProject-1727e80 | [
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookView.java",
"retrieved_chunk": " public void smoothScrollToPosition(int position) {\n bookRecyclerView.smoothScrollToPosition(position);\n }\n public void setAdapter(RecyclerView.Adapter adapter) {\n bookRecyclerView.setAdapter(adapter);\n }\n public void setItemViewBackgroundColor(int itemViewBackgroundColor) {\n this.itemViewBackgroundColor = itemViewBackgroundColor;\n }\n @Override",
"score": 0.8816269636154175
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookView.java",
"retrieved_chunk": " }\n public void setOnPositionChangedListener(OnPositionChangedListener onPositionChangedListener) {\n bookRecyclerView.setOnPositionChangedListener(onPositionChangedListener);\n }\n public void setOnClickMenuListener(OnClickMenuListener onClickMenuListener) {\n this.onClickMenuListener = onClickMenuListener;\n }\n public void scrollToPosition(int position) {\n bookRecyclerView.scrollToPosition(position);\n }",
"score": 0.8744277954101562
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookLayoutManager.java",
"retrieved_chunk": " private long horizontalOffset;\n private int childWidth = 0;\n private ValueAnimator selectAnimator;\n private boolean autoLeftScroll = false;\n private OnStopScroller onStopScroller;\n private OnForceLayoutCompleted onForceLayoutCompleted;\n public BookLayoutManager(Context context) {\n this.context = context;\n }\n public void setonStopScroller(OnStopScroller onStopScroller) {",
"score": 0.8711509108543396
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/PuppetView.java",
"retrieved_chunk": " if (null != animationEffecter) {\n animationEffecter.onScroll();\n }\n }\n @Override\n public void onExpectNext() {\n parentView.onExpectNext();\n }\n @Override\n public void onExpectPrevious() {",
"score": 0.8688428997993469
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/CoverAnimationEffecter.java",
"retrieved_chunk": " }\n @Override\n public boolean animInEffect() {\n return isTouching || coverAnimationRunning;\n }\n @Override\n public void onViewSizeChanged(int vWidth, int vHeight) {\n this.vWidth = vWidth;\n this.vHeight = vHeight;\n menuBounds.left = vWidth / 3F;",
"score": 0.8632630705833435
}
] | java | readLayoutManger.forceScrollToPosition(position); |
package factory.methodFactory;
import factory.methodFactory.food.Food;
/**
* @Title: Test
* @Author bubuwang
* @Date 2023/5/11 16:59
* @description: 测试类 工厂方法模式是简单共产模式的进一步扩展,在一个工厂不足以满足业务语义的时候,需要用到多个工厂
*/
public class Test {
public static void main(String[] args) {
//中国食物工厂
ChineseFoodFactory chineseFoodFactory = new ChineseFoodFactory();
//美国食物工厂
AmericanFoodFactory AmericanFoodFactory = new AmericanFoodFactory();
//生产中国A类食物
Food chineseFoodA = chineseFoodFactory.produce("A");
chineseFoodA.food();
//生产中国B类食物
Food chineseFoodB = chineseFoodFactory.produce("B");
chineseFoodB.food();
//生产美国A类食物
| Food americanFoodA = AmericanFoodFactory.produce("A"); |
americanFoodA.food();
//生产美国B类食物
Food americanFoodB = AmericanFoodFactory.produce("A");
americanFoodB.food();
}
}
| creatorMode/factory/methodFactory/Test.java | WHyxrs-DesignMode-5af30b7 | [
{
"filename": "creatorMode/factory/methodFactory/ChineseFoodFactory.java",
"retrieved_chunk": "package factory.methodFactory;\nimport factory.methodFactory.food.ChineseFood;\nimport factory.methodFactory.food.ChineseFoodA;\nimport factory.methodFactory.food.ChineseFoodB;\nimport factory.methodFactory.food.Food;\n/**\n * @Title: ChineseFoodFactory\n * @Author bubuwang\n * @Date 2023/5/11 16:47\n * @description: 中国食物工厂",
"score": 0.7951542139053345
},
{
"filename": "creatorMode/factory/methodFactory/AmericanFoodFactory.java",
"retrieved_chunk": "package factory.methodFactory;\nimport factory.methodFactory.food.AmericanFood;\nimport factory.methodFactory.food.AmericanFoodA;\nimport factory.methodFactory.food.AmericanFoodB;\nimport factory.methodFactory.food.Food;\n/**\n * @Title: AmericanFoodFactory\n * @Author bubuwang\n * @Date 2023/5/11 16:48\n * @description: 美国食物工厂",
"score": 0.7909975051879883
},
{
"filename": "creatorMode/factory/methodFactory/food/AmericanFoodA.java",
"retrieved_chunk": "package factory.methodFactory.food;\n/**\n * @Title: AmericanFoodA\n * @Author bubuwang\n * @Date 2023/5/11 16:42\n * @description: 美国食物A\n */\npublic class AmericanFoodA implements AmericanFood{\n @Override\n public void food() {",
"score": 0.7078537344932556
},
{
"filename": "creatorMode/factory/methodFactory/food/AmericanFoodB.java",
"retrieved_chunk": "package factory.methodFactory.food;\n/**\n * @Title: AmericanFoodB\n * @Author bubuwang\n * @Date 2023/5/11 16:42\n * @description: 美国食物B\n */\npublic class AmericanFoodB implements AmericanFood{\n @Override\n public void food() {",
"score": 0.7049532532691956
},
{
"filename": "creatorMode/factory/simpleFactory/Test.java",
"retrieved_chunk": " */\npublic class Test {\n public static void main(String[] args) {\n //通过工厂选择相应的生产线\n PhoneProduceLine xiaoMiProduceLine = new MobileFactory(\"XiaoMi\").createPhone();\n xiaoMiProduceLine.create();\n PhoneProduceLine huaWeiproduceLine = new MobileFactory(\"HuaWei\").createPhone();\n huaWeiproduceLine.create();\n }\n}",
"score": 0.7003262639045715
}
] | java | Food americanFoodA = AmericanFoodFactory.produce("A"); |
package factory.methodFactory;
import factory.methodFactory.food.Food;
/**
* @Title: Test
* @Author bubuwang
* @Date 2023/5/11 16:59
* @description: 测试类 工厂方法模式是简单共产模式的进一步扩展,在一个工厂不足以满足业务语义的时候,需要用到多个工厂
*/
public class Test {
public static void main(String[] args) {
//中国食物工厂
ChineseFoodFactory chineseFoodFactory = new ChineseFoodFactory();
//美国食物工厂
AmericanFoodFactory AmericanFoodFactory = new AmericanFoodFactory();
//生产中国A类食物
Food chineseFoodA = chineseFoodFactory.produce("A");
chineseFoodA.food();
//生产中国B类食物
Food chineseFoodB = chineseFoodFactory.produce("B");
chineseFoodB.food();
//生产美国A类食物
Food americanFoodA = AmericanFoodFactory.produce("A");
americanFoodA.food();
//生产美国B类食物
Food americanFoodB | = AmericanFoodFactory.produce("A"); |
americanFoodB.food();
}
}
| creatorMode/factory/methodFactory/Test.java | WHyxrs-DesignMode-5af30b7 | [
{
"filename": "creatorMode/factory/methodFactory/AmericanFoodFactory.java",
"retrieved_chunk": "package factory.methodFactory;\nimport factory.methodFactory.food.AmericanFood;\nimport factory.methodFactory.food.AmericanFoodA;\nimport factory.methodFactory.food.AmericanFoodB;\nimport factory.methodFactory.food.Food;\n/**\n * @Title: AmericanFoodFactory\n * @Author bubuwang\n * @Date 2023/5/11 16:48\n * @description: 美国食物工厂",
"score": 0.8089817762374878
},
{
"filename": "creatorMode/factory/methodFactory/ChineseFoodFactory.java",
"retrieved_chunk": "package factory.methodFactory;\nimport factory.methodFactory.food.ChineseFood;\nimport factory.methodFactory.food.ChineseFoodA;\nimport factory.methodFactory.food.ChineseFoodB;\nimport factory.methodFactory.food.Food;\n/**\n * @Title: ChineseFoodFactory\n * @Author bubuwang\n * @Date 2023/5/11 16:47\n * @description: 中国食物工厂",
"score": 0.8056734800338745
},
{
"filename": "creatorMode/factory/methodFactory/food/AmericanFoodA.java",
"retrieved_chunk": "package factory.methodFactory.food;\n/**\n * @Title: AmericanFoodA\n * @Author bubuwang\n * @Date 2023/5/11 16:42\n * @description: 美国食物A\n */\npublic class AmericanFoodA implements AmericanFood{\n @Override\n public void food() {",
"score": 0.7207489013671875
},
{
"filename": "creatorMode/factory/methodFactory/food/AmericanFoodB.java",
"retrieved_chunk": "package factory.methodFactory.food;\n/**\n * @Title: AmericanFoodB\n * @Author bubuwang\n * @Date 2023/5/11 16:42\n * @description: 美国食物B\n */\npublic class AmericanFoodB implements AmericanFood{\n @Override\n public void food() {",
"score": 0.7206972241401672
},
{
"filename": "creatorMode/factory/methodFactory/food/AmericanFood.java",
"retrieved_chunk": "package factory.methodFactory.food;\n/**\n * @Title: AmericanFood\n * @Author bubuwang\n * @Date 2023/5/11 16:35\n * @description: 美国食物\n */\npublic interface AmericanFood extends Food {\n public void food();\n}",
"score": 0.7021089792251587
}
] | java | = AmericanFoodFactory.produce("A"); |
package com.juziml.read.business.read.view;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.List;
/**
* 关闭了抛投效果
* create by zhusw on 2020-03-30 11:51
*/
public class BookRecyclerView extends RecyclerView implements RVInnerItemFunction, RVOuterFunction {
private final BookLayoutManager readLayoutManger;
private boolean allowInterceptTouchEvent = true;
private int currentPosition = 0;
private WeakReference<EventProxy> eventProxyWeakReference;
private AnimParentView animParentView;
private BookView.OnPositionChangedListener onPositionChangedListener;
public BookRecyclerView(Context context) {
this(context, null);
}
public BookRecyclerView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public BookRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
readLayoutManger = new BookLayoutManager(context);
setLayoutManager(readLayoutManger);
| readLayoutManger.setOnForceLayoutCompleted(new ItemOnForceLayoutCompleted()); |
readLayoutManger.setonStopScroller(new ItemOnScrollStop());
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
animParentView = (AnimParentView) getParent();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
eventProxyWeakReference.clear();
}
protected void bindReadCurlAnimProxy(EventProxy ic) {
if (null != eventProxyWeakReference) {
eventProxyWeakReference.clear();
}
eventProxyWeakReference = new WeakReference<>(ic);
}
protected void setOnPositionChangedListener(BookView.OnPositionChangedListener onPositionChangedListener) {
this.onPositionChangedListener = onPositionChangedListener;
}
@Override
public boolean fling(int velocityX, int velocityY) {
return false;
}
@Override
public void scrollToPosition(int position) {
readLayoutManger.forceScrollToPosition(position);
}
@Override
public void smoothScrollToPosition(int position) {
readLayoutManger.smoothScrollToPosition(position);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
readLayoutManger.onRecyclerViewSizeChange();
}
private final List<Float> moveSampling = new LinkedList<>();
private final int MAX_COUNT = 5;
@Override
public boolean isScrollContainer() {
if (allowInterceptTouchEvent) {
return super.isScrollContainer();
} else {
return false;
}
}
private float downX = 0F;
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouchEvent(MotionEvent e) {
if (!allowInterceptTouchEvent) return false;//[偶现 动画期间 产生了item滑动,这里最后杀手锏再屏蔽下]
switch (e.getAction()) {
case MotionEvent.ACTION_DOWN:
moveSampling.clear();
downX = e.getRawX();
break;
case MotionEvent.ACTION_MOVE:
float mx = e.getRawX();
if (moveSampling.size() == 0
|| mx != moveSampling.get(moveSampling.size() - 1)) {
moveSampling.add(mx);
}
if (moveSampling.size() > MAX_COUNT) {
moveSampling.remove(0);
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
if (moveSampling.size() > 0) {
float lastMoveX = moveSampling.get(moveSampling.size() - 1);
float firstMoveX = moveSampling.get(0);
float finallyMoveX = lastMoveX - firstMoveX;
if (lastMoveX - downX < 0) {//左滑
readLayoutManger.setAutoLeftScroll(finallyMoveX < 10);
} else {
readLayoutManger.setAutoLeftScroll(finallyMoveX < 0);
}
moveSampling.clear();
} else {
readLayoutManger.setAutoLeftScroll(false);
}
break;
default:
break;
}
return super.onTouchEvent(e);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent e) {
//交由父类处理滑动,flip = BookFlipMode.MODE_NORMAL,
if (allowInterceptTouchEvent) {
return super.onInterceptTouchEvent(e);
}
//交由子View自行处理,flip = BookFlipMode.MODE_COVER| BookFlipMode.MODE_CURL
return false;
}
@Override
public void onExpectNext(boolean smooth) {
Adapter adapter = getAdapter();
final int dataCount = adapter.getItemCount();
final int nextPos = currentPosition + 1;
if (nextPos < dataCount) {
if (smooth) {
smoothScrollToPosition(nextPos);
} else {
scrollToPosition(nextPos);
}
}
}
@Override
public void onExpectPrevious(boolean smooth) {
if (currentPosition - 1 >= 0) {
if (smooth) {
smoothScrollToPosition(currentPosition - 1);
} else {
scrollToPosition(currentPosition - 1);
}
}
}
protected void setFlipMode(int flipMode) {
readLayoutManger.setBookFlipMode(flipMode);
if (flipMode == BookLayoutManager.BookFlipMode.MODE_CURL
|| flipMode == BookLayoutManager.BookFlipMode.MODE_COVER) {
allowInterceptTouchEvent = false;
} else {
allowInterceptTouchEvent = true;
}
readLayoutManger.requestLayout();
}
@Override
public int getFlipMode() {
return readLayoutManger.getBookFlipMode();
}
@Override
public void onItemViewTouchEvent(MotionEvent event) {
if (null != eventProxyWeakReference && null != eventProxyWeakReference.get()) {
eventProxyWeakReference.get().onItemViewTouchEvent(event);
}
}
@Override
public boolean animRunning() {
if (null != eventProxyWeakReference && null != eventProxyWeakReference.get()) {
eventProxyWeakReference.get().animRunning();
}
return false;
}
@Override
public void onClickMenu() {
animParentView.onClickMenuArea();
}
private class ItemOnScrollStop implements BookLayoutManager.OnStopScroller {
@Override
public void onStop(boolean autoLeftScroll, int curPos) {
boolean arriveNext = currentPosition < curPos;
currentPosition = curPos;
if (null != onPositionChangedListener) {
onPositionChangedListener.onChanged(arriveNext, curPos);
}
}
}
private class ItemOnForceLayoutCompleted implements BookLayoutManager.OnForceLayoutCompleted {
@Override
public void onLayoutCompleted(final int curPos) {
boolean arriveNext = currentPosition < curPos;
currentPosition = curPos;
if (null != onPositionChangedListener) {
onPositionChangedListener.onChanged(arriveNext, curPos);
}
}
}
@Override
public Bitmap getPreviousBitmap() {
int prePos = currentPosition - 1;
Bitmap pb = null;
if (prePos >= 0) {
pb = printViewToBitmap(prePos);
}
return pb;
}
@Override
public Bitmap getCurrentBitmap() {
return printViewToBitmap(currentPosition);
}
@Override
public Bitmap getNextBitmap() {
final int dataCount = getAdapter().getItemCount();
int nextPos = currentPosition + 1;
Bitmap nb = null;
if (nextPos < dataCount) {
nb = printViewToBitmap(nextPos);
}
return nb;
}
/**
* 将view渲染结果 打印到一个bitmap上
*
* @param pos
* @return
*/
private Bitmap printViewToBitmap(int pos) {
View view = readLayoutManger.findViewByPosition(pos);
if (null != view) {
if (view instanceof PaperLayout) {
PaperLayout pageView = (PaperLayout) view;
Bitmap bitmapTarget = Bitmap.createBitmap(pageView.getWidth(), pageView.getHeight(), Bitmap.Config.ARGB_4444);
pageView.drawViewScreenShotToBitmap(bitmapTarget);
return bitmapTarget;
} else {
throw new IllegalArgumentException("item 根View必须使用 PaperLayout");
}
}
return null;
}
}
| app/src/main/java/com/juziml/read/business/read/view/BookRecyclerView.java | Western-parotia-BookViewProject-1727e80 | [
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/PaperLayout.java",
"retrieved_chunk": " public PaperLayout(@NonNull Context context) {\n this(context, null);\n }\n public PaperLayout(@NonNull Context context, @Nullable AttributeSet attrs) {\n this(context, attrs, 0);\n }\n public PaperLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n viewScreenShotCanvas = new Canvas();\n menuBounds = new RectF();",
"score": 0.878646731376648
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookView.java",
"retrieved_chunk": " private int itemViewBackgroundColor = Color.WHITE;\n private Runnable dataPendIntentTask;\n public BookView(@NonNull Context context) {\n this(context, null);\n }\n public BookView(@NonNull Context context, @Nullable AttributeSet attrs) {\n this(context, attrs, 0);\n }\n public BookView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);",
"score": 0.8745112419128418
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookView.java",
"retrieved_chunk": " public void smoothScrollToPosition(int position) {\n bookRecyclerView.smoothScrollToPosition(position);\n }\n public void setAdapter(RecyclerView.Adapter adapter) {\n bookRecyclerView.setAdapter(adapter);\n }\n public void setItemViewBackgroundColor(int itemViewBackgroundColor) {\n this.itemViewBackgroundColor = itemViewBackgroundColor;\n }\n @Override",
"score": 0.8553828001022339
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookLayoutManager.java",
"retrieved_chunk": " this.onStopScroller = onStopScroller;\n }\n @Override\n public RecyclerView.LayoutParams generateDefaultLayoutParams() {\n return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,\n ViewGroup.LayoutParams.WRAP_CONTENT);\n }\n public void setBookFlipMode(@BookFlipMode int bookFlipMode) {\n this.bookFlipMode = bookFlipMode;\n requestLayout();",
"score": 0.8540096282958984
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookView.java",
"retrieved_chunk": " animHelper = new AnimHelper();\n init();\n }\n private void init() {\n removeAllViews();\n bookRecyclerView = new BookRecyclerView(getContext());\n puppetView = new PuppetView(getContext());\n puppetView.setAnimMode(bookRecyclerView.getFlipMode());\n bookRecyclerView.bindReadCurlAnimProxy(puppetView);\n LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);",
"score": 0.8220033645629883
}
] | java | readLayoutManger.setOnForceLayoutCompleted(new ItemOnForceLayoutCompleted()); |
package net.xenyria.eem.utils;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.option.KeyBinding;
import net.minecraft.client.util.InputUtil;
import net.xenyria.eem.PlayingSessionInformation;
import org.lwjgl.glfw.GLFW;
public class Keybinds {
private static final KeyBinding Achievements = KeyBindingHelper.registerKeyBinding(new KeyBinding(
"key.xenyria_eem.achievements",
InputUtil.Type.KEYSYM,
GLFW.GLFW_KEY_K,
"key_category.xenyria_eem.xenyria"
));
private static final KeyBinding Ping = KeyBindingHelper.registerKeyBinding(new KeyBinding(
"key.xenyria_eem.ping",
InputUtil.Type.KEYSYM,
GLFW.GLFW_KEY_F8,
"key_category.xenyria_eem.xenyria"
));
private static final KeyBinding MusicSettings = KeyBindingHelper.registerKeyBinding(new KeyBinding(
"key.xenyria_eem.music_settings",
InputUtil.Type.KEYSYM,
GLFW.GLFW_KEY_F7,
"key_category.xenyria_eem.xenyria"
));
private static final KeyBinding Settings = KeyBindingHelper.registerKeyBinding(new KeyBinding(
"key.xenyria_eem.settings",
InputUtil.Type.KEYSYM,
GLFW.GLFW_KEY_F6,
"key_category.xenyria_eem.xenyria"
));
private static final KeyBinding Stats = KeyBindingHelper.registerKeyBinding(new KeyBinding(
"key.xenyria_eem.stats",
InputUtil.Type.KEYSYM,
GLFW.GLFW_KEY_F4,
"key_category.xenyria_eem.xenyria"
));
private static final KeyBinding Lobby = KeyBindingHelper.registerKeyBinding(new KeyBinding(
"key.xenyria_eem.lobby",
InputUtil.Type.KEYSYM,
GLFW.GLFW_KEY_UNKNOWN,
"key_category.xenyria_eem.xenyria"
));
private static final KeyBinding Hub = KeyBindingHelper.registerKeyBinding(new KeyBinding(
"key.xenyria_eem.hub",
InputUtil.Type.KEYSYM,
GLFW.GLFW_KEY_UNKNOWN,
"key_category.xenyria_eem.xenyria"
));
public static void register() {
ClientTickEvents.END_CLIENT_TICK.register(client -> {
if(client.player == null) return;
registerCommandKeybind(client, Achievements, "achievements");
registerCommandKeybind(client, Ping, "ping");
registerCommandKeybind(client, MusicSettings, "music");
registerCommandKeybind(client, Settings, "settings");
registerCommandKeybind(client, Stats, "stats");
registerCommandKeybind(client, Lobby, "lobby");
registerCommandKeybind(client, Hub, "hub");
});
}
private static void registerCommandKeybind(MinecraftClient client, KeyBinding keybinding, String command) {
// Check if the user is on the server since you don't want to trigger certain macros on other servers
if(! | PlayingSessionInformation.isOnNetwork()) { | return; }
while (keybinding.wasPressed()) client.player.networkHandler.sendChatCommand(command);
}
}
| src/main/java/net/xenyria/eem/utils/Keybinds.java | XenyriaNET-xeem-b635ea0 | [
{
"filename": "src/main/java/net/xenyria/eem/discord/DiscordRichPresenceIntegration.java",
"retrieved_chunk": " // The application ID has to be reset here so the core gets started up again once we receive data again\n lastApplicationID = 0;\n discordActivityAccess.stop();\n }\n // Run callbacks\n discordActivityAccess.runCallbacks();\n } catch (Exception e) {\n LOGGER.error(\"An error occurred during the rich presence update loop\", e);\n }\n }, UPDATE_INTERVAL, UPDATE_INTERVAL, TimeUnit.MILLISECONDS);",
"score": 0.7660785913467407
},
{
"filename": "src/main/java/net/xenyria/eem/paintsquad/PaintSquadInputManager.java",
"retrieved_chunk": " // Check if the player is holding the right mouse button\n boolean hasChanged = false;\n boolean isPressingRightMouseButton =\n MinecraftClient.getInstance().options.useKey.isPressed();\n // We only send state changes to the server (e.g. when the state switches from firing to not firing)\n // So in this case we just check if the state has changed compared to the last check\n if(isShooting != isPressingRightMouseButton) {\n hasChanged = true;\n isShooting = isPressingRightMouseButton;\n }",
"score": 0.755637526512146
},
{
"filename": "src/main/java/net/xenyria/eem/networking/PacketListener.java",
"retrieved_chunk": "public class PacketListener {\n public static Identifier ID;\n public static Logger LOGGER = Logger.getLogger(\"Xenyria/PacketListener\");\n public static void initialize() {\n ID = Identifier.of(\"xenyria\", \"mod_communication\");\n if(ID == null) throw new IllegalStateException(\"Identifier could not be initialized.\");\n LOGGER.info(\"Registering packet receiver for plugin messages...\");\n ClientPlayNetworking.registerGlobalReceiver(\n ID, (client, handler, buf, responseSender) -> {\n /*",
"score": 0.7460996508598328
},
{
"filename": "src/main/java/net/xenyria/eem/mixin/PaintSquadSwimFormMixin.java",
"retrieved_chunk": "public class PaintSquadSwimFormMixin {\n private static final String SWIM_FORM_DETECTION_NAME = \"\\u0001swim_form\";\n @Inject(at = @At(\"HEAD\"), method = \"tick()V\")\n private void tick(CallbackInfo info) {\n // Check if this setting is enabled in the first place...\n if(!PlayingSessionInformation.isOnNetwork()\n || !XenyriaConfigManager.getConfig().swimFormCameraForPaintSquad) {\n return;\n }\n // A player entity has to be present for this to work",
"score": 0.7324460744857788
},
{
"filename": "src/main/java/net/xenyria/eem/discord/DiscordRichPresenceIntegration.java",
"retrieved_chunk": " public static final long TIMEOUT = 3000L;\n // Delay in milliseconds for activity updates\n public static final long UPDATE_INTERVAL = 500L;\n // Constructor\n private DiscordRichPresenceIntegration() throws IllegalStateException {\n // Initialize the discord library\n discordActivityAccess = new DefaultDiscordActivityAccess();\n discordActivityAccess.initialize();\n // Start the rich presence update loop\n enterRichPresenceUpdateLoop();",
"score": 0.731864333152771
}
] | java | PlayingSessionInformation.isOnNetwork()) { |
package com.juziml.read.business.read.view;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.List;
/**
* 关闭了抛投效果
* create by zhusw on 2020-03-30 11:51
*/
public class BookRecyclerView extends RecyclerView implements RVInnerItemFunction, RVOuterFunction {
private final BookLayoutManager readLayoutManger;
private boolean allowInterceptTouchEvent = true;
private int currentPosition = 0;
private WeakReference<EventProxy> eventProxyWeakReference;
private AnimParentView animParentView;
private BookView.OnPositionChangedListener onPositionChangedListener;
public BookRecyclerView(Context context) {
this(context, null);
}
public BookRecyclerView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public BookRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
readLayoutManger = new BookLayoutManager(context);
setLayoutManager(readLayoutManger);
readLayoutManger.setOnForceLayoutCompleted(new ItemOnForceLayoutCompleted());
readLayoutManger.setonStopScroller(new ItemOnScrollStop());
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
animParentView = (AnimParentView) getParent();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
eventProxyWeakReference.clear();
}
protected void bindReadCurlAnimProxy(EventProxy ic) {
if (null != eventProxyWeakReference) {
eventProxyWeakReference.clear();
}
eventProxyWeakReference = new WeakReference<>(ic);
}
protected void setOnPositionChangedListener(BookView.OnPositionChangedListener onPositionChangedListener) {
this.onPositionChangedListener = onPositionChangedListener;
}
@Override
public boolean fling(int velocityX, int velocityY) {
return false;
}
@Override
public void scrollToPosition(int position) {
readLayoutManger.forceScrollToPosition(position);
}
@Override
public void smoothScrollToPosition(int position) {
readLayoutManger.smoothScrollToPosition(position);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
readLayoutManger.onRecyclerViewSizeChange();
}
private final List<Float> moveSampling = new LinkedList<>();
private final int MAX_COUNT = 5;
@Override
public boolean isScrollContainer() {
if (allowInterceptTouchEvent) {
return super.isScrollContainer();
} else {
return false;
}
}
private float downX = 0F;
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouchEvent(MotionEvent e) {
if (!allowInterceptTouchEvent) return false;//[偶现 动画期间 产生了item滑动,这里最后杀手锏再屏蔽下]
switch (e.getAction()) {
case MotionEvent.ACTION_DOWN:
moveSampling.clear();
downX = e.getRawX();
break;
case MotionEvent.ACTION_MOVE:
float mx = e.getRawX();
if (moveSampling.size() == 0
|| mx != moveSampling.get(moveSampling.size() - 1)) {
moveSampling.add(mx);
}
if (moveSampling.size() > MAX_COUNT) {
moveSampling.remove(0);
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
if (moveSampling.size() > 0) {
float lastMoveX = moveSampling.get(moveSampling.size() - 1);
float firstMoveX = moveSampling.get(0);
float finallyMoveX = lastMoveX - firstMoveX;
if (lastMoveX - downX < 0) {//左滑
readLayoutManger.setAutoLeftScroll(finallyMoveX < 10);
} else {
readLayoutManger.setAutoLeftScroll(finallyMoveX < 0);
}
moveSampling.clear();
} else {
readLayoutManger.setAutoLeftScroll(false);
}
break;
default:
break;
}
return super.onTouchEvent(e);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent e) {
//交由父类处理滑动,flip = BookFlipMode.MODE_NORMAL,
if (allowInterceptTouchEvent) {
return super.onInterceptTouchEvent(e);
}
//交由子View自行处理,flip = BookFlipMode.MODE_COVER| BookFlipMode.MODE_CURL
return false;
}
@Override
public void onExpectNext(boolean smooth) {
Adapter adapter = getAdapter();
final int dataCount = adapter.getItemCount();
final int nextPos = currentPosition + 1;
if (nextPos < dataCount) {
if (smooth) {
smoothScrollToPosition(nextPos);
} else {
scrollToPosition(nextPos);
}
}
}
@Override
public void onExpectPrevious(boolean smooth) {
if (currentPosition - 1 >= 0) {
if (smooth) {
smoothScrollToPosition(currentPosition - 1);
} else {
scrollToPosition(currentPosition - 1);
}
}
}
protected void setFlipMode(int flipMode) {
readLayoutManger.setBookFlipMode(flipMode);
if (flipMode == BookLayoutManager.BookFlipMode.MODE_CURL
|| flipMode == BookLayoutManager.BookFlipMode.MODE_COVER) {
allowInterceptTouchEvent = false;
} else {
allowInterceptTouchEvent = true;
}
readLayoutManger.requestLayout();
}
@Override
public int getFlipMode() {
return readLayoutManger.getBookFlipMode();
}
@Override
public void onItemViewTouchEvent(MotionEvent event) {
if (null != eventProxyWeakReference && null != eventProxyWeakReference.get()) {
eventProxyWeakReference.get().onItemViewTouchEvent(event);
}
}
@Override
public boolean animRunning() {
if (null != eventProxyWeakReference && null != eventProxyWeakReference.get()) {
eventProxyWeakReference.get().animRunning();
}
return false;
}
@Override
public void onClickMenu() {
| animParentView.onClickMenuArea(); |
}
private class ItemOnScrollStop implements BookLayoutManager.OnStopScroller {
@Override
public void onStop(boolean autoLeftScroll, int curPos) {
boolean arriveNext = currentPosition < curPos;
currentPosition = curPos;
if (null != onPositionChangedListener) {
onPositionChangedListener.onChanged(arriveNext, curPos);
}
}
}
private class ItemOnForceLayoutCompleted implements BookLayoutManager.OnForceLayoutCompleted {
@Override
public void onLayoutCompleted(final int curPos) {
boolean arriveNext = currentPosition < curPos;
currentPosition = curPos;
if (null != onPositionChangedListener) {
onPositionChangedListener.onChanged(arriveNext, curPos);
}
}
}
@Override
public Bitmap getPreviousBitmap() {
int prePos = currentPosition - 1;
Bitmap pb = null;
if (prePos >= 0) {
pb = printViewToBitmap(prePos);
}
return pb;
}
@Override
public Bitmap getCurrentBitmap() {
return printViewToBitmap(currentPosition);
}
@Override
public Bitmap getNextBitmap() {
final int dataCount = getAdapter().getItemCount();
int nextPos = currentPosition + 1;
Bitmap nb = null;
if (nextPos < dataCount) {
nb = printViewToBitmap(nextPos);
}
return nb;
}
/**
* 将view渲染结果 打印到一个bitmap上
*
* @param pos
* @return
*/
private Bitmap printViewToBitmap(int pos) {
View view = readLayoutManger.findViewByPosition(pos);
if (null != view) {
if (view instanceof PaperLayout) {
PaperLayout pageView = (PaperLayout) view;
Bitmap bitmapTarget = Bitmap.createBitmap(pageView.getWidth(), pageView.getHeight(), Bitmap.Config.ARGB_4444);
pageView.drawViewScreenShotToBitmap(bitmapTarget);
return bitmapTarget;
} else {
throw new IllegalArgumentException("item 根View必须使用 PaperLayout");
}
}
return null;
}
}
| app/src/main/java/com/juziml/read/business/read/view/BookRecyclerView.java | Western-parotia-BookViewProject-1727e80 | [
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/PuppetView.java",
"retrieved_chunk": " }\n @Override\n public boolean animRunning() {\n if (null != animationEffecter) {\n return animationEffecter.animInEffect();\n }\n return false;\n }\n @Override\n public void computeScroll() {",
"score": 0.8876376152038574
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/PuppetView.java",
"retrieved_chunk": " }\n public boolean animRunningOrTouching() {\n boolean animRunningOrTouching = false;\n if (null != animationEffecter) {\n animRunningOrTouching = animRunning();\n }\n return animRunningOrTouching;\n }\n @Override\n protected void onAttachedToWindow() {",
"score": 0.8635190725326538
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/PuppetView.java",
"retrieved_chunk": " previousViewBitmap = parentView.getPreviousBitmap();\n }\n performDrawCurlTexture = true;\n }\n @Override\n public boolean onItemViewTouchEvent(MotionEvent event) {\n if (null != animationEffecter) {\n animationEffecter.handlerEvent(event);\n }\n return true;",
"score": 0.8495737314224243
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/PuppetView.java",
"retrieved_chunk": " return parentView.getAnimHelper();\n }\n @Override\n public void onClickMenuArea() {\n parentView.onClickMenuArea();\n }\n @Override\n public void onClickNextArea() {\n parentView.onClickNextArea();\n }",
"score": 0.8477670550346375
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/PuppetView.java",
"retrieved_chunk": " if (null != animationEffecter) {\n animationEffecter.onScroll();\n }\n }\n @Override\n public void onExpectNext() {\n parentView.onExpectNext();\n }\n @Override\n public void onExpectPrevious() {",
"score": 0.8430581092834473
}
] | java | animParentView.onClickMenuArea(); |
package com.juziml.read.business.read.view;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.List;
/**
* 关闭了抛投效果
* create by zhusw on 2020-03-30 11:51
*/
public class BookRecyclerView extends RecyclerView implements RVInnerItemFunction, RVOuterFunction {
private final BookLayoutManager readLayoutManger;
private boolean allowInterceptTouchEvent = true;
private int currentPosition = 0;
private WeakReference<EventProxy> eventProxyWeakReference;
private AnimParentView animParentView;
private BookView.OnPositionChangedListener onPositionChangedListener;
public BookRecyclerView(Context context) {
this(context, null);
}
public BookRecyclerView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public BookRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
readLayoutManger = new BookLayoutManager(context);
setLayoutManager(readLayoutManger);
readLayoutManger.setOnForceLayoutCompleted(new ItemOnForceLayoutCompleted());
readLayoutManger.setonStopScroller(new ItemOnScrollStop());
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
animParentView = (AnimParentView) getParent();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
eventProxyWeakReference.clear();
}
protected void bindReadCurlAnimProxy(EventProxy ic) {
if (null != eventProxyWeakReference) {
eventProxyWeakReference.clear();
}
eventProxyWeakReference = new WeakReference<>(ic);
}
protected void setOnPositionChangedListener(BookView.OnPositionChangedListener onPositionChangedListener) {
this.onPositionChangedListener = onPositionChangedListener;
}
@Override
public boolean fling(int velocityX, int velocityY) {
return false;
}
@Override
public void scrollToPosition(int position) {
readLayoutManger.forceScrollToPosition(position);
}
@Override
public void smoothScrollToPosition(int position) {
readLayoutManger.smoothScrollToPosition(position);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
readLayoutManger.onRecyclerViewSizeChange();
}
private final List<Float> moveSampling = new LinkedList<>();
private final int MAX_COUNT = 5;
@Override
public boolean isScrollContainer() {
if (allowInterceptTouchEvent) {
return super.isScrollContainer();
} else {
return false;
}
}
private float downX = 0F;
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouchEvent(MotionEvent e) {
if (!allowInterceptTouchEvent) return false;//[偶现 动画期间 产生了item滑动,这里最后杀手锏再屏蔽下]
switch (e.getAction()) {
case MotionEvent.ACTION_DOWN:
moveSampling.clear();
downX = e.getRawX();
break;
case MotionEvent.ACTION_MOVE:
float mx = e.getRawX();
if (moveSampling.size() == 0
|| mx != moveSampling.get(moveSampling.size() - 1)) {
moveSampling.add(mx);
}
if (moveSampling.size() > MAX_COUNT) {
moveSampling.remove(0);
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
if (moveSampling.size() > 0) {
float lastMoveX = moveSampling.get(moveSampling.size() - 1);
float firstMoveX = moveSampling.get(0);
float finallyMoveX = lastMoveX - firstMoveX;
if (lastMoveX - downX < 0) {//左滑
readLayoutManger.setAutoLeftScroll(finallyMoveX < 10);
} else {
readLayoutManger.setAutoLeftScroll(finallyMoveX < 0);
}
moveSampling.clear();
} else {
readLayoutManger.setAutoLeftScroll(false);
}
break;
default:
break;
}
return super.onTouchEvent(e);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent e) {
//交由父类处理滑动,flip = BookFlipMode.MODE_NORMAL,
if (allowInterceptTouchEvent) {
return super.onInterceptTouchEvent(e);
}
//交由子View自行处理,flip = BookFlipMode.MODE_COVER| BookFlipMode.MODE_CURL
return false;
}
@Override
public void onExpectNext(boolean smooth) {
Adapter adapter = getAdapter();
final int dataCount = adapter.getItemCount();
final int nextPos = currentPosition + 1;
if (nextPos < dataCount) {
if (smooth) {
smoothScrollToPosition(nextPos);
} else {
scrollToPosition(nextPos);
}
}
}
@Override
public void onExpectPrevious(boolean smooth) {
if (currentPosition - 1 >= 0) {
if (smooth) {
smoothScrollToPosition(currentPosition - 1);
} else {
scrollToPosition(currentPosition - 1);
}
}
}
protected void setFlipMode(int flipMode) {
readLayoutManger.setBookFlipMode(flipMode);
if (flipMode == BookLayoutManager.BookFlipMode.MODE_CURL
|| flipMode == BookLayoutManager.BookFlipMode.MODE_COVER) {
allowInterceptTouchEvent = false;
} else {
allowInterceptTouchEvent = true;
}
readLayoutManger.requestLayout();
}
@Override
public int getFlipMode() {
return readLayoutManger.getBookFlipMode();
}
@Override
public void onItemViewTouchEvent(MotionEvent event) {
if (null != eventProxyWeakReference && null != eventProxyWeakReference.get()) {
eventProxyWeakReference.get().onItemViewTouchEvent(event);
}
}
@Override
public boolean animRunning() {
if (null != eventProxyWeakReference && null != eventProxyWeakReference.get()) {
eventProxyWeakReference.get( | ).animRunning(); |
}
return false;
}
@Override
public void onClickMenu() {
animParentView.onClickMenuArea();
}
private class ItemOnScrollStop implements BookLayoutManager.OnStopScroller {
@Override
public void onStop(boolean autoLeftScroll, int curPos) {
boolean arriveNext = currentPosition < curPos;
currentPosition = curPos;
if (null != onPositionChangedListener) {
onPositionChangedListener.onChanged(arriveNext, curPos);
}
}
}
private class ItemOnForceLayoutCompleted implements BookLayoutManager.OnForceLayoutCompleted {
@Override
public void onLayoutCompleted(final int curPos) {
boolean arriveNext = currentPosition < curPos;
currentPosition = curPos;
if (null != onPositionChangedListener) {
onPositionChangedListener.onChanged(arriveNext, curPos);
}
}
}
@Override
public Bitmap getPreviousBitmap() {
int prePos = currentPosition - 1;
Bitmap pb = null;
if (prePos >= 0) {
pb = printViewToBitmap(prePos);
}
return pb;
}
@Override
public Bitmap getCurrentBitmap() {
return printViewToBitmap(currentPosition);
}
@Override
public Bitmap getNextBitmap() {
final int dataCount = getAdapter().getItemCount();
int nextPos = currentPosition + 1;
Bitmap nb = null;
if (nextPos < dataCount) {
nb = printViewToBitmap(nextPos);
}
return nb;
}
/**
* 将view渲染结果 打印到一个bitmap上
*
* @param pos
* @return
*/
private Bitmap printViewToBitmap(int pos) {
View view = readLayoutManger.findViewByPosition(pos);
if (null != view) {
if (view instanceof PaperLayout) {
PaperLayout pageView = (PaperLayout) view;
Bitmap bitmapTarget = Bitmap.createBitmap(pageView.getWidth(), pageView.getHeight(), Bitmap.Config.ARGB_4444);
pageView.drawViewScreenShotToBitmap(bitmapTarget);
return bitmapTarget;
} else {
throw new IllegalArgumentException("item 根View必须使用 PaperLayout");
}
}
return null;
}
}
| app/src/main/java/com/juziml/read/business/read/view/BookRecyclerView.java | Western-parotia-BookViewProject-1727e80 | [
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/PuppetView.java",
"retrieved_chunk": " previousViewBitmap = parentView.getPreviousBitmap();\n }\n performDrawCurlTexture = true;\n }\n @Override\n public boolean onItemViewTouchEvent(MotionEvent event) {\n if (null != animationEffecter) {\n animationEffecter.handlerEvent(event);\n }\n return true;",
"score": 0.8332740068435669
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/PuppetView.java",
"retrieved_chunk": " }\n public boolean animRunningOrTouching() {\n boolean animRunningOrTouching = false;\n if (null != animationEffecter) {\n animRunningOrTouching = animRunning();\n }\n return animRunningOrTouching;\n }\n @Override\n protected void onAttachedToWindow() {",
"score": 0.8058019280433655
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookView.java",
"retrieved_chunk": " protected void onDetachedFromWindow() {\n super.onDetachedFromWindow();\n if (null != dataPendIntentTask) {\n bookRecyclerView.removeCallbacks(dataPendIntentTask);\n }\n }\n @Override\n public void onExpectNext() {\n bookRecyclerView.onExpectNext(false);\n if (null != dataPendIntentTask) {",
"score": 0.7946681976318359
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/PuppetView.java",
"retrieved_chunk": " }\n @Override\n public boolean animRunning() {\n if (null != animationEffecter) {\n return animationEffecter.animInEffect();\n }\n return false;\n }\n @Override\n public void computeScroll() {",
"score": 0.7945277094841003
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/view/BookLayoutManager.java",
"retrieved_chunk": " horizontalOffset += (long) distance;\n requestLayout();\n if (null != onForceLayoutCompleted) {\n onForceLayoutCompleted.onLayoutCompleted(position);\n }\n }\n }\n public void cancelAnimator() {\n if (selectAnimator != null && (selectAnimator.isStarted() || selectAnimator.isRunning())) {\n selectAnimator.cancel();",
"score": 0.7888301610946655
}
] | java | ).animRunning(); |
package com.juziml.read.business.read.anim;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.drawable.GradientDrawable;
import android.view.MotionEvent;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.Scroller;
import com.juziml.read.business.read.view.PuppetView;
import com.juziml.read.utils.DLog;
import java.util.LinkedList;
import java.util.List;
/**
* create by zhusw on 2020-08-24 14:06
*/
public class CoverAnimationEffecter implements IAnimationEffecter {
private final static int DOWN_AREA_NONE = -1;
private final static int DOWN_AREA_MENU = 1;
private final static int DOWN_AREA_LEFT = 2;
private final static int DOWN_AREA_RIGHT = 3;
int vWidth = 1;
int vHeight = 1;
private final PuppetView readAnimView;
private boolean isCancelFlip = false;
private boolean coverAnimationRunning = false;
private boolean isTouching = false;
private final Scroller scroller;
private final ScrollRunnable scrollRunnable;
private final RectF menuBounds;
private final Path pathA;
private final Path pathB;
private final Paint paint;
private final int shadowWidth;
public CoverAnimationEffecter(PuppetView readAnimView) {
this.readAnimView = readAnimView;
scroller = new Scroller(readAnimView.getContext(), new AccelerateDecelerateInterpolator());
scrollRunnable = new ScrollRunnable();
menuBounds = new RectF();
pathA = new Path();
pathB = new Path();
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
shadowWidth = 20;
}
private int downArea = DOWN_AREA_NONE;
private float downX = 0F;
private int coverSlideDirection = AnimHelper.SLID_DIRECTION_UNKNOWN;
private final List<Float> moveSampling = new LinkedList<>();
private final int MAX_COUNT = 5;
private boolean prepareDrawCoverAnimEffect = false;
private float currentX = -1;
@Override
public void handlerEvent(MotionEvent event) {
if (coverAnimationRunning) return;
float x = event.getRawX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
moveSampling.clear();
downX = x;
prepareDrawCoverAnimEffect = false;
isTouching = true;
currentX = -1;
downArea = DOWN_AREA_NONE;
coverSlideDirection = AnimHelper.SLID_DIRECTION_UNKNOWN;
if (x > menuBounds.left && y > menuBounds.top
&& x < menuBounds.right && y < menuBounds.bottom) {
downArea = DOWN_AREA_MENU;
} else if (x < vWidth / 2F) {
downArea = DOWN_AREA_LEFT;
} else {
downArea = DOWN_AREA_RIGHT;
}
break;
case MotionEvent.ACTION_MOVE:
isTouching = true;
float curDistance = x - downX;
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_UNKNOWN && checkDownArea(downArea)) {
if (curDistance > 0) {
coverSlideDirection = AnimHelper.SLID_DIRECTION_RIGHT;
} else {
coverSlideDirection = AnimHelper.SLID_DIRECTION_LEFT;
}
readAnimView.buildBitmap(coverSlideDirection);
prepareDrawCoverAnimEffect = checkAnimCondition(coverSlideDirection);
}
if (prepareDrawCoverAnimEffect) {
if (moveSampling.size() == 0
|| x != moveSampling.get(moveSampling.size() - 1)) {
moveSampling.add(x);
}
if (moveSampling.size() > MAX_COUNT) {
moveSampling.remove(0);
}
currentX = x;
invalidate();
}
break;
case MotionEvent.ACTION_CANCEL:
isTouching = false;
break;
case MotionEvent.ACTION_UP:
currentX = x;
if (prepareDrawCoverAnimEffect) {
if (moveSampling.size() > 0) {
float lastMoveX = moveSampling.get(moveSampling.size() - 1);
float firstMoveX = moveSampling.get(0);
float finallyMoveX = lastMoveX - firstMoveX;
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT) {
boolean lastFingerLeftSlop = finallyMoveX < 10;
touchUp(lastFingerLeftSlop);
} else if (coverSlideDirection == AnimHelper.SLID_DIRECTION_RIGHT) {
finallyMoveX = lastMoveX - firstMoveX;
touchUp(finallyMoveX < 0);
}
} else {
touchUp(false);
}
} else if (downArea == DOWN_AREA_MENU) {
if (x > menuBounds.left && x < menuBounds.right
&& y > menuBounds.top && y < menuBounds.bottom) {
readAnimView.onClickMenuArea();
}
} else if (downArea != DOWN_AREA_NONE) {
if (x == downX && downX >= vWidth / 2F) {//下一页
coverSlideDirection = AnimHelper.SLID_DIRECTION_LEFT;
readAnimView.buildBitmap(coverSlideDirection);
if (checkAnimCondition(coverSlideDirection)) {
touchUp(true);
}
} else if (x == downX && downX < vWidth / 2F) {//上一页
coverSlideDirection = AnimHelper.SLID_DIRECTION_RIGHT;
readAnimView.buildBitmap(coverSlideDirection);
if (checkAnimCondition(coverSlideDirection)) {
touchUp(false);
}
}
}
moveSampling.clear();
isTouching = false;
break;
default:
break;
}
}
private void touchUp(boolean lastFingerLeftSlop) {
DLog.log("touchUp coverAnimationRunning=%s", coverAnimationRunning);
coverAnimationRunning = true;
isCancelFlip = (coverSlideDirection == AnimHelper.SLID_DIRECTION_RIGHT && lastFingerLeftSlop)
|| (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT && !lastFingerLeftSlop);
int duration = isCancelFlip ? AnimHelper.CANCEL_ANIM_DURATION : AnimHelper.RELAY_ANIM_DURATION;
duration = (int) (duration * 0.7F);//cover动画时间减少一点
// duration = 1000;//cover动画时间减少一点
int startX = (int) currentX;
int startY = 0;
int dy = 0;
int dx;
if (lastFingerLeftSlop) {
dx = (int) -(vWidth - (downX - currentX));
} else {
dx = vWidth - (int) currentX;
}
scroller.startScroll(startX, startY, dx, dy, duration);
invalidate();
}
@Override
public void draw(Canvas canvas) {
if (currentX == -1) {
| DLog.log("CoverAnimationEffect draw 1"); |
return;
}
if (coverSlideDirection != AnimHelper.SLID_DIRECTION_LEFT && coverSlideDirection != AnimHelper.SLID_DIRECTION_RIGHT) {
DLog.log("CoverAnimationEffect draw 2");
return;
}
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT
&& (null == readAnimView.getCurrentBitmap() || null == readAnimView.getNextBitmap())) {
DLog.log("CoverAnimationEffect draw 3");
return;
}
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_RIGHT && null == readAnimView.getPreviousBitmap()) {
DLog.log("CoverAnimationEffect draw 4");
return;
}
DLog.log("CoverAnimationEffect draw 5");
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT) {
float offset = downX - currentX;
offset = Math.max(0, offset);
canvas.save();
canvas.clipPath(getPathAToLeft());
canvas.drawBitmap(readAnimView.getCurrentBitmap(), -offset, 0, paint);
canvas.restore();
canvas.save();
canvas.clipPath(getPathB());
canvas.drawBitmap(readAnimView.getNextBitmap(), 0, 0, paint);
canvas.restore();
drawShadow((int) (vWidth - offset), canvas);
} else {
float leftOffset = vWidth - currentX;
canvas.save();
canvas.clipPath(getPathAToRight());
canvas.drawBitmap(readAnimView.getPreviousBitmap(), -leftOffset, 0, paint);
canvas.restore();
drawShadow((int) currentX, canvas);
}
}
private void drawShadow(int left, Canvas canvas) {
GradientDrawable drawable = readAnimView.getAnimHelper().getCoverGradientDrawable();
drawable.setBounds(left, 0, left + shadowWidth, vHeight);
drawable.draw(canvas);
}
private Path getPathAToLeft() {
pathA.reset();
float x = vWidth - (downX - currentX);
x = Math.min(vWidth, x);
pathA.lineTo(x, 0);
pathA.lineTo(x, vHeight);
pathA.lineTo(0, vHeight);
pathA.close();
return pathA;
}
private Path getPathB() {
pathB.reset();
float x = vWidth - (downX - currentX);
x = Math.min(vWidth, x);
pathB.moveTo(x, 0);
pathB.lineTo(vWidth, 0);
pathB.lineTo(vWidth, vHeight);
pathB.lineTo(x, vHeight);
pathB.close();
return pathB;
}
private Path getPathAToRight() {
pathA.reset();
pathA.lineTo(currentX, 0);
pathA.lineTo(currentX, vHeight);
pathA.lineTo(0, vHeight);
pathA.close();
return pathA;
}
private boolean checkDownArea(int downArea) {
return downArea != DOWN_AREA_MENU && downArea != DOWN_AREA_NONE;
}
private boolean checkAnimCondition(int slideDirection) {
if (slideDirection == AnimHelper.SLID_DIRECTION_LEFT && (null != readAnimView.getNextBitmap() && null != readAnimView.getCurrentBitmap())) {
return true;
} else if (slideDirection == AnimHelper.SLID_DIRECTION_RIGHT && null != readAnimView.getPreviousBitmap()) {
return true;
}
return false;
}
@Override
public boolean animInEffect() {
return isTouching || coverAnimationRunning;
}
@Override
public void onViewSizeChanged(int vWidth, int vHeight) {
this.vWidth = vWidth;
this.vHeight = vHeight;
menuBounds.left = vWidth / 3F;
menuBounds.top = vHeight / 3F;
menuBounds.right = vWidth * 2 / 3F;
menuBounds.bottom = vHeight * 2 / 3F;
}
@Override
public void onViewAttachedToWindow() {
}
@Override
public void onViewDetachedFromWindow() {
readAnimView.removeCallbacks(scrollRunnable);
}
private void invalidate() {
readAnimView.postInvalidate();
}
@Override
public void onScroll() {
if (scroller.computeScrollOffset()) {
int x = scroller.getCurrX();
int y = scroller.getCurrY();
if (x == scroller.getFinalX() && y == scroller.getFinalY()) {
scroller.forceFinished(true);
//补一点时间,避免动画太快结束,提供两次动画触发间隔
DLog.log("coverAnimationRunning coverAnimationRunning=%s 结束,延时开启 状态重置", coverAnimationRunning);
readAnimView.post(scrollRunnable);
} else {
currentX = x;
invalidate();
}
}
}
protected class ScrollRunnable implements Runnable {
@Override
public void run() {
readAnimView.reset();
coverAnimationRunning = false;
if (!isCancelFlip) {
if (coverSlideDirection == AnimHelper.SLID_DIRECTION_LEFT) {
readAnimView.onExpectNext();
} else if (coverSlideDirection == AnimHelper.SLID_DIRECTION_RIGHT) {
readAnimView.onExpectPrevious();
}
}
invalidate();
}
}
}
| app/src/main/java/com/juziml/read/business/read/anim/CoverAnimationEffecter.java | Western-parotia-BookViewProject-1727e80 | [
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " cm.set(array);\n colorMatrixColorFilter = new ColorMatrixColorFilter(cm);\n scroller = new Scroller(readAnimView.getContext(), new LinearInterpolator());\n }\n @Override\n public void onScroll() {\n if (scroller.computeScrollOffset()) {\n int x = scroller.getCurrX();\n int y = scroller.getCurrY();\n int finalX = scroller.getFinalX();",
"score": 0.8759747743606567
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " } else {\n touchMove(x, y, curlSlideDirection, false, true);\n }\n }\n }\n @Override\n public void handlerEvent(MotionEvent event) {\n if (curlAnimationRunning) return;\n float x = event.getRawX();\n float y = event.getRawY();",
"score": 0.8634046316146851
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " @Override\n public void onViewDetachedFromWindow() {\n readAnimView.removeCallbacks(scrollRunnable);\n }\n @Override\n public void draw(Canvas canvas) {\n if (a.x == -1 && a.y == -1) {\n return;\n }\n if (curlSlideDirection != AnimHelper.SLID_DIRECTION_LEFT && curlSlideDirection != AnimHelper.SLID_DIRECTION_RIGHT) {",
"score": 0.8607842922210693
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " isTouching = false;\n downX = 0F;\n drawCurlAnimBefore = false;\n break;\n }\n }\n @Override\n public void onViewSizeChanged(int vWidth, int vHeight) {\n this.vWidth = vWidth;\n this.vHeight = vHeight;",
"score": 0.8532469272613525
},
{
"filename": "app/src/main/java/com/juziml/read/business/read/anim/SimulationAnimationEffecter.java",
"retrieved_chunk": " dy = (vHeight - ay);\n }\n this.isCancelFlip = isCancelFlip;\n int duration = isCancelFlip ? AnimHelper.CANCEL_ANIM_DURATION : AnimHelper.RELAY_ANIM_DURATION;\n curlAnimationRunning = true;\n scroller.startScroll(ax, ay, dx, dy, duration);\n invalidate();//猛然想起startScroll 需要在下一帧重绘时才生效\n }\n private int downArea = DOWN_AREA_NONE;\n private float downX = 0F;",
"score": 0.8362016081809998
}
] | java | DLog.log("CoverAnimationEffect draw 1"); |
package net.xenyria.eem.paintsquad;
import net.xenyria.eem.config.screen.XenyriaConfigManager;
import net.xenyria.eem.networking.PacketListener;
import net.xenyria.eem.networking.XenyriaServerPacket;
import net.minecraft.client.MinecraftClient;
import org.json.JSONObject;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class PaintSquadInputManager {
private static PaintSquadInputManager instance;
public static PaintSquadInputManager getInstance() { return instance; }
public static void createInstance() {
if(instance != null) return;
instance = new PaintSquadInputManager();
}
private PaintSquadInputManager() {
startTask();
}
private void startTask() {
PacketListener.LOGGER.info("Starting PaintSquad input polling task...");
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleAtFixedRate(new Runnable() {
private boolean isShooting;
@Override
public void run() {
// Check if this feature is enabled...
if( | !XenyriaConfigManager.getConfig().improvedShootingDetectionForPaintSquad) { |
return;
}
// Check if the player is holding the right mouse button
boolean hasChanged = false;
boolean isPressingRightMouseButton =
MinecraftClient.getInstance().options.useKey.isPressed();
// We only send state changes to the server (e.g. when the state switches from firing to not firing)
// So in this case we just check if the state has changed compared to the last check
if(isShooting != isPressingRightMouseButton) {
hasChanged = true;
isShooting = isPressingRightMouseButton;
}
// If a change has been detected we send a mod packet to the server
if(hasChanged) {
JSONObject payload = new JSONObject();
payload.put("shooting", isShooting);
XenyriaServerPacket packet = new XenyriaServerPacket(
XenyriaServerPacket.EPacketType.PS_SHOOTING_STATE, payload);
packet.sendToServer();
}
}
}, 10, 10, TimeUnit.MILLISECONDS);
}
}
| src/main/java/net/xenyria/eem/paintsquad/PaintSquadInputManager.java | XenyriaNET-xeem-b635ea0 | [
{
"filename": "src/main/java/net/xenyria/eem/discord/DiscordRichPresenceIntegration.java",
"retrieved_chunk": " ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();\n LOGGER.info(\"Starting API task...\");\n executor.scheduleAtFixedRate(() -> {\n try {\n JSONObject richPresenceData = null;\n boolean isDataPresent = false;\n // Lock so this#setLastReceivedRichPresence is blocked while we copy data\n synchronized (lock) {\n if (lastReceivedRichPresence != null) {\n long deltaSinceLastPacket = System.currentTimeMillis() - lastReceivedPacket;",
"score": 0.8490889668464661
},
{
"filename": "src/main/java/net/xenyria/eem/mixin/PaintSquadSwimFormMixin.java",
"retrieved_chunk": "public class PaintSquadSwimFormMixin {\n private static final String SWIM_FORM_DETECTION_NAME = \"\\u0001swim_form\";\n @Inject(at = @At(\"HEAD\"), method = \"tick()V\")\n private void tick(CallbackInfo info) {\n // Check if this setting is enabled in the first place...\n if(!PlayingSessionInformation.isOnNetwork()\n || !XenyriaConfigManager.getConfig().swimFormCameraForPaintSquad) {\n return;\n }\n // A player entity has to be present for this to work",
"score": 0.8368075489997864
},
{
"filename": "src/main/java/net/xenyria/eem/mixin/InitMixin.java",
"retrieved_chunk": "public class InitMixin {\n @Inject(at = @At(\"HEAD\"), method = \"init()V\")\n private void init(CallbackInfo info) {\n // Register the packet listener here for client-server communication\n PacketListener.initialize();\n // Load the configuration file\n try {\n XenyriaConfigManager.loadConfig();\n } catch (Exception exception) {\n XenyriaConfigManager.LOGGER.error(\"Failed to load XEEM's configuration file on start-up: \"",
"score": 0.7916507720947266
},
{
"filename": "src/main/java/net/xenyria/eem/discord/DiscordRichPresenceIntegration.java",
"retrieved_chunk": "import java.util.concurrent.TimeUnit;\npublic class DiscordRichPresenceIntegration {\n private static DiscordRichPresenceIntegration instance;\n public static DiscordRichPresenceIntegration getInstance() { return instance; }\n public static void createInstance() throws IllegalStateException {\n if(instance != null) return;\n instance = new DiscordRichPresenceIntegration();\n }\n public static Logger LOGGER = LoggerFactory.getLogger(\"Xenyria/DiscordIntegration\");\n // Delay in milliseconds until we assume that the connection to the server has been lost",
"score": 0.7747189402580261
},
{
"filename": "src/main/java/net/xenyria/eem/discord/activity/DefaultDiscordActivityAccess.java",
"retrieved_chunk": "import java.io.IOException;\nimport java.time.Instant;\npublic class DefaultDiscordActivityAccess implements IDiscordActivityAccess {\n public static Logger LOGGER = LoggerFactory.getLogger(\"Xenyria/DiscordActivity\");\n public static final File TEMP_DIRECTORY = new File(\"xenyria\" + File.separator + \"temp\");\n @Override\n public void initialize() throws IllegalStateException {\n LOGGER.info(\"Initializing Discord Game SDK for Rich Presence integration\");\n // We're storing a copy of Discord's Game SDK in a temporary folder\n // This folder has to exist in order for initialization to succeed",
"score": 0.7726457118988037
}
] | java | !XenyriaConfigManager.getConfig().improvedShootingDetectionForPaintSquad) { |
package net.xenyria.eem.config.screen;
import me.shedaniel.clothconfig2.api.ConfigBuilder;
import me.shedaniel.clothconfig2.api.ConfigCategory;
import net.minecraft.text.Text;
import net.xenyria.eem.networking.XenyriaServerPacket;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class XenyriaConfigManager {
public static final Logger LOGGER = LoggerFactory.getLogger("EEM/Settings");
private static final File configFolder = new File("config/xenyria");
private static final File configFile = new File(configFolder, "xenyria_eem.config.json");
private static XenyriaConfig config = new XenyriaConfig();
public static XenyriaConfig getConfig() { return config; }
public static void loadConfig() throws IOException, JSONException {
if(!configFile.exists()) {
// Use default config
config = new XenyriaConfig();
}
try(Scanner scanner = new Scanner(configFile)) {
StringBuilder jsonStringBuilder = new StringBuilder();
while (scanner.hasNextLine()) {
jsonStringBuilder.append(scanner.nextLine());
}
config = XenyriaConfig.load(new JSONObject(jsonStringBuilder.toString()));
}
}
public static void saveConfig() throws IOException, IllegalStateException{
if (!configFolder.exists()) {
if(!configFolder.mkdirs()) {
throw new IOException("Couldn't create the folder for the config file for Xenyria EEM.");
}
}
if(!configFile.exists()) {
try {
if(!configFile.createNewFile()) { throw new IOException("Config file couldn't be created."); }
} catch (IOException exception) {
throw new IOException("Couldn't save the config file for Xenyria EEM.");
}
}
String | configData = config.toJSON().toString(4); |
try(FileWriter writer = new FileWriter(configFile)) {
writer.write(configData);
}
if(!configFolder.isDirectory()) {
throw new IllegalStateException("Config folder has to be a folder, not a file.");
}
// Notify the server about config changes (e.g. resetting internal variables for PS's shooting detection)
var packet = new XenyriaServerPacket(XenyriaServerPacket.EPacketType.SETTINGS_CHANGED, new JSONObject());
packet.sendToServer();
}
public static ConfigBuilder getConfigurationBuilder() {
ConfigBuilder configBuilder = ConfigBuilder.create()
.setTitle(Text.translatable("config.xenyria.settings.title"))
.setEditable(true)
.setTransparentBackground(true)
.setSavingRunnable(() -> {
try {
saveConfig();
} catch (Exception e) {
LOGGER.error("Couldn't save config: " + e.getMessage());
}
});
ConfigCategory discordCategory
= configBuilder.getOrCreateCategory(Text.translatable("config_category.xenyria_eem.discord.title"));
discordCategory.addEntry(
configBuilder.entryBuilder()
.startBooleanToggle(
Text.translatable("config.xenyria_eem.discord.rp"),
config.enableDiscordRichPresence
)
.setDefaultValue(config.enableDiscordRichPresence)
.setTooltip(Text.translatable("config.xenyria_eem.discord.rp.tooltip"))
.setSaveConsumer((newState) -> config.enableDiscordRichPresence = newState)
.build()
);
discordCategory.addEntry(
configBuilder.entryBuilder()
.startBooleanToggle(
Text.translatable("config.xenyria_eem.discord.details"),
config.shareServerActivity
)
.setDefaultValue(config.shareServerActivity)
.setTooltip(Text.translatable("config.xenyria_eem.discord.details.tooltip"))
.setSaveConsumer((newState) -> config.shareServerActivity = newState)
.build()
);
ConfigCategory paintSquadCategory
= configBuilder.getOrCreateCategory(Text.translatable("config_category.xenyria_eem.paintsquad.title"));
paintSquadCategory.addEntry(
configBuilder.entryBuilder()
.startBooleanToggle(
Text.translatable("config.xenyria_eem.paintsquad.swim_cam"),
config.swimFormCameraForPaintSquad
)
.setDefaultValue(config.swimFormCameraForPaintSquad)
.setTooltip(Text.translatable("config.xenyria_eem.paintsquad.swim_cam.tooltip"))
.setSaveConsumer((newState) -> config.swimFormCameraForPaintSquad = newState)
.build()
);
paintSquadCategory.addEntry(
configBuilder.entryBuilder()
.startBooleanToggle(
Text.translatable("config.xenyria_eem.paintsquad.shooting"),
config.improvedShootingDetectionForPaintSquad
)
.setDefaultValue(config.improvedShootingDetectionForPaintSquad)
.setTooltip(Text.translatable("config.xenyria_eem.paintsquad.shooting.tooltip"))
.setSaveConsumer((newState) -> config.improvedShootingDetectionForPaintSquad = newState)
.build()
);
return configBuilder;
}
}
| src/main/java/net/xenyria/eem/config/screen/XenyriaConfigManager.java | XenyriaNET-xeem-b635ea0 | [
{
"filename": "src/main/java/net/xenyria/eem/discord/activity/DefaultDiscordActivityAccess.java",
"retrieved_chunk": " }\n try {\n if(coreInstance != null) {\n coreInstance.close();\n coreInstance = null;\n }\n } catch (Exception e1) {\n LOGGER.error(\"Couldn't close core instance after initialization failed\"\n + e1.getMessage());\n }",
"score": 0.8051395416259766
},
{
"filename": "src/main/java/net/xenyria/eem/discord/activity/DefaultDiscordActivityAccess.java",
"retrieved_chunk": " coreInstance = new Core(params);\n } catch (Exception e) {\n try {\n if(params != null) {\n params.close();\n params = null;\n }\n } catch (Exception e1) {\n LOGGER.error(\"Couldn't close create params, this is really bad and probably an issue with the underlying library: \"\n + e1.getMessage());",
"score": 0.7922455668449402
},
{
"filename": "src/main/java/net/xenyria/eem/discord/activity/DefaultDiscordActivityAccess.java",
"retrieved_chunk": " if(!nativeLibraryFile.exists()) {\n throw new FileNotFoundException(\"SDK has been downloaded but the required file couldn't be found.\");\n }\n } catch (IOException exception) {\n LOGGER.error(\"Downloading the Discord Game SDK has failed: \" + exception.getMessage());\n }\n }\n Core.init(nativeLibraryFile);\n }\n private Core coreInstance;",
"score": 0.7838001251220703
},
{
"filename": "src/main/java/net/xenyria/eem/discord/DiscordUtil.java",
"retrieved_chunk": " // Check if it's the file we are searching for...\n try {\n if (currentZipEntry.getName().equals(targetFileName)) {\n if (!output.getParentFile().exists() && !output.getParentFile().mkdirs())\n throw new IOException(\"Folder could not be created.\");\n // Copy to the system disk\n Files.copy(zipInputStream, output.toPath(), StandardCopyOption.REPLACE_EXISTING);\n // Exit from the loop\n break;\n }",
"score": 0.7681628465652466
},
{
"filename": "src/main/java/net/xenyria/eem/discord/activity/DefaultDiscordActivityAccess.java",
"retrieved_chunk": " }\n }\n @Override\n public synchronized void stop() {\n // Clean up\n if(coreInstance == null) return;\n try {\n coreInstance.close();\n } catch (Exception e) {\n LOGGER.error(\"Couldn't close core instance: \" + e.getMessage());",
"score": 0.7591680288314819
}
] | java | configData = config.toJSON().toString(4); |
package net.xenyria.eem.discord;
import net.xenyria.eem.config.screen.XenyriaConfigManager;
import net.xenyria.eem.discord.activity.DefaultDiscordActivityAccess;
import net.xenyria.eem.discord.activity.IDiscordActivityAccess;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class DiscordRichPresenceIntegration {
private static DiscordRichPresenceIntegration instance;
public static DiscordRichPresenceIntegration getInstance() { return instance; }
public static void createInstance() throws IllegalStateException {
if(instance != null) return;
instance = new DiscordRichPresenceIntegration();
}
public static Logger LOGGER = LoggerFactory.getLogger("Xenyria/DiscordIntegration");
// Delay in milliseconds until we assume that the connection to the server has been lost
public static final long TIMEOUT = 3000L;
// Delay in milliseconds for activity updates
public static final long UPDATE_INTERVAL = 500L;
// Constructor
private DiscordRichPresenceIntegration() throws IllegalStateException {
// Initialize the discord library
discordActivityAccess = new DefaultDiscordActivityAccess();
discordActivityAccess.initialize();
// Start the rich presence update loop
enterRichPresenceUpdateLoop();
}
public static JSONObject loadDefaultRichPresenceData() {
try(var stream = DiscordRichPresenceIntegration.class
.getResourceAsStream("/discord/anonymous_rich_presence.json")) {
byte[] data = stream.readAllBytes();
String rawJson = new String(data, StandardCharsets.UTF_8);
return new JSONObject(rawJson);
} catch (Exception e) {
LOGGER.error("Failed to load default rich presence data: " + e.getMessage());
}
return null;
}
/**
* Interface for accessing Discord's activity API
*/
private final IDiscordActivityAccess discordActivityAccess;
public IDiscordActivityAccess getActivityAccess() {
return discordActivityAccess;
}
/**
* The last known rich presence state is stored here along with a timestamp.
* If we don't receive any new data in the last few seconds we'll automatically
* stop sending rich presence data to the API.
* **/
private static final Object lock = new Object();
private static JSONObject lastReceivedRichPresence;
private static long lastReceivedPacket = 0L;
public static void setLastReceivedRichPresence(JSONObject lastReceivedRichPresence) {
synchronized (lock) {
lastReceivedPacket = System.currentTimeMillis();
DiscordRichPresenceIntegration.lastReceivedRichPresence = lastReceivedRichPresence;
}
}
// The last application ID that was used to initialize the activity access.
private long lastApplicationID = -1L;
/**
* Starts a thread that passes data to the activity access
*/
public void enterRichPresenceUpdateLoop() {
LOGGER.info("Entering rich presence update loop...");
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
LOGGER.info("Starting API task...");
executor.scheduleAtFixedRate(() -> {
try {
JSONObject richPresenceData = null;
boolean isDataPresent = false;
// Lock so this#setLastReceivedRichPresence is blocked while we copy data
synchronized (lock) {
if (lastReceivedRichPresence != null) {
long deltaSinceLastPacket = System.currentTimeMillis() - lastReceivedPacket;
if (deltaSinceLastPacket < TIMEOUT) {
isDataPresent = true;
richPresenceData = new JSONObject(lastReceivedRichPresence.toMap());
}
}
}
if (isDataPresent) {
// Replace the received rich presence data with generic content
// if the User doesn't want to share their activity on the server.
if (!XenyriaConfigManager.getConfig().shareServerActivity) {
richPresenceData = loadDefaultRichPresenceData();
}
long applicationId = richPresenceData.getLong("applicationId");
if (applicationId != lastApplicationID) {
// Application ID has changed - Therefore we restart our activity access with a different ID
lastApplicationID = applicationId;
LOGGER.info("Switching application ID to " + applicationId + "...");
discordActivityAccess.stop();
| discordActivityAccess.start(applicationId); |
return;
}
// Pass rich presence data down to the Discord activity access
var details = richPresenceData.getString("details");
var state = richPresenceData.getString("state");
var smallImageId = richPresenceData.getString("smallImageId");
var smallImageText = richPresenceData.getString("smallImageText");
var largeImageId = richPresenceData.getString("largeImageId");
var largeImageText = richPresenceData.getString("largeImageText");
var activityStart = richPresenceData.getLong("activityStart");
var activityEnd = richPresenceData.getLong("activityEnd");
discordActivityAccess.updateRichPresence(applicationId,
details,
state,
activityStart,
activityEnd,
smallImageId,
smallImageText,
largeImageId,
largeImageText);
} else {
// The application ID has to be reset here so the core gets started up again once we receive data again
lastApplicationID = 0;
discordActivityAccess.stop();
}
// Run callbacks
discordActivityAccess.runCallbacks();
} catch (Exception e) {
LOGGER.error("An error occurred during the rich presence update loop", e);
}
}, UPDATE_INTERVAL, UPDATE_INTERVAL, TimeUnit.MILLISECONDS);
}
}
| src/main/java/net/xenyria/eem/discord/DiscordRichPresenceIntegration.java | XenyriaNET-xeem-b635ea0 | [
{
"filename": "src/main/java/net/xenyria/eem/discord/activity/IDiscordActivityAccess.java",
"retrieved_chunk": "package net.xenyria.eem.discord.activity;\npublic interface IDiscordActivityAccess {\n void initialize() throws IllegalStateException;\n void start(long applicationId);\n void stop();\n void updateRichPresence(\n long applicationId,\n String details,\n String state,\n long activityStart,",
"score": 0.7715928554534912
},
{
"filename": "src/main/java/net/xenyria/eem/networking/PacketListener.java",
"retrieved_chunk": " }\n DiscordRichPresenceIntegration.setLastReceivedRichPresence(packet.getData());\n } else if (packet.getPacketType() == XenyriaServerPacket.EPacketType.HANDSHAKE_INIT) {\n // Orion sends one mod handshake packet on login\n // This packet contains the current server ID\n String instanceId = packet.getData().getString(\"server_id\");\n PlayingSessionInformation.setServerInstanceId(instanceId);\n PlayingSessionInformation.setOnNetwork(true);\n PlayingSessionInformation.setCurrentServerType(\n EXenyriaServerType.determineServerType(instanceId)",
"score": 0.7633293271064758
},
{
"filename": "src/main/java/net/xenyria/eem/networking/PacketListener.java",
"retrieved_chunk": " XenyriaServerPacket packet = XenyriaServerPacket.parsePacket(rawJsonText);\n if(packet == null) {\n LOGGER.warning(\"Unable to parse Xenyria packet with \" + bytesToRead + \" length.\");\n return;\n }\n // Do something with the received data\n if (packet.getPacketType() == XenyriaServerPacket.EPacketType.RP) {\n // If rich presence is disabled in the settings we ignore this packet\n if (!XenyriaConfigManager.getConfig().enableDiscordRichPresence) {\n return;",
"score": 0.7528125047683716
},
{
"filename": "src/main/java/net/xenyria/eem/config/screen/XenyriaConfigManager.java",
"retrieved_chunk": " .setTransparentBackground(true)\n .setSavingRunnable(() -> {\n try {\n saveConfig();\n } catch (Exception e) {\n LOGGER.error(\"Couldn't save config: \" + e.getMessage());\n }\n });\n ConfigCategory discordCategory\n = configBuilder.getOrCreateCategory(Text.translatable(\"config_category.xenyria_eem.discord.title\"));",
"score": 0.7500947117805481
},
{
"filename": "src/main/java/net/xenyria/eem/discord/activity/DefaultDiscordActivityAccess.java",
"retrieved_chunk": "import java.io.IOException;\nimport java.time.Instant;\npublic class DefaultDiscordActivityAccess implements IDiscordActivityAccess {\n public static Logger LOGGER = LoggerFactory.getLogger(\"Xenyria/DiscordActivity\");\n public static final File TEMP_DIRECTORY = new File(\"xenyria\" + File.separator + \"temp\");\n @Override\n public void initialize() throws IllegalStateException {\n LOGGER.info(\"Initializing Discord Game SDK for Rich Presence integration\");\n // We're storing a copy of Discord's Game SDK in a temporary folder\n // This folder has to exist in order for initialization to succeed",
"score": 0.7465305328369141
}
] | java | discordActivityAccess.start(applicationId); |
package net.xenyria.eem.discord;
import net.xenyria.eem.config.screen.XenyriaConfigManager;
import net.xenyria.eem.discord.activity.DefaultDiscordActivityAccess;
import net.xenyria.eem.discord.activity.IDiscordActivityAccess;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class DiscordRichPresenceIntegration {
private static DiscordRichPresenceIntegration instance;
public static DiscordRichPresenceIntegration getInstance() { return instance; }
public static void createInstance() throws IllegalStateException {
if(instance != null) return;
instance = new DiscordRichPresenceIntegration();
}
public static Logger LOGGER = LoggerFactory.getLogger("Xenyria/DiscordIntegration");
// Delay in milliseconds until we assume that the connection to the server has been lost
public static final long TIMEOUT = 3000L;
// Delay in milliseconds for activity updates
public static final long UPDATE_INTERVAL = 500L;
// Constructor
private DiscordRichPresenceIntegration() throws IllegalStateException {
// Initialize the discord library
discordActivityAccess = new DefaultDiscordActivityAccess();
discordActivityAccess.initialize();
// Start the rich presence update loop
enterRichPresenceUpdateLoop();
}
public static JSONObject loadDefaultRichPresenceData() {
try(var stream = DiscordRichPresenceIntegration.class
.getResourceAsStream("/discord/anonymous_rich_presence.json")) {
byte[] data = stream.readAllBytes();
String rawJson = new String(data, StandardCharsets.UTF_8);
return new JSONObject(rawJson);
} catch (Exception e) {
LOGGER.error("Failed to load default rich presence data: " + e.getMessage());
}
return null;
}
/**
* Interface for accessing Discord's activity API
*/
private final IDiscordActivityAccess discordActivityAccess;
public IDiscordActivityAccess getActivityAccess() {
return discordActivityAccess;
}
/**
* The last known rich presence state is stored here along with a timestamp.
* If we don't receive any new data in the last few seconds we'll automatically
* stop sending rich presence data to the API.
* **/
private static final Object lock = new Object();
private static JSONObject lastReceivedRichPresence;
private static long lastReceivedPacket = 0L;
public static void setLastReceivedRichPresence(JSONObject lastReceivedRichPresence) {
synchronized (lock) {
lastReceivedPacket = System.currentTimeMillis();
DiscordRichPresenceIntegration.lastReceivedRichPresence = lastReceivedRichPresence;
}
}
// The last application ID that was used to initialize the activity access.
private long lastApplicationID = -1L;
/**
* Starts a thread that passes data to the activity access
*/
public void enterRichPresenceUpdateLoop() {
LOGGER.info("Entering rich presence update loop...");
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
LOGGER.info("Starting API task...");
executor.scheduleAtFixedRate(() -> {
try {
JSONObject richPresenceData = null;
boolean isDataPresent = false;
// Lock so this#setLastReceivedRichPresence is blocked while we copy data
synchronized (lock) {
if (lastReceivedRichPresence != null) {
long deltaSinceLastPacket = System.currentTimeMillis() - lastReceivedPacket;
if (deltaSinceLastPacket < TIMEOUT) {
isDataPresent = true;
richPresenceData = new JSONObject(lastReceivedRichPresence.toMap());
}
}
}
if (isDataPresent) {
// Replace the received rich presence data with generic content
// if the User doesn't want to share their activity on the server.
if ( | !XenyriaConfigManager.getConfig().shareServerActivity) { |
richPresenceData = loadDefaultRichPresenceData();
}
long applicationId = richPresenceData.getLong("applicationId");
if (applicationId != lastApplicationID) {
// Application ID has changed - Therefore we restart our activity access with a different ID
lastApplicationID = applicationId;
LOGGER.info("Switching application ID to " + applicationId + "...");
discordActivityAccess.stop();
discordActivityAccess.start(applicationId);
return;
}
// Pass rich presence data down to the Discord activity access
var details = richPresenceData.getString("details");
var state = richPresenceData.getString("state");
var smallImageId = richPresenceData.getString("smallImageId");
var smallImageText = richPresenceData.getString("smallImageText");
var largeImageId = richPresenceData.getString("largeImageId");
var largeImageText = richPresenceData.getString("largeImageText");
var activityStart = richPresenceData.getLong("activityStart");
var activityEnd = richPresenceData.getLong("activityEnd");
discordActivityAccess.updateRichPresence(applicationId,
details,
state,
activityStart,
activityEnd,
smallImageId,
smallImageText,
largeImageId,
largeImageText);
} else {
// The application ID has to be reset here so the core gets started up again once we receive data again
lastApplicationID = 0;
discordActivityAccess.stop();
}
// Run callbacks
discordActivityAccess.runCallbacks();
} catch (Exception e) {
LOGGER.error("An error occurred during the rich presence update loop", e);
}
}, UPDATE_INTERVAL, UPDATE_INTERVAL, TimeUnit.MILLISECONDS);
}
}
| src/main/java/net/xenyria/eem/discord/DiscordRichPresenceIntegration.java | XenyriaNET-xeem-b635ea0 | [
{
"filename": "src/main/java/net/xenyria/eem/networking/PacketListener.java",
"retrieved_chunk": " XenyriaServerPacket packet = XenyriaServerPacket.parsePacket(rawJsonText);\n if(packet == null) {\n LOGGER.warning(\"Unable to parse Xenyria packet with \" + bytesToRead + \" length.\");\n return;\n }\n // Do something with the received data\n if (packet.getPacketType() == XenyriaServerPacket.EPacketType.RP) {\n // If rich presence is disabled in the settings we ignore this packet\n if (!XenyriaConfigManager.getConfig().enableDiscordRichPresence) {\n return;",
"score": 0.8112244606018066
},
{
"filename": "src/main/java/net/xenyria/eem/mixin/InitMixin.java",
"retrieved_chunk": "public class InitMixin {\n @Inject(at = @At(\"HEAD\"), method = \"init()V\")\n private void init(CallbackInfo info) {\n // Register the packet listener here for client-server communication\n PacketListener.initialize();\n // Load the configuration file\n try {\n XenyriaConfigManager.loadConfig();\n } catch (Exception exception) {\n XenyriaConfigManager.LOGGER.error(\"Failed to load XEEM's configuration file on start-up: \"",
"score": 0.7787572145462036
},
{
"filename": "src/main/java/net/xenyria/eem/discord/activity/DefaultDiscordActivityAccess.java",
"retrieved_chunk": " if(!nativeLibraryFile.exists()) {\n throw new FileNotFoundException(\"SDK has been downloaded but the required file couldn't be found.\");\n }\n } catch (IOException exception) {\n LOGGER.error(\"Downloading the Discord Game SDK has failed: \" + exception.getMessage());\n }\n }\n Core.init(nativeLibraryFile);\n }\n private Core coreInstance;",
"score": 0.7741808891296387
},
{
"filename": "src/main/java/net/xenyria/eem/utils/Keybinds.java",
"retrieved_chunk": " registerCommandKeybind(client, Hub, \"hub\");\n });\n }\n private static void registerCommandKeybind(MinecraftClient client, KeyBinding keybinding, String command) {\n // Check if the user is on the server since you don't want to trigger certain macros on other servers\n if(!PlayingSessionInformation.isOnNetwork()) { return; }\n while (keybinding.wasPressed()) client.player.networkHandler.sendChatCommand(command);\n }\n}",
"score": 0.7705069780349731
},
{
"filename": "src/main/java/net/xenyria/eem/networking/XenyriaServerPacket.java",
"retrieved_chunk": " /**\n * Parses raw JSON into packet objects\n */\n public static XenyriaServerPacket parsePacket(String rawJson) {\n JSONObject jsonData;\n try {\n jsonData = new JSONObject(rawJson);\n } catch (JSONException exception) {\n LOGGER.severe(\"Unable to parse packet from raw JSON: \" + rawJson);\n return null;",
"score": 0.7674147486686707
}
] | java | !XenyriaConfigManager.getConfig().shareServerActivity) { |
package net.xenyria.eem.networking;
import net.xenyria.eem.discord.DiscordRichPresenceIntegration;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
import net.minecraft.util.Identifier;
import net.xenyria.eem.EXenyriaServerType;
import net.xenyria.eem.PlayingSessionInformation;
import net.xenyria.eem.config.screen.XenyriaConfigManager;
import org.json.JSONObject;
import java.nio.charset.StandardCharsets;
import java.util.logging.Logger;
public class PacketListener {
public static Identifier ID;
public static Logger LOGGER = Logger.getLogger("Xenyria/PacketListener");
public static void initialize() {
ID = Identifier.of("xenyria", "mod_communication");
if(ID == null) throw new IllegalStateException("Identifier could not be initialized.");
LOGGER.info("Registering packet receiver for plugin messages...");
ClientPlayNetworking.registerGlobalReceiver(
ID, (client, handler, buf, responseSender) -> {
/*
* Packets sent by the server consist of a 4-byte Integer
* and a byte array that represents UTF-8 string data.
*/
int bytesToRead = buf.readInt();
// Allocate enough memory for reading the raw JSON string in the next step
byte[] buffer = new byte[bytesToRead];
buf.readBytes(buffer);
// Create a UTF-8 string from the received data
String rawJsonText = new String(buffer, StandardCharsets.UTF_8);
// Try to parse the packet
XenyriaServerPacket packet = XenyriaServerPacket.parsePacket(rawJsonText);
if(packet == null) {
LOGGER.warning("Unable to parse Xenyria packet with " + bytesToRead + " length.");
return;
}
// Do something with the received data
if (packet.getPacketType() == XenyriaServerPacket.EPacketType.RP) {
// If rich presence is disabled in the settings we ignore this packet
if (!XenyriaConfigManager.getConfig().enableDiscordRichPresence) {
return;
}
DiscordRichPresenceIntegration.setLastReceivedRichPresence(packet.getData());
} else if (packet.getPacketType() == XenyriaServerPacket.EPacketType.HANDSHAKE_INIT) {
// Orion sends one mod handshake packet on login
// This packet contains the current server ID
String instanceId = packet.getData().getString("server_id");
PlayingSessionInformation.setServerInstanceId(instanceId);
| PlayingSessionInformation.setOnNetwork(true); |
PlayingSessionInformation.setCurrentServerType(
EXenyriaServerType.determineServerType(instanceId)
);
// We respond back so that the server knows we're using XEEM
XenyriaServerPacket responsePacket = new XenyriaServerPacket(
XenyriaServerPacket.EPacketType.HANDSHAKE_RESPONSE,
new JSONObject()
);
responsePacket.sendToServer();
LOGGER.info("Successfully completed handshake with Orion");
} else if (packet.getPacketType() == XenyriaServerPacket.EPacketType.DEBUG) {
LOGGER.info("Current network state: " + PlayingSessionInformation.isOnNetwork());
LOGGER.info("Current server type: " + PlayingSessionInformation.getCurrentServerType());
LOGGER.info("Current server id: " + PlayingSessionInformation.getServerInstanceId());
}
}
);
}
}
| src/main/java/net/xenyria/eem/networking/PacketListener.java | XenyriaNET-xeem-b635ea0 | [
{
"filename": "src/main/java/net/xenyria/eem/paintsquad/PaintSquadInputManager.java",
"retrieved_chunk": " // If a change has been detected we send a mod packet to the server\n if(hasChanged) {\n JSONObject payload = new JSONObject();\n payload.put(\"shooting\", isShooting);\n XenyriaServerPacket packet = new XenyriaServerPacket(\n XenyriaServerPacket.EPacketType.PS_SHOOTING_STATE, payload);\n packet.sendToServer();\n }\n }\n }, 10, 10, TimeUnit.MILLISECONDS);",
"score": 0.8043692111968994
},
{
"filename": "src/main/java/net/xenyria/eem/discord/DiscordRichPresenceIntegration.java",
"retrieved_chunk": " if (deltaSinceLastPacket < TIMEOUT) {\n isDataPresent = true;\n richPresenceData = new JSONObject(lastReceivedRichPresence.toMap());\n }\n }\n }\n if (isDataPresent) {\n // Replace the received rich presence data with generic content\n // if the User doesn't want to share their activity on the server.\n if (!XenyriaConfigManager.getConfig().shareServerActivity) {",
"score": 0.7995295524597168
},
{
"filename": "src/main/java/net/xenyria/eem/config/screen/XenyriaConfigManager.java",
"retrieved_chunk": " throw new IllegalStateException(\"Config folder has to be a folder, not a file.\");\n }\n // Notify the server about config changes (e.g. resetting internal variables for PS's shooting detection)\n var packet = new XenyriaServerPacket(XenyriaServerPacket.EPacketType.SETTINGS_CHANGED, new JSONObject());\n packet.sendToServer();\n }\n public static ConfigBuilder getConfigurationBuilder() {\n ConfigBuilder configBuilder = ConfigBuilder.create()\n .setTitle(Text.translatable(\"config.xenyria.settings.title\"))\n .setEditable(true)",
"score": 0.7682902216911316
},
{
"filename": "src/main/java/net/xenyria/eem/discord/DiscordRichPresenceIntegration.java",
"retrieved_chunk": " richPresenceData = loadDefaultRichPresenceData();\n }\n long applicationId = richPresenceData.getLong(\"applicationId\");\n if (applicationId != lastApplicationID) {\n // Application ID has changed - Therefore we restart our activity access with a different ID\n lastApplicationID = applicationId;\n LOGGER.info(\"Switching application ID to \" + applicationId + \"...\");\n discordActivityAccess.stop();\n discordActivityAccess.start(applicationId);\n return;",
"score": 0.7660878896713257
},
{
"filename": "src/main/java/net/xenyria/eem/mixin/DisconnectMixin.java",
"retrieved_chunk": " @Inject(at = @At(\"HEAD\"), method = \"disconnect(Lnet/minecraft/client/gui/screen/Screen;)V\")\n public void handleDisconnect(CallbackInfo info) {\n PlayingSessionInformation.setOnNetwork(false);\n PlayingSessionInformation.setCurrentServerType(EXenyriaServerType.UNKNOWN);\n PlayingSessionInformation.setServerInstanceId(\"\");\n }\n}",
"score": 0.7463245391845703
}
] | java | PlayingSessionInformation.setOnNetwork(true); |
package net.xenyria.eem.discord;
import net.xenyria.eem.config.screen.XenyriaConfigManager;
import net.xenyria.eem.discord.activity.DefaultDiscordActivityAccess;
import net.xenyria.eem.discord.activity.IDiscordActivityAccess;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class DiscordRichPresenceIntegration {
private static DiscordRichPresenceIntegration instance;
public static DiscordRichPresenceIntegration getInstance() { return instance; }
public static void createInstance() throws IllegalStateException {
if(instance != null) return;
instance = new DiscordRichPresenceIntegration();
}
public static Logger LOGGER = LoggerFactory.getLogger("Xenyria/DiscordIntegration");
// Delay in milliseconds until we assume that the connection to the server has been lost
public static final long TIMEOUT = 3000L;
// Delay in milliseconds for activity updates
public static final long UPDATE_INTERVAL = 500L;
// Constructor
private DiscordRichPresenceIntegration() throws IllegalStateException {
// Initialize the discord library
discordActivityAccess = new DefaultDiscordActivityAccess();
discordActivityAccess.initialize();
// Start the rich presence update loop
enterRichPresenceUpdateLoop();
}
public static JSONObject loadDefaultRichPresenceData() {
try(var stream = DiscordRichPresenceIntegration.class
.getResourceAsStream("/discord/anonymous_rich_presence.json")) {
byte[] data = stream.readAllBytes();
String rawJson = new String(data, StandardCharsets.UTF_8);
return new JSONObject(rawJson);
} catch (Exception e) {
LOGGER.error("Failed to load default rich presence data: " + e.getMessage());
}
return null;
}
/**
* Interface for accessing Discord's activity API
*/
private final IDiscordActivityAccess discordActivityAccess;
public IDiscordActivityAccess getActivityAccess() {
return discordActivityAccess;
}
/**
* The last known rich presence state is stored here along with a timestamp.
* If we don't receive any new data in the last few seconds we'll automatically
* stop sending rich presence data to the API.
* **/
private static final Object lock = new Object();
private static JSONObject lastReceivedRichPresence;
private static long lastReceivedPacket = 0L;
public static void setLastReceivedRichPresence(JSONObject lastReceivedRichPresence) {
synchronized (lock) {
lastReceivedPacket = System.currentTimeMillis();
DiscordRichPresenceIntegration.lastReceivedRichPresence = lastReceivedRichPresence;
}
}
// The last application ID that was used to initialize the activity access.
private long lastApplicationID = -1L;
/**
* Starts a thread that passes data to the activity access
*/
public void enterRichPresenceUpdateLoop() {
LOGGER.info("Entering rich presence update loop...");
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
LOGGER.info("Starting API task...");
executor.scheduleAtFixedRate(() -> {
try {
JSONObject richPresenceData = null;
boolean isDataPresent = false;
// Lock so this#setLastReceivedRichPresence is blocked while we copy data
synchronized (lock) {
if (lastReceivedRichPresence != null) {
long deltaSinceLastPacket = System.currentTimeMillis() - lastReceivedPacket;
if (deltaSinceLastPacket < TIMEOUT) {
isDataPresent = true;
richPresenceData = new JSONObject(lastReceivedRichPresence.toMap());
}
}
}
if (isDataPresent) {
// Replace the received rich presence data with generic content
// if the User doesn't want to share their activity on the server.
if (!XenyriaConfigManager.getConfig().shareServerActivity) {
richPresenceData = loadDefaultRichPresenceData();
}
long applicationId = richPresenceData.getLong("applicationId");
if (applicationId != lastApplicationID) {
// Application ID has changed - Therefore we restart our activity access with a different ID
lastApplicationID = applicationId;
LOGGER.info("Switching application ID to " + applicationId + "...");
| discordActivityAccess.stop(); |
discordActivityAccess.start(applicationId);
return;
}
// Pass rich presence data down to the Discord activity access
var details = richPresenceData.getString("details");
var state = richPresenceData.getString("state");
var smallImageId = richPresenceData.getString("smallImageId");
var smallImageText = richPresenceData.getString("smallImageText");
var largeImageId = richPresenceData.getString("largeImageId");
var largeImageText = richPresenceData.getString("largeImageText");
var activityStart = richPresenceData.getLong("activityStart");
var activityEnd = richPresenceData.getLong("activityEnd");
discordActivityAccess.updateRichPresence(applicationId,
details,
state,
activityStart,
activityEnd,
smallImageId,
smallImageText,
largeImageId,
largeImageText);
} else {
// The application ID has to be reset here so the core gets started up again once we receive data again
lastApplicationID = 0;
discordActivityAccess.stop();
}
// Run callbacks
discordActivityAccess.runCallbacks();
} catch (Exception e) {
LOGGER.error("An error occurred during the rich presence update loop", e);
}
}, UPDATE_INTERVAL, UPDATE_INTERVAL, TimeUnit.MILLISECONDS);
}
}
| src/main/java/net/xenyria/eem/discord/DiscordRichPresenceIntegration.java | XenyriaNET-xeem-b635ea0 | [
{
"filename": "src/main/java/net/xenyria/eem/discord/activity/IDiscordActivityAccess.java",
"retrieved_chunk": "package net.xenyria.eem.discord.activity;\npublic interface IDiscordActivityAccess {\n void initialize() throws IllegalStateException;\n void start(long applicationId);\n void stop();\n void updateRichPresence(\n long applicationId,\n String details,\n String state,\n long activityStart,",
"score": 0.7859206199645996
},
{
"filename": "src/main/java/net/xenyria/eem/networking/PacketListener.java",
"retrieved_chunk": " XenyriaServerPacket packet = XenyriaServerPacket.parsePacket(rawJsonText);\n if(packet == null) {\n LOGGER.warning(\"Unable to parse Xenyria packet with \" + bytesToRead + \" length.\");\n return;\n }\n // Do something with the received data\n if (packet.getPacketType() == XenyriaServerPacket.EPacketType.RP) {\n // If rich presence is disabled in the settings we ignore this packet\n if (!XenyriaConfigManager.getConfig().enableDiscordRichPresence) {\n return;",
"score": 0.7834398746490479
},
{
"filename": "src/main/java/net/xenyria/eem/discord/activity/DefaultDiscordActivityAccess.java",
"retrieved_chunk": "import java.io.IOException;\nimport java.time.Instant;\npublic class DefaultDiscordActivityAccess implements IDiscordActivityAccess {\n public static Logger LOGGER = LoggerFactory.getLogger(\"Xenyria/DiscordActivity\");\n public static final File TEMP_DIRECTORY = new File(\"xenyria\" + File.separator + \"temp\");\n @Override\n public void initialize() throws IllegalStateException {\n LOGGER.info(\"Initializing Discord Game SDK for Rich Presence integration\");\n // We're storing a copy of Discord's Game SDK in a temporary folder\n // This folder has to exist in order for initialization to succeed",
"score": 0.7811235785484314
},
{
"filename": "src/main/java/net/xenyria/eem/networking/PacketListener.java",
"retrieved_chunk": " }\n DiscordRichPresenceIntegration.setLastReceivedRichPresence(packet.getData());\n } else if (packet.getPacketType() == XenyriaServerPacket.EPacketType.HANDSHAKE_INIT) {\n // Orion sends one mod handshake packet on login\n // This packet contains the current server ID\n String instanceId = packet.getData().getString(\"server_id\");\n PlayingSessionInformation.setServerInstanceId(instanceId);\n PlayingSessionInformation.setOnNetwork(true);\n PlayingSessionInformation.setCurrentServerType(\n EXenyriaServerType.determineServerType(instanceId)",
"score": 0.7643674612045288
},
{
"filename": "src/main/java/net/xenyria/eem/mixin/InitMixin.java",
"retrieved_chunk": "public class InitMixin {\n @Inject(at = @At(\"HEAD\"), method = \"init()V\")\n private void init(CallbackInfo info) {\n // Register the packet listener here for client-server communication\n PacketListener.initialize();\n // Load the configuration file\n try {\n XenyriaConfigManager.loadConfig();\n } catch (Exception exception) {\n XenyriaConfigManager.LOGGER.error(\"Failed to load XEEM's configuration file on start-up: \"",
"score": 0.7610971331596375
}
] | java | discordActivityAccess.stop(); |
package net.xenyria.eem.networking;
import net.xenyria.eem.discord.DiscordRichPresenceIntegration;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
import net.minecraft.util.Identifier;
import net.xenyria.eem.EXenyriaServerType;
import net.xenyria.eem.PlayingSessionInformation;
import net.xenyria.eem.config.screen.XenyriaConfigManager;
import org.json.JSONObject;
import java.nio.charset.StandardCharsets;
import java.util.logging.Logger;
public class PacketListener {
public static Identifier ID;
public static Logger LOGGER = Logger.getLogger("Xenyria/PacketListener");
public static void initialize() {
ID = Identifier.of("xenyria", "mod_communication");
if(ID == null) throw new IllegalStateException("Identifier could not be initialized.");
LOGGER.info("Registering packet receiver for plugin messages...");
ClientPlayNetworking.registerGlobalReceiver(
ID, (client, handler, buf, responseSender) -> {
/*
* Packets sent by the server consist of a 4-byte Integer
* and a byte array that represents UTF-8 string data.
*/
int bytesToRead = buf.readInt();
// Allocate enough memory for reading the raw JSON string in the next step
byte[] buffer = new byte[bytesToRead];
buf.readBytes(buffer);
// Create a UTF-8 string from the received data
String rawJsonText = new String(buffer, StandardCharsets.UTF_8);
// Try to parse the packet
XenyriaServerPacket packet = XenyriaServerPacket.parsePacket(rawJsonText);
if(packet == null) {
LOGGER.warning("Unable to parse Xenyria packet with " + bytesToRead + " length.");
return;
}
// Do something with the received data
if (packet.getPacketType() == XenyriaServerPacket.EPacketType.RP) {
// If rich presence is disabled in the settings we ignore this packet
if (!XenyriaConfigManager.getConfig().enableDiscordRichPresence) {
return;
}
DiscordRichPresenceIntegration.setLastReceivedRichPresence(packet.getData());
} else if (packet.getPacketType() == XenyriaServerPacket.EPacketType.HANDSHAKE_INIT) {
// Orion sends one mod handshake packet on login
// This packet contains the current server ID
| String instanceId = packet.getData().getString("server_id"); |
PlayingSessionInformation.setServerInstanceId(instanceId);
PlayingSessionInformation.setOnNetwork(true);
PlayingSessionInformation.setCurrentServerType(
EXenyriaServerType.determineServerType(instanceId)
);
// We respond back so that the server knows we're using XEEM
XenyriaServerPacket responsePacket = new XenyriaServerPacket(
XenyriaServerPacket.EPacketType.HANDSHAKE_RESPONSE,
new JSONObject()
);
responsePacket.sendToServer();
LOGGER.info("Successfully completed handshake with Orion");
} else if (packet.getPacketType() == XenyriaServerPacket.EPacketType.DEBUG) {
LOGGER.info("Current network state: " + PlayingSessionInformation.isOnNetwork());
LOGGER.info("Current server type: " + PlayingSessionInformation.getCurrentServerType());
LOGGER.info("Current server id: " + PlayingSessionInformation.getServerInstanceId());
}
}
);
}
}
| src/main/java/net/xenyria/eem/networking/PacketListener.java | XenyriaNET-xeem-b635ea0 | [
{
"filename": "src/main/java/net/xenyria/eem/discord/DiscordRichPresenceIntegration.java",
"retrieved_chunk": " if (deltaSinceLastPacket < TIMEOUT) {\n isDataPresent = true;\n richPresenceData = new JSONObject(lastReceivedRichPresence.toMap());\n }\n }\n }\n if (isDataPresent) {\n // Replace the received rich presence data with generic content\n // if the User doesn't want to share their activity on the server.\n if (!XenyriaConfigManager.getConfig().shareServerActivity) {",
"score": 0.8417491316795349
},
{
"filename": "src/main/java/net/xenyria/eem/paintsquad/PaintSquadInputManager.java",
"retrieved_chunk": " // If a change has been detected we send a mod packet to the server\n if(hasChanged) {\n JSONObject payload = new JSONObject();\n payload.put(\"shooting\", isShooting);\n XenyriaServerPacket packet = new XenyriaServerPacket(\n XenyriaServerPacket.EPacketType.PS_SHOOTING_STATE, payload);\n packet.sendToServer();\n }\n }\n }, 10, 10, TimeUnit.MILLISECONDS);",
"score": 0.8328598737716675
},
{
"filename": "src/main/java/net/xenyria/eem/config/screen/XenyriaConfigManager.java",
"retrieved_chunk": " throw new IllegalStateException(\"Config folder has to be a folder, not a file.\");\n }\n // Notify the server about config changes (e.g. resetting internal variables for PS's shooting detection)\n var packet = new XenyriaServerPacket(XenyriaServerPacket.EPacketType.SETTINGS_CHANGED, new JSONObject());\n packet.sendToServer();\n }\n public static ConfigBuilder getConfigurationBuilder() {\n ConfigBuilder configBuilder = ConfigBuilder.create()\n .setTitle(Text.translatable(\"config.xenyria.settings.title\"))\n .setEditable(true)",
"score": 0.8101904392242432
},
{
"filename": "src/main/java/net/xenyria/eem/mixin/InitMixin.java",
"retrieved_chunk": "public class InitMixin {\n @Inject(at = @At(\"HEAD\"), method = \"init()V\")\n private void init(CallbackInfo info) {\n // Register the packet listener here for client-server communication\n PacketListener.initialize();\n // Load the configuration file\n try {\n XenyriaConfigManager.loadConfig();\n } catch (Exception exception) {\n XenyriaConfigManager.LOGGER.error(\"Failed to load XEEM's configuration file on start-up: \"",
"score": 0.7866866588592529
},
{
"filename": "src/main/java/net/xenyria/eem/networking/XenyriaServerPacket.java",
"retrieved_chunk": "import java.nio.charset.StandardCharsets;\nimport static net.xenyria.eem.networking.PacketListener.LOGGER;\npublic class XenyriaServerPacket {\n /** Packets are separated into different types/categories **/\n public enum EPacketType {\n RP, // Rich-Presence (Discord Integration)\n PS_SHOOTING_STATE, // PaintSquad\n HANDSHAKE_INIT, // Server Switch / Server Info Change (Sent by the server)\n HANDSHAKE_RESPONSE, // Sent by the client, informs the server about the mod being active\n DEBUG, // Debug Operation (printing client-side variables into the chat)",
"score": 0.7815372943878174
}
] | java | String instanceId = packet.getData().getString("server_id"); |
package net.xenyria.eem.networking;
import net.xenyria.eem.discord.DiscordRichPresenceIntegration;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
import net.minecraft.util.Identifier;
import net.xenyria.eem.EXenyriaServerType;
import net.xenyria.eem.PlayingSessionInformation;
import net.xenyria.eem.config.screen.XenyriaConfigManager;
import org.json.JSONObject;
import java.nio.charset.StandardCharsets;
import java.util.logging.Logger;
public class PacketListener {
public static Identifier ID;
public static Logger LOGGER = Logger.getLogger("Xenyria/PacketListener");
public static void initialize() {
ID = Identifier.of("xenyria", "mod_communication");
if(ID == null) throw new IllegalStateException("Identifier could not be initialized.");
LOGGER.info("Registering packet receiver for plugin messages...");
ClientPlayNetworking.registerGlobalReceiver(
ID, (client, handler, buf, responseSender) -> {
/*
* Packets sent by the server consist of a 4-byte Integer
* and a byte array that represents UTF-8 string data.
*/
int bytesToRead = buf.readInt();
// Allocate enough memory for reading the raw JSON string in the next step
byte[] buffer = new byte[bytesToRead];
buf.readBytes(buffer);
// Create a UTF-8 string from the received data
String rawJsonText = new String(buffer, StandardCharsets.UTF_8);
// Try to parse the packet
XenyriaServerPacket packet = XenyriaServerPacket.parsePacket(rawJsonText);
if(packet == null) {
LOGGER.warning("Unable to parse Xenyria packet with " + bytesToRead + " length.");
return;
}
// Do something with the received data
if (packet.getPacketType() == XenyriaServerPacket.EPacketType.RP) {
// If rich presence is disabled in the settings we ignore this packet
if (!XenyriaConfigManager.getConfig().enableDiscordRichPresence) {
return;
}
DiscordRichPresenceIntegration. | setLastReceivedRichPresence(packet.getData()); |
} else if (packet.getPacketType() == XenyriaServerPacket.EPacketType.HANDSHAKE_INIT) {
// Orion sends one mod handshake packet on login
// This packet contains the current server ID
String instanceId = packet.getData().getString("server_id");
PlayingSessionInformation.setServerInstanceId(instanceId);
PlayingSessionInformation.setOnNetwork(true);
PlayingSessionInformation.setCurrentServerType(
EXenyriaServerType.determineServerType(instanceId)
);
// We respond back so that the server knows we're using XEEM
XenyriaServerPacket responsePacket = new XenyriaServerPacket(
XenyriaServerPacket.EPacketType.HANDSHAKE_RESPONSE,
new JSONObject()
);
responsePacket.sendToServer();
LOGGER.info("Successfully completed handshake with Orion");
} else if (packet.getPacketType() == XenyriaServerPacket.EPacketType.DEBUG) {
LOGGER.info("Current network state: " + PlayingSessionInformation.isOnNetwork());
LOGGER.info("Current server type: " + PlayingSessionInformation.getCurrentServerType());
LOGGER.info("Current server id: " + PlayingSessionInformation.getServerInstanceId());
}
}
);
}
}
| src/main/java/net/xenyria/eem/networking/PacketListener.java | XenyriaNET-xeem-b635ea0 | [
{
"filename": "src/main/java/net/xenyria/eem/discord/DiscordRichPresenceIntegration.java",
"retrieved_chunk": " if (deltaSinceLastPacket < TIMEOUT) {\n isDataPresent = true;\n richPresenceData = new JSONObject(lastReceivedRichPresence.toMap());\n }\n }\n }\n if (isDataPresent) {\n // Replace the received rich presence data with generic content\n // if the User doesn't want to share their activity on the server.\n if (!XenyriaConfigManager.getConfig().shareServerActivity) {",
"score": 0.8679764270782471
},
{
"filename": "src/main/java/net/xenyria/eem/paintsquad/PaintSquadInputManager.java",
"retrieved_chunk": " // If a change has been detected we send a mod packet to the server\n if(hasChanged) {\n JSONObject payload = new JSONObject();\n payload.put(\"shooting\", isShooting);\n XenyriaServerPacket packet = new XenyriaServerPacket(\n XenyriaServerPacket.EPacketType.PS_SHOOTING_STATE, payload);\n packet.sendToServer();\n }\n }\n }, 10, 10, TimeUnit.MILLISECONDS);",
"score": 0.799348771572113
},
{
"filename": "src/main/java/net/xenyria/eem/config/screen/XenyriaConfigManager.java",
"retrieved_chunk": " throw new IllegalStateException(\"Config folder has to be a folder, not a file.\");\n }\n // Notify the server about config changes (e.g. resetting internal variables for PS's shooting detection)\n var packet = new XenyriaServerPacket(XenyriaServerPacket.EPacketType.SETTINGS_CHANGED, new JSONObject());\n packet.sendToServer();\n }\n public static ConfigBuilder getConfigurationBuilder() {\n ConfigBuilder configBuilder = ConfigBuilder.create()\n .setTitle(Text.translatable(\"config.xenyria.settings.title\"))\n .setEditable(true)",
"score": 0.7855429649353027
},
{
"filename": "src/main/java/net/xenyria/eem/networking/XenyriaServerPacket.java",
"retrieved_chunk": " return null;\n }\n if(!jsonData.has(\"data\")) {\n LOGGER.severe(\"Malformed packet, missing data field.\");\n return null;\n }\n return new XenyriaServerPacket(parsedPacketType, jsonData.getJSONObject(\"data\"));\n }\n /** Attempt to send this packet to the currently connected server as a plugin message **/\n public void sendToServer() {",
"score": 0.7788791656494141
},
{
"filename": "src/main/java/net/xenyria/eem/discord/DiscordRichPresenceIntegration.java",
"retrieved_chunk": " richPresenceData = loadDefaultRichPresenceData();\n }\n long applicationId = richPresenceData.getLong(\"applicationId\");\n if (applicationId != lastApplicationID) {\n // Application ID has changed - Therefore we restart our activity access with a different ID\n lastApplicationID = applicationId;\n LOGGER.info(\"Switching application ID to \" + applicationId + \"...\");\n discordActivityAccess.stop();\n discordActivityAccess.start(applicationId);\n return;",
"score": 0.77309250831604
}
] | java | setLastReceivedRichPresence(packet.getData()); |
package net.xenyria.eem.networking;
import net.xenyria.eem.discord.DiscordRichPresenceIntegration;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
import net.minecraft.util.Identifier;
import net.xenyria.eem.EXenyriaServerType;
import net.xenyria.eem.PlayingSessionInformation;
import net.xenyria.eem.config.screen.XenyriaConfigManager;
import org.json.JSONObject;
import java.nio.charset.StandardCharsets;
import java.util.logging.Logger;
public class PacketListener {
public static Identifier ID;
public static Logger LOGGER = Logger.getLogger("Xenyria/PacketListener");
public static void initialize() {
ID = Identifier.of("xenyria", "mod_communication");
if(ID == null) throw new IllegalStateException("Identifier could not be initialized.");
LOGGER.info("Registering packet receiver for plugin messages...");
ClientPlayNetworking.registerGlobalReceiver(
ID, (client, handler, buf, responseSender) -> {
/*
* Packets sent by the server consist of a 4-byte Integer
* and a byte array that represents UTF-8 string data.
*/
int bytesToRead = buf.readInt();
// Allocate enough memory for reading the raw JSON string in the next step
byte[] buffer = new byte[bytesToRead];
buf.readBytes(buffer);
// Create a UTF-8 string from the received data
String rawJsonText = new String(buffer, StandardCharsets.UTF_8);
// Try to parse the packet
XenyriaServerPacket packet = XenyriaServerPacket.parsePacket(rawJsonText);
if(packet == null) {
LOGGER.warning("Unable to parse Xenyria packet with " + bytesToRead + " length.");
return;
}
// Do something with the received data
if (packet.getPacketType() == XenyriaServerPacket.EPacketType.RP) {
// If rich presence is disabled in the settings we ignore this packet
if (!XenyriaConfigManager.getConfig().enableDiscordRichPresence) {
return;
}
DiscordRichPresenceIntegration.setLastReceivedRichPresence(packet.getData());
} else if (packet.getPacketType() == XenyriaServerPacket.EPacketType.HANDSHAKE_INIT) {
// Orion sends one mod handshake packet on login
// This packet contains the current server ID
String instanceId = packet.getData().getString("server_id");
PlayingSessionInformation.setServerInstanceId(instanceId);
PlayingSessionInformation.setOnNetwork(true);
PlayingSessionInformation.setCurrentServerType(
EXenyriaServerType.determineServerType(instanceId)
);
// We respond back so that the server knows we're using XEEM
XenyriaServerPacket responsePacket = new XenyriaServerPacket(
XenyriaServerPacket.EPacketType.HANDSHAKE_RESPONSE,
new JSONObject()
);
responsePacket.sendToServer();
LOGGER.info("Successfully completed handshake with Orion");
} else if (packet.getPacketType() == XenyriaServerPacket.EPacketType.DEBUG) {
LOGGER.info("Current network state: " + PlayingSessionInformation.isOnNetwork());
LOGGER.info("Current server type: " + PlayingSessionInformation.getCurrentServerType());
LOGGER.info( | "Current server id: " + PlayingSessionInformation.getServerInstanceId()); |
}
}
);
}
}
| src/main/java/net/xenyria/eem/networking/PacketListener.java | XenyriaNET-xeem-b635ea0 | [
{
"filename": "src/main/java/net/xenyria/eem/paintsquad/PaintSquadInputManager.java",
"retrieved_chunk": " // If a change has been detected we send a mod packet to the server\n if(hasChanged) {\n JSONObject payload = new JSONObject();\n payload.put(\"shooting\", isShooting);\n XenyriaServerPacket packet = new XenyriaServerPacket(\n XenyriaServerPacket.EPacketType.PS_SHOOTING_STATE, payload);\n packet.sendToServer();\n }\n }\n }, 10, 10, TimeUnit.MILLISECONDS);",
"score": 0.8161478042602539
},
{
"filename": "src/main/java/net/xenyria/eem/config/screen/XenyriaConfigManager.java",
"retrieved_chunk": " throw new IllegalStateException(\"Config folder has to be a folder, not a file.\");\n }\n // Notify the server about config changes (e.g. resetting internal variables for PS's shooting detection)\n var packet = new XenyriaServerPacket(XenyriaServerPacket.EPacketType.SETTINGS_CHANGED, new JSONObject());\n packet.sendToServer();\n }\n public static ConfigBuilder getConfigurationBuilder() {\n ConfigBuilder configBuilder = ConfigBuilder.create()\n .setTitle(Text.translatable(\"config.xenyria.settings.title\"))\n .setEditable(true)",
"score": 0.7849427461624146
},
{
"filename": "src/main/java/net/xenyria/eem/PlayingSessionInformation.java",
"retrieved_chunk": "package net.xenyria.eem;\npublic class PlayingSessionInformation {\n private static boolean onNetwork;\n public static boolean isOnNetwork() { return onNetwork; }\n public static void setOnNetwork(boolean onNetwork) { PlayingSessionInformation.onNetwork = onNetwork; }\n private static EXenyriaServerType currentServerType = EXenyriaServerType.UNKNOWN;\n public static EXenyriaServerType getCurrentServerType() { return currentServerType; }\n public static void setCurrentServerType(EXenyriaServerType currentServerType) {\n PlayingSessionInformation.currentServerType = currentServerType;\n }",
"score": 0.775743842124939
},
{
"filename": "src/main/java/net/xenyria/eem/discord/DiscordRichPresenceIntegration.java",
"retrieved_chunk": " if (deltaSinceLastPacket < TIMEOUT) {\n isDataPresent = true;\n richPresenceData = new JSONObject(lastReceivedRichPresence.toMap());\n }\n }\n }\n if (isDataPresent) {\n // Replace the received rich presence data with generic content\n // if the User doesn't want to share their activity on the server.\n if (!XenyriaConfigManager.getConfig().shareServerActivity) {",
"score": 0.7657569050788879
},
{
"filename": "src/main/java/net/xenyria/eem/networking/XenyriaServerPacket.java",
"retrieved_chunk": " // 4 bytes are used to store the length of the JSON object that follows\n dataOutputStream.writeInt(jsonContent.length);\n dataOutputStream.write(jsonContent, 0, jsonContent.length);\n } catch (IOException e) {\n LOGGER.severe(\"Couldn't convert packet into bytes: \" + e.getMessage());\n }\n // Send data to the server\n CustomPayloadC2SPacket packet = new CustomPayloadC2SPacket(\n PacketListener.ID, new PacketByteBuf(\n Unpooled.wrappedBuffer(rawPacketBytes.toByteArray()))",
"score": 0.7621309757232666
}
] | java | "Current server id: " + PlayingSessionInformation.getServerInstanceId()); |
package net.xenyria.eem.networking;
import net.xenyria.eem.discord.DiscordRichPresenceIntegration;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
import net.minecraft.util.Identifier;
import net.xenyria.eem.EXenyriaServerType;
import net.xenyria.eem.PlayingSessionInformation;
import net.xenyria.eem.config.screen.XenyriaConfigManager;
import org.json.JSONObject;
import java.nio.charset.StandardCharsets;
import java.util.logging.Logger;
public class PacketListener {
public static Identifier ID;
public static Logger LOGGER = Logger.getLogger("Xenyria/PacketListener");
public static void initialize() {
ID = Identifier.of("xenyria", "mod_communication");
if(ID == null) throw new IllegalStateException("Identifier could not be initialized.");
LOGGER.info("Registering packet receiver for plugin messages...");
ClientPlayNetworking.registerGlobalReceiver(
ID, (client, handler, buf, responseSender) -> {
/*
* Packets sent by the server consist of a 4-byte Integer
* and a byte array that represents UTF-8 string data.
*/
int bytesToRead = buf.readInt();
// Allocate enough memory for reading the raw JSON string in the next step
byte[] buffer = new byte[bytesToRead];
buf.readBytes(buffer);
// Create a UTF-8 string from the received data
String rawJsonText = new String(buffer, StandardCharsets.UTF_8);
// Try to parse the packet
XenyriaServerPacket packet = XenyriaServerPacket.parsePacket(rawJsonText);
if(packet == null) {
LOGGER.warning("Unable to parse Xenyria packet with " + bytesToRead + " length.");
return;
}
// Do something with the received data
if (packet.getPacketType() == XenyriaServerPacket.EPacketType.RP) {
// If rich presence is disabled in the settings we ignore this packet
if (!XenyriaConfigManager.getConfig().enableDiscordRichPresence) {
return;
}
DiscordRichPresenceIntegration.setLastReceivedRichPresence(packet.getData());
} else if (packet.getPacketType() == XenyriaServerPacket.EPacketType.HANDSHAKE_INIT) {
// Orion sends one mod handshake packet on login
// This packet contains the current server ID
String instanceId = packet.getData().getString("server_id");
PlayingSessionInformation.setServerInstanceId(instanceId);
PlayingSessionInformation.setOnNetwork(true);
PlayingSessionInformation.setCurrentServerType(
| EXenyriaServerType.determineServerType(instanceId)
); |
// We respond back so that the server knows we're using XEEM
XenyriaServerPacket responsePacket = new XenyriaServerPacket(
XenyriaServerPacket.EPacketType.HANDSHAKE_RESPONSE,
new JSONObject()
);
responsePacket.sendToServer();
LOGGER.info("Successfully completed handshake with Orion");
} else if (packet.getPacketType() == XenyriaServerPacket.EPacketType.DEBUG) {
LOGGER.info("Current network state: " + PlayingSessionInformation.isOnNetwork());
LOGGER.info("Current server type: " + PlayingSessionInformation.getCurrentServerType());
LOGGER.info("Current server id: " + PlayingSessionInformation.getServerInstanceId());
}
}
);
}
}
| src/main/java/net/xenyria/eem/networking/PacketListener.java | XenyriaNET-xeem-b635ea0 | [
{
"filename": "src/main/java/net/xenyria/eem/paintsquad/PaintSquadInputManager.java",
"retrieved_chunk": " // If a change has been detected we send a mod packet to the server\n if(hasChanged) {\n JSONObject payload = new JSONObject();\n payload.put(\"shooting\", isShooting);\n XenyriaServerPacket packet = new XenyriaServerPacket(\n XenyriaServerPacket.EPacketType.PS_SHOOTING_STATE, payload);\n packet.sendToServer();\n }\n }\n }, 10, 10, TimeUnit.MILLISECONDS);",
"score": 0.8065552115440369
},
{
"filename": "src/main/java/net/xenyria/eem/PlayingSessionInformation.java",
"retrieved_chunk": "package net.xenyria.eem;\npublic class PlayingSessionInformation {\n private static boolean onNetwork;\n public static boolean isOnNetwork() { return onNetwork; }\n public static void setOnNetwork(boolean onNetwork) { PlayingSessionInformation.onNetwork = onNetwork; }\n private static EXenyriaServerType currentServerType = EXenyriaServerType.UNKNOWN;\n public static EXenyriaServerType getCurrentServerType() { return currentServerType; }\n public static void setCurrentServerType(EXenyriaServerType currentServerType) {\n PlayingSessionInformation.currentServerType = currentServerType;\n }",
"score": 0.768025279045105
},
{
"filename": "src/main/java/net/xenyria/eem/mixin/DisconnectMixin.java",
"retrieved_chunk": " @Inject(at = @At(\"HEAD\"), method = \"disconnect(Lnet/minecraft/client/gui/screen/Screen;)V\")\n public void handleDisconnect(CallbackInfo info) {\n PlayingSessionInformation.setOnNetwork(false);\n PlayingSessionInformation.setCurrentServerType(EXenyriaServerType.UNKNOWN);\n PlayingSessionInformation.setServerInstanceId(\"\");\n }\n}",
"score": 0.7650622129440308
},
{
"filename": "src/main/java/net/xenyria/eem/discord/DiscordRichPresenceIntegration.java",
"retrieved_chunk": " if (deltaSinceLastPacket < TIMEOUT) {\n isDataPresent = true;\n richPresenceData = new JSONObject(lastReceivedRichPresence.toMap());\n }\n }\n }\n if (isDataPresent) {\n // Replace the received rich presence data with generic content\n // if the User doesn't want to share their activity on the server.\n if (!XenyriaConfigManager.getConfig().shareServerActivity) {",
"score": 0.7532409429550171
},
{
"filename": "src/main/java/net/xenyria/eem/config/screen/XenyriaConfigManager.java",
"retrieved_chunk": " throw new IllegalStateException(\"Config folder has to be a folder, not a file.\");\n }\n // Notify the server about config changes (e.g. resetting internal variables for PS's shooting detection)\n var packet = new XenyriaServerPacket(XenyriaServerPacket.EPacketType.SETTINGS_CHANGED, new JSONObject());\n packet.sendToServer();\n }\n public static ConfigBuilder getConfigurationBuilder() {\n ConfigBuilder configBuilder = ConfigBuilder.create()\n .setTitle(Text.translatable(\"config.xenyria.settings.title\"))\n .setEditable(true)",
"score": 0.752549946308136
}
] | java | EXenyriaServerType.determineServerType(instanceId)
); |
package net.xenyria.eem.networking;
import net.xenyria.eem.discord.DiscordRichPresenceIntegration;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
import net.minecraft.util.Identifier;
import net.xenyria.eem.EXenyriaServerType;
import net.xenyria.eem.PlayingSessionInformation;
import net.xenyria.eem.config.screen.XenyriaConfigManager;
import org.json.JSONObject;
import java.nio.charset.StandardCharsets;
import java.util.logging.Logger;
public class PacketListener {
public static Identifier ID;
public static Logger LOGGER = Logger.getLogger("Xenyria/PacketListener");
public static void initialize() {
ID = Identifier.of("xenyria", "mod_communication");
if(ID == null) throw new IllegalStateException("Identifier could not be initialized.");
LOGGER.info("Registering packet receiver for plugin messages...");
ClientPlayNetworking.registerGlobalReceiver(
ID, (client, handler, buf, responseSender) -> {
/*
* Packets sent by the server consist of a 4-byte Integer
* and a byte array that represents UTF-8 string data.
*/
int bytesToRead = buf.readInt();
// Allocate enough memory for reading the raw JSON string in the next step
byte[] buffer = new byte[bytesToRead];
buf.readBytes(buffer);
// Create a UTF-8 string from the received data
String rawJsonText = new String(buffer, StandardCharsets.UTF_8);
// Try to parse the packet
XenyriaServerPacket packet = XenyriaServerPacket.parsePacket(rawJsonText);
if(packet == null) {
LOGGER.warning("Unable to parse Xenyria packet with " + bytesToRead + " length.");
return;
}
// Do something with the received data
if (packet.getPacketType() == XenyriaServerPacket.EPacketType.RP) {
// If rich presence is disabled in the settings we ignore this packet
if (!XenyriaConfigManager.getConfig().enableDiscordRichPresence) {
return;
}
DiscordRichPresenceIntegration.setLastReceivedRichPresence(packet.getData());
} else if (packet.getPacketType() == XenyriaServerPacket.EPacketType.HANDSHAKE_INIT) {
// Orion sends one mod handshake packet on login
// This packet contains the current server ID
String instanceId = packet.getData().getString("server_id");
PlayingSessionInformation.setServerInstanceId(instanceId);
PlayingSessionInformation.setOnNetwork(true);
PlayingSessionInformation.setCurrentServerType(
EXenyriaServerType.determineServerType(instanceId)
);
// We respond back so that the server knows we're using XEEM
XenyriaServerPacket responsePacket = new XenyriaServerPacket(
XenyriaServerPacket.EPacketType.HANDSHAKE_RESPONSE,
new JSONObject()
);
| responsePacket.sendToServer(); |
LOGGER.info("Successfully completed handshake with Orion");
} else if (packet.getPacketType() == XenyriaServerPacket.EPacketType.DEBUG) {
LOGGER.info("Current network state: " + PlayingSessionInformation.isOnNetwork());
LOGGER.info("Current server type: " + PlayingSessionInformation.getCurrentServerType());
LOGGER.info("Current server id: " + PlayingSessionInformation.getServerInstanceId());
}
}
);
}
}
| src/main/java/net/xenyria/eem/networking/PacketListener.java | XenyriaNET-xeem-b635ea0 | [
{
"filename": "src/main/java/net/xenyria/eem/paintsquad/PaintSquadInputManager.java",
"retrieved_chunk": " // If a change has been detected we send a mod packet to the server\n if(hasChanged) {\n JSONObject payload = new JSONObject();\n payload.put(\"shooting\", isShooting);\n XenyriaServerPacket packet = new XenyriaServerPacket(\n XenyriaServerPacket.EPacketType.PS_SHOOTING_STATE, payload);\n packet.sendToServer();\n }\n }\n }, 10, 10, TimeUnit.MILLISECONDS);",
"score": 0.875137984752655
},
{
"filename": "src/main/java/net/xenyria/eem/config/screen/XenyriaConfigManager.java",
"retrieved_chunk": " throw new IllegalStateException(\"Config folder has to be a folder, not a file.\");\n }\n // Notify the server about config changes (e.g. resetting internal variables for PS's shooting detection)\n var packet = new XenyriaServerPacket(XenyriaServerPacket.EPacketType.SETTINGS_CHANGED, new JSONObject());\n packet.sendToServer();\n }\n public static ConfigBuilder getConfigurationBuilder() {\n ConfigBuilder configBuilder = ConfigBuilder.create()\n .setTitle(Text.translatable(\"config.xenyria.settings.title\"))\n .setEditable(true)",
"score": 0.809008002281189
},
{
"filename": "src/main/java/net/xenyria/eem/PlayingSessionInformation.java",
"retrieved_chunk": "package net.xenyria.eem;\npublic class PlayingSessionInformation {\n private static boolean onNetwork;\n public static boolean isOnNetwork() { return onNetwork; }\n public static void setOnNetwork(boolean onNetwork) { PlayingSessionInformation.onNetwork = onNetwork; }\n private static EXenyriaServerType currentServerType = EXenyriaServerType.UNKNOWN;\n public static EXenyriaServerType getCurrentServerType() { return currentServerType; }\n public static void setCurrentServerType(EXenyriaServerType currentServerType) {\n PlayingSessionInformation.currentServerType = currentServerType;\n }",
"score": 0.7886905074119568
},
{
"filename": "src/main/java/net/xenyria/eem/networking/XenyriaServerPacket.java",
"retrieved_chunk": "import java.nio.charset.StandardCharsets;\nimport static net.xenyria.eem.networking.PacketListener.LOGGER;\npublic class XenyriaServerPacket {\n /** Packets are separated into different types/categories **/\n public enum EPacketType {\n RP, // Rich-Presence (Discord Integration)\n PS_SHOOTING_STATE, // PaintSquad\n HANDSHAKE_INIT, // Server Switch / Server Info Change (Sent by the server)\n HANDSHAKE_RESPONSE, // Sent by the client, informs the server about the mod being active\n DEBUG, // Debug Operation (printing client-side variables into the chat)",
"score": 0.734960675239563
},
{
"filename": "src/main/java/net/xenyria/eem/config/screen/XenyriaConfig.java",
"retrieved_chunk": "package net.xenyria.eem.config.screen;\nimport org.json.JSONObject;\npublic class XenyriaConfig {\n public boolean enableDiscordRichPresence = true;\n public boolean shareServerActivity = true;\n public boolean improvedShootingDetectionForPaintSquad = true;\n public boolean swimFormCameraForPaintSquad = true;\n public static XenyriaConfig load(JSONObject object) {\n XenyriaConfig config = new XenyriaConfig();\n if(object.has(\"discord\")) {",
"score": 0.7329733371734619
}
] | java | responsePacket.sendToServer(); |
package net.xenyria.eem.networking;
import net.xenyria.eem.discord.DiscordRichPresenceIntegration;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
import net.minecraft.util.Identifier;
import net.xenyria.eem.EXenyriaServerType;
import net.xenyria.eem.PlayingSessionInformation;
import net.xenyria.eem.config.screen.XenyriaConfigManager;
import org.json.JSONObject;
import java.nio.charset.StandardCharsets;
import java.util.logging.Logger;
public class PacketListener {
public static Identifier ID;
public static Logger LOGGER = Logger.getLogger("Xenyria/PacketListener");
public static void initialize() {
ID = Identifier.of("xenyria", "mod_communication");
if(ID == null) throw new IllegalStateException("Identifier could not be initialized.");
LOGGER.info("Registering packet receiver for plugin messages...");
ClientPlayNetworking.registerGlobalReceiver(
ID, (client, handler, buf, responseSender) -> {
/*
* Packets sent by the server consist of a 4-byte Integer
* and a byte array that represents UTF-8 string data.
*/
int bytesToRead = buf.readInt();
// Allocate enough memory for reading the raw JSON string in the next step
byte[] buffer = new byte[bytesToRead];
buf.readBytes(buffer);
// Create a UTF-8 string from the received data
String rawJsonText = new String(buffer, StandardCharsets.UTF_8);
// Try to parse the packet
| XenyriaServerPacket packet = XenyriaServerPacket.parsePacket(rawJsonText); |
if(packet == null) {
LOGGER.warning("Unable to parse Xenyria packet with " + bytesToRead + " length.");
return;
}
// Do something with the received data
if (packet.getPacketType() == XenyriaServerPacket.EPacketType.RP) {
// If rich presence is disabled in the settings we ignore this packet
if (!XenyriaConfigManager.getConfig().enableDiscordRichPresence) {
return;
}
DiscordRichPresenceIntegration.setLastReceivedRichPresence(packet.getData());
} else if (packet.getPacketType() == XenyriaServerPacket.EPacketType.HANDSHAKE_INIT) {
// Orion sends one mod handshake packet on login
// This packet contains the current server ID
String instanceId = packet.getData().getString("server_id");
PlayingSessionInformation.setServerInstanceId(instanceId);
PlayingSessionInformation.setOnNetwork(true);
PlayingSessionInformation.setCurrentServerType(
EXenyriaServerType.determineServerType(instanceId)
);
// We respond back so that the server knows we're using XEEM
XenyriaServerPacket responsePacket = new XenyriaServerPacket(
XenyriaServerPacket.EPacketType.HANDSHAKE_RESPONSE,
new JSONObject()
);
responsePacket.sendToServer();
LOGGER.info("Successfully completed handshake with Orion");
} else if (packet.getPacketType() == XenyriaServerPacket.EPacketType.DEBUG) {
LOGGER.info("Current network state: " + PlayingSessionInformation.isOnNetwork());
LOGGER.info("Current server type: " + PlayingSessionInformation.getCurrentServerType());
LOGGER.info("Current server id: " + PlayingSessionInformation.getServerInstanceId());
}
}
);
}
}
| src/main/java/net/xenyria/eem/networking/PacketListener.java | XenyriaNET-xeem-b635ea0 | [
{
"filename": "src/main/java/net/xenyria/eem/networking/XenyriaServerPacket.java",
"retrieved_chunk": " /**\n * Parses raw JSON into packet objects\n */\n public static XenyriaServerPacket parsePacket(String rawJson) {\n JSONObject jsonData;\n try {\n jsonData = new JSONObject(rawJson);\n } catch (JSONException exception) {\n LOGGER.severe(\"Unable to parse packet from raw JSON: \" + rawJson);\n return null;",
"score": 0.8480579853057861
},
{
"filename": "src/main/java/net/xenyria/eem/networking/XenyriaServerPacket.java",
"retrieved_chunk": " // 4 bytes are used to store the length of the JSON object that follows\n dataOutputStream.writeInt(jsonContent.length);\n dataOutputStream.write(jsonContent, 0, jsonContent.length);\n } catch (IOException e) {\n LOGGER.severe(\"Couldn't convert packet into bytes: \" + e.getMessage());\n }\n // Send data to the server\n CustomPayloadC2SPacket packet = new CustomPayloadC2SPacket(\n PacketListener.ID, new PacketByteBuf(\n Unpooled.wrappedBuffer(rawPacketBytes.toByteArray()))",
"score": 0.8355836272239685
},
{
"filename": "src/main/java/net/xenyria/eem/networking/XenyriaServerPacket.java",
"retrieved_chunk": " SETTINGS_CHANGED // Sent by the client when settings are changed\n }\n private final EPacketType packetType;\n public EPacketType getPacketType() { return packetType; }\n private final JSONObject data;\n public JSONObject getData() { return data; }\n public XenyriaServerPacket(EPacketType parsedPacketType, JSONObject data) {\n this.packetType = parsedPacketType;\n this.data = data;\n }",
"score": 0.8012446761131287
},
{
"filename": "src/main/java/net/xenyria/eem/networking/XenyriaServerPacket.java",
"retrieved_chunk": " return null;\n }\n if(!jsonData.has(\"data\")) {\n LOGGER.severe(\"Malformed packet, missing data field.\");\n return null;\n }\n return new XenyriaServerPacket(parsedPacketType, jsonData.getJSONObject(\"data\"));\n }\n /** Attempt to send this packet to the currently connected server as a plugin message **/\n public void sendToServer() {",
"score": 0.7946197390556335
},
{
"filename": "src/main/java/net/xenyria/eem/discord/DiscordRichPresenceIntegration.java",
"retrieved_chunk": " ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();\n LOGGER.info(\"Starting API task...\");\n executor.scheduleAtFixedRate(() -> {\n try {\n JSONObject richPresenceData = null;\n boolean isDataPresent = false;\n // Lock so this#setLastReceivedRichPresence is blocked while we copy data\n synchronized (lock) {\n if (lastReceivedRichPresence != null) {\n long deltaSinceLastPacket = System.currentTimeMillis() - lastReceivedPacket;",
"score": 0.7800967693328857
}
] | java | XenyriaServerPacket packet = XenyriaServerPacket.parsePacket(rawJsonText); |
package net.xenyria.eem.networking;
import net.xenyria.eem.discord.DiscordRichPresenceIntegration;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
import net.minecraft.util.Identifier;
import net.xenyria.eem.EXenyriaServerType;
import net.xenyria.eem.PlayingSessionInformation;
import net.xenyria.eem.config.screen.XenyriaConfigManager;
import org.json.JSONObject;
import java.nio.charset.StandardCharsets;
import java.util.logging.Logger;
public class PacketListener {
public static Identifier ID;
public static Logger LOGGER = Logger.getLogger("Xenyria/PacketListener");
public static void initialize() {
ID = Identifier.of("xenyria", "mod_communication");
if(ID == null) throw new IllegalStateException("Identifier could not be initialized.");
LOGGER.info("Registering packet receiver for plugin messages...");
ClientPlayNetworking.registerGlobalReceiver(
ID, (client, handler, buf, responseSender) -> {
/*
* Packets sent by the server consist of a 4-byte Integer
* and a byte array that represents UTF-8 string data.
*/
int bytesToRead = buf.readInt();
// Allocate enough memory for reading the raw JSON string in the next step
byte[] buffer = new byte[bytesToRead];
buf.readBytes(buffer);
// Create a UTF-8 string from the received data
String rawJsonText = new String(buffer, StandardCharsets.UTF_8);
// Try to parse the packet
XenyriaServerPacket packet = XenyriaServerPacket.parsePacket(rawJsonText);
if(packet == null) {
LOGGER.warning("Unable to parse Xenyria packet with " + bytesToRead + " length.");
return;
}
// Do something with the received data
if (packet.getPacketType() == XenyriaServerPacket.EPacketType.RP) {
// If rich presence is disabled in the settings we ignore this packet
if (!XenyriaConfigManager.getConfig().enableDiscordRichPresence) {
return;
}
DiscordRichPresenceIntegration.setLastReceivedRichPresence(packet.getData());
} else if (packet.getPacketType() == XenyriaServerPacket.EPacketType.HANDSHAKE_INIT) {
// Orion sends one mod handshake packet on login
// This packet contains the current server ID
String instanceId = packet.getData().getString("server_id");
PlayingSessionInformation.setServerInstanceId(instanceId);
PlayingSessionInformation.setOnNetwork(true);
PlayingSessionInformation.setCurrentServerType(
EXenyriaServerType.determineServerType(instanceId)
);
// We respond back so that the server knows we're using XEEM
XenyriaServerPacket responsePacket = new XenyriaServerPacket(
XenyriaServerPacket.EPacketType.HANDSHAKE_RESPONSE,
new JSONObject()
);
responsePacket.sendToServer();
LOGGER.info("Successfully completed handshake with Orion");
} else if (packet.getPacketType() == XenyriaServerPacket.EPacketType.DEBUG) {
LOGGER.info | ("Current network state: " + PlayingSessionInformation.isOnNetwork()); |
LOGGER.info("Current server type: " + PlayingSessionInformation.getCurrentServerType());
LOGGER.info("Current server id: " + PlayingSessionInformation.getServerInstanceId());
}
}
);
}
}
| src/main/java/net/xenyria/eem/networking/PacketListener.java | XenyriaNET-xeem-b635ea0 | [
{
"filename": "src/main/java/net/xenyria/eem/paintsquad/PaintSquadInputManager.java",
"retrieved_chunk": " // If a change has been detected we send a mod packet to the server\n if(hasChanged) {\n JSONObject payload = new JSONObject();\n payload.put(\"shooting\", isShooting);\n XenyriaServerPacket packet = new XenyriaServerPacket(\n XenyriaServerPacket.EPacketType.PS_SHOOTING_STATE, payload);\n packet.sendToServer();\n }\n }\n }, 10, 10, TimeUnit.MILLISECONDS);",
"score": 0.8794246912002563
},
{
"filename": "src/main/java/net/xenyria/eem/config/screen/XenyriaConfigManager.java",
"retrieved_chunk": " throw new IllegalStateException(\"Config folder has to be a folder, not a file.\");\n }\n // Notify the server about config changes (e.g. resetting internal variables for PS's shooting detection)\n var packet = new XenyriaServerPacket(XenyriaServerPacket.EPacketType.SETTINGS_CHANGED, new JSONObject());\n packet.sendToServer();\n }\n public static ConfigBuilder getConfigurationBuilder() {\n ConfigBuilder configBuilder = ConfigBuilder.create()\n .setTitle(Text.translatable(\"config.xenyria.settings.title\"))\n .setEditable(true)",
"score": 0.8229970932006836
},
{
"filename": "src/main/java/net/xenyria/eem/mixin/InitMixin.java",
"retrieved_chunk": "public class InitMixin {\n @Inject(at = @At(\"HEAD\"), method = \"init()V\")\n private void init(CallbackInfo info) {\n // Register the packet listener here for client-server communication\n PacketListener.initialize();\n // Load the configuration file\n try {\n XenyriaConfigManager.loadConfig();\n } catch (Exception exception) {\n XenyriaConfigManager.LOGGER.error(\"Failed to load XEEM's configuration file on start-up: \"",
"score": 0.77364581823349
},
{
"filename": "src/main/java/net/xenyria/eem/networking/XenyriaServerPacket.java",
"retrieved_chunk": "import java.nio.charset.StandardCharsets;\nimport static net.xenyria.eem.networking.PacketListener.LOGGER;\npublic class XenyriaServerPacket {\n /** Packets are separated into different types/categories **/\n public enum EPacketType {\n RP, // Rich-Presence (Discord Integration)\n PS_SHOOTING_STATE, // PaintSquad\n HANDSHAKE_INIT, // Server Switch / Server Info Change (Sent by the server)\n HANDSHAKE_RESPONSE, // Sent by the client, informs the server about the mod being active\n DEBUG, // Debug Operation (printing client-side variables into the chat)",
"score": 0.7675303220748901
},
{
"filename": "src/main/java/net/xenyria/eem/networking/XenyriaServerPacket.java",
"retrieved_chunk": " return null;\n }\n if(!jsonData.has(\"data\")) {\n LOGGER.severe(\"Malformed packet, missing data field.\");\n return null;\n }\n return new XenyriaServerPacket(parsedPacketType, jsonData.getJSONObject(\"data\"));\n }\n /** Attempt to send this packet to the currently connected server as a plugin message **/\n public void sendToServer() {",
"score": 0.7667615413665771
}
] | java | ("Current network state: " + PlayingSessionInformation.isOnNetwork()); |
package net.xenyria.eem.networking;
import net.xenyria.eem.discord.DiscordRichPresenceIntegration;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
import net.minecraft.util.Identifier;
import net.xenyria.eem.EXenyriaServerType;
import net.xenyria.eem.PlayingSessionInformation;
import net.xenyria.eem.config.screen.XenyriaConfigManager;
import org.json.JSONObject;
import java.nio.charset.StandardCharsets;
import java.util.logging.Logger;
public class PacketListener {
public static Identifier ID;
public static Logger LOGGER = Logger.getLogger("Xenyria/PacketListener");
public static void initialize() {
ID = Identifier.of("xenyria", "mod_communication");
if(ID == null) throw new IllegalStateException("Identifier could not be initialized.");
LOGGER.info("Registering packet receiver for plugin messages...");
ClientPlayNetworking.registerGlobalReceiver(
ID, (client, handler, buf, responseSender) -> {
/*
* Packets sent by the server consist of a 4-byte Integer
* and a byte array that represents UTF-8 string data.
*/
int bytesToRead = buf.readInt();
// Allocate enough memory for reading the raw JSON string in the next step
byte[] buffer = new byte[bytesToRead];
buf.readBytes(buffer);
// Create a UTF-8 string from the received data
String rawJsonText = new String(buffer, StandardCharsets.UTF_8);
// Try to parse the packet
XenyriaServerPacket packet = XenyriaServerPacket.parsePacket(rawJsonText);
if(packet == null) {
LOGGER.warning("Unable to parse Xenyria packet with " + bytesToRead + " length.");
return;
}
// Do something with the received data
if (packet.getPacketType() == XenyriaServerPacket.EPacketType.RP) {
// If rich presence is disabled in the settings we ignore this packet
if (! | XenyriaConfigManager.getConfig().enableDiscordRichPresence) { |
return;
}
DiscordRichPresenceIntegration.setLastReceivedRichPresence(packet.getData());
} else if (packet.getPacketType() == XenyriaServerPacket.EPacketType.HANDSHAKE_INIT) {
// Orion sends one mod handshake packet on login
// This packet contains the current server ID
String instanceId = packet.getData().getString("server_id");
PlayingSessionInformation.setServerInstanceId(instanceId);
PlayingSessionInformation.setOnNetwork(true);
PlayingSessionInformation.setCurrentServerType(
EXenyriaServerType.determineServerType(instanceId)
);
// We respond back so that the server knows we're using XEEM
XenyriaServerPacket responsePacket = new XenyriaServerPacket(
XenyriaServerPacket.EPacketType.HANDSHAKE_RESPONSE,
new JSONObject()
);
responsePacket.sendToServer();
LOGGER.info("Successfully completed handshake with Orion");
} else if (packet.getPacketType() == XenyriaServerPacket.EPacketType.DEBUG) {
LOGGER.info("Current network state: " + PlayingSessionInformation.isOnNetwork());
LOGGER.info("Current server type: " + PlayingSessionInformation.getCurrentServerType());
LOGGER.info("Current server id: " + PlayingSessionInformation.getServerInstanceId());
}
}
);
}
}
| src/main/java/net/xenyria/eem/networking/PacketListener.java | XenyriaNET-xeem-b635ea0 | [
{
"filename": "src/main/java/net/xenyria/eem/discord/DiscordRichPresenceIntegration.java",
"retrieved_chunk": " if (deltaSinceLastPacket < TIMEOUT) {\n isDataPresent = true;\n richPresenceData = new JSONObject(lastReceivedRichPresence.toMap());\n }\n }\n }\n if (isDataPresent) {\n // Replace the received rich presence data with generic content\n // if the User doesn't want to share their activity on the server.\n if (!XenyriaConfigManager.getConfig().shareServerActivity) {",
"score": 0.8398652076721191
},
{
"filename": "src/main/java/net/xenyria/eem/networking/XenyriaServerPacket.java",
"retrieved_chunk": " return null;\n }\n if(!jsonData.has(\"data\")) {\n LOGGER.severe(\"Malformed packet, missing data field.\");\n return null;\n }\n return new XenyriaServerPacket(parsedPacketType, jsonData.getJSONObject(\"data\"));\n }\n /** Attempt to send this packet to the currently connected server as a plugin message **/\n public void sendToServer() {",
"score": 0.8312565088272095
},
{
"filename": "src/main/java/net/xenyria/eem/paintsquad/PaintSquadInputManager.java",
"retrieved_chunk": " // If a change has been detected we send a mod packet to the server\n if(hasChanged) {\n JSONObject payload = new JSONObject();\n payload.put(\"shooting\", isShooting);\n XenyriaServerPacket packet = new XenyriaServerPacket(\n XenyriaServerPacket.EPacketType.PS_SHOOTING_STATE, payload);\n packet.sendToServer();\n }\n }\n }, 10, 10, TimeUnit.MILLISECONDS);",
"score": 0.8299645185470581
},
{
"filename": "src/main/java/net/xenyria/eem/networking/XenyriaServerPacket.java",
"retrieved_chunk": " /**\n * Parses raw JSON into packet objects\n */\n public static XenyriaServerPacket parsePacket(String rawJson) {\n JSONObject jsonData;\n try {\n jsonData = new JSONObject(rawJson);\n } catch (JSONException exception) {\n LOGGER.severe(\"Unable to parse packet from raw JSON: \" + rawJson);\n return null;",
"score": 0.8257148265838623
},
{
"filename": "src/main/java/net/xenyria/eem/config/screen/XenyriaConfigManager.java",
"retrieved_chunk": " throw new IllegalStateException(\"Config folder has to be a folder, not a file.\");\n }\n // Notify the server about config changes (e.g. resetting internal variables for PS's shooting detection)\n var packet = new XenyriaServerPacket(XenyriaServerPacket.EPacketType.SETTINGS_CHANGED, new JSONObject());\n packet.sendToServer();\n }\n public static ConfigBuilder getConfigurationBuilder() {\n ConfigBuilder configBuilder = ConfigBuilder.create()\n .setTitle(Text.translatable(\"config.xenyria.settings.title\"))\n .setEditable(true)",
"score": 0.8173877000808716
}
] | java | XenyriaConfigManager.getConfig().enableDiscordRichPresence) { |
package net.xenyria.eem.networking;
import net.xenyria.eem.discord.DiscordRichPresenceIntegration;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
import net.minecraft.util.Identifier;
import net.xenyria.eem.EXenyriaServerType;
import net.xenyria.eem.PlayingSessionInformation;
import net.xenyria.eem.config.screen.XenyriaConfigManager;
import org.json.JSONObject;
import java.nio.charset.StandardCharsets;
import java.util.logging.Logger;
public class PacketListener {
public static Identifier ID;
public static Logger LOGGER = Logger.getLogger("Xenyria/PacketListener");
public static void initialize() {
ID = Identifier.of("xenyria", "mod_communication");
if(ID == null) throw new IllegalStateException("Identifier could not be initialized.");
LOGGER.info("Registering packet receiver for plugin messages...");
ClientPlayNetworking.registerGlobalReceiver(
ID, (client, handler, buf, responseSender) -> {
/*
* Packets sent by the server consist of a 4-byte Integer
* and a byte array that represents UTF-8 string data.
*/
int bytesToRead = buf.readInt();
// Allocate enough memory for reading the raw JSON string in the next step
byte[] buffer = new byte[bytesToRead];
buf.readBytes(buffer);
// Create a UTF-8 string from the received data
String rawJsonText = new String(buffer, StandardCharsets.UTF_8);
// Try to parse the packet
XenyriaServerPacket packet = XenyriaServerPacket.parsePacket(rawJsonText);
if(packet == null) {
LOGGER.warning("Unable to parse Xenyria packet with " + bytesToRead + " length.");
return;
}
// Do something with the received data
if (packet.getPacketType() == XenyriaServerPacket.EPacketType.RP) {
// If rich presence is disabled in the settings we ignore this packet
if (!XenyriaConfigManager.getConfig().enableDiscordRichPresence) {
return;
}
DiscordRichPresenceIntegration.setLastReceivedRichPresence(packet.getData());
} else if (packet.getPacketType() == XenyriaServerPacket.EPacketType.HANDSHAKE_INIT) {
// Orion sends one mod handshake packet on login
// This packet contains the current server ID
String instanceId = packet.getData().getString("server_id");
| PlayingSessionInformation.setServerInstanceId(instanceId); |
PlayingSessionInformation.setOnNetwork(true);
PlayingSessionInformation.setCurrentServerType(
EXenyriaServerType.determineServerType(instanceId)
);
// We respond back so that the server knows we're using XEEM
XenyriaServerPacket responsePacket = new XenyriaServerPacket(
XenyriaServerPacket.EPacketType.HANDSHAKE_RESPONSE,
new JSONObject()
);
responsePacket.sendToServer();
LOGGER.info("Successfully completed handshake with Orion");
} else if (packet.getPacketType() == XenyriaServerPacket.EPacketType.DEBUG) {
LOGGER.info("Current network state: " + PlayingSessionInformation.isOnNetwork());
LOGGER.info("Current server type: " + PlayingSessionInformation.getCurrentServerType());
LOGGER.info("Current server id: " + PlayingSessionInformation.getServerInstanceId());
}
}
);
}
}
| src/main/java/net/xenyria/eem/networking/PacketListener.java | XenyriaNET-xeem-b635ea0 | [
{
"filename": "src/main/java/net/xenyria/eem/discord/DiscordRichPresenceIntegration.java",
"retrieved_chunk": " if (deltaSinceLastPacket < TIMEOUT) {\n isDataPresent = true;\n richPresenceData = new JSONObject(lastReceivedRichPresence.toMap());\n }\n }\n }\n if (isDataPresent) {\n // Replace the received rich presence data with generic content\n // if the User doesn't want to share their activity on the server.\n if (!XenyriaConfigManager.getConfig().shareServerActivity) {",
"score": 0.8508792519569397
},
{
"filename": "src/main/java/net/xenyria/eem/paintsquad/PaintSquadInputManager.java",
"retrieved_chunk": " // If a change has been detected we send a mod packet to the server\n if(hasChanged) {\n JSONObject payload = new JSONObject();\n payload.put(\"shooting\", isShooting);\n XenyriaServerPacket packet = new XenyriaServerPacket(\n XenyriaServerPacket.EPacketType.PS_SHOOTING_STATE, payload);\n packet.sendToServer();\n }\n }\n }, 10, 10, TimeUnit.MILLISECONDS);",
"score": 0.8139965534210205
},
{
"filename": "src/main/java/net/xenyria/eem/discord/DiscordRichPresenceIntegration.java",
"retrieved_chunk": " richPresenceData = loadDefaultRichPresenceData();\n }\n long applicationId = richPresenceData.getLong(\"applicationId\");\n if (applicationId != lastApplicationID) {\n // Application ID has changed - Therefore we restart our activity access with a different ID\n lastApplicationID = applicationId;\n LOGGER.info(\"Switching application ID to \" + applicationId + \"...\");\n discordActivityAccess.stop();\n discordActivityAccess.start(applicationId);\n return;",
"score": 0.7974185943603516
},
{
"filename": "src/main/java/net/xenyria/eem/config/screen/XenyriaConfigManager.java",
"retrieved_chunk": " throw new IllegalStateException(\"Config folder has to be a folder, not a file.\");\n }\n // Notify the server about config changes (e.g. resetting internal variables for PS's shooting detection)\n var packet = new XenyriaServerPacket(XenyriaServerPacket.EPacketType.SETTINGS_CHANGED, new JSONObject());\n packet.sendToServer();\n }\n public static ConfigBuilder getConfigurationBuilder() {\n ConfigBuilder configBuilder = ConfigBuilder.create()\n .setTitle(Text.translatable(\"config.xenyria.settings.title\"))\n .setEditable(true)",
"score": 0.7946093678474426
},
{
"filename": "src/main/java/net/xenyria/eem/mixin/InitMixin.java",
"retrieved_chunk": "public class InitMixin {\n @Inject(at = @At(\"HEAD\"), method = \"init()V\")\n private void init(CallbackInfo info) {\n // Register the packet listener here for client-server communication\n PacketListener.initialize();\n // Load the configuration file\n try {\n XenyriaConfigManager.loadConfig();\n } catch (Exception exception) {\n XenyriaConfigManager.LOGGER.error(\"Failed to load XEEM's configuration file on start-up: \"",
"score": 0.7727054357528687
}
] | java | PlayingSessionInformation.setServerInstanceId(instanceId); |
package net.xenyria.eem.networking;
import net.xenyria.eem.discord.DiscordRichPresenceIntegration;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
import net.minecraft.util.Identifier;
import net.xenyria.eem.EXenyriaServerType;
import net.xenyria.eem.PlayingSessionInformation;
import net.xenyria.eem.config.screen.XenyriaConfigManager;
import org.json.JSONObject;
import java.nio.charset.StandardCharsets;
import java.util.logging.Logger;
public class PacketListener {
public static Identifier ID;
public static Logger LOGGER = Logger.getLogger("Xenyria/PacketListener");
public static void initialize() {
ID = Identifier.of("xenyria", "mod_communication");
if(ID == null) throw new IllegalStateException("Identifier could not be initialized.");
LOGGER.info("Registering packet receiver for plugin messages...");
ClientPlayNetworking.registerGlobalReceiver(
ID, (client, handler, buf, responseSender) -> {
/*
* Packets sent by the server consist of a 4-byte Integer
* and a byte array that represents UTF-8 string data.
*/
int bytesToRead = buf.readInt();
// Allocate enough memory for reading the raw JSON string in the next step
byte[] buffer = new byte[bytesToRead];
buf.readBytes(buffer);
// Create a UTF-8 string from the received data
String rawJsonText = new String(buffer, StandardCharsets.UTF_8);
// Try to parse the packet
XenyriaServerPacket packet = XenyriaServerPacket.parsePacket(rawJsonText);
if(packet == null) {
LOGGER.warning("Unable to parse Xenyria packet with " + bytesToRead + " length.");
return;
}
// Do something with the received data
if | (packet.getPacketType() == XenyriaServerPacket.EPacketType.RP) { |
// If rich presence is disabled in the settings we ignore this packet
if (!XenyriaConfigManager.getConfig().enableDiscordRichPresence) {
return;
}
DiscordRichPresenceIntegration.setLastReceivedRichPresence(packet.getData());
} else if (packet.getPacketType() == XenyriaServerPacket.EPacketType.HANDSHAKE_INIT) {
// Orion sends one mod handshake packet on login
// This packet contains the current server ID
String instanceId = packet.getData().getString("server_id");
PlayingSessionInformation.setServerInstanceId(instanceId);
PlayingSessionInformation.setOnNetwork(true);
PlayingSessionInformation.setCurrentServerType(
EXenyriaServerType.determineServerType(instanceId)
);
// We respond back so that the server knows we're using XEEM
XenyriaServerPacket responsePacket = new XenyriaServerPacket(
XenyriaServerPacket.EPacketType.HANDSHAKE_RESPONSE,
new JSONObject()
);
responsePacket.sendToServer();
LOGGER.info("Successfully completed handshake with Orion");
} else if (packet.getPacketType() == XenyriaServerPacket.EPacketType.DEBUG) {
LOGGER.info("Current network state: " + PlayingSessionInformation.isOnNetwork());
LOGGER.info("Current server type: " + PlayingSessionInformation.getCurrentServerType());
LOGGER.info("Current server id: " + PlayingSessionInformation.getServerInstanceId());
}
}
);
}
}
| src/main/java/net/xenyria/eem/networking/PacketListener.java | XenyriaNET-xeem-b635ea0 | [
{
"filename": "src/main/java/net/xenyria/eem/paintsquad/PaintSquadInputManager.java",
"retrieved_chunk": " // If a change has been detected we send a mod packet to the server\n if(hasChanged) {\n JSONObject payload = new JSONObject();\n payload.put(\"shooting\", isShooting);\n XenyriaServerPacket packet = new XenyriaServerPacket(\n XenyriaServerPacket.EPacketType.PS_SHOOTING_STATE, payload);\n packet.sendToServer();\n }\n }\n }, 10, 10, TimeUnit.MILLISECONDS);",
"score": 0.836967945098877
},
{
"filename": "src/main/java/net/xenyria/eem/networking/XenyriaServerPacket.java",
"retrieved_chunk": " return null;\n }\n if(!jsonData.has(\"data\")) {\n LOGGER.severe(\"Malformed packet, missing data field.\");\n return null;\n }\n return new XenyriaServerPacket(parsedPacketType, jsonData.getJSONObject(\"data\"));\n }\n /** Attempt to send this packet to the currently connected server as a plugin message **/\n public void sendToServer() {",
"score": 0.8294343948364258
},
{
"filename": "src/main/java/net/xenyria/eem/networking/XenyriaServerPacket.java",
"retrieved_chunk": " /**\n * Parses raw JSON into packet objects\n */\n public static XenyriaServerPacket parsePacket(String rawJson) {\n JSONObject jsonData;\n try {\n jsonData = new JSONObject(rawJson);\n } catch (JSONException exception) {\n LOGGER.severe(\"Unable to parse packet from raw JSON: \" + rawJson);\n return null;",
"score": 0.8219753503799438
},
{
"filename": "src/main/java/net/xenyria/eem/networking/XenyriaServerPacket.java",
"retrieved_chunk": " // 4 bytes are used to store the length of the JSON object that follows\n dataOutputStream.writeInt(jsonContent.length);\n dataOutputStream.write(jsonContent, 0, jsonContent.length);\n } catch (IOException e) {\n LOGGER.severe(\"Couldn't convert packet into bytes: \" + e.getMessage());\n }\n // Send data to the server\n CustomPayloadC2SPacket packet = new CustomPayloadC2SPacket(\n PacketListener.ID, new PacketByteBuf(\n Unpooled.wrappedBuffer(rawPacketBytes.toByteArray()))",
"score": 0.8100322484970093
},
{
"filename": "src/main/java/net/xenyria/eem/config/screen/XenyriaConfigManager.java",
"retrieved_chunk": " throw new IllegalStateException(\"Config folder has to be a folder, not a file.\");\n }\n // Notify the server about config changes (e.g. resetting internal variables for PS's shooting detection)\n var packet = new XenyriaServerPacket(XenyriaServerPacket.EPacketType.SETTINGS_CHANGED, new JSONObject());\n packet.sendToServer();\n }\n public static ConfigBuilder getConfigurationBuilder() {\n ConfigBuilder configBuilder = ConfigBuilder.create()\n .setTitle(Text.translatable(\"config.xenyria.settings.title\"))\n .setEditable(true)",
"score": 0.8000282049179077
}
] | java | (packet.getPacketType() == XenyriaServerPacket.EPacketType.RP) { |
package net.xenyria.eem.networking;
import net.xenyria.eem.discord.DiscordRichPresenceIntegration;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
import net.minecraft.util.Identifier;
import net.xenyria.eem.EXenyriaServerType;
import net.xenyria.eem.PlayingSessionInformation;
import net.xenyria.eem.config.screen.XenyriaConfigManager;
import org.json.JSONObject;
import java.nio.charset.StandardCharsets;
import java.util.logging.Logger;
public class PacketListener {
public static Identifier ID;
public static Logger LOGGER = Logger.getLogger("Xenyria/PacketListener");
public static void initialize() {
ID = Identifier.of("xenyria", "mod_communication");
if(ID == null) throw new IllegalStateException("Identifier could not be initialized.");
LOGGER.info("Registering packet receiver for plugin messages...");
ClientPlayNetworking.registerGlobalReceiver(
ID, (client, handler, buf, responseSender) -> {
/*
* Packets sent by the server consist of a 4-byte Integer
* and a byte array that represents UTF-8 string data.
*/
int bytesToRead = buf.readInt();
// Allocate enough memory for reading the raw JSON string in the next step
byte[] buffer = new byte[bytesToRead];
buf.readBytes(buffer);
// Create a UTF-8 string from the received data
String rawJsonText = new String(buffer, StandardCharsets.UTF_8);
// Try to parse the packet
XenyriaServerPacket packet = XenyriaServerPacket.parsePacket(rawJsonText);
if(packet == null) {
LOGGER.warning("Unable to parse Xenyria packet with " + bytesToRead + " length.");
return;
}
// Do something with the received data
if (packet.getPacketType() == XenyriaServerPacket.EPacketType.RP) {
// If rich presence is disabled in the settings we ignore this packet
if (!XenyriaConfigManager.getConfig().enableDiscordRichPresence) {
return;
}
DiscordRichPresenceIntegration.setLastReceivedRichPresence(packet.getData());
} else if (packet.getPacketType() == XenyriaServerPacket.EPacketType.HANDSHAKE_INIT) {
// Orion sends one mod handshake packet on login
// This packet contains the current server ID
String instanceId = packet.getData().getString("server_id");
PlayingSessionInformation.setServerInstanceId(instanceId);
PlayingSessionInformation.setOnNetwork(true);
PlayingSessionInformation.setCurrentServerType(
EXenyriaServerType.determineServerType(instanceId)
);
// We respond back so that the server knows we're using XEEM
XenyriaServerPacket responsePacket = new XenyriaServerPacket(
XenyriaServerPacket.EPacketType.HANDSHAKE_RESPONSE,
new JSONObject()
);
responsePacket.sendToServer();
LOGGER.info("Successfully completed handshake with Orion");
} | else if (packet.getPacketType() == XenyriaServerPacket.EPacketType.DEBUG) { |
LOGGER.info("Current network state: " + PlayingSessionInformation.isOnNetwork());
LOGGER.info("Current server type: " + PlayingSessionInformation.getCurrentServerType());
LOGGER.info("Current server id: " + PlayingSessionInformation.getServerInstanceId());
}
}
);
}
}
| src/main/java/net/xenyria/eem/networking/PacketListener.java | XenyriaNET-xeem-b635ea0 | [
{
"filename": "src/main/java/net/xenyria/eem/paintsquad/PaintSquadInputManager.java",
"retrieved_chunk": " // If a change has been detected we send a mod packet to the server\n if(hasChanged) {\n JSONObject payload = new JSONObject();\n payload.put(\"shooting\", isShooting);\n XenyriaServerPacket packet = new XenyriaServerPacket(\n XenyriaServerPacket.EPacketType.PS_SHOOTING_STATE, payload);\n packet.sendToServer();\n }\n }\n }, 10, 10, TimeUnit.MILLISECONDS);",
"score": 0.8704167604446411
},
{
"filename": "src/main/java/net/xenyria/eem/config/screen/XenyriaConfigManager.java",
"retrieved_chunk": " throw new IllegalStateException(\"Config folder has to be a folder, not a file.\");\n }\n // Notify the server about config changes (e.g. resetting internal variables for PS's shooting detection)\n var packet = new XenyriaServerPacket(XenyriaServerPacket.EPacketType.SETTINGS_CHANGED, new JSONObject());\n packet.sendToServer();\n }\n public static ConfigBuilder getConfigurationBuilder() {\n ConfigBuilder configBuilder = ConfigBuilder.create()\n .setTitle(Text.translatable(\"config.xenyria.settings.title\"))\n .setEditable(true)",
"score": 0.8091840744018555
},
{
"filename": "src/main/java/net/xenyria/eem/mixin/InitMixin.java",
"retrieved_chunk": "public class InitMixin {\n @Inject(at = @At(\"HEAD\"), method = \"init()V\")\n private void init(CallbackInfo info) {\n // Register the packet listener here for client-server communication\n PacketListener.initialize();\n // Load the configuration file\n try {\n XenyriaConfigManager.loadConfig();\n } catch (Exception exception) {\n XenyriaConfigManager.LOGGER.error(\"Failed to load XEEM's configuration file on start-up: \"",
"score": 0.7605469226837158
},
{
"filename": "src/main/java/net/xenyria/eem/networking/XenyriaServerPacket.java",
"retrieved_chunk": " return null;\n }\n if(!jsonData.has(\"data\")) {\n LOGGER.severe(\"Malformed packet, missing data field.\");\n return null;\n }\n return new XenyriaServerPacket(parsedPacketType, jsonData.getJSONObject(\"data\"));\n }\n /** Attempt to send this packet to the currently connected server as a plugin message **/\n public void sendToServer() {",
"score": 0.754650354385376
},
{
"filename": "src/main/java/net/xenyria/eem/networking/XenyriaServerPacket.java",
"retrieved_chunk": "import java.nio.charset.StandardCharsets;\nimport static net.xenyria.eem.networking.PacketListener.LOGGER;\npublic class XenyriaServerPacket {\n /** Packets are separated into different types/categories **/\n public enum EPacketType {\n RP, // Rich-Presence (Discord Integration)\n PS_SHOOTING_STATE, // PaintSquad\n HANDSHAKE_INIT, // Server Switch / Server Info Change (Sent by the server)\n HANDSHAKE_RESPONSE, // Sent by the client, informs the server about the mod being active\n DEBUG, // Debug Operation (printing client-side variables into the chat)",
"score": 0.7522173523902893
}
] | java | else if (packet.getPacketType() == XenyriaServerPacket.EPacketType.DEBUG) { |
package io.wispforest.lavendermd;
import com.google.common.collect.ImmutableList;
import io.wispforest.lavendermd.compiler.MarkdownCompiler;
import io.wispforest.lavendermd.compiler.TextCompiler;
import io.wispforest.lavendermd.feature.*;
import net.minecraft.text.Text;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.function.Supplier;
/**
* A Markdown-processor models the pipeline required to lex, parse and compile
* some Markdown input into a result of type {@code R}. For this purpose, it employs
* a set of {@link MarkdownFeature}s installed into a {@link Lexer} and {@link Parser},
* the resulting AST of which it compiles using a {@link MarkdownCompiler}.
* <p>
* To create a processor, either use one of the default factories and optionally customize
* them using the provided copyWith functions, or invoke the constructor and supply
* the desired compiler factory and feature-set
*/
public class MarkdownProcessor<R> {
private final Supplier<MarkdownCompiler<R>> compilerFactory;
private final List<MarkdownFeature> features;
private final Lexer lexer;
private final Parser parser;
public MarkdownProcessor(Supplier<MarkdownCompiler<R>> compilerFactory, MarkdownFeature... features) {
this(compilerFactory, Arrays.asList(features));
}
public MarkdownProcessor(Supplier<MarkdownCompiler<R>> compilerFactory, List<MarkdownFeature> features) {
this.compilerFactory = compilerFactory;
this.features = ImmutableList.copyOf(features);
var testCompiler = this.compilerFactory.get();
for (var feature : this.features) {
if (!feature.supportsCompiler(testCompiler)) {
throw new IllegalStateException("Feature '" | + feature.name() + "' is incompatible with compiler '" + testCompiler.name() + "'"); |
}
}
this.lexer = new Lexer();
this.parser = new Parser();
for (var extension : features) {
extension.registerTokens(this.lexer);
extension.registerNodes(this.parser);
}
}
public Collection<MarkdownFeature> installedFeatures() {
return this.features;
}
public boolean hasFeature(Class<?> featureClass) {
for (var extension : this.features) {
if (featureClass.isInstance(extension)) {
return true;
}
}
return false;
}
public R process(String markdown) {
var compiler = this.compilerFactory.get();
this.parser.parse(this.lexer.lex(markdown)).visit(compiler);
return compiler.compile();
}
// --- copy constructors ---
/**
* Create a copy of this processor with {@code features} added
* to the copy's feature-set
*/
public MarkdownProcessor<R> copyWith(MarkdownFeature... features) {
var newFeatures = new ArrayList<>(this.features);
for (var feature : features) {
if (this.hasFeature(feature.getClass())) continue;
newFeatures.add(feature);
}
return new MarkdownProcessor<>(this.compilerFactory, newFeatures);
}
/**
* Create a copy of this processor with its compiler factory
* replaced by {@code compilerFactory}
*/
public <R2> MarkdownProcessor<R2> copyWith(Supplier<MarkdownCompiler<R2>> compilerFactory) {
return new MarkdownProcessor<>(compilerFactory, this.features);
}
// --- default factories ---
/**
* Create a new Markdown-processor with support for basic text formatting, that is:
* <ul>
* <li>Bold & Italic Emphasis</li>
* <li>Discord-like underscore and strikethrough formatting</li>
* <li>Colors using <pre>{<color name>|#RRGGBB}content here{}</pre> syntax</li>
* </ul>
*/
public static MarkdownProcessor<Text> text() {
return new MarkdownProcessor<>(TextCompiler::new, new BasicFormattingFeature(false), new ColorFeature());
}
/**
* Create a new Markdown-processor with support for rich text formatting, that is:
* <ul>
* <li>Bold & Italic Emphasis</li>
* <li>Discord-like underscore and strikethrough formatting</li>
* <li>Horizontal Rules</li>
* <li>Colors using <pre>{<color name>|#RRGGBB}content here{}</pre> syntax</li>
* <li>Hyperlinks</li>
* <li>Ordered & unordered lists</li>
* <li>Block quotes</li>
* </ul>
*/
public static MarkdownProcessor<Text> richText(int assumedOutputWidth) {
return new MarkdownProcessor<>(() -> new TextCompiler(assumedOutputWidth), new BasicFormattingFeature(), new ColorFeature(), new LinkFeature(), new ListFeature(), new BlockQuoteFeature());
}
}
| src/main/java/io/wispforest/lavendermd/MarkdownProcessor.java | wisp-forest-lavender-md-87862e2 | [
{
"filename": "src/main/java/io/wispforest/lavendermd/feature/ListFeature.java",
"retrieved_chunk": " return \"lists\";\n }\n @Override\n public boolean supportsCompiler(MarkdownCompiler<?> compiler) {\n return true;\n }\n @Override\n public void registerTokens(TokenRegistrar registrar) {\n // unordered\n registrar.registerToken((nibbler, tokens) -> {",
"score": 0.8196571469306946
},
{
"filename": "src/main/java/io/wispforest/lavendermd/feature/ColorFeature.java",
"retrieved_chunk": " return \"colors\";\n }\n @Override\n public boolean supportsCompiler(MarkdownCompiler<?> compiler) {\n return true;\n }\n @Override\n public void registerTokens(TokenRegistrar registrar) {\n registrar.registerToken((nibbler, tokens) -> {\n nibbler.skip();",
"score": 0.8159065246582031
},
{
"filename": "owo-ui-extension/src/main/java/io/wispforest/lavendermd/feature/OwoUITemplateFeature.java",
"retrieved_chunk": " @Override\n public String name() {\n return \"owo_ui_templates\";\n }\n @Override\n public boolean supportsCompiler(MarkdownCompiler<?> compiler) {\n return compiler instanceof OwoUICompiler;\n }\n @Override\n public void registerTokens(TokenRegistrar registrar) {",
"score": 0.8151764869689941
},
{
"filename": "src/main/java/io/wispforest/lavendermd/MarkdownFeature.java",
"retrieved_chunk": " * to be of said type\n */\n boolean supportsCompiler(MarkdownCompiler<?> compiler);\n /**\n * Add this feature's set of tokens to {@code registrar}\n */\n void registerTokens(TokenRegistrar registrar);\n /**\n * Add this feature's set of nodes to {@code registrar}\n */",
"score": 0.8120702505111694
},
{
"filename": "owo-ui-extension/src/main/java/io/wispforest/lavendermd/feature/EntityFeature.java",
"retrieved_chunk": " }\n @Override\n public boolean supportsCompiler(MarkdownCompiler<?> compiler) {\n return compiler instanceof OwoUICompiler;\n }\n @Override\n public void registerTokens(TokenRegistrar registrar) {\n registrar.registerToken((nibbler, tokens) -> {\n if (!nibbler.tryConsume(\"<entity;\")) return false;\n var entityString = nibbler.consumeUntil('>');",
"score": 0.8066336512565613
}
] | java | + feature.name() + "' is incompatible with compiler '" + testCompiler.name() + "'"); |
package io.wispforest.lavendermd;
import com.google.common.collect.ImmutableList;
import io.wispforest.lavendermd.compiler.MarkdownCompiler;
import io.wispforest.lavendermd.compiler.TextCompiler;
import io.wispforest.lavendermd.feature.*;
import net.minecraft.text.Text;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.function.Supplier;
/**
* A Markdown-processor models the pipeline required to lex, parse and compile
* some Markdown input into a result of type {@code R}. For this purpose, it employs
* a set of {@link MarkdownFeature}s installed into a {@link Lexer} and {@link Parser},
* the resulting AST of which it compiles using a {@link MarkdownCompiler}.
* <p>
* To create a processor, either use one of the default factories and optionally customize
* them using the provided copyWith functions, or invoke the constructor and supply
* the desired compiler factory and feature-set
*/
public class MarkdownProcessor<R> {
private final Supplier<MarkdownCompiler<R>> compilerFactory;
private final List<MarkdownFeature> features;
private final Lexer lexer;
private final Parser parser;
public MarkdownProcessor(Supplier<MarkdownCompiler<R>> compilerFactory, MarkdownFeature... features) {
this(compilerFactory, Arrays.asList(features));
}
public MarkdownProcessor(Supplier<MarkdownCompiler<R>> compilerFactory, List<MarkdownFeature> features) {
this.compilerFactory = compilerFactory;
this.features = ImmutableList.copyOf(features);
var testCompiler = this.compilerFactory.get();
for (var feature : this.features) {
if (!feature.supportsCompiler(testCompiler)) {
throw new IllegalStateException("Feature '" + feature.name() + "' is incompatible with compiler '" + testCompiler.name() + "'");
}
}
this.lexer = new Lexer();
this.parser = new Parser();
for (var extension : features) {
extension.registerTokens(this.lexer);
extension.registerNodes(this.parser);
}
}
public Collection<MarkdownFeature> installedFeatures() {
return this.features;
}
public boolean hasFeature(Class<?> featureClass) {
for (var extension : this.features) {
if (featureClass.isInstance(extension)) {
return true;
}
}
return false;
}
public R process(String markdown) {
var compiler = this.compilerFactory.get();
this.parser.parse(this | .lexer.lex(markdown)).visit(compiler); |
return compiler.compile();
}
// --- copy constructors ---
/**
* Create a copy of this processor with {@code features} added
* to the copy's feature-set
*/
public MarkdownProcessor<R> copyWith(MarkdownFeature... features) {
var newFeatures = new ArrayList<>(this.features);
for (var feature : features) {
if (this.hasFeature(feature.getClass())) continue;
newFeatures.add(feature);
}
return new MarkdownProcessor<>(this.compilerFactory, newFeatures);
}
/**
* Create a copy of this processor with its compiler factory
* replaced by {@code compilerFactory}
*/
public <R2> MarkdownProcessor<R2> copyWith(Supplier<MarkdownCompiler<R2>> compilerFactory) {
return new MarkdownProcessor<>(compilerFactory, this.features);
}
// --- default factories ---
/**
* Create a new Markdown-processor with support for basic text formatting, that is:
* <ul>
* <li>Bold & Italic Emphasis</li>
* <li>Discord-like underscore and strikethrough formatting</li>
* <li>Colors using <pre>{<color name>|#RRGGBB}content here{}</pre> syntax</li>
* </ul>
*/
public static MarkdownProcessor<Text> text() {
return new MarkdownProcessor<>(TextCompiler::new, new BasicFormattingFeature(false), new ColorFeature());
}
/**
* Create a new Markdown-processor with support for rich text formatting, that is:
* <ul>
* <li>Bold & Italic Emphasis</li>
* <li>Discord-like underscore and strikethrough formatting</li>
* <li>Horizontal Rules</li>
* <li>Colors using <pre>{<color name>|#RRGGBB}content here{}</pre> syntax</li>
* <li>Hyperlinks</li>
* <li>Ordered & unordered lists</li>
* <li>Block quotes</li>
* </ul>
*/
public static MarkdownProcessor<Text> richText(int assumedOutputWidth) {
return new MarkdownProcessor<>(() -> new TextCompiler(assumedOutputWidth), new BasicFormattingFeature(), new ColorFeature(), new LinkFeature(), new ListFeature(), new BlockQuoteFeature());
}
}
| src/main/java/io/wispforest/lavendermd/MarkdownProcessor.java | wisp-forest-lavender-md-87862e2 | [
{
"filename": "src/main/java/io/wispforest/lavendermd/Parser.java",
"retrieved_chunk": " @Override\n protected void visitEnd(MarkdownCompiler<?> compiler) {\n compiler.visitStyleEnd();\n }\n protected Style applyStyle(Style style) {\n return this.formatting.apply(style);\n }\n }\n}",
"score": 0.8237696290016174
},
{
"filename": "src/main/java/io/wispforest/lavendermd/feature/ColorFeature.java",
"retrieved_chunk": " return \"colors\";\n }\n @Override\n public boolean supportsCompiler(MarkdownCompiler<?> compiler) {\n return true;\n }\n @Override\n public void registerTokens(TokenRegistrar registrar) {\n registrar.registerToken((nibbler, tokens) -> {\n nibbler.skip();",
"score": 0.8169448375701904
},
{
"filename": "owo-ui-extension/src/main/java/io/wispforest/lavendermd/feature/EntityFeature.java",
"retrieved_chunk": " }\n @Override\n public boolean supportsCompiler(MarkdownCompiler<?> compiler) {\n return compiler instanceof OwoUICompiler;\n }\n @Override\n public void registerTokens(TokenRegistrar registrar) {\n registrar.registerToken((nibbler, tokens) -> {\n if (!nibbler.tryConsume(\"<entity;\")) return false;\n var entityString = nibbler.consumeUntil('>');",
"score": 0.8134381771087646
},
{
"filename": "src/main/java/io/wispforest/lavendermd/Parser.java",
"retrieved_chunk": " for (var child : this.children) {\n child.visit(compiler);\n }\n this.visitEnd(compiler);\n }\n protected abstract void visitStart(MarkdownCompiler<?> compiler);\n protected abstract void visitEnd(MarkdownCompiler<?> compiler);\n public static Node empty() {\n return new Node() {\n @Override",
"score": 0.8070008754730225
},
{
"filename": "src/main/java/io/wispforest/lavendermd/feature/ListFeature.java",
"retrieved_chunk": " return \"lists\";\n }\n @Override\n public boolean supportsCompiler(MarkdownCompiler<?> compiler) {\n return true;\n }\n @Override\n public void registerTokens(TokenRegistrar registrar) {\n // unordered\n registrar.registerToken((nibbler, tokens) -> {",
"score": 0.8057743906974792
}
] | java | .lexer.lex(markdown)).visit(compiler); |
package io.wispforest.lavendermd.compiler;
import io.wispforest.lavendermd.util.TextBuilder;
import net.minecraft.text.MutableText;
import net.minecraft.text.Style;
import net.minecraft.text.Text;
import net.minecraft.util.Formatting;
import net.minecraft.util.Identifier;
import java.util.OptionalInt;
import java.util.function.UnaryOperator;
/**
* lavender-md's default compiler implementation which compiles to a
* single Minecraft {@link Text} component - depending on the input
* AST it might contain multiple lines
*/
public class TextCompiler implements MarkdownCompiler<Text> {
private final TextBuilder builder = new TextBuilder();
private final int assumedOutputWidth;
private int quoteDepth = 0;
private int listDepth = 0;
public TextCompiler() {
this(50);
}
public TextCompiler(int assumedOutputWidth) {
this.assumedOutputWidth = assumedOutputWidth;
}
@Override
public void visitText(String text) {
if (this.quoteDepth != 0 && text.contains("\n")) {
if (text.equals("\n")) {
this.builder.append(this.quoteMarker());
} else {
for (var line : text.split("\n")) {
this.builder.append(this.quoteMarker().append(Text.literal(line)));
}
}
} else if (this.listDepth != 0 && text.contains("\n")) {
if (text.equals("\n")) {
this.builder.append(Text.literal("\n " + " ".repeat(this.listDepth - 1)));
} else {
var lines = text.split("\n");
for (int i = 0; i < lines.length; i++) {
this.builder.append(Text.literal((i > 0 ? "\n " : " ") + " ".repeat(this.listDepth - 1)).append(Text.literal(lines[i])));
}
}
} else {
this.builder.append(Text.literal(text));
}
}
@Override
public void visitStyle(UnaryOperator<Style> style) {
this.builder.pushStyle(style);
}
@Override
public void visitStyleEnd() {
this.builder.popStyle();
}
@Override
public void visitBlockQuote() {
this.quoteDepth++;
this.builder.append(this.quoteMarker());
this.builder.pushStyle(style -> style.withColor(Formatting.GRAY).withItalic(true));
}
@Override
public void visitBlockQuoteEnd() {
| this.builder.popStyle(); |
this.quoteDepth--;
if (this.quoteDepth > 0) {
this.builder.append(this.quoteMarker());
} else {
this.builder.append(Text.literal("\n"));
}
}
private MutableText quoteMarker() {
return Text.literal("\n >" + ">".repeat(this.quoteDepth) + " ").formatted(Formatting.DARK_GRAY);
}
@Override
public void visitHorizontalRule() {
this.builder.append(Text.literal("-".repeat(this.assumedOutputWidth)).formatted(Formatting.DARK_GRAY));
}
@Override
public void visitImage(Identifier image, String description, boolean fit) {
this.builder.append(Text.literal("[" + description + "]").formatted(Formatting.YELLOW));
}
@Override
public void visitListItem(OptionalInt ordinal) {
var listPrefix = ordinal.isPresent() ? " " + ordinal.getAsInt() + ". " : " • ";
if (this.listDepth > 0) {
this.builder.append(Text.literal("\n" + " ".repeat(this.listDepth) + listPrefix));
} else {
this.builder.append(Text.literal(listPrefix));
}
this.listDepth++;
}
@Override
public void visitListItemEnd() {
this.listDepth--;
if (this.listDepth > 0) {
this.builder.append(Text.literal(" ".repeat(this.listDepth)));
} else {
this.builder.append(Text.literal("\n"));
}
}
@Override
public Text compile() {
return this.builder.build();
}
@Override
public String name() {
return "lavender_builtin_text";
}
}
| src/main/java/io/wispforest/lavendermd/compiler/TextCompiler.java | wisp-forest-lavender-md-87862e2 | [
{
"filename": "owo-ui-extension/src/main/java/io/wispforest/lavendermd/compiler/OwoUICompiler.java",
"retrieved_chunk": " @Override\n public void visitBlockQuoteEnd() {\n this.textBuilder.popStyle();\n this.pop();\n }\n @Override\n public void visitHorizontalRule() {\n this.append(new BoxComponent(Sizing.fill(100), Sizing.fixed(2)).color(Color.ofRgb(0x777777)).fill(true));\n }\n @Override",
"score": 0.8765054941177368
},
{
"filename": "owo-ui-extension/src/main/java/io/wispforest/lavendermd/compiler/OwoUICompiler.java",
"retrieved_chunk": " public void visitText(String text) {\n this.textBuilder.append(Text.literal(text));\n }\n @Override\n public void visitStyle(UnaryOperator<Style> style) {\n this.textBuilder.pushStyle(style);\n }\n @Override\n public void visitStyleEnd() {\n this.textBuilder.popStyle();",
"score": 0.862034797668457
},
{
"filename": "src/main/java/io/wispforest/lavendermd/Parser.java",
"retrieved_chunk": " @Override\n protected void visitEnd(MarkdownCompiler<?> compiler) {\n compiler.visitStyleEnd();\n }\n protected Style applyStyle(Style style) {\n return this.formatting.apply(style);\n }\n }\n}",
"score": 0.7776835560798645
},
{
"filename": "owo-ui-extension/src/main/java/io/wispforest/lavendermd/compiler/OwoUICompiler.java",
"retrieved_chunk": " }\n @Override\n public void visitBlockQuote() {\n this.textBuilder.pushStyle(style -> style.withFormatting(Formatting.GRAY));\n var quotation = Containers.verticalFlow(Sizing.content(), Sizing.content());\n quotation.padding(Insets.of(5, 5, 7, 5)).surface((context, component) -> {\n context.fill(component.x(), component.y() + 3, component.x() + 2, component.y() + component.height() - 3, 0xFF777777);\n });\n this.push(quotation);\n }",
"score": 0.7758908271789551
},
{
"filename": "src/main/java/io/wispforest/lavendermd/util/TextBuilder.java",
"retrieved_chunk": " * Append {@code text} to this builder's result\n */\n public void append(MutableText text) {\n this.text.append(text.styled(style -> style.withParent(this.styles.peek())));\n this.empty = false;\n }\n /**\n * Push {@code style} onto this builder's stack\n */\n public void pushStyle(UnaryOperator<Style> style) {",
"score": 0.7679672241210938
}
] | java | this.builder.popStyle(); |
package io.wispforest.lavendermd.compiler;
import io.wispforest.lavendermd.util.TextBuilder;
import net.minecraft.text.MutableText;
import net.minecraft.text.Style;
import net.minecraft.text.Text;
import net.minecraft.util.Formatting;
import net.minecraft.util.Identifier;
import java.util.OptionalInt;
import java.util.function.UnaryOperator;
/**
* lavender-md's default compiler implementation which compiles to a
* single Minecraft {@link Text} component - depending on the input
* AST it might contain multiple lines
*/
public class TextCompiler implements MarkdownCompiler<Text> {
private final TextBuilder builder = new TextBuilder();
private final int assumedOutputWidth;
private int quoteDepth = 0;
private int listDepth = 0;
public TextCompiler() {
this(50);
}
public TextCompiler(int assumedOutputWidth) {
this.assumedOutputWidth = assumedOutputWidth;
}
@Override
public void visitText(String text) {
if (this.quoteDepth != 0 && text.contains("\n")) {
if (text.equals("\n")) {
this.builder.append(this.quoteMarker());
} else {
for (var line : text.split("\n")) {
this.builder.append(this.quoteMarker().append(Text.literal(line)));
}
}
} else if (this.listDepth != 0 && text.contains("\n")) {
if (text.equals("\n")) {
this.builder.append(Text.literal("\n " + " ".repeat(this.listDepth - 1)));
} else {
var lines = text.split("\n");
for (int i = 0; i < lines.length; i++) {
this.builder.append(Text.literal((i > 0 ? "\n " : " ") + " ".repeat(this.listDepth - 1)).append(Text.literal(lines[i])));
}
}
} else {
this.builder.append(Text.literal(text));
}
}
@Override
public void visitStyle(UnaryOperator<Style> style) {
this.builder.pushStyle(style);
}
@Override
public void visitStyleEnd() {
this.builder.popStyle();
}
@Override
public void visitBlockQuote() {
this.quoteDepth++;
this.builder.append(this.quoteMarker());
this. | builder.pushStyle(style -> style.withColor(Formatting.GRAY).withItalic(true)); |
}
@Override
public void visitBlockQuoteEnd() {
this.builder.popStyle();
this.quoteDepth--;
if (this.quoteDepth > 0) {
this.builder.append(this.quoteMarker());
} else {
this.builder.append(Text.literal("\n"));
}
}
private MutableText quoteMarker() {
return Text.literal("\n >" + ">".repeat(this.quoteDepth) + " ").formatted(Formatting.DARK_GRAY);
}
@Override
public void visitHorizontalRule() {
this.builder.append(Text.literal("-".repeat(this.assumedOutputWidth)).formatted(Formatting.DARK_GRAY));
}
@Override
public void visitImage(Identifier image, String description, boolean fit) {
this.builder.append(Text.literal("[" + description + "]").formatted(Formatting.YELLOW));
}
@Override
public void visitListItem(OptionalInt ordinal) {
var listPrefix = ordinal.isPresent() ? " " + ordinal.getAsInt() + ". " : " • ";
if (this.listDepth > 0) {
this.builder.append(Text.literal("\n" + " ".repeat(this.listDepth) + listPrefix));
} else {
this.builder.append(Text.literal(listPrefix));
}
this.listDepth++;
}
@Override
public void visitListItemEnd() {
this.listDepth--;
if (this.listDepth > 0) {
this.builder.append(Text.literal(" ".repeat(this.listDepth)));
} else {
this.builder.append(Text.literal("\n"));
}
}
@Override
public Text compile() {
return this.builder.build();
}
@Override
public String name() {
return "lavender_builtin_text";
}
}
| src/main/java/io/wispforest/lavendermd/compiler/TextCompiler.java | wisp-forest-lavender-md-87862e2 | [
{
"filename": "owo-ui-extension/src/main/java/io/wispforest/lavendermd/compiler/OwoUICompiler.java",
"retrieved_chunk": " @Override\n public void visitBlockQuoteEnd() {\n this.textBuilder.popStyle();\n this.pop();\n }\n @Override\n public void visitHorizontalRule() {\n this.append(new BoxComponent(Sizing.fill(100), Sizing.fixed(2)).color(Color.ofRgb(0x777777)).fill(true));\n }\n @Override",
"score": 0.8901113271713257
},
{
"filename": "owo-ui-extension/src/main/java/io/wispforest/lavendermd/compiler/OwoUICompiler.java",
"retrieved_chunk": " public void visitText(String text) {\n this.textBuilder.append(Text.literal(text));\n }\n @Override\n public void visitStyle(UnaryOperator<Style> style) {\n this.textBuilder.pushStyle(style);\n }\n @Override\n public void visitStyleEnd() {\n this.textBuilder.popStyle();",
"score": 0.8750671148300171
},
{
"filename": "src/main/java/io/wispforest/lavendermd/Parser.java",
"retrieved_chunk": " @Override\n protected void visitEnd(MarkdownCompiler<?> compiler) {\n compiler.visitStyleEnd();\n }\n protected Style applyStyle(Style style) {\n return this.formatting.apply(style);\n }\n }\n}",
"score": 0.8045670986175537
},
{
"filename": "src/main/java/io/wispforest/lavendermd/util/TextBuilder.java",
"retrieved_chunk": " * Append {@code text} to this builder's result\n */\n public void append(MutableText text) {\n this.text.append(text.styled(style -> style.withParent(this.styles.peek())));\n this.empty = false;\n }\n /**\n * Push {@code style} onto this builder's stack\n */\n public void pushStyle(UnaryOperator<Style> style) {",
"score": 0.801383912563324
},
{
"filename": "owo-ui-extension/src/main/java/io/wispforest/lavendermd/compiler/OwoUICompiler.java",
"retrieved_chunk": " }\n @Override\n public void visitBlockQuote() {\n this.textBuilder.pushStyle(style -> style.withFormatting(Formatting.GRAY));\n var quotation = Containers.verticalFlow(Sizing.content(), Sizing.content());\n quotation.padding(Insets.of(5, 5, 7, 5)).surface((context, component) -> {\n context.fill(component.x(), component.y() + 3, component.x() + 2, component.y() + component.height() - 3, 0xFF777777);\n });\n this.push(quotation);\n }",
"score": 0.782049298286438
}
] | java | builder.pushStyle(style -> style.withColor(Formatting.GRAY).withItalic(true)); |
package com.xtracr.realcamera.api;
import com.xtracr.realcamera.RealCameraCore;
import com.xtracr.realcamera.config.ConfigFile;
import com.xtracr.realcamera.config.ModConfig;
import net.minecraft.client.util.math.MatrixStack;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiPredicate;
/**
* @see CompatExample
*/
public class VirtualRenderer {
public static final ModConfig config = ConfigFile.modConfig;
private static final Map<String, BiPredicate<Float, MatrixStack>> functionProvider = new HashMap<>();
/**
* @param modid {@code mandatory}
* @param function {@code mandatory} turn to vanilla rendering if return true.
* {@link CompatExample#virtualRender See example here}
*/
public static void register(String modid, BiPredicate<Float, MatrixStack> function) {
functionProvider.put(modid, function);
}
/**
* @return the value of {@link com.xtracr.realcamera.config.ModConfig.Compats#modModelPart modModelPart}
* option in the config
*/
public static String getModelPartName() {
return config.getModModelPartName();
}
/**
* @see com.xtracr.realcamera.mixins.MixinPlayerEntityRenderer#onSetModelPoseRETURN
* MixinPlayerEntityRenderer.onSetModelPoseRETURN
*/
public static boolean shouldDisableRender(String modelPartName) {
ModConfig.Disable.optionalParts.add(modelPartName);
| return RealCameraCore.isRenderingWorld && config.shouldDisableRender(modelPartName) && RealCameraCore.isActive(); |
}
public static boolean virtualRender(float tickDelta, MatrixStack matrixStack) {
return functionProvider.get(config.getModelModID()).test(tickDelta, matrixStack);
}
public static String[] getModidList() {
return functionProvider.keySet().toArray(new String[functionProvider.size()]);
}
}
| common/src/main/java/com/xtracr/realcamera/api/VirtualRenderer.java | xTracr-RealCamera-7675633 | [
{
"filename": "forge/src/main/java/com/xtracr/realcamera/EventHandler.java",
"retrieved_chunk": " event.setYaw(camera.getYaw());\n event.setRoll(RealCameraCore.getRoll());\n }\n }\n @SubscribeEvent\n public static void onRenderWorldStage(RenderLevelStageEvent event) {\n if (RenderLevelStageEvent.Stage.AFTER_SKY.equals(event.getStage())) {\n RealCameraCore.isRenderingWorld = true;\n if (ConfigFile.modConfig.isCrosshairDynamic() && RealCameraCore.isActive()) {\n CrosshairUtils.update(MinecraftClient.getInstance(), event.getCamera(),",
"score": 0.8017390370368958
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ModConfig.java",
"retrieved_chunk": " public boolean shouldDisableRender(String modelPartName) {\n if (disable.onlyInBinding && general.classic) return false;\n return (disable.renderModelPart && disable.disabledModelParts.contains(modelPartName)) ||\n shouldDisable(MinecraftClient.getInstance(), modelPartName);\n }\n public boolean allowRenderingHandWhen(MinecraftClient client) {\n if (disable.onlyInBinding && general.classic) return false;\n return shouldDisable(client, \"allow_rendering_hand\");\n }\n public boolean disableModWhen(MinecraftClient client) {",
"score": 0.7969062328338623
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/mixins/MixinEntityRenderer.java",
"retrieved_chunk": "import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;\n@Mixin(EntityRenderer.class)\npublic abstract class MixinEntityRenderer {\n @Inject(method = \"shouldRender\", at = @At(\"HEAD\"), cancellable = true)\n private <T extends Entity> void onShouldRenderHEAD(T entity, Frustum frustum, double x, double y, double z,\n CallbackInfoReturnable<Boolean> cInfo) {\n if (ConfigFile.modConfig.isRendering() && RealCameraCore.isActive() && entity instanceof ClientPlayerEntity) {\n cInfo.setReturnValue(true);\n }\n }",
"score": 0.7854335308074951
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/api/CompatExample.java",
"retrieved_chunk": " public static final String modid = \"minecraft\";\n private static final Map<String, String> nameMap = new HashMap<>();\n /**\n * {@code = VirtualRenderer.class.getDeclaredMethod(\"getModelPartName\")}\n *\n * <p>return the value of {@link com.xtracr.realcamera.config.ModConfig.Compats#modModelPart modModelPart}\n * option in the config.</p>\n *\n * @see #register()\n * @see VirtualRenderer#getModelPartName() getModelPartName()",
"score": 0.7831857800483704
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/mixins/MixinGameRenderer.java",
"retrieved_chunk": " .multiply(client.interactionManager.getReachDistance())).expand(1.0, 1.0, 1.0);\n CrosshairUtils.capturedEntityHitResult = ProjectileUtil.raycast(cameraEntity, startVec, endVec, box, entity -> !entity.isSpectator() && entity.canHit(), sqDistance);\n }\n return CrosshairUtils.capturedEntityHitResult;\n }\n @Inject(method = \"renderHand\", at = @At(value = \"INVOKE\",\n target = \"Lnet/minecraft/client/util/math/MatrixStack;push()V\"))\n private void setThirdPerson(MatrixStack matrices, Camera camera, float tickDelta, CallbackInfo cInfo) {\n if (ConfigFile.modConfig.isRendering() && camera.isThirdPerson() && RealCameraCore.isActive() &&\n !ConfigFile.modConfig.allowRenderingHandWhen(client)) {",
"score": 0.7713172435760498
}
] | java | return RealCameraCore.isRenderingWorld && config.shouldDisableRender(modelPartName) && RealCameraCore.isActive(); |
package com.xtracr.realcamera.config;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.xtracr.realcamera.RealCamera;
import net.minecraft.client.MinecraftClient;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
public class ConfigFile {
public static final ModConfig modConfig = new ModConfig();
private static final String FILE_NAME = RealCamera.MODID + ".json";
private static final Path PATH;
private static final Gson GSON = new GsonBuilder()
.setPrettyPrinting()
.create();
static {
final File configDir = new File(MinecraftClient.getInstance().runDirectory, "config");
if (!configDir.exists()) configDir.mkdirs();
PATH = configDir.toPath().resolve(FILE_NAME);
}
public static void load() {
try (BufferedReader reader = Files.newBufferedReader(PATH)) {
modConfig.set(GSON.fromJson(reader, ModConfig.class));
modConfig.clamp();
} catch (Exception exception) {
RealCamera.LOGGER.warn("Failed to load " + FILE_NAME);
save();
}
}
public static void save() {
try (BufferedWriter writer = Files.newBufferedWriter(PATH)) {
GSON.toJson(modConfig, writer);
} catch (Exception exception) {
RealCamera.LOGGER.warn("Failed to save " + FILE_NAME, exception);
reset();
}
}
public static void reset() {
try (BufferedWriter writer = Files.newBufferedWriter(PATH)) {
| modConfig.set(new ModConfig()); |
GSON.toJson(modConfig, writer);
} catch (Exception exception) {
RealCamera.LOGGER.warn("Failed to reset " + FILE_NAME, exception);
}
}
}
| common/src/main/java/com/xtracr/realcamera/config/ConfigFile.java | xTracr-RealCamera-7675633 | [
{
"filename": "common/src/main/java/com/xtracr/realcamera/utils/ReflectUtils.java",
"retrieved_chunk": " return fld.get(object);\n } catch (IllegalArgumentException | IllegalAccessException ignored) {\n return null;\n }\n });\n }\n public static void setField(final Optional<Field> field, @Nullable final Object object, Object value) {\n field.ifPresent(fld -> {\n try {\n fld.set(object, value);",
"score": 0.762671709060669
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/api/CompatExample.java",
"retrieved_chunk": " getModelPartNameMethod = virtualRendererClass.getDeclaredMethod(\"getModelPartName\");\n final Method registerMethod = virtualRendererClass.getDeclaredMethod(\"register\", String.class, BiPredicate.class);\n final BiPredicate<Float, MatrixStack> function = CompatExample::virtualRender;\n registerMethod.invoke(null, modid, function);\n } catch (Exception exception) {\n // handle exception\n }\n }\n /**\n * <b>mandatory</b>",
"score": 0.7435799837112427
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/utils/ReflectUtils.java",
"retrieved_chunk": " } catch (IllegalArgumentException | IllegalAccessException ignored) {\n }\n });\n }\n public static Optional<Method> getMethod(final Optional<Class<?>> classObj, final String methodName, Class<?>... args) {\n return classObj.map(cls -> {\n try {\n final Method mtd = cls.getMethod(methodName, args);\n mtd.setAccessible(true);\n return mtd;",
"score": 0.7379271984100342
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/utils/ReflectUtils.java",
"retrieved_chunk": " return fld;\n } catch (NoSuchFieldException | SecurityException ignored) {\n return null;\n }\n });\n }\n public static Optional<Field> getDeclaredField(final Optional<Class<?>> classObj, final String fieldName) {\n return classObj.map(cls -> {\n try {\n final Field fld = cls.getDeclaredField(fieldName);",
"score": 0.7377578020095825
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/utils/ReflectUtils.java",
"retrieved_chunk": " } catch (NoSuchMethodException | SecurityException ignored) {\n return null;\n }\n });\n }\n public static Optional<Method> getDeclaredMethod(final Optional<Class<?>> classObj, final String methodName, Class<?>... args) {\n return classObj.map(cls -> {\n try {\n final Method mtd = cls.getDeclaredMethod(methodName, args);\n mtd.setAccessible(true);",
"score": 0.7348309755325317
}
] | java | modConfig.set(new ModConfig()); |
package com.xtracr.realcamera;
import com.xtracr.realcamera.config.ConfigFile;
import com.xtracr.realcamera.config.ModConfig;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.option.KeyBinding;
import net.minecraft.client.util.InputUtil;
import org.lwjgl.glfw.GLFW;
public final class KeyBindings {
private static final ModConfig config = ConfigFile.modConfig;
private static final String KEY_CATEGORY = "key.category.xtracr_" + RealCamera.MODID;
private static final String KEY_ID = "key.xtracr_" + RealCamera.MODID + "_";
public static final KeyBinding TOGGLE_PERSPECTIVE = new KeyBinding(
KEY_ID + "togglePerspective", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_F6, KEY_CATEGORY);
public static final KeyBinding TOGGLE_ADJUST_MODE = new KeyBinding(
KEY_ID + "toggleAdjustMode", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding TOGGLE_CAMERA_MODE = new KeyBinding(
KEY_ID + "toggleCameraMode", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_UP = new KeyBinding(
KEY_ID + "adjustUP", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_DOWN = new KeyBinding(
KEY_ID + "adjustDOWN", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_FRONT = new KeyBinding(
KEY_ID + "adjustFRONT", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_BACK = new KeyBinding(
KEY_ID + "adjustBACK", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_LEFT = new KeyBinding(
KEY_ID + "adjustLEFT", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_RIGHT = new KeyBinding(
KEY_ID + "adjustRIGHT", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static void handle(MinecraftClient client) {
if (client.player == null || client.currentScreen != null) return;
while (TOGGLE_PERSPECTIVE.wasPressed()) {
boolean enabled = config.isEnabled();
ConfigFile.load();
config.setEnabled(!enabled);
ConfigFile.save();
}
while (TOGGLE_ADJUST_MODE.wasPressed()) {
if (config.isClassic()) config.cycleClassicAdjustMode();
| else config.setAdjustOffset(!config.isAdjustingOffset()); |
ConfigFile.save();
}
while (TOGGLE_CAMERA_MODE.wasPressed()) {
config.setClassic(!config.isClassic());
ConfigFile.save();
}
while (ADJUST_LEFT.wasPressed()) {
if (config.isClassic()) config.adjustClassicZ(true);
else config.adjustBindingZ(true);
ConfigFile.save();
}
while (ADJUST_RIGHT.wasPressed()) {
if (config.isClassic()) config.adjustClassicZ(false);
else config.adjustBindingZ(false);
ConfigFile.save();
}
while (ADJUST_UP.wasPressed()) {
if (config.isClassic()) config.adjustClassicY(true);
else config.adjustBindingY(true);
ConfigFile.save();
}
while (ADJUST_DOWN.wasPressed()) {
if (config.isClassic()) config.adjustClassicY(false);
else config.adjustBindingY(false);
ConfigFile.save();
}
while (ADJUST_FRONT.wasPressed()) {
if (config.isClassic()) config.adjustClassicX(true);
else config.adjustBindingX(true);
ConfigFile.save();
}
while (ADJUST_BACK.wasPressed()) {
if (config.isClassic()) config.adjustClassicX(false);
else config.adjustBindingX(false);
ConfigFile.save();
}
}
}
| common/src/main/java/com/xtracr/realcamera/KeyBindings.java | xTracr-RealCamera-7675633 | [
{
"filename": "common/src/main/java/com/xtracr/realcamera/RealCameraCore.java",
"retrieved_chunk": " && client.player != null && !config.disableModWhen(client);\n }\n public static void updateCamera(Camera camera, MinecraftClient client, float tickDelta) {\n cameraRoll = 0.0F;\n if (config.isRendering() && !config.disableRenderingWhen(client)) {\n ((CameraAccessor) camera).setThirdPerson(true);\n }\n if (config.isClassic()) {\n classicModeUpdate(camera, client, tickDelta);\n } else {",
"score": 0.745922327041626
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ModConfig.java",
"retrieved_chunk": " switch (classic.adjustMode) {\n case CENTER -> classic.centerZ += s * getAdjustStep();\n case ROTATION -> classic.pitch += s * 4 * (float) getAdjustStep();\n default -> classic.cameraZ += s * getAdjustStep();\n }\n classic.clamp();\n }\n // compats\n public boolean isUsingModModel() {\n return compats.useModModel;",
"score": 0.7402442097663879
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ConfigScreen.java",
"retrieved_chunk": " .setSaveConsumer(b -> config.disable.sleeping = b)\n .build());\n disableModWhen.add(entryBuilder.startBooleanToggle(Text.translatable(OPTION + \"screenOpened\"), config.disable.screenOpened)\n .setDefaultValue(false)\n .setSaveConsumer(b -> config.disable.screenOpened = b)\n .build());\n disable.addEntry(disableModWhen.build());\n return builder.build();\n }\n}",
"score": 0.7264136075973511
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ModConfig.java",
"retrieved_chunk": " public void adjustClassicX(boolean add) {\n int s = add ? 1 : -1;\n switch (classic.adjustMode) {\n case CENTER -> classic.centerX += s * getAdjustStep();\n case ROTATION -> classic.roll += s * 4 * (float) getAdjustStep();\n default -> classic.cameraX += s * getAdjustStep();\n }\n classic.clamp();\n }\n public void adjustClassicY(boolean add) {",
"score": 0.7215330600738525
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ModConfig.java",
"retrieved_chunk": " int s = add ? 1 : -1;\n switch (classic.adjustMode) {\n case CENTER -> classic.centerY += s * getAdjustStep();\n case ROTATION -> classic.yaw += s * 4 * (float) getAdjustStep();\n default -> classic.cameraY += s * getAdjustStep();\n }\n classic.clamp();\n }\n public void adjustClassicZ(boolean add) {\n int s = add ? 1 : -1;",
"score": 0.7172415256500244
}
] | java | else config.setAdjustOffset(!config.isAdjustingOffset()); |
package com.xtracr.realcamera.api;
import com.xtracr.realcamera.RealCameraCore;
import com.xtracr.realcamera.config.ConfigFile;
import com.xtracr.realcamera.config.ModConfig;
import net.minecraft.client.util.math.MatrixStack;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiPredicate;
/**
* @see CompatExample
*/
public class VirtualRenderer {
public static final ModConfig config = ConfigFile.modConfig;
private static final Map<String, BiPredicate<Float, MatrixStack>> functionProvider = new HashMap<>();
/**
* @param modid {@code mandatory}
* @param function {@code mandatory} turn to vanilla rendering if return true.
* {@link CompatExample#virtualRender See example here}
*/
public static void register(String modid, BiPredicate<Float, MatrixStack> function) {
functionProvider.put(modid, function);
}
/**
* @return the value of {@link com.xtracr.realcamera.config.ModConfig.Compats#modModelPart modModelPart}
* option in the config
*/
public static String getModelPartName() {
return config.getModModelPartName();
}
/**
* @see com.xtracr.realcamera.mixins.MixinPlayerEntityRenderer#onSetModelPoseRETURN
* MixinPlayerEntityRenderer.onSetModelPoseRETURN
*/
public static boolean shouldDisableRender(String modelPartName) {
ModConfig.Disable.optionalParts.add(modelPartName);
return RealCameraCore.isRenderingWorld && config.shouldDisableRender(modelPartName) && RealCameraCore.isActive();
}
public static boolean virtualRender(float tickDelta, MatrixStack matrixStack) {
return functionProvider. | get(config.getModelModID()).test(tickDelta, matrixStack); |
}
public static String[] getModidList() {
return functionProvider.keySet().toArray(new String[functionProvider.size()]);
}
}
| common/src/main/java/com/xtracr/realcamera/api/VirtualRenderer.java | xTracr-RealCamera-7675633 | [
{
"filename": "common/src/main/java/com/xtracr/realcamera/mixins/MixinGameRenderer.java",
"retrieved_chunk": " .multiply(client.interactionManager.getReachDistance())).expand(1.0, 1.0, 1.0);\n CrosshairUtils.capturedEntityHitResult = ProjectileUtil.raycast(cameraEntity, startVec, endVec, box, entity -> !entity.isSpectator() && entity.canHit(), sqDistance);\n }\n return CrosshairUtils.capturedEntityHitResult;\n }\n @Inject(method = \"renderHand\", at = @At(value = \"INVOKE\",\n target = \"Lnet/minecraft/client/util/math/MatrixStack;push()V\"))\n private void setThirdPerson(MatrixStack matrices, Camera camera, float tickDelta, CallbackInfo cInfo) {\n if (ConfigFile.modConfig.isRendering() && camera.isThirdPerson() && RealCameraCore.isActive() &&\n !ConfigFile.modConfig.allowRenderingHandWhen(client)) {",
"score": 0.8198057413101196
},
{
"filename": "forge/src/main/java/com/xtracr/realcamera/EventHandler.java",
"retrieved_chunk": " event.setYaw(camera.getYaw());\n event.setRoll(RealCameraCore.getRoll());\n }\n }\n @SubscribeEvent\n public static void onRenderWorldStage(RenderLevelStageEvent event) {\n if (RenderLevelStageEvent.Stage.AFTER_SKY.equals(event.getStage())) {\n RealCameraCore.isRenderingWorld = true;\n if (ConfigFile.modConfig.isCrosshairDynamic() && RealCameraCore.isActive()) {\n CrosshairUtils.update(MinecraftClient.getInstance(), event.getCamera(),",
"score": 0.8149522542953491
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/mixins/MixinEntityRenderer.java",
"retrieved_chunk": "import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;\n@Mixin(EntityRenderer.class)\npublic abstract class MixinEntityRenderer {\n @Inject(method = \"shouldRender\", at = @At(\"HEAD\"), cancellable = true)\n private <T extends Entity> void onShouldRenderHEAD(T entity, Frustum frustum, double x, double y, double z,\n CallbackInfoReturnable<Boolean> cInfo) {\n if (ConfigFile.modConfig.isRendering() && RealCameraCore.isActive() && entity instanceof ClientPlayerEntity) {\n cInfo.setReturnValue(true);\n }\n }",
"score": 0.8131608963012695
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/mixins/MixinClientPlayerEntity.java",
"retrieved_chunk": " target = \"Lnet/minecraft/client/option/Perspective;isFirstPerson()Z\"))\n private boolean returnFalse(Perspective perspective) {\n if (ConfigFile.modConfig.isRendering() && RealCameraCore.isActive()) return false;\n return perspective.isFirstPerson();\n }\n @Override\n public HitResult raycast(double maxDistance, float tickDelta, boolean includeFluids) {\n if (!ConfigFile.modConfig.isCrosshairDynamic() && RealCameraCore.isActive()) {\n RaycastUtils.update(this, maxDistance * maxDistance, tickDelta);\n return getWorld().raycast(RaycastUtils.getRaycastContext(RaycastContext.ShapeType.OUTLINE,",
"score": 0.8114180564880371
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/RealCameraCore.java",
"retrieved_chunk": " double l = hitResult.getPos().distanceTo(start);\n if (hitResult.getType() == HitResult.Type.MISS || l >= offset.length()) continue;\n offset = offset.multiply(l / offset.length());\n }\n ((CameraAccessor) camera).invokeSetPos(referVec.add(offset));\n }\n private static void virtualRender(AbstractClientPlayerEntity player, PlayerEntityRenderer playerRenderer,\n float tickDelta, MatrixStack matrixStack) {\n if (config.isUsingModModel()) {\n status = \"Successful\";",
"score": 0.7947400808334351
}
] | java | get(config.getModelModID()).test(tickDelta, matrixStack); |
package com.xtracr.realcamera;
import com.xtracr.realcamera.config.ConfigFile;
import com.xtracr.realcamera.config.ModConfig;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.option.KeyBinding;
import net.minecraft.client.util.InputUtil;
import org.lwjgl.glfw.GLFW;
public final class KeyBindings {
private static final ModConfig config = ConfigFile.modConfig;
private static final String KEY_CATEGORY = "key.category.xtracr_" + RealCamera.MODID;
private static final String KEY_ID = "key.xtracr_" + RealCamera.MODID + "_";
public static final KeyBinding TOGGLE_PERSPECTIVE = new KeyBinding(
KEY_ID + "togglePerspective", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_F6, KEY_CATEGORY);
public static final KeyBinding TOGGLE_ADJUST_MODE = new KeyBinding(
KEY_ID + "toggleAdjustMode", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding TOGGLE_CAMERA_MODE = new KeyBinding(
KEY_ID + "toggleCameraMode", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_UP = new KeyBinding(
KEY_ID + "adjustUP", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_DOWN = new KeyBinding(
KEY_ID + "adjustDOWN", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_FRONT = new KeyBinding(
KEY_ID + "adjustFRONT", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_BACK = new KeyBinding(
KEY_ID + "adjustBACK", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_LEFT = new KeyBinding(
KEY_ID + "adjustLEFT", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_RIGHT = new KeyBinding(
KEY_ID + "adjustRIGHT", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static void handle(MinecraftClient client) {
if (client.player == null || client.currentScreen != null) return;
while (TOGGLE_PERSPECTIVE.wasPressed()) {
boolean enabled = config.isEnabled();
ConfigFile.load();
config.setEnabled(!enabled);
ConfigFile.save();
}
while (TOGGLE_ADJUST_MODE.wasPressed()) {
if (config.isClassic()) config.cycleClassicAdjustMode();
else config.setAdjustOffset(!config.isAdjustingOffset());
ConfigFile.save();
}
while (TOGGLE_CAMERA_MODE.wasPressed()) {
config.setClassic(!config.isClassic());
ConfigFile.save();
}
while (ADJUST_LEFT.wasPressed()) {
if | (config.isClassic()) config.adjustClassicZ(true); |
else config.adjustBindingZ(true);
ConfigFile.save();
}
while (ADJUST_RIGHT.wasPressed()) {
if (config.isClassic()) config.adjustClassicZ(false);
else config.adjustBindingZ(false);
ConfigFile.save();
}
while (ADJUST_UP.wasPressed()) {
if (config.isClassic()) config.adjustClassicY(true);
else config.adjustBindingY(true);
ConfigFile.save();
}
while (ADJUST_DOWN.wasPressed()) {
if (config.isClassic()) config.adjustClassicY(false);
else config.adjustBindingY(false);
ConfigFile.save();
}
while (ADJUST_FRONT.wasPressed()) {
if (config.isClassic()) config.adjustClassicX(true);
else config.adjustBindingX(true);
ConfigFile.save();
}
while (ADJUST_BACK.wasPressed()) {
if (config.isClassic()) config.adjustClassicX(false);
else config.adjustBindingX(false);
ConfigFile.save();
}
}
}
| common/src/main/java/com/xtracr/realcamera/KeyBindings.java | xTracr-RealCamera-7675633 | [
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ConfigScreen.java",
"retrieved_chunk": " .setSaveConsumer(f -> config.binding.yaw = f)\n .build());\n bindingCameraRotation.add(entryBuilder.startFloatField(Text.translatable(OPTION + \"roll\"), config.binding.roll)\n .setDefaultValue(0.0F)\n .setMin(-180.0F)\n .setMax(180.0F)\n .setSaveConsumer(f -> config.binding.roll = f)\n .build());\n binding.addEntry(bindingCameraRotation.build());\n classic.addEntry(entryBuilder.startEnumSelector(Text.translatable(OPTION + \"classicAdjustMode\"), ModConfig.Classic.AdjustMode.class, config.classic.adjustMode)",
"score": 0.7223941087722778
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ModConfig.java",
"retrieved_chunk": " switch (classic.adjustMode) {\n case CENTER -> classic.centerZ += s * getAdjustStep();\n case ROTATION -> classic.pitch += s * 4 * (float) getAdjustStep();\n default -> classic.cameraZ += s * getAdjustStep();\n }\n classic.clamp();\n }\n // compats\n public boolean isUsingModModel() {\n return compats.useModModel;",
"score": 0.7025567293167114
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ConfigScreen.java",
"retrieved_chunk": " .setSaveConsumer(b -> config.binding.bindPitching = b)\n .build());\n bindingCameraRotation.add(entryBuilder.startBooleanToggle(Text.translatable(OPTION + \"bindYawing\"), config.binding.bindYawing)\n .setDefaultValue(true)\n .setSaveConsumer(b -> config.binding.bindYawing = b)\n .build());\n bindingCameraRotation.add(entryBuilder.startBooleanToggle(Text.translatable(OPTION + \"bindRolling\"), config.binding.bindRolling)\n .setDefaultValue(true)\n .setSaveConsumer(b -> config.binding.bindRolling = b)\n .build());",
"score": 0.6968863010406494
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ConfigScreen.java",
"retrieved_chunk": " .setSaveConsumer(d -> config.classic.cameraX = d)\n .build());\n classicCameraOffset.add(entryBuilder.startDoubleField(Text.translatable(OPTION + \"cameraOffset\", \"Y\"), config.classic.cameraY)\n .setDefaultValue(2.0D)\n .setMin(ModConfig.MIN_DOUBLE)\n .setMax(ModConfig.MAX_DOUBLE)\n .setSaveConsumer(d -> config.classic.cameraY = d)\n .build());\n classicCameraOffset.add(entryBuilder.startDoubleField(Text.translatable(OPTION + \"cameraOffset\", \"Z\"), config.classic.cameraZ)\n .setDefaultValue(-16.0D)",
"score": 0.6931875944137573
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ConfigScreen.java",
"retrieved_chunk": " .setDefaultValue(ModConfig.Classic.AdjustMode.CAMERA)\n .setTooltip(Text.translatable(TOOLTIP + \"classicAdjustMode\"))\n .setSaveConsumer(e -> config.classic.adjustMode = e)\n .build());\n SubCategoryBuilder classicCameraOffset = entryBuilder.startSubCategory(Text.translatable(CATEGORY + \"cameraOffset\"))\n .setTooltip(Text.translatable(TOOLTIP + \"classicOffset\"), Text.translatable(TOOLTIP + \"referOffset\"), Text.translatable(TOOLTIP + \"classicOffset_n\"));\n classicCameraOffset.add(entryBuilder.startDoubleField(Text.translatable(OPTION + \"cameraOffset\", \"X\"), config.classic.cameraX)\n .setDefaultValue(-60.0D)\n .setMin(ModConfig.MIN_DOUBLE)\n .setMax(ModConfig.MAX_DOUBLE)",
"score": 0.6927410364151001
}
] | java | (config.isClassic()) config.adjustClassicZ(true); |
package com.xtracr.realcamera;
import com.xtracr.realcamera.config.ConfigFile;
import com.xtracr.realcamera.config.ModConfig;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.option.KeyBinding;
import net.minecraft.client.util.InputUtil;
import org.lwjgl.glfw.GLFW;
public final class KeyBindings {
private static final ModConfig config = ConfigFile.modConfig;
private static final String KEY_CATEGORY = "key.category.xtracr_" + RealCamera.MODID;
private static final String KEY_ID = "key.xtracr_" + RealCamera.MODID + "_";
public static final KeyBinding TOGGLE_PERSPECTIVE = new KeyBinding(
KEY_ID + "togglePerspective", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_F6, KEY_CATEGORY);
public static final KeyBinding TOGGLE_ADJUST_MODE = new KeyBinding(
KEY_ID + "toggleAdjustMode", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding TOGGLE_CAMERA_MODE = new KeyBinding(
KEY_ID + "toggleCameraMode", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_UP = new KeyBinding(
KEY_ID + "adjustUP", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_DOWN = new KeyBinding(
KEY_ID + "adjustDOWN", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_FRONT = new KeyBinding(
KEY_ID + "adjustFRONT", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_BACK = new KeyBinding(
KEY_ID + "adjustBACK", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_LEFT = new KeyBinding(
KEY_ID + "adjustLEFT", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_RIGHT = new KeyBinding(
KEY_ID + "adjustRIGHT", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static void handle(MinecraftClient client) {
if (client.player == null || client.currentScreen != null) return;
while (TOGGLE_PERSPECTIVE.wasPressed()) {
boolean enabled = config.isEnabled();
ConfigFile.load();
config.setEnabled(!enabled);
ConfigFile.save();
}
while (TOGGLE_ADJUST_MODE.wasPressed()) {
if | (config.isClassic()) config.cycleClassicAdjustMode(); |
else config.setAdjustOffset(!config.isAdjustingOffset());
ConfigFile.save();
}
while (TOGGLE_CAMERA_MODE.wasPressed()) {
config.setClassic(!config.isClassic());
ConfigFile.save();
}
while (ADJUST_LEFT.wasPressed()) {
if (config.isClassic()) config.adjustClassicZ(true);
else config.adjustBindingZ(true);
ConfigFile.save();
}
while (ADJUST_RIGHT.wasPressed()) {
if (config.isClassic()) config.adjustClassicZ(false);
else config.adjustBindingZ(false);
ConfigFile.save();
}
while (ADJUST_UP.wasPressed()) {
if (config.isClassic()) config.adjustClassicY(true);
else config.adjustBindingY(true);
ConfigFile.save();
}
while (ADJUST_DOWN.wasPressed()) {
if (config.isClassic()) config.adjustClassicY(false);
else config.adjustBindingY(false);
ConfigFile.save();
}
while (ADJUST_FRONT.wasPressed()) {
if (config.isClassic()) config.adjustClassicX(true);
else config.adjustBindingX(true);
ConfigFile.save();
}
while (ADJUST_BACK.wasPressed()) {
if (config.isClassic()) config.adjustClassicX(false);
else config.adjustBindingX(false);
ConfigFile.save();
}
}
}
| common/src/main/java/com/xtracr/realcamera/KeyBindings.java | xTracr-RealCamera-7675633 | [
{
"filename": "common/src/main/java/com/xtracr/realcamera/RealCameraCore.java",
"retrieved_chunk": " && client.player != null && !config.disableModWhen(client);\n }\n public static void updateCamera(Camera camera, MinecraftClient client, float tickDelta) {\n cameraRoll = 0.0F;\n if (config.isRendering() && !config.disableRenderingWhen(client)) {\n ((CameraAccessor) camera).setThirdPerson(true);\n }\n if (config.isClassic()) {\n classicModeUpdate(camera, client, tickDelta);\n } else {",
"score": 0.7421215772628784
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ModConfig.java",
"retrieved_chunk": " switch (classic.adjustMode) {\n case CENTER -> classic.centerZ += s * getAdjustStep();\n case ROTATION -> classic.pitch += s * 4 * (float) getAdjustStep();\n default -> classic.cameraZ += s * getAdjustStep();\n }\n classic.clamp();\n }\n // compats\n public boolean isUsingModModel() {\n return compats.useModModel;",
"score": 0.7386077642440796
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ConfigScreen.java",
"retrieved_chunk": " .setSaveConsumer(b -> config.disable.sleeping = b)\n .build());\n disableModWhen.add(entryBuilder.startBooleanToggle(Text.translatable(OPTION + \"screenOpened\"), config.disable.screenOpened)\n .setDefaultValue(false)\n .setSaveConsumer(b -> config.disable.screenOpened = b)\n .build());\n disable.addEntry(disableModWhen.build());\n return builder.build();\n }\n}",
"score": 0.7255536317825317
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ModConfig.java",
"retrieved_chunk": " public void adjustClassicX(boolean add) {\n int s = add ? 1 : -1;\n switch (classic.adjustMode) {\n case CENTER -> classic.centerX += s * getAdjustStep();\n case ROTATION -> classic.roll += s * 4 * (float) getAdjustStep();\n default -> classic.cameraX += s * getAdjustStep();\n }\n classic.clamp();\n }\n public void adjustClassicY(boolean add) {",
"score": 0.7193450927734375
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ModConfig.java",
"retrieved_chunk": " int s = add ? 1 : -1;\n switch (classic.adjustMode) {\n case CENTER -> classic.centerY += s * getAdjustStep();\n case ROTATION -> classic.yaw += s * 4 * (float) getAdjustStep();\n default -> classic.cameraY += s * getAdjustStep();\n }\n classic.clamp();\n }\n public void adjustClassicZ(boolean add) {\n int s = add ? 1 : -1;",
"score": 0.7165212631225586
}
] | java | (config.isClassic()) config.cycleClassicAdjustMode(); |
package com.xtracr.realcamera.api;
import com.xtracr.realcamera.RealCameraCore;
import com.xtracr.realcamera.config.ConfigFile;
import com.xtracr.realcamera.config.ModConfig;
import net.minecraft.client.util.math.MatrixStack;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiPredicate;
/**
* @see CompatExample
*/
public class VirtualRenderer {
public static final ModConfig config = ConfigFile.modConfig;
private static final Map<String, BiPredicate<Float, MatrixStack>> functionProvider = new HashMap<>();
/**
* @param modid {@code mandatory}
* @param function {@code mandatory} turn to vanilla rendering if return true.
* {@link CompatExample#virtualRender See example here}
*/
public static void register(String modid, BiPredicate<Float, MatrixStack> function) {
functionProvider.put(modid, function);
}
/**
* @return the value of {@link com.xtracr.realcamera.config.ModConfig.Compats#modModelPart modModelPart}
* option in the config
*/
public static String getModelPartName() {
return config.getModModelPartName();
}
/**
* @see com.xtracr.realcamera.mixins.MixinPlayerEntityRenderer#onSetModelPoseRETURN
* MixinPlayerEntityRenderer.onSetModelPoseRETURN
*/
public static boolean shouldDisableRender(String modelPartName) {
ModConfig.Disable.optionalParts.add(modelPartName);
return RealCameraCore.isRenderingWorld && config.shouldDisableRender(modelPartName) && | RealCameraCore.isActive(); |
}
public static boolean virtualRender(float tickDelta, MatrixStack matrixStack) {
return functionProvider.get(config.getModelModID()).test(tickDelta, matrixStack);
}
public static String[] getModidList() {
return functionProvider.keySet().toArray(new String[functionProvider.size()]);
}
}
| common/src/main/java/com/xtracr/realcamera/api/VirtualRenderer.java | xTracr-RealCamera-7675633 | [
{
"filename": "forge/src/main/java/com/xtracr/realcamera/EventHandler.java",
"retrieved_chunk": " event.setYaw(camera.getYaw());\n event.setRoll(RealCameraCore.getRoll());\n }\n }\n @SubscribeEvent\n public static void onRenderWorldStage(RenderLevelStageEvent event) {\n if (RenderLevelStageEvent.Stage.AFTER_SKY.equals(event.getStage())) {\n RealCameraCore.isRenderingWorld = true;\n if (ConfigFile.modConfig.isCrosshairDynamic() && RealCameraCore.isActive()) {\n CrosshairUtils.update(MinecraftClient.getInstance(), event.getCamera(),",
"score": 0.809601902961731
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/mixins/MixinEntityRenderer.java",
"retrieved_chunk": "import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;\n@Mixin(EntityRenderer.class)\npublic abstract class MixinEntityRenderer {\n @Inject(method = \"shouldRender\", at = @At(\"HEAD\"), cancellable = true)\n private <T extends Entity> void onShouldRenderHEAD(T entity, Frustum frustum, double x, double y, double z,\n CallbackInfoReturnable<Boolean> cInfo) {\n if (ConfigFile.modConfig.isRendering() && RealCameraCore.isActive() && entity instanceof ClientPlayerEntity) {\n cInfo.setReturnValue(true);\n }\n }",
"score": 0.7934244871139526
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/mixins/MixinGameRenderer.java",
"retrieved_chunk": " .multiply(client.interactionManager.getReachDistance())).expand(1.0, 1.0, 1.0);\n CrosshairUtils.capturedEntityHitResult = ProjectileUtil.raycast(cameraEntity, startVec, endVec, box, entity -> !entity.isSpectator() && entity.canHit(), sqDistance);\n }\n return CrosshairUtils.capturedEntityHitResult;\n }\n @Inject(method = \"renderHand\", at = @At(value = \"INVOKE\",\n target = \"Lnet/minecraft/client/util/math/MatrixStack;push()V\"))\n private void setThirdPerson(MatrixStack matrices, Camera camera, float tickDelta, CallbackInfo cInfo) {\n if (ConfigFile.modConfig.isRendering() && camera.isThirdPerson() && RealCameraCore.isActive() &&\n !ConfigFile.modConfig.allowRenderingHandWhen(client)) {",
"score": 0.784953236579895
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ModConfig.java",
"retrieved_chunk": " public boolean shouldDisableRender(String modelPartName) {\n if (disable.onlyInBinding && general.classic) return false;\n return (disable.renderModelPart && disable.disabledModelParts.contains(modelPartName)) ||\n shouldDisable(MinecraftClient.getInstance(), modelPartName);\n }\n public boolean allowRenderingHandWhen(MinecraftClient client) {\n if (disable.onlyInBinding && general.classic) return false;\n return shouldDisable(client, \"allow_rendering_hand\");\n }\n public boolean disableModWhen(MinecraftClient client) {",
"score": 0.7740342617034912
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/mixins/MixinInGameHud.java",
"retrieved_chunk": "@Mixin(InGameHud.class)\npublic abstract class MixinInGameHud {\n @Inject(method = \"renderCrosshair(Lnet/minecraft/client/gui/DrawContext;)V\", at = @At(\"HEAD\"))\n private void onRenderCrosshairHEAD(DrawContext context, CallbackInfo cInfo) {\n if (ConfigFile.modConfig.isCrosshairDynamic() && RealCameraCore.isActive()) {\n context.getMatrices().push();\n CrosshairUtils.translateMatrices(context.getMatrices());\n }\n }\n @Inject(method = \"renderCrosshair(Lnet/minecraft/client/gui/DrawContext;)V\", at = @At(\"RETURN\"))",
"score": 0.7723139524459839
}
] | java | RealCameraCore.isActive(); |
package com.xtracr.realcamera;
import com.xtracr.realcamera.config.ConfigFile;
import com.xtracr.realcamera.config.ModConfig;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.option.KeyBinding;
import net.minecraft.client.util.InputUtil;
import org.lwjgl.glfw.GLFW;
public final class KeyBindings {
private static final ModConfig config = ConfigFile.modConfig;
private static final String KEY_CATEGORY = "key.category.xtracr_" + RealCamera.MODID;
private static final String KEY_ID = "key.xtracr_" + RealCamera.MODID + "_";
public static final KeyBinding TOGGLE_PERSPECTIVE = new KeyBinding(
KEY_ID + "togglePerspective", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_F6, KEY_CATEGORY);
public static final KeyBinding TOGGLE_ADJUST_MODE = new KeyBinding(
KEY_ID + "toggleAdjustMode", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding TOGGLE_CAMERA_MODE = new KeyBinding(
KEY_ID + "toggleCameraMode", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_UP = new KeyBinding(
KEY_ID + "adjustUP", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_DOWN = new KeyBinding(
KEY_ID + "adjustDOWN", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_FRONT = new KeyBinding(
KEY_ID + "adjustFRONT", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_BACK = new KeyBinding(
KEY_ID + "adjustBACK", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_LEFT = new KeyBinding(
KEY_ID + "adjustLEFT", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_RIGHT = new KeyBinding(
KEY_ID + "adjustRIGHT", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static void handle(MinecraftClient client) {
if (client.player == null || client.currentScreen != null) return;
while (TOGGLE_PERSPECTIVE.wasPressed()) {
boolean enabled = config.isEnabled();
ConfigFile.load();
config.setEnabled(!enabled);
ConfigFile.save();
}
while (TOGGLE_ADJUST_MODE.wasPressed()) {
if (config.isClassic()) config.cycleClassicAdjustMode();
else config.setAdjustOffset(!config.isAdjustingOffset());
ConfigFile.save();
}
while (TOGGLE_CAMERA_MODE.wasPressed()) {
config.setClassic( | !config.isClassic()); |
ConfigFile.save();
}
while (ADJUST_LEFT.wasPressed()) {
if (config.isClassic()) config.adjustClassicZ(true);
else config.adjustBindingZ(true);
ConfigFile.save();
}
while (ADJUST_RIGHT.wasPressed()) {
if (config.isClassic()) config.adjustClassicZ(false);
else config.adjustBindingZ(false);
ConfigFile.save();
}
while (ADJUST_UP.wasPressed()) {
if (config.isClassic()) config.adjustClassicY(true);
else config.adjustBindingY(true);
ConfigFile.save();
}
while (ADJUST_DOWN.wasPressed()) {
if (config.isClassic()) config.adjustClassicY(false);
else config.adjustBindingY(false);
ConfigFile.save();
}
while (ADJUST_FRONT.wasPressed()) {
if (config.isClassic()) config.adjustClassicX(true);
else config.adjustBindingX(true);
ConfigFile.save();
}
while (ADJUST_BACK.wasPressed()) {
if (config.isClassic()) config.adjustClassicX(false);
else config.adjustBindingX(false);
ConfigFile.save();
}
}
}
| common/src/main/java/com/xtracr/realcamera/KeyBindings.java | xTracr-RealCamera-7675633 | [
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ConfigScreen.java",
"retrieved_chunk": " .setSaveConsumer(f -> config.binding.yaw = f)\n .build());\n bindingCameraRotation.add(entryBuilder.startFloatField(Text.translatable(OPTION + \"roll\"), config.binding.roll)\n .setDefaultValue(0.0F)\n .setMin(-180.0F)\n .setMax(180.0F)\n .setSaveConsumer(f -> config.binding.roll = f)\n .build());\n binding.addEntry(bindingCameraRotation.build());\n classic.addEntry(entryBuilder.startEnumSelector(Text.translatable(OPTION + \"classicAdjustMode\"), ModConfig.Classic.AdjustMode.class, config.classic.adjustMode)",
"score": 0.7201350927352905
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ModConfig.java",
"retrieved_chunk": " switch (classic.adjustMode) {\n case CENTER -> classic.centerZ += s * getAdjustStep();\n case ROTATION -> classic.pitch += s * 4 * (float) getAdjustStep();\n default -> classic.cameraZ += s * getAdjustStep();\n }\n classic.clamp();\n }\n // compats\n public boolean isUsingModModel() {\n return compats.useModModel;",
"score": 0.7060104608535767
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ConfigScreen.java",
"retrieved_chunk": " .setSaveConsumer(b -> config.disable.sleeping = b)\n .build());\n disableModWhen.add(entryBuilder.startBooleanToggle(Text.translatable(OPTION + \"screenOpened\"), config.disable.screenOpened)\n .setDefaultValue(false)\n .setSaveConsumer(b -> config.disable.screenOpened = b)\n .build());\n disable.addEntry(disableModWhen.build());\n return builder.build();\n }\n}",
"score": 0.695056676864624
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ConfigScreen.java",
"retrieved_chunk": " .setSaveConsumer(b -> config.binding.bindPitching = b)\n .build());\n bindingCameraRotation.add(entryBuilder.startBooleanToggle(Text.translatable(OPTION + \"bindYawing\"), config.binding.bindYawing)\n .setDefaultValue(true)\n .setSaveConsumer(b -> config.binding.bindYawing = b)\n .build());\n bindingCameraRotation.add(entryBuilder.startBooleanToggle(Text.translatable(OPTION + \"bindRolling\"), config.binding.bindRolling)\n .setDefaultValue(true)\n .setSaveConsumer(b -> config.binding.bindRolling = b)\n .build());",
"score": 0.6914039850234985
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ModConfig.java",
"retrieved_chunk": " public void adjustClassicX(boolean add) {\n int s = add ? 1 : -1;\n switch (classic.adjustMode) {\n case CENTER -> classic.centerX += s * getAdjustStep();\n case ROTATION -> classic.roll += s * 4 * (float) getAdjustStep();\n default -> classic.cameraX += s * getAdjustStep();\n }\n classic.clamp();\n }\n public void adjustClassicY(boolean add) {",
"score": 0.6858713030815125
}
] | java | !config.isClassic()); |
package com.xtracr.realcamera;
import com.xtracr.realcamera.config.ConfigFile;
import com.xtracr.realcamera.config.ModConfig;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.option.KeyBinding;
import net.minecraft.client.util.InputUtil;
import org.lwjgl.glfw.GLFW;
public final class KeyBindings {
private static final ModConfig config = ConfigFile.modConfig;
private static final String KEY_CATEGORY = "key.category.xtracr_" + RealCamera.MODID;
private static final String KEY_ID = "key.xtracr_" + RealCamera.MODID + "_";
public static final KeyBinding TOGGLE_PERSPECTIVE = new KeyBinding(
KEY_ID + "togglePerspective", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_F6, KEY_CATEGORY);
public static final KeyBinding TOGGLE_ADJUST_MODE = new KeyBinding(
KEY_ID + "toggleAdjustMode", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding TOGGLE_CAMERA_MODE = new KeyBinding(
KEY_ID + "toggleCameraMode", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_UP = new KeyBinding(
KEY_ID + "adjustUP", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_DOWN = new KeyBinding(
KEY_ID + "adjustDOWN", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_FRONT = new KeyBinding(
KEY_ID + "adjustFRONT", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_BACK = new KeyBinding(
KEY_ID + "adjustBACK", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_LEFT = new KeyBinding(
KEY_ID + "adjustLEFT", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_RIGHT = new KeyBinding(
KEY_ID + "adjustRIGHT", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static void handle(MinecraftClient client) {
if (client.player == null || client.currentScreen != null) return;
while (TOGGLE_PERSPECTIVE.wasPressed()) {
boolean enabled = config.isEnabled();
ConfigFile.load();
config.setEnabled(!enabled);
ConfigFile.save();
}
while (TOGGLE_ADJUST_MODE.wasPressed()) {
if ( | config.isClassic()) config.cycleClassicAdjustMode(); |
else config.setAdjustOffset(!config.isAdjustingOffset());
ConfigFile.save();
}
while (TOGGLE_CAMERA_MODE.wasPressed()) {
config.setClassic(!config.isClassic());
ConfigFile.save();
}
while (ADJUST_LEFT.wasPressed()) {
if (config.isClassic()) config.adjustClassicZ(true);
else config.adjustBindingZ(true);
ConfigFile.save();
}
while (ADJUST_RIGHT.wasPressed()) {
if (config.isClassic()) config.adjustClassicZ(false);
else config.adjustBindingZ(false);
ConfigFile.save();
}
while (ADJUST_UP.wasPressed()) {
if (config.isClassic()) config.adjustClassicY(true);
else config.adjustBindingY(true);
ConfigFile.save();
}
while (ADJUST_DOWN.wasPressed()) {
if (config.isClassic()) config.adjustClassicY(false);
else config.adjustBindingY(false);
ConfigFile.save();
}
while (ADJUST_FRONT.wasPressed()) {
if (config.isClassic()) config.adjustClassicX(true);
else config.adjustBindingX(true);
ConfigFile.save();
}
while (ADJUST_BACK.wasPressed()) {
if (config.isClassic()) config.adjustClassicX(false);
else config.adjustBindingX(false);
ConfigFile.save();
}
}
}
| common/src/main/java/com/xtracr/realcamera/KeyBindings.java | xTracr-RealCamera-7675633 | [
{
"filename": "common/src/main/java/com/xtracr/realcamera/RealCameraCore.java",
"retrieved_chunk": " && client.player != null && !config.disableModWhen(client);\n }\n public static void updateCamera(Camera camera, MinecraftClient client, float tickDelta) {\n cameraRoll = 0.0F;\n if (config.isRendering() && !config.disableRenderingWhen(client)) {\n ((CameraAccessor) camera).setThirdPerson(true);\n }\n if (config.isClassic()) {\n classicModeUpdate(camera, client, tickDelta);\n } else {",
"score": 0.7595492601394653
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ModConfig.java",
"retrieved_chunk": " switch (classic.adjustMode) {\n case CENTER -> classic.centerZ += s * getAdjustStep();\n case ROTATION -> classic.pitch += s * 4 * (float) getAdjustStep();\n default -> classic.cameraZ += s * getAdjustStep();\n }\n classic.clamp();\n }\n // compats\n public boolean isUsingModModel() {\n return compats.useModModel;",
"score": 0.7557536363601685
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ModConfig.java",
"retrieved_chunk": " public void adjustClassicX(boolean add) {\n int s = add ? 1 : -1;\n switch (classic.adjustMode) {\n case CENTER -> classic.centerX += s * getAdjustStep();\n case ROTATION -> classic.roll += s * 4 * (float) getAdjustStep();\n default -> classic.cameraX += s * getAdjustStep();\n }\n classic.clamp();\n }\n public void adjustClassicY(boolean add) {",
"score": 0.7404627799987793
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ModConfig.java",
"retrieved_chunk": " int s = add ? 1 : -1;\n switch (classic.adjustMode) {\n case CENTER -> classic.centerY += s * getAdjustStep();\n case ROTATION -> classic.yaw += s * 4 * (float) getAdjustStep();\n default -> classic.cameraY += s * getAdjustStep();\n }\n classic.clamp();\n }\n public void adjustClassicZ(boolean add) {\n int s = add ? 1 : -1;",
"score": 0.7390156984329224
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/mixins/MixinGameRenderer.java",
"retrieved_chunk": " client.options.setPerspective(Perspective.THIRD_PERSON_BACK);\n toggled = true;\n }\n }\n @Inject(method = \"renderHand\", at = @At(value = \"INVOKE\",\n target = \"Lnet/minecraft/client/util/math/MatrixStack;pop()V\"))\n private void setFirstPerson(CallbackInfo cInfo) {\n if (toggled) {\n client.options.setPerspective(Perspective.FIRST_PERSON);\n toggled = false;",
"score": 0.7254257202148438
}
] | java | config.isClassic()) config.cycleClassicAdjustMode(); |
package com.xtracr.realcamera;
import com.xtracr.realcamera.config.ConfigFile;
import com.xtracr.realcamera.config.ModConfig;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.option.KeyBinding;
import net.minecraft.client.util.InputUtil;
import org.lwjgl.glfw.GLFW;
public final class KeyBindings {
private static final ModConfig config = ConfigFile.modConfig;
private static final String KEY_CATEGORY = "key.category.xtracr_" + RealCamera.MODID;
private static final String KEY_ID = "key.xtracr_" + RealCamera.MODID + "_";
public static final KeyBinding TOGGLE_PERSPECTIVE = new KeyBinding(
KEY_ID + "togglePerspective", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_F6, KEY_CATEGORY);
public static final KeyBinding TOGGLE_ADJUST_MODE = new KeyBinding(
KEY_ID + "toggleAdjustMode", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding TOGGLE_CAMERA_MODE = new KeyBinding(
KEY_ID + "toggleCameraMode", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_UP = new KeyBinding(
KEY_ID + "adjustUP", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_DOWN = new KeyBinding(
KEY_ID + "adjustDOWN", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_FRONT = new KeyBinding(
KEY_ID + "adjustFRONT", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_BACK = new KeyBinding(
KEY_ID + "adjustBACK", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_LEFT = new KeyBinding(
KEY_ID + "adjustLEFT", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_RIGHT = new KeyBinding(
KEY_ID + "adjustRIGHT", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static void handle(MinecraftClient client) {
if (client.player == null || client.currentScreen != null) return;
while (TOGGLE_PERSPECTIVE.wasPressed()) {
boolean enabled = | config.isEnabled(); |
ConfigFile.load();
config.setEnabled(!enabled);
ConfigFile.save();
}
while (TOGGLE_ADJUST_MODE.wasPressed()) {
if (config.isClassic()) config.cycleClassicAdjustMode();
else config.setAdjustOffset(!config.isAdjustingOffset());
ConfigFile.save();
}
while (TOGGLE_CAMERA_MODE.wasPressed()) {
config.setClassic(!config.isClassic());
ConfigFile.save();
}
while (ADJUST_LEFT.wasPressed()) {
if (config.isClassic()) config.adjustClassicZ(true);
else config.adjustBindingZ(true);
ConfigFile.save();
}
while (ADJUST_RIGHT.wasPressed()) {
if (config.isClassic()) config.adjustClassicZ(false);
else config.adjustBindingZ(false);
ConfigFile.save();
}
while (ADJUST_UP.wasPressed()) {
if (config.isClassic()) config.adjustClassicY(true);
else config.adjustBindingY(true);
ConfigFile.save();
}
while (ADJUST_DOWN.wasPressed()) {
if (config.isClassic()) config.adjustClassicY(false);
else config.adjustBindingY(false);
ConfigFile.save();
}
while (ADJUST_FRONT.wasPressed()) {
if (config.isClassic()) config.adjustClassicX(true);
else config.adjustBindingX(true);
ConfigFile.save();
}
while (ADJUST_BACK.wasPressed()) {
if (config.isClassic()) config.adjustClassicX(false);
else config.adjustBindingX(false);
ConfigFile.save();
}
}
}
| common/src/main/java/com/xtracr/realcamera/KeyBindings.java | xTracr-RealCamera-7675633 | [
{
"filename": "forge/src/main/java/com/xtracr/realcamera/RealCameraForge.java",
"retrieved_chunk": " @SubscribeEvent\n public void onKeyRegister(RegisterKeyMappingsEvent event) {\n event.register(KeyBindings.TOGGLE_PERSPECTIVE);\n event.register(KeyBindings.TOGGLE_ADJUST_MODE);\n event.register(KeyBindings.TOGGLE_CAMERA_MODE);\n event.register(KeyBindings.ADJUST_UP);\n event.register(KeyBindings.ADJUST_DOWN);\n event.register(KeyBindings.ADJUST_BACK);\n event.register(KeyBindings.ADJUST_FRONT);\n event.register(KeyBindings.ADJUST_LEFT);",
"score": 0.7884382009506226
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ConfigScreen.java",
"retrieved_chunk": "import java.util.List;\nimport java.util.Optional;\npublic class ConfigScreen {\n private static final String CATEGORY = \"config.category.xtracr_\" + RealCamera.MODID + \"_\";\n private static final String OPTION = \"config.option.xtracr_\" + RealCamera.MODID + \"_\";\n private static final String TOOLTIP = \"config.tooltip.xtracr_\" + RealCamera.MODID + \"_\";\n public static Screen create(Screen parent) {\n ConfigFile.load();\n final ModConfig config = ConfigFile.modConfig;\n final ConfigBuilder builder = ConfigBuilder.create()",
"score": 0.768383264541626
},
{
"filename": "fabric/src/main/java/com/xtracr/realcamera/RealCameraFabric.java",
"retrieved_chunk": " public void onInitializeClient() {\n RealCamera.setup();\n ClientTickEvents.END_CLIENT_TICK.register(KeyBindings::handle);\n WorldRenderEvents.START.register(EventHandler::onWorldRenderStart);\n WorldRenderEvents.END.register(context -> RealCameraCore.isRenderingWorld = false);\n KeyBindingHelper.registerKeyBinding(KeyBindings.TOGGLE_PERSPECTIVE);\n KeyBindingHelper.registerKeyBinding(KeyBindings.TOGGLE_ADJUST_MODE);\n KeyBindingHelper.registerKeyBinding(KeyBindings.TOGGLE_CAMERA_MODE);\n KeyBindingHelper.registerKeyBinding(KeyBindings.ADJUST_UP);\n KeyBindingHelper.registerKeyBinding(KeyBindings.ADJUST_DOWN);",
"score": 0.7603803277015686
},
{
"filename": "forge/src/main/java/com/xtracr/realcamera/EventHandler.java",
"retrieved_chunk": " @SubscribeEvent\n public static void onKeyInput(Key event) {\n KeyBindings.handle(MinecraftClient.getInstance());\n }\n @SubscribeEvent\n public static void onCameraUpdate(ComputeCameraAngles event) {\n if (RealCameraCore.isActive()) {\n Camera camera = event.getCamera();\n RealCameraCore.updateCamera(camera, event.getRenderer().getClient(), (float) event.getPartialTick());\n event.setPitch(camera.getPitch());",
"score": 0.7454487085342407
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ModConfig.java",
"retrieved_chunk": " public double scale = 1.0D;\n private void clamp() {\n adjustStep = MathHelper.clamp(adjustStep, 0.0D, MAX_DOUBLE);\n scale = MathHelper.clamp(scale, 0.0D, MAX_DOUBLE);\n }\n }\n public static class Binding {\n public VanillaModelPart vanillaModelPart = VanillaModelPart.head;\n public boolean adjustOffset = true;\n public double cameraX = 3.25D;",
"score": 0.7375857830047607
}
] | java | config.isEnabled(); |
package com.xtracr.realcamera;
import com.xtracr.realcamera.config.ConfigFile;
import com.xtracr.realcamera.config.ModConfig;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.option.KeyBinding;
import net.minecraft.client.util.InputUtil;
import org.lwjgl.glfw.GLFW;
public final class KeyBindings {
private static final ModConfig config = ConfigFile.modConfig;
private static final String KEY_CATEGORY = "key.category.xtracr_" + RealCamera.MODID;
private static final String KEY_ID = "key.xtracr_" + RealCamera.MODID + "_";
public static final KeyBinding TOGGLE_PERSPECTIVE = new KeyBinding(
KEY_ID + "togglePerspective", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_F6, KEY_CATEGORY);
public static final KeyBinding TOGGLE_ADJUST_MODE = new KeyBinding(
KEY_ID + "toggleAdjustMode", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding TOGGLE_CAMERA_MODE = new KeyBinding(
KEY_ID + "toggleCameraMode", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_UP = new KeyBinding(
KEY_ID + "adjustUP", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_DOWN = new KeyBinding(
KEY_ID + "adjustDOWN", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_FRONT = new KeyBinding(
KEY_ID + "adjustFRONT", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_BACK = new KeyBinding(
KEY_ID + "adjustBACK", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_LEFT = new KeyBinding(
KEY_ID + "adjustLEFT", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_RIGHT = new KeyBinding(
KEY_ID + "adjustRIGHT", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static void handle(MinecraftClient client) {
if (client.player == null || client.currentScreen != null) return;
while (TOGGLE_PERSPECTIVE.wasPressed()) {
boolean enabled = config.isEnabled();
ConfigFile.load();
config.setEnabled(!enabled);
ConfigFile.save();
}
while (TOGGLE_ADJUST_MODE.wasPressed()) {
if (config.isClassic()) config.cycleClassicAdjustMode();
else config.setAdjustOffset(!config.isAdjustingOffset());
ConfigFile.save();
}
while (TOGGLE_CAMERA_MODE.wasPressed()) {
config.setClassic(!config.isClassic());
ConfigFile.save();
}
while (ADJUST_LEFT.wasPressed()) {
if (config.isClassic( | )) config.adjustClassicZ(true); |
else config.adjustBindingZ(true);
ConfigFile.save();
}
while (ADJUST_RIGHT.wasPressed()) {
if (config.isClassic()) config.adjustClassicZ(false);
else config.adjustBindingZ(false);
ConfigFile.save();
}
while (ADJUST_UP.wasPressed()) {
if (config.isClassic()) config.adjustClassicY(true);
else config.adjustBindingY(true);
ConfigFile.save();
}
while (ADJUST_DOWN.wasPressed()) {
if (config.isClassic()) config.adjustClassicY(false);
else config.adjustBindingY(false);
ConfigFile.save();
}
while (ADJUST_FRONT.wasPressed()) {
if (config.isClassic()) config.adjustClassicX(true);
else config.adjustBindingX(true);
ConfigFile.save();
}
while (ADJUST_BACK.wasPressed()) {
if (config.isClassic()) config.adjustClassicX(false);
else config.adjustBindingX(false);
ConfigFile.save();
}
}
}
| common/src/main/java/com/xtracr/realcamera/KeyBindings.java | xTracr-RealCamera-7675633 | [
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ConfigScreen.java",
"retrieved_chunk": " .setSaveConsumer(f -> config.binding.yaw = f)\n .build());\n bindingCameraRotation.add(entryBuilder.startFloatField(Text.translatable(OPTION + \"roll\"), config.binding.roll)\n .setDefaultValue(0.0F)\n .setMin(-180.0F)\n .setMax(180.0F)\n .setSaveConsumer(f -> config.binding.roll = f)\n .build());\n binding.addEntry(bindingCameraRotation.build());\n classic.addEntry(entryBuilder.startEnumSelector(Text.translatable(OPTION + \"classicAdjustMode\"), ModConfig.Classic.AdjustMode.class, config.classic.adjustMode)",
"score": 0.7187641263008118
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ModConfig.java",
"retrieved_chunk": " switch (classic.adjustMode) {\n case CENTER -> classic.centerZ += s * getAdjustStep();\n case ROTATION -> classic.pitch += s * 4 * (float) getAdjustStep();\n default -> classic.cameraZ += s * getAdjustStep();\n }\n classic.clamp();\n }\n // compats\n public boolean isUsingModModel() {\n return compats.useModModel;",
"score": 0.7089234590530396
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ConfigScreen.java",
"retrieved_chunk": " .setSaveConsumer(d -> config.classic.cameraX = d)\n .build());\n classicCameraOffset.add(entryBuilder.startDoubleField(Text.translatable(OPTION + \"cameraOffset\", \"Y\"), config.classic.cameraY)\n .setDefaultValue(2.0D)\n .setMin(ModConfig.MIN_DOUBLE)\n .setMax(ModConfig.MAX_DOUBLE)\n .setSaveConsumer(d -> config.classic.cameraY = d)\n .build());\n classicCameraOffset.add(entryBuilder.startDoubleField(Text.translatable(OPTION + \"cameraOffset\", \"Z\"), config.classic.cameraZ)\n .setDefaultValue(-16.0D)",
"score": 0.6912514567375183
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ConfigScreen.java",
"retrieved_chunk": " .setSaveConsumer(b -> config.binding.bindPitching = b)\n .build());\n bindingCameraRotation.add(entryBuilder.startBooleanToggle(Text.translatable(OPTION + \"bindYawing\"), config.binding.bindYawing)\n .setDefaultValue(true)\n .setSaveConsumer(b -> config.binding.bindYawing = b)\n .build());\n bindingCameraRotation.add(entryBuilder.startBooleanToggle(Text.translatable(OPTION + \"bindRolling\"), config.binding.bindRolling)\n .setDefaultValue(true)\n .setSaveConsumer(b -> config.binding.bindRolling = b)\n .build());",
"score": 0.6909369230270386
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ConfigScreen.java",
"retrieved_chunk": " .setSaveConsumer(b -> config.disable.sleeping = b)\n .build());\n disableModWhen.add(entryBuilder.startBooleanToggle(Text.translatable(OPTION + \"screenOpened\"), config.disable.screenOpened)\n .setDefaultValue(false)\n .setSaveConsumer(b -> config.disable.screenOpened = b)\n .build());\n disable.addEntry(disableModWhen.build());\n return builder.build();\n }\n}",
"score": 0.6896829605102539
}
] | java | )) config.adjustClassicZ(true); |
package com.xtracr.realcamera.api;
import com.xtracr.realcamera.RealCameraCore;
import com.xtracr.realcamera.config.ConfigFile;
import com.xtracr.realcamera.config.ModConfig;
import net.minecraft.client.util.math.MatrixStack;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiPredicate;
/**
* @see CompatExample
*/
public class VirtualRenderer {
public static final ModConfig config = ConfigFile.modConfig;
private static final Map<String, BiPredicate<Float, MatrixStack>> functionProvider = new HashMap<>();
/**
* @param modid {@code mandatory}
* @param function {@code mandatory} turn to vanilla rendering if return true.
* {@link CompatExample#virtualRender See example here}
*/
public static void register(String modid, BiPredicate<Float, MatrixStack> function) {
functionProvider.put(modid, function);
}
/**
* @return the value of {@link com.xtracr.realcamera.config.ModConfig.Compats#modModelPart modModelPart}
* option in the config
*/
public static String getModelPartName() {
| return config.getModModelPartName(); |
}
/**
* @see com.xtracr.realcamera.mixins.MixinPlayerEntityRenderer#onSetModelPoseRETURN
* MixinPlayerEntityRenderer.onSetModelPoseRETURN
*/
public static boolean shouldDisableRender(String modelPartName) {
ModConfig.Disable.optionalParts.add(modelPartName);
return RealCameraCore.isRenderingWorld && config.shouldDisableRender(modelPartName) && RealCameraCore.isActive();
}
public static boolean virtualRender(float tickDelta, MatrixStack matrixStack) {
return functionProvider.get(config.getModelModID()).test(tickDelta, matrixStack);
}
public static String[] getModidList() {
return functionProvider.keySet().toArray(new String[functionProvider.size()]);
}
}
| common/src/main/java/com/xtracr/realcamera/api/VirtualRenderer.java | xTracr-RealCamera-7675633 | [
{
"filename": "common/src/main/java/com/xtracr/realcamera/api/CompatExample.java",
"retrieved_chunk": " public static final String modid = \"minecraft\";\n private static final Map<String, String> nameMap = new HashMap<>();\n /**\n * {@code = VirtualRenderer.class.getDeclaredMethod(\"getModelPartName\")}\n *\n * <p>return the value of {@link com.xtracr.realcamera.config.ModConfig.Compats#modModelPart modModelPart}\n * option in the config.</p>\n *\n * @see #register()\n * @see VirtualRenderer#getModelPartName() getModelPartName()",
"score": 0.8934401273727417
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/api/CompatExample.java",
"retrieved_chunk": " getModelPartNameMethod = virtualRendererClass.getDeclaredMethod(\"getModelPartName\");\n final Method registerMethod = virtualRendererClass.getDeclaredMethod(\"register\", String.class, BiPredicate.class);\n final BiPredicate<Float, MatrixStack> function = CompatExample::virtualRender;\n registerMethod.invoke(null, modid, function);\n } catch (Exception exception) {\n // handle exception\n }\n }\n /**\n * <b>mandatory</b>",
"score": 0.8234645128250122
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ModConfig.java",
"retrieved_chunk": " }\n public String getModelModID() {\n return compats.modelModID;\n }\n public String getModModelPartName() {\n return compats.modModelPart;\n }\n public boolean compatDoABarrelRoll() {\n return compats.doABarrelRoll;\n }",
"score": 0.8100433349609375
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/api/CompatExample.java",
"retrieved_chunk": " * Your should register before the first time camera setup.\n *\n * <p>This method is called in {@link com.xtracr.realcamera.RealCamera#setup()}.</p>\n *\n * @see VirtualRenderer#register(String, BiPredicate)\n */\n public static void register() {\n //if ( Real Camera isn't loaded ) return;\n try {\n final Class<?> virtualRendererClass = Class.forName(\"com.xtracr.realcamera.api.VirtualRenderer\");",
"score": 0.7959984540939331
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ConfigScreen.java",
"retrieved_chunk": "import java.util.List;\nimport java.util.Optional;\npublic class ConfigScreen {\n private static final String CATEGORY = \"config.category.xtracr_\" + RealCamera.MODID + \"_\";\n private static final String OPTION = \"config.option.xtracr_\" + RealCamera.MODID + \"_\";\n private static final String TOOLTIP = \"config.tooltip.xtracr_\" + RealCamera.MODID + \"_\";\n public static Screen create(Screen parent) {\n ConfigFile.load();\n final ModConfig config = ConfigFile.modConfig;\n final ConfigBuilder builder = ConfigBuilder.create()",
"score": 0.7766014337539673
}
] | java | return config.getModModelPartName(); |
package com.xtracr.realcamera;
import com.xtracr.realcamera.config.ConfigFile;
import com.xtracr.realcamera.config.ModConfig;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.option.KeyBinding;
import net.minecraft.client.util.InputUtil;
import org.lwjgl.glfw.GLFW;
public final class KeyBindings {
private static final ModConfig config = ConfigFile.modConfig;
private static final String KEY_CATEGORY = "key.category.xtracr_" + RealCamera.MODID;
private static final String KEY_ID = "key.xtracr_" + RealCamera.MODID + "_";
public static final KeyBinding TOGGLE_PERSPECTIVE = new KeyBinding(
KEY_ID + "togglePerspective", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_F6, KEY_CATEGORY);
public static final KeyBinding TOGGLE_ADJUST_MODE = new KeyBinding(
KEY_ID + "toggleAdjustMode", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding TOGGLE_CAMERA_MODE = new KeyBinding(
KEY_ID + "toggleCameraMode", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_UP = new KeyBinding(
KEY_ID + "adjustUP", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_DOWN = new KeyBinding(
KEY_ID + "adjustDOWN", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_FRONT = new KeyBinding(
KEY_ID + "adjustFRONT", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_BACK = new KeyBinding(
KEY_ID + "adjustBACK", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_LEFT = new KeyBinding(
KEY_ID + "adjustLEFT", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_RIGHT = new KeyBinding(
KEY_ID + "adjustRIGHT", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static void handle(MinecraftClient client) {
if (client.player == null || client.currentScreen != null) return;
while (TOGGLE_PERSPECTIVE.wasPressed()) {
boolean enabled = config.isEnabled();
ConfigFile.load();
config.setEnabled(!enabled);
ConfigFile.save();
}
while (TOGGLE_ADJUST_MODE.wasPressed()) {
if (config.isClassic()) config.cycleClassicAdjustMode();
else config.setAdjustOffset(!config.isAdjustingOffset());
ConfigFile.save();
}
while (TOGGLE_CAMERA_MODE.wasPressed()) {
config.setClassic(!config.isClassic());
ConfigFile.save();
}
while (ADJUST_LEFT.wasPressed()) {
if (config.isClassic()) config.adjustClassicZ(true);
else | config.adjustBindingZ(true); |
ConfigFile.save();
}
while (ADJUST_RIGHT.wasPressed()) {
if (config.isClassic()) config.adjustClassicZ(false);
else config.adjustBindingZ(false);
ConfigFile.save();
}
while (ADJUST_UP.wasPressed()) {
if (config.isClassic()) config.adjustClassicY(true);
else config.adjustBindingY(true);
ConfigFile.save();
}
while (ADJUST_DOWN.wasPressed()) {
if (config.isClassic()) config.adjustClassicY(false);
else config.adjustBindingY(false);
ConfigFile.save();
}
while (ADJUST_FRONT.wasPressed()) {
if (config.isClassic()) config.adjustClassicX(true);
else config.adjustBindingX(true);
ConfigFile.save();
}
while (ADJUST_BACK.wasPressed()) {
if (config.isClassic()) config.adjustClassicX(false);
else config.adjustBindingX(false);
ConfigFile.save();
}
}
}
| common/src/main/java/com/xtracr/realcamera/KeyBindings.java | xTracr-RealCamera-7675633 | [
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ConfigScreen.java",
"retrieved_chunk": " .setSaveConsumer(f -> config.binding.yaw = f)\n .build());\n bindingCameraRotation.add(entryBuilder.startFloatField(Text.translatable(OPTION + \"roll\"), config.binding.roll)\n .setDefaultValue(0.0F)\n .setMin(-180.0F)\n .setMax(180.0F)\n .setSaveConsumer(f -> config.binding.roll = f)\n .build());\n binding.addEntry(bindingCameraRotation.build());\n classic.addEntry(entryBuilder.startEnumSelector(Text.translatable(OPTION + \"classicAdjustMode\"), ModConfig.Classic.AdjustMode.class, config.classic.adjustMode)",
"score": 0.7232036590576172
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ModConfig.java",
"retrieved_chunk": " switch (classic.adjustMode) {\n case CENTER -> classic.centerZ += s * getAdjustStep();\n case ROTATION -> classic.pitch += s * 4 * (float) getAdjustStep();\n default -> classic.cameraZ += s * getAdjustStep();\n }\n classic.clamp();\n }\n // compats\n public boolean isUsingModModel() {\n return compats.useModModel;",
"score": 0.7155829668045044
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ConfigScreen.java",
"retrieved_chunk": " .setSaveConsumer(b -> config.binding.bindPitching = b)\n .build());\n bindingCameraRotation.add(entryBuilder.startBooleanToggle(Text.translatable(OPTION + \"bindYawing\"), config.binding.bindYawing)\n .setDefaultValue(true)\n .setSaveConsumer(b -> config.binding.bindYawing = b)\n .build());\n bindingCameraRotation.add(entryBuilder.startBooleanToggle(Text.translatable(OPTION + \"bindRolling\"), config.binding.bindRolling)\n .setDefaultValue(true)\n .setSaveConsumer(b -> config.binding.bindRolling = b)\n .build());",
"score": 0.7106922268867493
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ModConfig.java",
"retrieved_chunk": " }\n public void adjustBindingZ(boolean add) {\n int s = add ? 1 : -1;\n if (isAdjustingOffset()) binding.cameraZ += s * getAdjustStep();\n else binding.pitch += s * 4 * (float) getAdjustStep();\n binding.clamp();\n }\n // classic\n public Classic.AdjustMode getClassicAdjustMode() {\n return classic.adjustMode;",
"score": 0.7039361000061035
},
{
"filename": "forge/src/main/java/com/xtracr/realcamera/RealCameraForge.java",
"retrieved_chunk": " @SubscribeEvent\n public void onKeyRegister(RegisterKeyMappingsEvent event) {\n event.register(KeyBindings.TOGGLE_PERSPECTIVE);\n event.register(KeyBindings.TOGGLE_ADJUST_MODE);\n event.register(KeyBindings.TOGGLE_CAMERA_MODE);\n event.register(KeyBindings.ADJUST_UP);\n event.register(KeyBindings.ADJUST_DOWN);\n event.register(KeyBindings.ADJUST_BACK);\n event.register(KeyBindings.ADJUST_FRONT);\n event.register(KeyBindings.ADJUST_LEFT);",
"score": 0.7031421065330505
}
] | java | config.adjustBindingZ(true); |
package io.xzxj.canal.core.factory;
import com.alibaba.otter.canal.protocol.CanalEntry;
import io.xzxj.canal.core.listener.EntryListener;
import io.xzxj.canal.core.util.TableFieldUtil;
import io.xzxj.canal.core.util.TableInfoUtil;
import org.apache.commons.lang3.StringUtils;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author xzxj
* @date 2023/3/12 12:10
*/
public class EntryColumnConvertFactory extends AbstractConvertFactory<List<CanalEntry.Column>> {
@Override
<R> R newInstance(Class<R> clazz, List<CanalEntry.Column> columnList) throws InstantiationException, IllegalAccessException, NoSuchFieldException {
R object = clazz.newInstance();
Map<String, String> fieldMap = TableFieldUtil.getFieldMap(object.getClass());
for (CanalEntry.Column column : columnList) {
String fieldName = fieldMap.get(column.getName());
if (StringUtils.isNotEmpty(fieldName)) {
TableFieldUtil.setFieldValue(object, fieldName, column.getValue());
}
}
return object;
}
@Override
public <R> R newInstance(EntryListener<?> entryHandler, List<CanalEntry.Column> columnList, Set<String> updateColumn) throws InstantiationException, IllegalAccessException, NoSuchFieldException {
Class<R> tableClass = TableInfoUtil.getTableClass(entryHandler);
if (tableClass == null) {
return null;
}
R r = tableClass.newInstance();
Map<String, String> columnNames = | TableFieldUtil.getFieldMap(r.getClass()); |
for (CanalEntry.Column column : columnList) {
if (!updateColumn.contains(column.getName())) {
continue;
}
String fieldName = columnNames.get(column.getName());
if (StringUtils.isNotEmpty(fieldName)) {
TableFieldUtil.setFieldValue(r, fieldName, column.getValue());
}
}
return r;
}
}
| canal-client-core/src/main/java/io/xzxj/canal/core/factory/EntryColumnConvertFactory.java | xizixuejie-canal-spring-849e5c4 | [
{
"filename": "canal-client-core/src/main/java/io/xzxj/canal/core/factory/AbstractConvertFactory.java",
"retrieved_chunk": " Class<R> tableClass = TableInfoUtil.getTableClass(entryListener);\n if (tableClass != null) {\n return newInstance(tableClass, t);\n }\n return null;\n }\n abstract <R> R newInstance(Class<R> clazz, T t) throws InstantiationException, IllegalAccessException, NoSuchFieldException;\n}",
"score": 0.9139891862869263
},
{
"filename": "canal-client-core/src/main/java/io/xzxj/canal/core/handler/impl/RowDataHandlerImpl.java",
"retrieved_chunk": " @Override\n public <R> void handleRowData(CanalEntry.RowData rowData, EntryListener<R> entryListener, CanalEntry.EventType eventType) throws Exception {\n if (entryListener == null) {\n log.warn(\"entryListener not found\");\n return;\n }\n switch (eventType) {\n case INSERT:\n R object = convertFactory.newInstance(entryListener, rowData.getAfterColumnsList());\n entryListener.insert(object);",
"score": 0.8722105026245117
},
{
"filename": "canal-client-core/src/main/java/io/xzxj/canal/core/handler/impl/MapRowDataHandlerImpl.java",
"retrieved_chunk": " public <R> void handleRowData(List<Map<String, String>> mapList,\n EntryListener<R> entryListener,\n CanalEntry.EventType eventType) throws Exception {\n if (entryListener == null) {\n return;\n }\n switch (eventType) {\n case INSERT:\n R entry = convertFactory.newInstance(entryListener, mapList.get(0));\n entryListener.insert(entry);",
"score": 0.8668748140335083
},
{
"filename": "canal-client-core/src/main/java/io/xzxj/canal/core/factory/IConvertFactory.java",
"retrieved_chunk": " <R> R newInstance(EntryListener<?> entryHandler, T t) throws Exception;\n default <R> R newInstance(EntryListener<?> entryHandler, T t, Set<String> updateColumn) throws InstantiationException, IllegalAccessException, NoSuchFieldException {\n return null;\n }\n}",
"score": 0.8626127243041992
},
{
"filename": "canal-client-core/src/main/java/io/xzxj/canal/core/util/TableInfoUtil.java",
"retrieved_chunk": " public static String findTableName(EntryListener<?> entryListener) {\n Class<Object> tableClass = getTableClass(entryListener);\n if (tableClass == null) {\n return null;\n }\n TableName tableName = tableClass.getAnnotation(TableName.class);\n if (tableName != null && StringUtils.isNotBlank(tableName.value())) {\n return tableName.value();\n }\n Table table = tableClass.getAnnotation(Table.class);",
"score": 0.8548994064331055
}
] | java | TableFieldUtil.getFieldMap(r.getClass()); |
package io.xzxj.canal.core.util;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.google.common.base.CaseFormat;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import javax.persistence.Column;
import java.beans.Transient;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
/**
* @author xzxj
* @date 2023/3/12 12:16
*/
public class TableFieldUtil {
private static final Map<Class<?>, Map<String, String>> TABLE_FILED_CACHE_MAP = new ConcurrentHashMap<>();
/**
* 获取字段名称和实体属性的对应关系
*
* @param clazz
* @return
*/
public static Map<String, String> getFieldMap(Class<?> clazz) {
Map<String, String> map = TABLE_FILED_CACHE_MAP.get(clazz);
if (map == null) {
List<Field> fields = FieldUtils.getAllFieldsList(clazz);
//如果实体类中存在column 注解,则使用注解的名称为字段名
map = fields.stream().filter(TableFieldUtil::tableColumnFiled)
.filter(field -> !Modifier.isStatic(field.getModifiers()))
.collect(Collectors.toMap(TableFieldUtil::getColumnName, Field::getName));
TABLE_FILED_CACHE_MAP.putIfAbsent(clazz, map);
}
return map;
}
private static String getColumnName(Field field) {
TableId tableId = field.getAnnotation(TableId.class);
if (tableId != null && StringUtils.isNotBlank(tableId.value())) {
return tableId.value();
}
TableField tableField = field.getAnnotation(TableField.class);
if (tableField != null && StringUtils.isNotBlank(tableField.value())) {
return tableField.value();
}
Column column = field.getAnnotation(Column.class);
if (column != null && StringUtils.isNotBlank(column.name())) {
return column.name();
}
return defaultColumnName(field);
}
private static String defaultColumnName(Field field) {
return CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, field.getName());
}
private static boolean tableColumnFiled(Field field) {
TableField tableField = field.getAnnotation(TableField.class);
Transient annotation = field.getAnnotation(Transient.class);
return tableField == null || tableField.exist() || annotation == null;
}
public static <R> void setFieldValue(R object, String fieldName, String value) throws NoSuchFieldException, IllegalAccessException {
Field field;
try {
field = object.getClass().getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
field = object.getClass().getSuperclass().getDeclaredField(fieldName);
}
field.setAccessible(true);
Class<?> type = field.getType();
| Object result = StringConvertUtil.convertType(type, value); |
field.set(object, result);
}
}
| canal-client-core/src/main/java/io/xzxj/canal/core/util/TableFieldUtil.java | xizixuejie-canal-spring-849e5c4 | [
{
"filename": "canal-client-core/src/main/java/io/xzxj/canal/core/factory/MapConvertFactory.java",
"retrieved_chunk": " <R> R newInstance(Class<R> clazz, Map<String, String> valueMap) throws InstantiationException, IllegalAccessException, NoSuchFieldException {\n R object = clazz.newInstance();\n Map<String, String> fieldMap = TableFieldUtil.getFieldMap(object.getClass());\n for (Map.Entry<String, String> entry : valueMap.entrySet()) {\n String fieldName = fieldMap.get(entry.getKey());\n if (StringUtils.isNotEmpty(fieldName)) {\n TableFieldUtil.setFieldValue(object, fieldName, entry.getValue());\n }\n }\n return object;",
"score": 0.8671532869338989
},
{
"filename": "canal-spring-boot-starter/src/main/java/io/xzxj/canal/spring/registrar/CanalListenerRegistrar.java",
"retrieved_chunk": " String name = getBeanNameByAnnotation(definition);\n if (name != null && !\"\".equals(name)) {\n return name;\n }\n return super.generateBeanName(definition, registry);\n }\n private String getBeanNameByAnnotation(BeanDefinition definition) {\n String beanClassName = definition.getBeanClassName();\n try {\n Class<?> clazz = Class.forName(beanClassName);",
"score": 0.8007631301879883
},
{
"filename": "canal-client-core/src/main/java/io/xzxj/canal/core/factory/EntryColumnConvertFactory.java",
"retrieved_chunk": " if (StringUtils.isNotEmpty(fieldName)) {\n TableFieldUtil.setFieldValue(object, fieldName, column.getValue());\n }\n }\n return object;\n }\n @Override\n public <R> R newInstance(EntryListener<?> entryHandler, List<CanalEntry.Column> columnList, Set<String> updateColumn) throws InstantiationException, IllegalAccessException, NoSuchFieldException {\n Class<R> tableClass = TableInfoUtil.getTableClass(entryHandler);\n if (tableClass == null) {",
"score": 0.7989068627357483
},
{
"filename": "canal-client-core/src/main/java/io/xzxj/canal/core/util/TableInfoUtil.java",
"retrieved_chunk": " public static String findTableName(EntryListener<?> entryListener) {\n Class<Object> tableClass = getTableClass(entryListener);\n if (tableClass == null) {\n return null;\n }\n TableName tableName = tableClass.getAnnotation(TableName.class);\n if (tableName != null && StringUtils.isNotBlank(tableName.value())) {\n return tableName.value();\n }\n Table table = tableClass.getAnnotation(Table.class);",
"score": 0.7756325006484985
},
{
"filename": "canal-client-core/src/main/java/io/xzxj/canal/core/factory/EntryColumnConvertFactory.java",
"retrieved_chunk": " return null;\n }\n R r = tableClass.newInstance();\n Map<String, String> columnNames = TableFieldUtil.getFieldMap(r.getClass());\n for (CanalEntry.Column column : columnList) {\n if (!updateColumn.contains(column.getName())) {\n continue;\n }\n String fieldName = columnNames.get(column.getName());\n if (StringUtils.isNotEmpty(fieldName)) {",
"score": 0.7723722457885742
}
] | java | Object result = StringConvertUtil.convertType(type, value); |
package com.xtracr.realcamera;
import com.xtracr.realcamera.config.ConfigFile;
import com.xtracr.realcamera.config.ModConfig;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.option.KeyBinding;
import net.minecraft.client.util.InputUtil;
import org.lwjgl.glfw.GLFW;
public final class KeyBindings {
private static final ModConfig config = ConfigFile.modConfig;
private static final String KEY_CATEGORY = "key.category.xtracr_" + RealCamera.MODID;
private static final String KEY_ID = "key.xtracr_" + RealCamera.MODID + "_";
public static final KeyBinding TOGGLE_PERSPECTIVE = new KeyBinding(
KEY_ID + "togglePerspective", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_F6, KEY_CATEGORY);
public static final KeyBinding TOGGLE_ADJUST_MODE = new KeyBinding(
KEY_ID + "toggleAdjustMode", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding TOGGLE_CAMERA_MODE = new KeyBinding(
KEY_ID + "toggleCameraMode", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_UP = new KeyBinding(
KEY_ID + "adjustUP", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_DOWN = new KeyBinding(
KEY_ID + "adjustDOWN", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_FRONT = new KeyBinding(
KEY_ID + "adjustFRONT", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_BACK = new KeyBinding(
KEY_ID + "adjustBACK", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_LEFT = new KeyBinding(
KEY_ID + "adjustLEFT", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static final KeyBinding ADJUST_RIGHT = new KeyBinding(
KEY_ID + "adjustRIGHT", InputUtil.Type.KEYSYM, InputUtil.UNKNOWN_KEY.getCode(), KEY_CATEGORY);
public static void handle(MinecraftClient client) {
if (client.player == null || client.currentScreen != null) return;
while (TOGGLE_PERSPECTIVE.wasPressed()) {
boolean enabled = config.isEnabled();
ConfigFile.load();
config.setEnabled(!enabled);
ConfigFile.save();
}
while (TOGGLE_ADJUST_MODE.wasPressed()) {
if (config.isClassic()) config.cycleClassicAdjustMode();
else config.setAdjustOffset(!config.isAdjustingOffset());
ConfigFile.save();
}
while (TOGGLE_CAMERA_MODE.wasPressed()) {
config.setClassic(!config.isClassic());
ConfigFile.save();
}
while (ADJUST_LEFT.wasPressed()) {
if (config.isClassic()) config.adjustClassicZ(true);
else config.adjustBindingZ(true);
ConfigFile.save();
}
while (ADJUST_RIGHT.wasPressed()) {
if (config.isClassic()) config.adjustClassicZ(false);
else config.adjustBindingZ(false);
ConfigFile.save();
}
while (ADJUST_UP.wasPressed()) {
if (config.isClassic()) config.adjustClassicY(true);
else config.adjustBindingY(true);
ConfigFile.save();
}
while (ADJUST_DOWN.wasPressed()) {
if (config.isClassic()) config.adjustClassicY(false);
else config.adjustBindingY(false);
ConfigFile.save();
}
while (ADJUST_FRONT.wasPressed()) {
if (config.isClassic()) config.adjustClassicX(true);
else config.adjustBindingX(true);
ConfigFile.save();
}
while (ADJUST_BACK.wasPressed()) {
if (config.isClassic() | ) config.adjustClassicX(false); |
else config.adjustBindingX(false);
ConfigFile.save();
}
}
}
| common/src/main/java/com/xtracr/realcamera/KeyBindings.java | xTracr-RealCamera-7675633 | [
{
"filename": "fabric/src/main/java/com/xtracr/realcamera/RealCameraFabric.java",
"retrieved_chunk": " KeyBindingHelper.registerKeyBinding(KeyBindings.ADJUST_BACK);\n KeyBindingHelper.registerKeyBinding(KeyBindings.ADJUST_FRONT);\n KeyBindingHelper.registerKeyBinding(KeyBindings.ADJUST_LEFT);\n KeyBindingHelper.registerKeyBinding(KeyBindings.ADJUST_RIGHT);\n }\n}",
"score": 0.6977859139442444
},
{
"filename": "forge/src/main/java/com/xtracr/realcamera/RealCameraForge.java",
"retrieved_chunk": " @SubscribeEvent\n public void onKeyRegister(RegisterKeyMappingsEvent event) {\n event.register(KeyBindings.TOGGLE_PERSPECTIVE);\n event.register(KeyBindings.TOGGLE_ADJUST_MODE);\n event.register(KeyBindings.TOGGLE_CAMERA_MODE);\n event.register(KeyBindings.ADJUST_UP);\n event.register(KeyBindings.ADJUST_DOWN);\n event.register(KeyBindings.ADJUST_BACK);\n event.register(KeyBindings.ADJUST_FRONT);\n event.register(KeyBindings.ADJUST_LEFT);",
"score": 0.6835854053497314
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ModConfig.java",
"retrieved_chunk": " if (triple.getMiddle() == null) triple.setMiddle(source.getMiddle());\n if (triple.getRight() == null) triple.setRight(source.getRight());\n }\n public void set(ModConfig modConfig) {\n general = modConfig.general;\n binding = modConfig.binding;\n classic = modConfig.classic;\n compats = modConfig.compats;\n disable = modConfig.disable;\n }",
"score": 0.6795499324798584
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ConfigScreen.java",
"retrieved_chunk": " .setSaveConsumer(f -> config.binding.yaw = f)\n .build());\n bindingCameraRotation.add(entryBuilder.startFloatField(Text.translatable(OPTION + \"roll\"), config.binding.roll)\n .setDefaultValue(0.0F)\n .setMin(-180.0F)\n .setMax(180.0F)\n .setSaveConsumer(f -> config.binding.roll = f)\n .build());\n binding.addEntry(bindingCameraRotation.build());\n classic.addEntry(entryBuilder.startEnumSelector(Text.translatable(OPTION + \"classicAdjustMode\"), ModConfig.Classic.AdjustMode.class, config.classic.adjustMode)",
"score": 0.6729607582092285
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ConfigScreen.java",
"retrieved_chunk": " .setSaveConsumer(b -> config.binding.bindPitching = b)\n .build());\n bindingCameraRotation.add(entryBuilder.startBooleanToggle(Text.translatable(OPTION + \"bindYawing\"), config.binding.bindYawing)\n .setDefaultValue(true)\n .setSaveConsumer(b -> config.binding.bindYawing = b)\n .build());\n bindingCameraRotation.add(entryBuilder.startBooleanToggle(Text.translatable(OPTION + \"bindRolling\"), config.binding.bindRolling)\n .setDefaultValue(true)\n .setSaveConsumer(b -> config.binding.bindRolling = b)\n .build());",
"score": 0.6691007614135742
}
] | java | ) config.adjustClassicX(false); |
package io.xzxj.canal.spring.autoconfigure;
import com.alibaba.otter.canal.protocol.FlatMessage;
import io.xzxj.canal.core.client.AbstractCanalClient;
import io.xzxj.canal.core.client.RabbitMqCanalClient;
import io.xzxj.canal.core.factory.MapConvertFactory;
import io.xzxj.canal.core.handler.IMessageHandler;
import io.xzxj.canal.core.handler.RowDataHandler;
import io.xzxj.canal.core.handler.impl.AsyncFlatMessageHandlerImpl;
import io.xzxj.canal.core.handler.impl.MapRowDataHandlerImpl;
import io.xzxj.canal.core.handler.impl.SyncFlatMessageHandlerImpl;
import io.xzxj.canal.core.listener.EntryListener;
import io.xzxj.canal.spring.properties.CanalProperties;
import io.xzxj.canal.spring.properties.CanalRabbitMqProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
/**
* @author xzxj
* @date 2023/3/24 9:49
*/
@EnableConfigurationProperties(CanalProperties.class)
@ConditionalOnProperty(value = "canal.server-mode", havingValue = "rabbit_mq")
@Import(ThreadPoolAutoConfiguration.class)
public class RabbitMqClientAutoConfiguration {
private final CanalProperties canalProperties;
public RabbitMqClientAutoConfiguration(CanalProperties canalProperties) {
this.canalProperties = canalProperties;
}
@Bean
@ConditionalOnMissingBean(RowDataHandler.class)
public RowDataHandler<List<Map<String, String>>> rowDataHandler() {
return new MapRowDataHandlerImpl(new MapConvertFactory());
}
@Bean
@ConditionalOnProperty(value = "canal.async", havingValue = "true", matchIfMissing = true)
@ConditionalOnMissingBean(IMessageHandler.class)
public IMessageHandler<FlatMessage> asyncFlatMessageHandler(RowDataHandler<List<Map<String, String>>> rowDataHandler,
List<EntryListener<?>> entryListenerList,
ExecutorService executorService) {
return new AsyncFlatMessageHandlerImpl(entryListenerList, rowDataHandler, executorService);
}
@Bean
@ConditionalOnProperty(value = "canal.async", havingValue = "false")
@ConditionalOnMissingBean(IMessageHandler.class)
public IMessageHandler<FlatMessage> syncFlatMessageHandler(RowDataHandler<List<Map<String, String>>> rowDataHandler,
List<EntryListener<?>> entryListenerList) {
return new SyncFlatMessageHandlerImpl(entryListenerList, rowDataHandler);
}
@Bean(initMethod = "init", destroyMethod = "destroy")
@ConditionalOnMissingBean(AbstractCanalClient.class)
public RabbitMqCanalClient rabbitMqCanalClient(IMessageHandler<FlatMessage> messageHandler) {
CanalRabbitMqProperties mqProperties | = canalProperties.getRabbitMq(); |
return RabbitMqCanalClient.builder().servers(canalProperties.getServer())
.virtualHost(mqProperties.getVirtualHost())
.queueName(canalProperties.getDestination())
.accessKey(mqProperties.getAccessKey())
.secretKey(mqProperties.getSecretKey())
.resourceOwnerId(mqProperties.getResourceOwnerId())
.username(mqProperties.getUsername())
.password(mqProperties.getPassword())
.messageHandler(messageHandler)
.batchSize(canalProperties.getBatchSize())
.filter(canalProperties.getFilter())
.timeout(canalProperties.getTimeout())
.unit(canalProperties.getUnit())
.build();
}
}
| canal-spring-boot-starter/src/main/java/io/xzxj/canal/spring/autoconfigure/RabbitMqClientAutoConfiguration.java | xizixuejie-canal-spring-849e5c4 | [
{
"filename": "canal-spring-boot-starter/src/main/java/io/xzxj/canal/spring/autoconfigure/KafkaClientAutoConfiguration.java",
"retrieved_chunk": " @ConditionalOnMissingBean(IMessageHandler.class)\n public IMessageHandler<FlatMessage> asyncFlatMessageHandler(RowDataHandler<List<Map<String, String>>> rowDataHandler,\n List<EntryListener<?>> entryHandlers,\n ExecutorService executorService) {\n return new AsyncFlatMessageHandlerImpl(entryHandlers, rowDataHandler, executorService);\n }\n @Bean\n @ConditionalOnProperty(value = \"canal.async\", havingValue = \"false\")\n @ConditionalOnMissingBean(IMessageHandler.class)\n public IMessageHandler<FlatMessage> syncFlatMessageHandler(RowDataHandler<List<Map<String, String>>> rowDataHandler,",
"score": 0.9212695956230164
},
{
"filename": "canal-spring-boot-starter/src/main/java/io/xzxj/canal/spring/autoconfigure/TcpClientAutoConfiguration.java",
"retrieved_chunk": " public IMessageHandler<Message> asyncMessageHandler(List<EntryListener<?>> entryListenerList,\n RowDataHandler<CanalEntry.RowData> rowDataHandler,\n ExecutorService executorService) {\n return new AsyncMessageHandlerImpl(entryListenerList, rowDataHandler, executorService);\n }\n @Bean\n @ConditionalOnProperty(value = \"canal.async\", havingValue = \"false\")\n @ConditionalOnMissingBean(IMessageHandler.class)\n public IMessageHandler<Message> syncMessageHandler(List<EntryListener<?>> entryListenerList,\n RowDataHandler<CanalEntry.RowData> rowDataHandler) {",
"score": 0.9196518659591675
},
{
"filename": "canal-spring-boot-starter/src/main/java/io/xzxj/canal/spring/autoconfigure/TcpClientAutoConfiguration.java",
"retrieved_chunk": " this.canalProperties = canalProperties;\n }\n @Bean\n @ConditionalOnMissingBean(RowDataHandler.class)\n public RowDataHandler<CanalEntry.RowData> rowDataHandler() {\n return new RowDataHandlerImpl(new EntryColumnConvertFactory());\n }\n @Bean\n @ConditionalOnProperty(value = \"canal.async\", havingValue = \"true\", matchIfMissing = true)\n @ConditionalOnMissingBean(IMessageHandler.class)",
"score": 0.8771668076515198
},
{
"filename": "canal-spring-boot-starter/src/main/java/io/xzxj/canal/spring/autoconfigure/KafkaClientAutoConfiguration.java",
"retrieved_chunk": " List<EntryListener<?>> entryHandlers) {\n return new SyncFlatMessageHandlerImpl(entryHandlers, rowDataHandler);\n }\n @Bean(initMethod = \"init\", destroyMethod = \"destroy\")\n @ConditionalOnMissingBean(AbstractCanalClient.class)\n public KafkaCanalClient kafkaCanalClient(IMessageHandler<FlatMessage> messageHandler) {\n return KafkaCanalClient.builder().servers(canalProperties.getServer())\n .groupId(canalProperties.getKafka().getGroupId())\n .topic(canalProperties.getDestination())\n .partition(canalProperties.getKafka().getPartition())",
"score": 0.8693998456001282
},
{
"filename": "canal-spring-boot-starter/src/main/java/io/xzxj/canal/spring/autoconfigure/KafkaClientAutoConfiguration.java",
"retrieved_chunk": " public KafkaClientAutoConfiguration(CanalProperties canalProperties) {\n this.canalProperties = canalProperties;\n }\n @Bean\n @ConditionalOnMissingBean(RowDataHandler.class)\n public RowDataHandler<List<Map<String, String>>> rowDataHandler() {\n return new MapRowDataHandlerImpl(new MapConvertFactory());\n }\n @Bean\n @ConditionalOnProperty(value = \"canal.async\", havingValue = \"true\", matchIfMissing = true)",
"score": 0.8683688044548035
}
] | java | = canalProperties.getRabbitMq(); |
package com.xtracr.realcamera.mixins;
import com.xtracr.realcamera.api.VirtualRenderer;
import net.minecraft.client.network.AbstractClientPlayerEntity;
import net.minecraft.client.network.ClientPlayerEntity;
import net.minecraft.client.render.entity.EntityRendererFactory.Context;
import net.minecraft.client.render.entity.LivingEntityRenderer;
import net.minecraft.client.render.entity.PlayerEntityRenderer;
import net.minecraft.client.render.entity.model.PlayerEntityModel;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(PlayerEntityRenderer.class)
public abstract class MixinPlayerEntityRenderer
extends LivingEntityRenderer<AbstractClientPlayerEntity, PlayerEntityModel<AbstractClientPlayerEntity>> {
public MixinPlayerEntityRenderer(Context ctx, PlayerEntityModel<AbstractClientPlayerEntity> model,
float shadowRadius) {
super(ctx, model, shadowRadius);
}
@Inject(method = "setModelPose", at = @At("RETURN"))
private void onSetModelPoseRETURN(AbstractClientPlayerEntity player, CallbackInfo cInfo) {
if (!(player instanceof ClientPlayerEntity)) return;
if (VirtualRenderer.shouldDisableRender("head")) model.head.visible = false;
if (VirtualRenderer.shouldDisableRender("hat")) model.hat.visible = false;
if (VirtualRenderer.shouldDisableRender("body")) model.body.visible = false;
if (VirtualRenderer.shouldDisableRender("rightArm")) model.rightArm.visible = false;
if (VirtualRenderer.shouldDisableRender("leftArm")) model.leftArm.visible = false;
if (VirtualRenderer.shouldDisableRender("rightLeg")) model.rightLeg.visible = false;
if (VirtualRenderer.shouldDisableRender("leftLeg")) model.leftLeg.visible = false;
if (VirtualRenderer.shouldDisableRender("leftSleeve")) model.leftSleeve.visible = false;
if (VirtualRenderer.shouldDisableRender("rightSleeve")) model.rightSleeve.visible = false;
if (VirtualRenderer.shouldDisableRender("leftPants")) model.leftPants.visible = false;
if (VirtualRenderer.shouldDisableRender("rightPants")) model.rightPants.visible = false;
if | (VirtualRenderer.shouldDisableRender("jacket")) model.jacket.visible = false; |
}
}
| common/src/main/java/com/xtracr/realcamera/mixins/MixinPlayerEntityRenderer.java | xTracr-RealCamera-7675633 | [
{
"filename": "common/src/main/java/com/xtracr/realcamera/mixins/MixinArmorFeatureRenderer.java",
"retrieved_chunk": " (VirtualRenderer.shouldDisableRender(\"chestplate\") && armorSlot == EquipmentSlot.CHEST) ||\n (VirtualRenderer.shouldDisableRender(\"leggings\") && armorSlot == EquipmentSlot.LEGS) ||\n (VirtualRenderer.shouldDisableRender(\"boots\") && armorSlot == EquipmentSlot.FEET)) {\n cInfo.cancel();\n }\n }\n}",
"score": 0.7342988848686218
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ModConfig.java",
"retrieved_chunk": " if (disable.onlyInBinding && general.classic) return false;\n return shouldDisable(client, \"disable_mod\") ||\n (client.player.isFallFlying() && disable.fallFlying) ||\n (client.player.isSwimming() && disable.swimming) ||\n (client.player.isCrawling() && disable.crawling) ||\n (client.player.isSneaking() && disable.sneaking) ||\n (client.player.isSleeping() && disable.sleeping) ||\n (client.currentScreen != null && disable.screenOpened);\n }\n public boolean disableRenderingWhen(MinecraftClient client) {",
"score": 0.7232199907302856
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ConfigScreen.java",
"retrieved_chunk": " .setSaveConsumer(b -> config.compats.physicsMod = b)\n .build());\n compats.addEntry(compatSwitches.build());\n disable.addEntry(entryBuilder.startBooleanToggle(Text.translatable(OPTION + \"onlyInBinding\"), config.disable.onlyInBinding)\n .setDefaultValue(true)\n .setSaveConsumer(b -> config.disable.onlyInBinding = b)\n .build());\n disable.addEntry(entryBuilder.startBooleanToggle(Text.translatable(OPTION + \"renderModelPart\"), config.disable.renderModelPart)\n .setDefaultValue(false)\n .setSaveConsumer(b -> config.disable.renderModelPart = b)",
"score": 0.6964393258094788
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ModConfig.java",
"retrieved_chunk": " public boolean shouldDisableRender(String modelPartName) {\n if (disable.onlyInBinding && general.classic) return false;\n return (disable.renderModelPart && disable.disabledModelParts.contains(modelPartName)) ||\n shouldDisable(MinecraftClient.getInstance(), modelPartName);\n }\n public boolean allowRenderingHandWhen(MinecraftClient client) {\n if (disable.onlyInBinding && general.classic) return false;\n return shouldDisable(client, \"allow_rendering_hand\");\n }\n public boolean disableModWhen(MinecraftClient client) {",
"score": 0.6960986852645874
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ConfigScreen.java",
"retrieved_chunk": " }));\n SubCategoryBuilder disableModWhen = entryBuilder.startSubCategory(Text.translatable(CATEGORY + \"disableModWhen\"));\n disableModWhen.add(entryBuilder.startBooleanToggle(Text.translatable(OPTION + \"fallFlying\"), config.disable.fallFlying)\n .setDefaultValue(true)\n .setSaveConsumer(b -> config.disable.fallFlying = b)\n .build());\n disableModWhen.add(entryBuilder.startBooleanToggle(Text.translatable(OPTION + \"swimming\"), config.disable.swimming)\n .setDefaultValue(false)\n .setSaveConsumer(b -> config.disable.swimming = b)\n .build());",
"score": 0.6789039969444275
}
] | java | (VirtualRenderer.shouldDisableRender("jacket")) model.jacket.visible = false; |
package com.xtracr.realcamera.mixins;
import com.xtracr.realcamera.RealCameraCore;
import com.xtracr.realcamera.compat.DoABarrelRollCompat;
import com.xtracr.realcamera.config.ConfigFile;
import com.xtracr.realcamera.utils.CrosshairUtils;
import com.xtracr.realcamera.utils.RaycastUtils;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.option.Perspective;
import net.minecraft.client.render.Camera;
import net.minecraft.client.render.GameRenderer;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.entity.Entity;
import net.minecraft.entity.projectile.ProjectileUtil;
import net.minecraft.util.hit.EntityHitResult;
import net.minecraft.util.math.Box;
import net.minecraft.util.math.Vec3d;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.ModifyVariable;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(GameRenderer.class)
public abstract class MixinGameRenderer {
@Unique
private static boolean toggled = false;
@Shadow
@Final MinecraftClient client;
@ModifyVariable(method = "updateTargetedEntity", at = @At("STORE"), ordinal = 0)
private EntityHitResult modifyEntityHitResult(EntityHitResult entityHitResult) {
CrosshairUtils.capturedEntityHitResult = entityHitResult;
if (!ConfigFile.modConfig.isCrosshairDynamic() && RealCameraCore.isActive()) {
Vec3d startVec = RaycastUtils.getStartVec();
Vec3d endVec = RaycastUtils.getEndVec();
double sqDistance = (client.crosshairTarget != null ?
client.crosshairTarget.getPos().squaredDistanceTo(startVec) : endVec.squaredDistanceTo(startVec));
Entity cameraEntity = client.getCameraEntity();
Box box = cameraEntity.getBoundingBox().stretch(cameraEntity.getRotationVec(client.getTickDelta())
.multiply(client.interactionManager.getReachDistance())).expand(1.0, 1.0, 1.0);
CrosshairUtils.capturedEntityHitResult = ProjectileUtil.raycast(cameraEntity, startVec, endVec, box, entity -> !entity.isSpectator() && entity.canHit(), sqDistance);
}
return CrosshairUtils.capturedEntityHitResult;
}
@Inject(method = "renderHand", at = @At(value = "INVOKE",
target = "Lnet/minecraft/client/util/math/MatrixStack;push()V"))
private void setThirdPerson(MatrixStack matrices, Camera camera, float tickDelta, CallbackInfo cInfo) {
if (ConfigFile.modConfig.isRendering() && camera.isThirdPerson() && RealCameraCore.isActive() &&
!ConfigFile.modConfig.allowRenderingHandWhen(client)) {
client.options.setPerspective(Perspective.THIRD_PERSON_BACK);
toggled = true;
}
}
@Inject(method = "renderHand", at = @At(value = "INVOKE",
target = "Lnet/minecraft/client/util/math/MatrixStack;pop()V"))
private void setFirstPerson(CallbackInfo cInfo) {
if (toggled) {
client.options.setPerspective(Perspective.FIRST_PERSON);
toggled = false;
}
}
@Inject(method = "renderWorld", at = @At(value = "INVOKE",
target = "Lnet/minecraft/client/render/Camera;update(Lnet/minecraft/world/BlockView;Lnet/minecraft/entity/Entity;ZZF)V",
shift = At.Shift.BY, by = -2))
private void onBeforeCameraUpdate(float tickDelta, long limitTime, MatrixStack matrixStack, CallbackInfo cInfo) {
if (ConfigFile.modConfig.compatDoABarrelRoll() && DoABarrelRollCompat | .modEnabled() && RealCameraCore.isActive()) { |
matrixStack.loadIdentity();
}
}
}
| common/src/main/java/com/xtracr/realcamera/mixins/MixinGameRenderer.java | xTracr-RealCamera-7675633 | [
{
"filename": "fabric/src/main/java/com/xtracr/realcamera/mixins/GameRendererEvents.java",
"retrieved_chunk": " target = \"Lnet/minecraft/client/render/Camera;update(Lnet/minecraft/world/BlockView;Lnet/minecraft/entity/Entity;ZZF)V\",\n shift = At.Shift.AFTER))\n private void onAfterCameraUpdate(float tickDelta, long limitTime, MatrixStack matrixStack, CallbackInfo cInfo) {\n if (RealCameraCore.isActive()) {\n RealCameraCore.updateCamera(camera, client, tickDelta);\n matrixStack.multiply(RotationAxis.POSITIVE_Z.rotationDegrees(RealCameraCore.getRoll()));\n }\n }\n}",
"score": 0.8893624544143677
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/mixins/MixinInGameHud.java",
"retrieved_chunk": "@Mixin(InGameHud.class)\npublic abstract class MixinInGameHud {\n @Inject(method = \"renderCrosshair(Lnet/minecraft/client/gui/DrawContext;)V\", at = @At(\"HEAD\"))\n private void onRenderCrosshairHEAD(DrawContext context, CallbackInfo cInfo) {\n if (ConfigFile.modConfig.isCrosshairDynamic() && RealCameraCore.isActive()) {\n context.getMatrices().push();\n CrosshairUtils.translateMatrices(context.getMatrices());\n }\n }\n @Inject(method = \"renderCrosshair(Lnet/minecraft/client/gui/DrawContext;)V\", at = @At(\"RETURN\"))",
"score": 0.8546020984649658
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/mixins/MixinEntityRenderer.java",
"retrieved_chunk": "import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;\n@Mixin(EntityRenderer.class)\npublic abstract class MixinEntityRenderer {\n @Inject(method = \"shouldRender\", at = @At(\"HEAD\"), cancellable = true)\n private <T extends Entity> void onShouldRenderHEAD(T entity, Frustum frustum, double x, double y, double z,\n CallbackInfoReturnable<Boolean> cInfo) {\n if (ConfigFile.modConfig.isRendering() && RealCameraCore.isActive() && entity instanceof ClientPlayerEntity) {\n cInfo.setReturnValue(true);\n }\n }",
"score": 0.8389073610305786
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/mixins/MixinClientPlayerEntity.java",
"retrieved_chunk": " target = \"Lnet/minecraft/client/option/Perspective;isFirstPerson()Z\"))\n private boolean returnFalse(Perspective perspective) {\n if (ConfigFile.modConfig.isRendering() && RealCameraCore.isActive()) return false;\n return perspective.isFirstPerson();\n }\n @Override\n public HitResult raycast(double maxDistance, float tickDelta, boolean includeFluids) {\n if (!ConfigFile.modConfig.isCrosshairDynamic() && RealCameraCore.isActive()) {\n RaycastUtils.update(this, maxDistance * maxDistance, tickDelta);\n return getWorld().raycast(RaycastUtils.getRaycastContext(RaycastContext.ShapeType.OUTLINE,",
"score": 0.8159610033035278
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/mixins/MixinItem.java",
"retrieved_chunk": "import org.spongepowered.asm.mixin.injection.At;\nimport org.spongepowered.asm.mixin.injection.Inject;\nimport org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;\n@Mixin(Item.class)\npublic abstract class MixinItem {\n @Inject(method = \"raycast\", at = @At(\"HEAD\"), cancellable = true)\n private static void coverRaycast(World world, PlayerEntity player, RaycastContext.FluidHandling fluidHandling,\n CallbackInfoReturnable<BlockHitResult> cInfo) {\n if (!ConfigFile.modConfig.isCrosshairDynamic() && RealCameraCore.isActive()) {\n RaycastUtils.update(player, 25.0D, 1.0F);",
"score": 0.8139325380325317
}
] | java | .modEnabled() && RealCameraCore.isActive()) { |
package com.xtracr.realcamera.mixins;
import com.xtracr.realcamera.RealCameraCore;
import com.xtracr.realcamera.compat.DoABarrelRollCompat;
import com.xtracr.realcamera.config.ConfigFile;
import com.xtracr.realcamera.utils.CrosshairUtils;
import com.xtracr.realcamera.utils.RaycastUtils;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.option.Perspective;
import net.minecraft.client.render.Camera;
import net.minecraft.client.render.GameRenderer;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.entity.Entity;
import net.minecraft.entity.projectile.ProjectileUtil;
import net.minecraft.util.hit.EntityHitResult;
import net.minecraft.util.math.Box;
import net.minecraft.util.math.Vec3d;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.ModifyVariable;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(GameRenderer.class)
public abstract class MixinGameRenderer {
@Unique
private static boolean toggled = false;
@Shadow
@Final MinecraftClient client;
@ModifyVariable(method = "updateTargetedEntity", at = @At("STORE"), ordinal = 0)
private EntityHitResult modifyEntityHitResult(EntityHitResult entityHitResult) {
CrosshairUtils.capturedEntityHitResult = entityHitResult;
if (!ConfigFile.modConfig.isCrosshairDynamic() && RealCameraCore.isActive()) {
Vec3d startVec = RaycastUtils.getStartVec();
Vec3d endVec = RaycastUtils.getEndVec();
double sqDistance = (client.crosshairTarget != null ?
client.crosshairTarget.getPos().squaredDistanceTo(startVec) : endVec.squaredDistanceTo(startVec));
Entity cameraEntity = client.getCameraEntity();
Box box = cameraEntity.getBoundingBox().stretch(cameraEntity.getRotationVec(client.getTickDelta())
.multiply(client.interactionManager.getReachDistance())).expand(1.0, 1.0, 1.0);
CrosshairUtils.capturedEntityHitResult = ProjectileUtil.raycast(cameraEntity, startVec, endVec, box, entity -> !entity.isSpectator() && entity.canHit(), sqDistance);
}
return CrosshairUtils.capturedEntityHitResult;
}
@Inject(method = "renderHand", at = @At(value = "INVOKE",
target = "Lnet/minecraft/client/util/math/MatrixStack;push()V"))
private void setThirdPerson(MatrixStack matrices, Camera camera, float tickDelta, CallbackInfo cInfo) {
if (ConfigFile.modConfig.isRendering() | && camera.isThirdPerson() && RealCameraCore.isActive() &&
!ConfigFile.modConfig.allowRenderingHandWhen(client)) { |
client.options.setPerspective(Perspective.THIRD_PERSON_BACK);
toggled = true;
}
}
@Inject(method = "renderHand", at = @At(value = "INVOKE",
target = "Lnet/minecraft/client/util/math/MatrixStack;pop()V"))
private void setFirstPerson(CallbackInfo cInfo) {
if (toggled) {
client.options.setPerspective(Perspective.FIRST_PERSON);
toggled = false;
}
}
@Inject(method = "renderWorld", at = @At(value = "INVOKE",
target = "Lnet/minecraft/client/render/Camera;update(Lnet/minecraft/world/BlockView;Lnet/minecraft/entity/Entity;ZZF)V",
shift = At.Shift.BY, by = -2))
private void onBeforeCameraUpdate(float tickDelta, long limitTime, MatrixStack matrixStack, CallbackInfo cInfo) {
if (ConfigFile.modConfig.compatDoABarrelRoll() && DoABarrelRollCompat.modEnabled() && RealCameraCore.isActive()) {
matrixStack.loadIdentity();
}
}
}
| common/src/main/java/com/xtracr/realcamera/mixins/MixinGameRenderer.java | xTracr-RealCamera-7675633 | [
{
"filename": "common/src/main/java/com/xtracr/realcamera/mixins/MixinClientPlayerEntity.java",
"retrieved_chunk": " target = \"Lnet/minecraft/client/option/Perspective;isFirstPerson()Z\"))\n private boolean returnFalse(Perspective perspective) {\n if (ConfigFile.modConfig.isRendering() && RealCameraCore.isActive()) return false;\n return perspective.isFirstPerson();\n }\n @Override\n public HitResult raycast(double maxDistance, float tickDelta, boolean includeFluids) {\n if (!ConfigFile.modConfig.isCrosshairDynamic() && RealCameraCore.isActive()) {\n RaycastUtils.update(this, maxDistance * maxDistance, tickDelta);\n return getWorld().raycast(RaycastUtils.getRaycastContext(RaycastContext.ShapeType.OUTLINE,",
"score": 0.8799053430557251
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/mixins/MixinEntityRenderer.java",
"retrieved_chunk": "import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;\n@Mixin(EntityRenderer.class)\npublic abstract class MixinEntityRenderer {\n @Inject(method = \"shouldRender\", at = @At(\"HEAD\"), cancellable = true)\n private <T extends Entity> void onShouldRenderHEAD(T entity, Frustum frustum, double x, double y, double z,\n CallbackInfoReturnable<Boolean> cInfo) {\n if (ConfigFile.modConfig.isRendering() && RealCameraCore.isActive() && entity instanceof ClientPlayerEntity) {\n cInfo.setReturnValue(true);\n }\n }",
"score": 0.8692654371261597
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/mixins/MixinInGameHud.java",
"retrieved_chunk": "@Mixin(InGameHud.class)\npublic abstract class MixinInGameHud {\n @Inject(method = \"renderCrosshair(Lnet/minecraft/client/gui/DrawContext;)V\", at = @At(\"HEAD\"))\n private void onRenderCrosshairHEAD(DrawContext context, CallbackInfo cInfo) {\n if (ConfigFile.modConfig.isCrosshairDynamic() && RealCameraCore.isActive()) {\n context.getMatrices().push();\n CrosshairUtils.translateMatrices(context.getMatrices());\n }\n }\n @Inject(method = \"renderCrosshair(Lnet/minecraft/client/gui/DrawContext;)V\", at = @At(\"RETURN\"))",
"score": 0.8557029962539673
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/RealCameraCore.java",
"retrieved_chunk": " double l = hitResult.getPos().distanceTo(start);\n if (hitResult.getType() == HitResult.Type.MISS || l >= offset.length()) continue;\n offset = offset.multiply(l / offset.length());\n }\n ((CameraAccessor) camera).invokeSetPos(referVec.add(offset));\n }\n private static void virtualRender(AbstractClientPlayerEntity player, PlayerEntityRenderer playerRenderer,\n float tickDelta, MatrixStack matrixStack) {\n if (config.isUsingModModel()) {\n status = \"Successful\";",
"score": 0.8466605544090271
},
{
"filename": "fabric/src/main/java/com/xtracr/realcamera/mixins/GameRendererEvents.java",
"retrieved_chunk": " target = \"Lnet/minecraft/client/render/Camera;update(Lnet/minecraft/world/BlockView;Lnet/minecraft/entity/Entity;ZZF)V\",\n shift = At.Shift.AFTER))\n private void onAfterCameraUpdate(float tickDelta, long limitTime, MatrixStack matrixStack, CallbackInfo cInfo) {\n if (RealCameraCore.isActive()) {\n RealCameraCore.updateCamera(camera, client, tickDelta);\n matrixStack.multiply(RotationAxis.POSITIVE_Z.rotationDegrees(RealCameraCore.getRoll()));\n }\n }\n}",
"score": 0.8387538194656372
}
] | java | && camera.isThirdPerson() && RealCameraCore.isActive() &&
!ConfigFile.modConfig.allowRenderingHandWhen(client)) { |
package com.xuanwenchao.metaphor.manager;
import android.util.Log;
import android.util.SparseArray;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import com.xuanwenchao.metaphor.annotation.MetaphorRes;
import com.xuanwenchao.metaphor.exception.MetaphorException;
import com.xuanwenchao.metaphor.interfaces.IMetaphorManager;
import com.xuanwenchao.metaphor.interfaces.IMetaphorMessage;
import com.xuanwenchao.metaphor.interfaces.IMetaphorSubFragmentManager;
import java.util.HashMap;
/**
* @author Xuan Wenchao
* @Package com.xuanwenchao.metaphor.manager
* @Description: base function had been supplied implements IMetaphorManager, optional strategy class
* @date Dec 03,2022
*/
public abstract class MetaphorManager implements IMetaphorManager {
static final String kErrorTag = "Metaphor Error:";
public static boolean isPrintLog = true;
// hashcode of base object : MetaphorManager object
static SparseArray m_metaphorManagers = new SparseArray<IMetaphorManager>();
//map is (Hash Code of fragment address) : (IMetaphorMessage)
SparseArray m_fragmentToListener = new SparseArray<IMetaphorMessage>();
//map is (container view ID) : (FragmentManager)
SparseArray m_containerViewMap = new SparseArray<androidx.fragment.app.FragmentManager>();
//map is (Hash Code of fragment address) : (container view ID)
SparseArray m_fragmentToContainerView = new SparseArray<Integer>();
//map is (Tag String of fragment) : (container view ID)
HashMap<String, Fragment> m_tagToFragment = new HashMap<>();
int[] m_containerViewIds;
Object m_baseObject = null;
IMetaphorMessage m_metaphorMessage;
Fragment m_currentSubFragment; //the fragment that called findMetaphorManager
public static IMetaphorManager createMetaphorManager(@NonNull Object object) {
int objectCode = System.identityHashCode(object);
IMetaphorManager iMetaphorManager = (IMetaphorManager) m_metaphorManagers.get(objectCode);
if (iMetaphorManager != null) {
return iMetaphorManager;
}
if (object instanceof AppCompatActivity) {
MetaphorActivityManager metaphorManager = MetaphorActivityManager.createActivityManager((AppCompatActivity) object);
m_metaphorManagers.put(objectCode, metaphorManager);
return metaphorManager;
} else if (object instanceof Fragment) {
IMetaphorManager metaphorManager = MetaphorFragmentManager.createFragmentManager((Fragment) object);
m_metaphorManagers.put(objectCode, metaphorManager);
return metaphorManager;
} else {
throw new MetaphorException("Base class must used on AppCompatActivity or Fragment");
}
}
/**
* @param object It is a fragment that has been added to MetaphorManager
* @Description: Find the relative MetaphorManager by sub fragment
* @return: MetaphorManager or null if not exist
**/
public static IMetaphorSubFragmentManager findMetaphorManager(@NonNull Fragment object) {
for (int i = 0; i < m_metaphorManagers.size(); i++) {
MetaphorManager metaphorManager = (MetaphorManager) (m_metaphorManagers.valueAt(i));
int objectCode = System.identityHashCode(object);
if (metaphorManager.isContainFragmentCode(objectCode)) {
metaphorManager.m_currentSubFragment = object;
return MetaphorSubFragmentManager.create(metaphorManager, (Fragment) object);
}
}
return null;
}
/**
* @Description: Retrieve the resource configuration with annotation
* @return: void
*/
MetaphorManager(@NonNull Object object) {
Class<?> clazz = object.getClass();
MetaphorRes metaphorRes = clazz.getAnnotation(MetaphorRes.class);
int[] cvIDs = metaphorRes.containerViewIDs();
if (cvIDs.length > 0) {
m_containerViewIds = cvIDs;
}
}
/**
* @Description: Release static space (m_metaphorManagers) after object is destroy.
* @return: void
*/
void OnMetaphorManagerDestroy() {
if (m_baseObject != null) {
int objectCode = System.identityHashCode(m_baseObject);
m_metaphorManagers.remove(objectCode);
m_baseObject = null;
}
}
@Override
public IMetaphorManager bindListener(IMetaphorMessage metaphorMessage) {
m_metaphorMessage = metaphorMessage;
return this;
}
void sendMessageToBase(int code, Object msg) {
if (m_metaphorMessage != null) {
m_metaphorMessage.OnMessageReceive(m_currentSubFragment, code, msg);
} else {
printErrorLog("sendMessageToBase -> code:" + code + " msg:" + msg.toString() + ": base is not bind listener");
}
}
void bindFragmentListener(IMetaphorMessage metaphorMessage) {
if (m_currentSubFragment != null && metaphorMessage != null) {
int fragmentCode = System.identityHashCode(m_currentSubFragment);
m_fragmentToListener.put(fragmentCode, metaphorMessage);
} else {
printErrorLog("bindFragmentListener -> m_currentSubFragment=" + m_currentSubFragment + ",metaphorMessage=" + metaphorMessage);
}
}
public void sendMessageToFragment(String tagForFragment, int code, Object msg) {
if (tagForFragment != null) {
Fragment fragment = m_tagToFragment.get(tagForFragment);
if (fragment != null) {
sendMessageToFragment(fragment, code, msg);
} else {
printErrorLog("sendMessageToFragment -> tag name:" + tagForFragment + " could not be found.");
}
} else {
printErrorLog("sendMessageToFragment -> tag is null");
}
}
public void sendMessageToFragment(Fragment fragment, int code, Object msg) {
int fragmentCode = System.identityHashCode(fragment);
Object iMetaphorMessage = m_fragmentToListener.get(fragmentCode, null);
if (iMetaphorMessage != null) {
if (m_currentSubFragment != null) {
((IMetaphorMessage) iMetaphorMessage).OnMessageReceive(m_currentSubFragment, code, msg);
} else {
((IMetaphorMessage) iMetaphorMessage | ).OnMessageReceive(m_baseObject, code, msg); |
}
} else {
printErrorLog("sendMessageToFragment -> Fragment:" + fragment + ": is not bind listener");
}
}
void printErrorLog(String strMessage) {
if (isPrintLog) {
Log.e(kErrorTag, strMessage);
}
}
boolean isContainFragmentCode(int fragmentCode) {
Object obj = m_fragmentToContainerView.get(fragmentCode);
return obj != null;
}
@Override
public IMetaphorManager addFragment(@NonNull Fragment fragment) {
return this.addFragment(fragment, null);
}
@Override
public IMetaphorManager addFragment(@NonNull Fragment fragment, @NonNull String strTag) {
if (m_containerViewMap.size() <= 0) {
throw new MetaphorException("No container view ID be specified! 22178!");
}
Integer key = m_containerViewMap.keyAt(0);
return this.addFragment(key, fragment, strTag);
}
@Override
public IMetaphorManager addFragment(int containerViewId, @NonNull Fragment fragment, @NonNull String strTag) {
this.addContainerViewID(containerViewId);
int fragmentCode = System.identityHashCode(fragment);
Integer cvIDexist = (Integer) m_fragmentToContainerView.get(fragmentCode);
if (cvIDexist != null) {
//The fragment will be remove from FragmentManager if existed.
((androidx.fragment.app.FragmentManager) m_containerViewMap.get(containerViewId)).beginTransaction().remove(fragment);
m_fragmentToContainerView.delete(fragmentCode);
}
m_fragmentToContainerView.put(fragmentCode, containerViewId);
FragmentTransaction fragmentTransaction = ((FragmentManager) m_containerViewMap.get(containerViewId)).beginTransaction();
if (strTag == null || strTag.length() == 0) {
fragmentTransaction.add(containerViewId, fragment).hide(fragment);
} else {
m_tagToFragment.remove(strTag);
m_tagToFragment.put(strTag, fragment);
fragmentTransaction.add(containerViewId, fragment, strTag).hide(fragment);
}
fragmentTransaction.commitNowAllowingStateLoss();
return this;
}
@Override
public IMetaphorManager addFragment(@NonNull Fragment... fragments) {
return this.addFragment(null, fragments);
}
@Override
public IMetaphorManager addFragment(int containerViewSerialNumber, @NonNull Fragment... fragments) {
return this.addFragment(containerViewSerialNumber, null, fragments);
}
@Override
public IMetaphorManager addFragment(@NonNull String[] strTags, @NonNull Fragment... fragments) {
return this.addFragment(0, strTags, fragments);
}
@Override
public IMetaphorManager addFragment(int containerViewSerialNumber, @NonNull String[] strTags, @NonNull Fragment... fragments) {
if (m_containerViewMap.size() <= containerViewSerialNumber) {
throw new MetaphorException("No container view ID be specified! 22220!");
}
Integer cvID = m_containerViewMap.keyAt(containerViewSerialNumber);
androidx.fragment.app.FragmentManager fmg = (androidx.fragment.app.FragmentManager) m_containerViewMap.valueAt(containerViewSerialNumber);
FragmentTransaction ft = fmg.beginTransaction();
int i = 0;
for (Fragment f : fragments) {
if (strTags != null && strTags.length > i) {
m_tagToFragment.remove(strTags[i]);
m_tagToFragment.put(strTags[i], f);
ft.add(cvID, f, strTags[i]).hide(f);
} else {
ft.add(cvID, f).hide(f);
}
int fragmentCode = System.identityHashCode(f);
Integer cvIDexist = (Integer) m_fragmentToContainerView.get(fragmentCode);
if (cvIDexist != null) {
//The fragment will be remove from FragmentManager if existed.
ft.remove(f);
m_fragmentToContainerView.delete(fragmentCode);
}
m_fragmentToContainerView.put(fragmentCode, cvID);
i++;
}
ft.commit();
// ft.commitNowAllowingStateLoss();
return this;
}
@Override
public IMetaphorManager showFragment(@NonNull Fragment fragment) {
int fragmentCode = System.identityHashCode(fragment);
Integer cvIDexist = (Integer) m_fragmentToContainerView.get(fragmentCode);
if (cvIDexist != null) {
androidx.fragment.app.FragmentManager fragmentManager = ((androidx.fragment.app.FragmentManager) m_containerViewMap.get(cvIDexist));
FragmentTransaction ft = fragmentManager.beginTransaction();
for (Fragment f : fragmentManager.getFragments()) {
int fc = System.identityHashCode(f);
Integer cv = (Integer) m_fragmentToContainerView.get(fc);
if (cv != null && cv.intValue() == cvIDexist.intValue() && f != fragment) {
ft.hide(f);
}
}
ft.show(fragment);//.addToBackStack(null);
ft.commit();
// ft.commitAllowingStateLoss();
int a = 10;
} else {
throw new MetaphorException("No container view ID be found! 221266!");
}
return this;
}
@Override
public IMetaphorManager showFragment(@NonNull String strTag) {
Fragment fragment = m_tagToFragment.get(strTag);
if (fragment != null) {
this.showFragment(fragment);
} else {
printErrorLog("showFragment -> strTag:" + strTag + ": is not exist");
}
return this;
}
@Override
public void hideFragment(@NonNull Fragment fragment) {
int fragmentCode = System.identityHashCode(fragment);
Integer cvIDexist = (Integer) m_fragmentToContainerView.get(fragmentCode);
if (cvIDexist != null) {
androidx.fragment.app.FragmentManager fragmentManager = ((androidx.fragment.app.FragmentManager) m_containerViewMap.get(cvIDexist));
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.hide(fragment);
ft.commit();
} else {
throw new MetaphorException("No container view ID be found! 221290!");
}
}
@Override
public void hideFragment(@NonNull String strTag) {
Fragment fragment = m_tagToFragment.get(strTag);
if (fragment != null) {
this.hideFragment(fragment);
} else {
printErrorLog("hideFragment -> strTag:" + strTag + ": is not exist");
}
}
@Override
public boolean isTagExist(@NonNull String strTag) {
Fragment fragment = m_tagToFragment.get(strTag);
return fragment != null ? true : false;
}
}
| Metaphor/src/main/java/com/xuanwenchao/metaphor/manager/MetaphorManager.java | xuanwenchao-Metaphor-0176f35 | [
{
"filename": "Metaphor/src/main/java/com/xuanwenchao/metaphor/manager/MetaphorSubFragmentManager.java",
"retrieved_chunk": " m_metaphorManager = metaphorManager;\n m_fragment = fragment;\n }\n @Override\n public IMetaphorSubFragmentManager sendMessageToBase(int code, Object msg) {\n m_metaphorManager.sendMessageToBase(code, msg);\n return this;\n }\n @Override\n public void bindFragmentListener(IMetaphorMessage metaphorMessage) {",
"score": 0.8393834829330444
},
{
"filename": "Metaphor/src/main/java/com/xuanwenchao/metaphor/manager/MetaphorSubFragmentManager.java",
"retrieved_chunk": " m_metaphorManager.bindFragmentListener(metaphorMessage);\n }\n @Override\n public void sendMessageToFragment(String tagForFragment, int code, Object msg) {\n m_metaphorManager.sendMessageToFragment(tagForFragment, code, msg);\n }\n @Override\n public void sendMessageToFragment(Fragment fragment, int code, Object msg) {\n m_metaphorManager.sendMessageToFragment(fragment, code, msg);\n }",
"score": 0.8264795541763306
},
{
"filename": "app/src/main/java/com/xuanwenchao/metaphor_demo/MainActivity.java",
"retrieved_chunk": " //add and show a fragment who name is m_fa to specify serial number container (R.id.container_number_one)\n metaphorManager.addFragment(m_fa, \"FA\").showFragment(\"FA\");\n metaphorManager.bindListener(new IMetaphorMessage() {\n @Override\n public void OnMessageReceive(Object from, int code, Object msg) {\n if (from == m_fa || from == m_fb || from == m_fc) {\n switch (code) {\n case METAPHOR_MESSAGE_TO_SHOW_FA: {\n metaphorManager.showFragment(\"FA\");\n }",
"score": 0.7840238809585571
},
{
"filename": "Metaphor/src/main/java/com/xuanwenchao/metaphor/manager/MetaphorSubFragmentManager.java",
"retrieved_chunk": " @Override\n public IMetaphorSubFragmentManager showFragment(@NonNull String strTag) {\n m_metaphorManager.showFragment(strTag);\n return this;\n }\n @Override\n public IMetaphorSubFragmentManager showFragment(@NonNull Fragment fragment) {\n m_metaphorManager.showFragment(fragment);\n return this;\n }",
"score": 0.7771557569503784
},
{
"filename": "Metaphor/src/main/java/com/xuanwenchao/metaphor/manager/MetaphorActivityManager.java",
"retrieved_chunk": " }\n }\n @Override\n public void addContainerViewID(int containerViewId) {\n if (m_baseObject == null) {\n throw new MetaphorException(\"No base fragment or activity be specified!\");\n }\n if (m_containerViewMap.get(containerViewId) == null) {\n m_containerViewMap.put(containerViewId, ((AppCompatActivity) m_baseObject).getSupportFragmentManager());\n }",
"score": 0.7697854042053223
}
] | java | ).OnMessageReceive(m_baseObject, code, msg); |
package com.xtracr.realcamera.mixins;
import com.xtracr.realcamera.RealCameraCore;
import com.xtracr.realcamera.compat.DoABarrelRollCompat;
import com.xtracr.realcamera.config.ConfigFile;
import com.xtracr.realcamera.utils.CrosshairUtils;
import com.xtracr.realcamera.utils.RaycastUtils;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.option.Perspective;
import net.minecraft.client.render.Camera;
import net.minecraft.client.render.GameRenderer;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.entity.Entity;
import net.minecraft.entity.projectile.ProjectileUtil;
import net.minecraft.util.hit.EntityHitResult;
import net.minecraft.util.math.Box;
import net.minecraft.util.math.Vec3d;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.ModifyVariable;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(GameRenderer.class)
public abstract class MixinGameRenderer {
@Unique
private static boolean toggled = false;
@Shadow
@Final MinecraftClient client;
@ModifyVariable(method = "updateTargetedEntity", at = @At("STORE"), ordinal = 0)
private EntityHitResult modifyEntityHitResult(EntityHitResult entityHitResult) {
CrosshairUtils.capturedEntityHitResult = entityHitResult;
if (!ConfigFile.modConfig.isCrosshairDynamic() && RealCameraCore.isActive()) {
Vec3d startVec = RaycastUtils.getStartVec();
Vec3d endVec = RaycastUtils.getEndVec();
double sqDistance = (client.crosshairTarget != null ?
client.crosshairTarget.getPos().squaredDistanceTo(startVec) : endVec.squaredDistanceTo(startVec));
Entity cameraEntity = client.getCameraEntity();
Box box = cameraEntity.getBoundingBox().stretch(cameraEntity.getRotationVec(client.getTickDelta())
.multiply(client.interactionManager.getReachDistance())).expand(1.0, 1.0, 1.0);
CrosshairUtils.capturedEntityHitResult = ProjectileUtil.raycast(cameraEntity, startVec, endVec, box, entity -> !entity.isSpectator() && entity.canHit(), sqDistance);
}
return CrosshairUtils.capturedEntityHitResult;
}
@Inject(method = "renderHand", at = @At(value = "INVOKE",
target = "Lnet/minecraft/client/util/math/MatrixStack;push()V"))
private void setThirdPerson(MatrixStack matrices, Camera camera, float tickDelta, CallbackInfo cInfo) {
if (ConfigFile.modConfig.isRendering() && camera.isThirdPerson() && RealCameraCore.isActive() &&
!ConfigFile.modConfig.allowRenderingHandWhen(client)) {
client.options.setPerspective(Perspective.THIRD_PERSON_BACK);
toggled = true;
}
}
@Inject(method = "renderHand", at = @At(value = "INVOKE",
target = "Lnet/minecraft/client/util/math/MatrixStack;pop()V"))
private void setFirstPerson(CallbackInfo cInfo) {
if (toggled) {
client.options.setPerspective(Perspective.FIRST_PERSON);
toggled = false;
}
}
@Inject(method = "renderWorld", at = @At(value = "INVOKE",
target = "Lnet/minecraft/client/render/Camera;update(Lnet/minecraft/world/BlockView;Lnet/minecraft/entity/Entity;ZZF)V",
shift = At.Shift.BY, by = -2))
private void onBeforeCameraUpdate(float tickDelta, long limitTime, MatrixStack matrixStack, CallbackInfo cInfo) {
if (ConfigFile.modConfig.compatDoABarrelRoll | () && DoABarrelRollCompat.modEnabled() && RealCameraCore.isActive()) { |
matrixStack.loadIdentity();
}
}
}
| common/src/main/java/com/xtracr/realcamera/mixins/MixinGameRenderer.java | xTracr-RealCamera-7675633 | [
{
"filename": "fabric/src/main/java/com/xtracr/realcamera/mixins/GameRendererEvents.java",
"retrieved_chunk": " target = \"Lnet/minecraft/client/render/Camera;update(Lnet/minecraft/world/BlockView;Lnet/minecraft/entity/Entity;ZZF)V\",\n shift = At.Shift.AFTER))\n private void onAfterCameraUpdate(float tickDelta, long limitTime, MatrixStack matrixStack, CallbackInfo cInfo) {\n if (RealCameraCore.isActive()) {\n RealCameraCore.updateCamera(camera, client, tickDelta);\n matrixStack.multiply(RotationAxis.POSITIVE_Z.rotationDegrees(RealCameraCore.getRoll()));\n }\n }\n}",
"score": 0.8905559182167053
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/mixins/MixinInGameHud.java",
"retrieved_chunk": "@Mixin(InGameHud.class)\npublic abstract class MixinInGameHud {\n @Inject(method = \"renderCrosshair(Lnet/minecraft/client/gui/DrawContext;)V\", at = @At(\"HEAD\"))\n private void onRenderCrosshairHEAD(DrawContext context, CallbackInfo cInfo) {\n if (ConfigFile.modConfig.isCrosshairDynamic() && RealCameraCore.isActive()) {\n context.getMatrices().push();\n CrosshairUtils.translateMatrices(context.getMatrices());\n }\n }\n @Inject(method = \"renderCrosshair(Lnet/minecraft/client/gui/DrawContext;)V\", at = @At(\"RETURN\"))",
"score": 0.8546133041381836
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/mixins/MixinEntityRenderer.java",
"retrieved_chunk": "import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;\n@Mixin(EntityRenderer.class)\npublic abstract class MixinEntityRenderer {\n @Inject(method = \"shouldRender\", at = @At(\"HEAD\"), cancellable = true)\n private <T extends Entity> void onShouldRenderHEAD(T entity, Frustum frustum, double x, double y, double z,\n CallbackInfoReturnable<Boolean> cInfo) {\n if (ConfigFile.modConfig.isRendering() && RealCameraCore.isActive() && entity instanceof ClientPlayerEntity) {\n cInfo.setReturnValue(true);\n }\n }",
"score": 0.8348473310470581
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/mixins/MixinItem.java",
"retrieved_chunk": "import org.spongepowered.asm.mixin.injection.At;\nimport org.spongepowered.asm.mixin.injection.Inject;\nimport org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;\n@Mixin(Item.class)\npublic abstract class MixinItem {\n @Inject(method = \"raycast\", at = @At(\"HEAD\"), cancellable = true)\n private static void coverRaycast(World world, PlayerEntity player, RaycastContext.FluidHandling fluidHandling,\n CallbackInfoReturnable<BlockHitResult> cInfo) {\n if (!ConfigFile.modConfig.isCrosshairDynamic() && RealCameraCore.isActive()) {\n RaycastUtils.update(player, 25.0D, 1.0F);",
"score": 0.8139110803604126
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/mixins/MixinClientPlayerEntity.java",
"retrieved_chunk": " target = \"Lnet/minecraft/client/option/Perspective;isFirstPerson()Z\"))\n private boolean returnFalse(Perspective perspective) {\n if (ConfigFile.modConfig.isRendering() && RealCameraCore.isActive()) return false;\n return perspective.isFirstPerson();\n }\n @Override\n public HitResult raycast(double maxDistance, float tickDelta, boolean includeFluids) {\n if (!ConfigFile.modConfig.isCrosshairDynamic() && RealCameraCore.isActive()) {\n RaycastUtils.update(this, maxDistance * maxDistance, tickDelta);\n return getWorld().raycast(RaycastUtils.getRaycastContext(RaycastContext.ShapeType.OUTLINE,",
"score": 0.8122808933258057
}
] | java | () && DoABarrelRollCompat.modEnabled() && RealCameraCore.isActive()) { |
package com.xtracr.realcamera.mixins;
import com.xtracr.realcamera.api.VirtualRenderer;
import net.minecraft.client.network.AbstractClientPlayerEntity;
import net.minecraft.client.network.ClientPlayerEntity;
import net.minecraft.client.render.entity.EntityRendererFactory.Context;
import net.minecraft.client.render.entity.LivingEntityRenderer;
import net.minecraft.client.render.entity.PlayerEntityRenderer;
import net.minecraft.client.render.entity.model.PlayerEntityModel;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(PlayerEntityRenderer.class)
public abstract class MixinPlayerEntityRenderer
extends LivingEntityRenderer<AbstractClientPlayerEntity, PlayerEntityModel<AbstractClientPlayerEntity>> {
public MixinPlayerEntityRenderer(Context ctx, PlayerEntityModel<AbstractClientPlayerEntity> model,
float shadowRadius) {
super(ctx, model, shadowRadius);
}
@Inject(method = "setModelPose", at = @At("RETURN"))
private void onSetModelPoseRETURN(AbstractClientPlayerEntity player, CallbackInfo cInfo) {
if (!(player instanceof ClientPlayerEntity)) return;
if (VirtualRenderer.shouldDisableRender("head")) model.head.visible = false;
if (VirtualRenderer.shouldDisableRender("hat")) model.hat.visible = false;
if (VirtualRenderer.shouldDisableRender("body")) model.body.visible = false;
if (VirtualRenderer.shouldDisableRender("rightArm")) model.rightArm.visible = false;
if (VirtualRenderer.shouldDisableRender("leftArm")) model.leftArm.visible = false;
if (VirtualRenderer.shouldDisableRender("rightLeg")) model.rightLeg.visible = false;
if (VirtualRenderer.shouldDisableRender("leftLeg")) model.leftLeg.visible = false;
if (VirtualRenderer.shouldDisableRender("leftSleeve")) model.leftSleeve.visible = false;
if (VirtualRenderer.shouldDisableRender("rightSleeve")) model.rightSleeve.visible = false;
| if (VirtualRenderer.shouldDisableRender("leftPants")) model.leftPants.visible = false; |
if (VirtualRenderer.shouldDisableRender("rightPants")) model.rightPants.visible = false;
if (VirtualRenderer.shouldDisableRender("jacket")) model.jacket.visible = false;
}
}
| common/src/main/java/com/xtracr/realcamera/mixins/MixinPlayerEntityRenderer.java | xTracr-RealCamera-7675633 | [
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ModConfig.java",
"retrieved_chunk": " if (disable.onlyInBinding && general.classic) return false;\n return shouldDisable(client, \"disable_mod\") ||\n (client.player.isFallFlying() && disable.fallFlying) ||\n (client.player.isSwimming() && disable.swimming) ||\n (client.player.isCrawling() && disable.crawling) ||\n (client.player.isSneaking() && disable.sneaking) ||\n (client.player.isSleeping() && disable.sleeping) ||\n (client.currentScreen != null && disable.screenOpened);\n }\n public boolean disableRenderingWhen(MinecraftClient client) {",
"score": 0.7061036825180054
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/mixins/MixinArmorFeatureRenderer.java",
"retrieved_chunk": " (VirtualRenderer.shouldDisableRender(\"chestplate\") && armorSlot == EquipmentSlot.CHEST) ||\n (VirtualRenderer.shouldDisableRender(\"leggings\") && armorSlot == EquipmentSlot.LEGS) ||\n (VirtualRenderer.shouldDisableRender(\"boots\") && armorSlot == EquipmentSlot.FEET)) {\n cInfo.cancel();\n }\n }\n}",
"score": 0.6919610500335693
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ConfigScreen.java",
"retrieved_chunk": " .setSaveConsumer(b -> config.compats.physicsMod = b)\n .build());\n compats.addEntry(compatSwitches.build());\n disable.addEntry(entryBuilder.startBooleanToggle(Text.translatable(OPTION + \"onlyInBinding\"), config.disable.onlyInBinding)\n .setDefaultValue(true)\n .setSaveConsumer(b -> config.disable.onlyInBinding = b)\n .build());\n disable.addEntry(entryBuilder.startBooleanToggle(Text.translatable(OPTION + \"renderModelPart\"), config.disable.renderModelPart)\n .setDefaultValue(false)\n .setSaveConsumer(b -> config.disable.renderModelPart = b)",
"score": 0.675459086894989
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ModConfig.java",
"retrieved_chunk": " public boolean shouldDisableRender(String modelPartName) {\n if (disable.onlyInBinding && general.classic) return false;\n return (disable.renderModelPart && disable.disabledModelParts.contains(modelPartName)) ||\n shouldDisable(MinecraftClient.getInstance(), modelPartName);\n }\n public boolean allowRenderingHandWhen(MinecraftClient client) {\n if (disable.onlyInBinding && general.classic) return false;\n return shouldDisable(client, \"allow_rendering_hand\");\n }\n public boolean disableModWhen(MinecraftClient client) {",
"score": 0.6723698377609253
},
{
"filename": "common/src/main/java/com/xtracr/realcamera/config/ConfigScreen.java",
"retrieved_chunk": " }));\n SubCategoryBuilder disableModWhen = entryBuilder.startSubCategory(Text.translatable(CATEGORY + \"disableModWhen\"));\n disableModWhen.add(entryBuilder.startBooleanToggle(Text.translatable(OPTION + \"fallFlying\"), config.disable.fallFlying)\n .setDefaultValue(true)\n .setSaveConsumer(b -> config.disable.fallFlying = b)\n .build());\n disableModWhen.add(entryBuilder.startBooleanToggle(Text.translatable(OPTION + \"swimming\"), config.disable.swimming)\n .setDefaultValue(false)\n .setSaveConsumer(b -> config.disable.swimming = b)\n .build());",
"score": 0.6624155044555664
}
] | java | if (VirtualRenderer.shouldDisableRender("leftPants")) model.leftPants.visible = false; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.