file_name
stringlengths 6
86
| file_path
stringlengths 45
249
| content
stringlengths 47
6.26M
| file_size
int64 47
6.26M
| language
stringclasses 1
value | extension
stringclasses 1
value | repo_name
stringclasses 767
values | repo_stars
int64 8
14.4k
| repo_forks
int64 0
1.17k
| repo_open_issues
int64 0
788
| repo_created_at
stringclasses 767
values | repo_pushed_at
stringclasses 767
values |
---|---|---|---|---|---|---|---|---|---|---|---|
ShowDeletedMessagesPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/twitch/patches/ShowDeletedMessagesPatch.java | package app.revanced.integrations.twitch.patches;
import static app.revanced.integrations.shared.StringRef.str;
import android.graphics.Color;
import android.graphics.Typeface;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.style.ForegroundColorSpan;
import android.text.style.StrikethroughSpan;
import android.text.style.StyleSpan;
import androidx.annotation.Nullable;
import app.revanced.integrations.twitch.settings.Settings;
import tv.twitch.android.shared.chat.util.ClickableUsernameSpan;
@SuppressWarnings("unused")
public class ShowDeletedMessagesPatch {
/**
* Injection point.
*/
public static boolean shouldUseSpoiler() {
return "spoiler".equals(Settings.SHOW_DELETED_MESSAGES.get());
}
public static boolean shouldCrossOut() {
return "cross-out".equals(Settings.SHOW_DELETED_MESSAGES.get());
}
@Nullable
public static Spanned reformatDeletedMessage(Spanned original) {
if (!shouldCrossOut())
return null;
SpannableStringBuilder ssb = new SpannableStringBuilder(original);
ssb.setSpan(new StrikethroughSpan(), 0, original.length(), 0);
ssb.append(" (").append(str("revanced_deleted_msg")).append(")");
ssb.setSpan(new StyleSpan(Typeface.ITALIC), original.length(), ssb.length(), 0);
// Gray-out username
ClickableUsernameSpan[] usernameSpans = original.getSpans(0, original.length(), ClickableUsernameSpan.class);
if (usernameSpans.length > 0) {
ssb.setSpan(new ForegroundColorSpan(Color.parseColor("#ADADB8")), 0, original.getSpanEnd(usernameSpans[0]), 0);
}
return new SpannedString(ssb);
}
}
| 1,758 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
AppCompatActivityHook.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/twitch/settings/AppCompatActivityHook.java | package app.revanced.integrations.twitch.settings;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.ActionBar;
import app.revanced.integrations.shared.Logger;
import app.revanced.integrations.shared.Utils;
import app.revanced.integrations.twitch.settings.preference.ReVancedPreferenceFragment;
import tv.twitch.android.feature.settings.menu.SettingsMenuGroup;
import tv.twitch.android.settings.SettingsActivity;
import java.util.ArrayList;
import java.util.List;
/**
* Hooks AppCompatActivity.
* <p>
* This class is responsible for injecting our own fragment by replacing the AppCompatActivity.
* @noinspection unused
*/
public class AppCompatActivityHook {
private static final int REVANCED_SETTINGS_MENU_ITEM_ID = 0x7;
private static final String EXTRA_REVANCED_SETTINGS = "app.revanced.twitch.settings";
/**
* Launches SettingsActivity and show ReVanced settings
*/
public static void startSettingsActivity() {
Logger.printDebug(() -> "Launching ReVanced settings");
final var context = Utils.getContext();
if (context != null) {
Intent intent = new Intent(context, SettingsActivity.class);
Bundle bundle = new Bundle();
bundle.putBoolean(EXTRA_REVANCED_SETTINGS, true);
intent.putExtras(bundle);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
/**
* Helper for easy access in smali
* @return Returns string resource id
*/
public static int getReVancedSettingsString() {
return app.revanced.integrations.twitch.Utils.getStringId("revanced_settings");
}
/**
* Intercepts settings menu group list creation in SettingsMenuPresenter$Event.MenuGroupsUpdated
* @return Returns a modified list of menu groups
*/
public static List<SettingsMenuGroup> handleSettingMenuCreation(List<SettingsMenuGroup> settingGroups, Object revancedEntry) {
List<SettingsMenuGroup> groups = new ArrayList<>(settingGroups);
if (groups.isEmpty()) {
// Create new menu group if none exist yet
List<Object> items = new ArrayList<>();
items.add(revancedEntry);
groups.add(new SettingsMenuGroup(items));
} else {
// Add to last menu group
int groupIdx = groups.size() - 1;
List<Object> items = new ArrayList<>(groups.remove(groupIdx).getSettingsMenuItems());
items.add(revancedEntry);
groups.add(new SettingsMenuGroup(items));
}
Logger.printDebug(() -> settingGroups.size() + " menu groups in list");
return groups;
}
/**
* Intercepts settings menu group onclick events
* @return Returns true if handled, otherwise false
*/
@SuppressWarnings("rawtypes")
public static boolean handleSettingMenuOnClick(Enum item) {
Logger.printDebug(() -> "item " + item.ordinal() + " clicked");
if (item.ordinal() != REVANCED_SETTINGS_MENU_ITEM_ID) {
return false;
}
startSettingsActivity();
return true;
}
/**
* Intercepts fragment loading in SettingsActivity.onCreate
* @return Returns true if the revanced settings have been requested by the user, otherwise false
*/
public static boolean handleSettingsCreation(androidx.appcompat.app.AppCompatActivity base) {
if (!base.getIntent().getBooleanExtra(EXTRA_REVANCED_SETTINGS, false)) {
Logger.printDebug(() -> "Revanced settings not requested");
return false; // User wants to enter another settings fragment
}
Logger.printDebug(() -> "ReVanced settings requested");
ReVancedPreferenceFragment fragment = new ReVancedPreferenceFragment();
ActionBar supportActionBar = base.getSupportActionBar();
if (supportActionBar != null)
supportActionBar.setTitle(app.revanced.integrations.twitch.Utils.getStringId("revanced_settings"));
base.getFragmentManager()
.beginTransaction()
.replace(Utils.getResourceIdentifier("fragment_container", "id"), fragment)
.commit();
return true;
}
}
| 4,284 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
Settings.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/twitch/settings/Settings.java | package app.revanced.integrations.twitch.settings;
import app.revanced.integrations.shared.settings.BooleanSetting;
import app.revanced.integrations.shared.settings.BaseSettings;
import app.revanced.integrations.shared.settings.StringSetting;
import static java.lang.Boolean.FALSE;
import static java.lang.Boolean.TRUE;
public class Settings extends BaseSettings {
/* Ads */
public static final BooleanSetting BLOCK_VIDEO_ADS = new BooleanSetting("revanced_block_video_ads", TRUE);
public static final BooleanSetting BLOCK_AUDIO_ADS = new BooleanSetting("revanced_block_audio_ads", TRUE);
public static final StringSetting BLOCK_EMBEDDED_ADS = new StringSetting("revanced_block_embedded_ads", "luminous");
/* Chat */
public static final StringSetting SHOW_DELETED_MESSAGES = new StringSetting("revanced_show_deleted_messages", "cross-out");
public static final BooleanSetting AUTO_CLAIM_CHANNEL_POINTS = new BooleanSetting("revanced_auto_claim_channel_points", TRUE);
/* Misc */
/**
* Not to be confused with {@link BaseSettings#DEBUG}.
*/
public static final BooleanSetting TWITCH_DEBUG_MODE = new BooleanSetting("revanced_twitch_debug_mode", FALSE, true);
}
| 1,215 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
CustomPreferenceCategory.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/twitch/settings/preference/CustomPreferenceCategory.java | package app.revanced.integrations.twitch.settings.preference;
import android.content.Context;
import android.graphics.Color;
import android.preference.PreferenceCategory;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;
public class CustomPreferenceCategory extends PreferenceCategory {
public CustomPreferenceCategory(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onBindView(View rootView) {
super.onBindView(rootView);
if(rootView instanceof TextView) {
((TextView) rootView).setTextColor(Color.parseColor("#8161b3"));
}
}
} | 680 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
ReVancedPreferenceFragment.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/twitch/settings/preference/ReVancedPreferenceFragment.java | package app.revanced.integrations.twitch.settings.preference;
import app.revanced.integrations.shared.Logger;
import app.revanced.integrations.shared.settings.preference.AbstractPreferenceFragment;
import app.revanced.integrations.twitch.settings.Settings;
/**
* Preference fragment for ReVanced settings
*/
public class ReVancedPreferenceFragment extends AbstractPreferenceFragment {
@Override
protected void initialize() {
super.initialize();
// Do anything that forces this apps Settings bundle to load.
if (Settings.BLOCK_VIDEO_ADS.get()) {
Logger.printDebug(() -> "Block video ads enabled"); // Any statement that references the app settings.
}
}
}
| 716 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
RetrofitClient.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/twitch/api/RetrofitClient.java | package app.revanced.integrations.twitch.api;
import retrofit2.Retrofit;
public class RetrofitClient {
private static RetrofitClient instance = null;
private final PurpleAdblockApi purpleAdblockApi;
private RetrofitClient() {
Retrofit retrofit = new Retrofit.Builder().baseUrl("http://localhost" /* dummy */).build();
purpleAdblockApi = retrofit.create(PurpleAdblockApi.class);
}
public static synchronized RetrofitClient getInstance() {
if (instance == null) {
instance = new RetrofitClient();
}
return instance;
}
public PurpleAdblockApi getPurpleAdblockApi() {
return purpleAdblockApi;
}
} | 690 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
RequestInterceptor.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/twitch/api/RequestInterceptor.java | package app.revanced.integrations.twitch.api;
import androidx.annotation.NonNull;
import app.revanced.integrations.shared.Logger;
import app.revanced.integrations.shared.Utils;
import app.revanced.integrations.twitch.adblock.IAdblockService;
import app.revanced.integrations.twitch.adblock.LuminousService;
import app.revanced.integrations.twitch.adblock.PurpleAdblockService;
import app.revanced.integrations.twitch.settings.Settings;
import okhttp3.Interceptor;
import okhttp3.Response;
import java.io.IOException;
import static app.revanced.integrations.shared.StringRef.str;
public class RequestInterceptor implements Interceptor {
private IAdblockService activeService = null;
private static final String PROXY_DISABLED = str("revanced_block_embedded_ads_entry_1");
private static final String LUMINOUS_SERVICE = str("revanced_block_embedded_ads_entry_2");
private static final String PURPLE_ADBLOCK_SERVICE = str("revanced_block_embedded_ads_entry_3");
@NonNull
@Override
public Response intercept(@NonNull Chain chain) throws IOException {
var originalRequest = chain.request();
if (Settings.BLOCK_EMBEDDED_ADS.get().equals(PROXY_DISABLED)) {
return chain.proceed(originalRequest);
}
Logger.printDebug(() -> "Intercepted request to URL:" + originalRequest.url());
// Skip if not HLS manifest request
if (!originalRequest.url().host().contains("usher.ttvnw.net")) {
return chain.proceed(originalRequest);
}
final String isVod;
if (IAdblockService.isVod(originalRequest)) isVod = "yes";
else isVod = "no";
Logger.printDebug(() -> "Found HLS manifest request. Is VOD? " +
isVod +
"; Channel: " +
IAdblockService.channelName(originalRequest)
);
// None of the services support VODs currently
if (IAdblockService.isVod(originalRequest)) return chain.proceed(originalRequest);
updateActiveService();
if (activeService != null) {
var available = activeService.isAvailable();
var rewritten = activeService.rewriteHlsRequest(originalRequest);
if (!available || rewritten == null) {
Utils.showToastShort(String.format(
str("revanced_embedded_ads_service_unavailable"), activeService.friendlyName()
));
return chain.proceed(originalRequest);
}
Logger.printDebug(() -> "Rewritten HLS stream URL: " + rewritten.url());
var maxAttempts = activeService.maxAttempts();
for (var i = 1; i <= maxAttempts; i++) {
// Execute rewritten request and close body to allow multiple proceed() calls
var response = chain.proceed(rewritten);
response.close();
if (!response.isSuccessful()) {
int attempt = i;
Logger.printException(() -> "Request failed (attempt " +
attempt +
"/" + maxAttempts + "): HTTP error " +
response.code() +
" (" + response.message() + ")"
);
try {
Thread.sleep(50);
} catch (InterruptedException e) {
Logger.printException(() -> "Failed to sleep", e);
}
} else {
// Accept response from ad blocker
Logger.printDebug(() -> "Ad-blocker used");
return chain.proceed(rewritten);
}
}
// maxAttempts exceeded; giving up on using the ad blocker
Utils.showToastLong(String.format(
str("revanced_embedded_ads_service_failed"),
activeService.friendlyName())
);
}
// Adblock disabled
return chain.proceed(originalRequest);
}
private void updateActiveService() {
var current = Settings.BLOCK_EMBEDDED_ADS.get();
if (current.equals(LUMINOUS_SERVICE) && !(activeService instanceof LuminousService))
activeService = new LuminousService();
else if (current.equals(PURPLE_ADBLOCK_SERVICE) && !(activeService instanceof PurpleAdblockService))
activeService = new PurpleAdblockService();
else if (current.equals(PROXY_DISABLED))
activeService = null;
}
}
| 4,579 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
PurpleAdblockApi.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/twitch/api/PurpleAdblockApi.java | package app.revanced.integrations.twitch.api;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Url;
/* only used for service pings */
public interface PurpleAdblockApi {
@GET /* root */
Call<ResponseBody> ping(@Url String baseUrl);
} | 295 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
LuminousService.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/twitch/adblock/LuminousService.java | package app.revanced.integrations.twitch.adblock;
import app.revanced.integrations.shared.Logger;
import okhttp3.HttpUrl;
import okhttp3.Request;
import static app.revanced.integrations.shared.StringRef.str;
public class LuminousService implements IAdblockService {
@Override
public String friendlyName() {
return str("revanced_proxy_luminous");
}
@Override
public Integer maxAttempts() {
return 2;
}
@Override
public Boolean isAvailable() {
return true;
}
@Override
public Request rewriteHlsRequest(Request originalRequest) {
var type = IAdblockService.isVod(originalRequest) ? "vod" : "playlist";
var url = HttpUrl.parse("https://eu.luminous.dev/" +
type +
"/" +
IAdblockService.channelName(originalRequest) +
".m3u8" +
"%3Fallow_source%3Dtrue%26allow_audio_only%3Dtrue%26fast_bread%3Dtrue"
);
if (url == null) {
Logger.printException(() -> "Failed to parse rewritten URL");
return null;
}
// Overwrite old request
return new Request.Builder()
.get()
.url(url)
.build();
}
}
| 1,265 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
PurpleAdblockService.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/twitch/adblock/PurpleAdblockService.java | package app.revanced.integrations.twitch.adblock;
import app.revanced.integrations.shared.Logger;
import app.revanced.integrations.twitch.api.RetrofitClient;
import okhttp3.HttpUrl;
import okhttp3.Request;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static app.revanced.integrations.shared.StringRef.str;
public class PurpleAdblockService implements IAdblockService {
private final Map<String, Boolean> tunnels = new HashMap<>() {{
put("https://eu1.jupter.ga", false);
put("https://eu2.jupter.ga", false);
}};
@Override
public String friendlyName() {
return str("revanced_proxy_purpleadblock");
}
@Override
public Integer maxAttempts() {
return 3;
}
@Override
public Boolean isAvailable() {
for (String tunnel : tunnels.keySet()) {
var success = true;
try {
var response = RetrofitClient.getInstance().getPurpleAdblockApi().ping(tunnel).execute();
if (!response.isSuccessful()) {
Logger.printException(() ->
"PurpleAdBlock tunnel $tunnel returned an error: HTTP code " + response.code()
);
Logger.printDebug(response::message);
try (var errorBody = response.errorBody()) {
if (errorBody != null) {
Logger.printDebug(() -> {
try {
return errorBody.string();
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
}
success = false;
}
} catch (Exception ex) {
Logger.printException(() -> "PurpleAdBlock tunnel $tunnel is unavailable", ex);
success = false;
}
// Cache availability data
tunnels.put(tunnel, success);
if (success)
return true;
}
return false;
}
@Override
public Request rewriteHlsRequest(Request originalRequest) {
for (Map.Entry<String, Boolean> entry : tunnels.entrySet()) {
if (!entry.getValue()) continue;
var server = entry.getKey();
// Compose new URL
var url = HttpUrl.parse(server + "/channel/" + IAdblockService.channelName(originalRequest));
if (url == null) {
Logger.printException(() -> "Failed to parse rewritten URL");
return null;
}
// Overwrite old request
return new Request.Builder()
.get()
.url(url)
.build();
}
Logger.printException(() -> "No tunnels are available");
return null;
}
}
| 3,017 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
IAdblockService.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/twitch/adblock/IAdblockService.java | package app.revanced.integrations.twitch.adblock;
import okhttp3.Request;
public interface IAdblockService {
String friendlyName();
Integer maxAttempts();
Boolean isAvailable();
Request rewriteHlsRequest(Request originalRequest);
static boolean isVod(Request request){
return request.url().pathSegments().contains("vod");
}
static String channelName(Request request) {
for (String pathSegment : request.url().pathSegments()) {
if (pathSegment.endsWith(".m3u8")) {
return pathSegment.replace(".m3u8", "");
}
}
return null;
}
}
| 637 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
FilterPromotedLinksPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/reddit/patches/FilterPromotedLinksPatch.java | package app.revanced.integrations.reddit.patches;
import com.reddit.domain.model.ILink;
import java.util.ArrayList;
import java.util.List;
public final class FilterPromotedLinksPatch {
/**
* Filters list from promoted links.
**/
public static List<?> filterChildren(final Iterable<?> links) {
final List<Object> filteredList = new ArrayList<>();
for (Object item : links) {
if (item instanceof ILink && ((ILink) item).getPromoted()) continue;
filteredList.add(item);
}
return filteredList;
}
}
| 578 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
RemoveScreencaptureRestrictionPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/all/screencapture/removerestriction/RemoveScreencaptureRestrictionPatch.java | package app.revanced.integrations.all.screencapture.removerestriction;
import android.media.AudioAttributes;
import android.os.Build;
import androidx.annotation.RequiresApi;
public final class RemoveScreencaptureRestrictionPatch {
// Member of AudioAttributes.Builder
@RequiresApi(api = Build.VERSION_CODES.Q)
public static AudioAttributes.Builder setAllowedCapturePolicy(final AudioAttributes.Builder builder, final int capturePolicy) {
builder.setAllowedCapturePolicy(AudioAttributes.ALLOW_CAPTURE_BY_ALL);
return builder;
}
// Member of AudioManager static class
public static void setAllowedCapturePolicy(final int capturePolicy) {
// Ignore request
}
}
| 715 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
RemoveScreenshotRestrictionPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/all/screenshot/removerestriction/RemoveScreenshotRestrictionPatch.java | package app.revanced.integrations.all.screenshot.removerestriction;
import android.view.Window;
import android.view.WindowManager;
public class RemoveScreenshotRestrictionPatch {
public static void addFlags(Window window, int flags) {
window.addFlags(flags & ~WindowManager.LayoutParams.FLAG_SECURE);
}
public static void setFlags(Window window, int flags, int mask) {
window.setFlags(flags & ~WindowManager.LayoutParams.FLAG_SECURE, mask & ~WindowManager.LayoutParams.FLAG_SECURE);
}
}
| 523 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
SpoofWifiPatch.java | /FileExtraction/Java_unseen/ReVanced_revanced-integrations/app/src/main/java/app/revanced/integrations/all/connectivity/wifi/spoof/SpoofWifiPatch.java | package app.revanced.integrations.all.connectivity.wifi.spoof;
import android.app.PendingIntent;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.NetworkRequest;
import android.os.Build;
import android.os.Handler;
import androidx.annotation.RequiresApi;
public class SpoofWifiPatch {
// Used to check what the (real or fake) active network is (take a look at `hasTransport`).
private static ConnectivityManager CONNECTIVITY_MANAGER;
// If Wifi is not enabled, these are types that would pretend to be Wifi for android.net.Network (lower index = higher priority).
// This does not apply to android.net.NetworkInfo, because we can pretend that Wifi is always active there.
//
// VPN should be a fallback, because Reverse Tethering uses VPN.
private static final int[] FAKE_FALLBACK_NETWORKS = { NetworkCapabilities.TRANSPORT_ETHERNET, NetworkCapabilities.TRANSPORT_VPN };
// In order to initialize our own ConnectivityManager, if it isn't initialized yet.
public static Object getSystemService(Context context, String name) {
Object result = context.getSystemService(name);
if (CONNECTIVITY_MANAGER == null) {
if (Context.CONNECTIVITY_SERVICE.equals(name)) {
CONNECTIVITY_MANAGER = (ConnectivityManager) result;
} else {
CONNECTIVITY_MANAGER = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
}
}
return result;
}
// In order to initialize our own ConnectivityManager, if it isn't initialized yet.
public static Object getSystemService(Context context, Class<?> serviceClass) {
Object result = context.getSystemService(serviceClass);
if (CONNECTIVITY_MANAGER == null) {
if (serviceClass == ConnectivityManager.class) {
CONNECTIVITY_MANAGER = (ConnectivityManager) result;
} else {
CONNECTIVITY_MANAGER = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
}
}
return result;
}
// Simply always return Wifi as active network.
public static NetworkInfo getActiveNetworkInfo(ConnectivityManager connectivityManager) {
for (NetworkInfo networkInfo : connectivityManager.getAllNetworkInfo()) {
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
return networkInfo;
}
}
return connectivityManager.getActiveNetworkInfo();
}
// Pretend Wifi is always connected.
public static boolean isConnected(NetworkInfo networkInfo) {
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
return true;
}
return networkInfo.isConnected();
}
// Pretend Wifi is always connected.
public static boolean isConnectedOrConnecting(NetworkInfo networkInfo) {
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
return true;
}
return networkInfo.isConnectedOrConnecting();
}
// Pretend Wifi is always available.
public static boolean isAvailable(NetworkInfo networkInfo) {
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
return true;
}
return networkInfo.isAvailable();
}
// Pretend Wifi is always connected.
public static NetworkInfo.State getState(NetworkInfo networkInfo) {
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
return NetworkInfo.State.CONNECTED;
}
return networkInfo.getState();
}
// Pretend Wifi is always connected.
public static NetworkInfo.DetailedState getDetailedState(NetworkInfo networkInfo) {
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
return NetworkInfo.DetailedState.CONNECTED;
}
return networkInfo.getDetailedState();
}
// Pretend Wifi is enabled, so connection isn't metered.
public static boolean isActiveNetworkMetered(ConnectivityManager connectivityManager) {
return false;
}
// Returns the Wifi network, if Wifi is enabled.
// Otherwise if one of our fallbacks has a connection, return them.
// And as a last resort, return the default active network.
public static Network getActiveNetwork(ConnectivityManager connectivityManager) {
Network[] prioritizedNetworks = new Network[FAKE_FALLBACK_NETWORKS.length];
for (Network network : connectivityManager.getAllNetworks()) {
NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(network);
if (networkCapabilities == null) {
continue;
}
if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
return network;
}
if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
for (int i = 0; i < FAKE_FALLBACK_NETWORKS.length; i++) {
int transportType = FAKE_FALLBACK_NETWORKS[i];
if (networkCapabilities.hasTransport(transportType)) {
prioritizedNetworks[i] = network;
break;
}
}
}
}
for (Network network : prioritizedNetworks) {
if (network != null) {
return network;
}
}
return connectivityManager.getActiveNetwork();
}
// If the given network is a real or fake Wifi connection, return a Wifi network.
// Otherwise fallback to default implementation.
public static NetworkInfo getNetworkInfo(ConnectivityManager connectivityManager, Network network) {
NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(network);
if (networkCapabilities != null && hasTransport(networkCapabilities, NetworkCapabilities.TRANSPORT_WIFI)) {
for (NetworkInfo networkInfo : connectivityManager.getAllNetworkInfo()) {
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
return networkInfo;
}
}
}
return connectivityManager.getNetworkInfo(network);
}
// If we are checking if the NetworkCapabilities use Wifi, return yes if
// - it is a real Wifi connection,
// - or the NetworkCapabilities are from a network pretending being a Wifi network.
// Otherwise fallback to default implementation.
public static boolean hasTransport(NetworkCapabilities networkCapabilities, int transportType) {
if (transportType == NetworkCapabilities.TRANSPORT_WIFI) {
if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
return true;
}
if (CONNECTIVITY_MANAGER != null) {
Network activeNetwork = getActiveNetwork(CONNECTIVITY_MANAGER);
NetworkCapabilities activeNetworkCapabilities = CONNECTIVITY_MANAGER.getNetworkCapabilities(activeNetwork);
if (activeNetworkCapabilities != null) {
for (int fallbackTransportType : FAKE_FALLBACK_NETWORKS) {
if (activeNetworkCapabilities.hasTransport(fallbackTransportType) && networkCapabilities.hasTransport(fallbackTransportType)) {
return true;
}
}
}
}
}
return networkCapabilities.hasTransport(transportType);
}
// If the given network is a real or fake Wifi connection, pretend it has a connection (and some other things).
public static boolean hasCapability(NetworkCapabilities networkCapabilities, int capability) {
if (hasTransport(networkCapabilities, NetworkCapabilities.TRANSPORT_WIFI) && (
capability == NetworkCapabilities.NET_CAPABILITY_INTERNET
|| capability == NetworkCapabilities.NET_CAPABILITY_FOREGROUND
|| capability == NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED
|| capability == NetworkCapabilities.NET_CAPABILITY_NOT_METERED
|| capability == NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED
|| capability == NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING
|| capability == NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED
|| capability == NetworkCapabilities.NET_CAPABILITY_NOT_VPN
|| capability == NetworkCapabilities.NET_CAPABILITY_TRUSTED
|| capability == NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
return true;
}
return networkCapabilities.hasCapability(capability);
}
// If it waits for Wifi connectivity, pretend it is fulfilled immediately if we have an active network.
@RequiresApi(api = Build.VERSION_CODES.S)
public static void registerBestMatchingNetworkCallback(ConnectivityManager connectivityManager, NetworkRequest request, ConnectivityManager.NetworkCallback networkCallback, Handler handler) {
Utils.networkCallback(
connectivityManager,
Utils.Option.of(request),
Utils.Option.of(networkCallback),
Utils.Option.empty(),
Utils.Option.of(handler),
() -> connectivityManager.registerBestMatchingNetworkCallback(request, networkCallback, handler)
);
}
// If it waits for Wifi connectivity, pretend it is fulfilled immediately if we have an active network.
@RequiresApi(api = Build.VERSION_CODES.N)
public static void registerDefaultNetworkCallback(ConnectivityManager connectivityManager, ConnectivityManager.NetworkCallback networkCallback) {
Utils.networkCallback(
connectivityManager,
Utils.Option.empty(),
Utils.Option.of(networkCallback),
Utils.Option.empty(),
Utils.Option.empty(),
() -> connectivityManager.registerDefaultNetworkCallback(networkCallback)
);
}
// If it waits for Wifi connectivity, pretend it is fulfilled immediately if we have an active network.
@RequiresApi(api = Build.VERSION_CODES.O)
public static void registerDefaultNetworkCallback(ConnectivityManager connectivityManager, ConnectivityManager.NetworkCallback networkCallback, Handler handler) {
Utils.networkCallback(
connectivityManager,
Utils.Option.empty(),
Utils.Option.of(networkCallback),
Utils.Option.empty(),
Utils.Option.of(handler),
() -> connectivityManager.registerDefaultNetworkCallback(networkCallback, handler)
);
}
// If it waits for Wifi connectivity, pretend it is fulfilled immediately if we have an active network.
public static void registerNetworkCallback(ConnectivityManager connectivityManager, NetworkRequest request, ConnectivityManager.NetworkCallback networkCallback) {
Utils.networkCallback(
connectivityManager,
Utils.Option.of(request),
Utils.Option.of(networkCallback),
Utils.Option.empty(),
Utils.Option.empty(),
() -> connectivityManager.registerNetworkCallback(request, networkCallback)
);
}
// If it waits for Wifi connectivity, pretend it is fulfilled immediately.
public static void registerNetworkCallback(ConnectivityManager connectivityManager, NetworkRequest request, PendingIntent operation) {
Utils.networkCallback(
connectivityManager,
Utils.Option.of(request),
Utils.Option.empty(),
Utils.Option.of(operation),
Utils.Option.empty(),
() -> connectivityManager.registerNetworkCallback(request, operation)
);
}
// If it waits for Wifi connectivity, pretend it is fulfilled immediately if we have an active network.
@RequiresApi(api = Build.VERSION_CODES.O)
public static void registerNetworkCallback(ConnectivityManager connectivityManager, NetworkRequest request, ConnectivityManager.NetworkCallback networkCallback, Handler handler) {
Utils.networkCallback(
connectivityManager,
Utils.Option.of(request),
Utils.Option.of(networkCallback),
Utils.Option.empty(),
Utils.Option.of(handler),
() -> connectivityManager.registerNetworkCallback(request, networkCallback, handler)
);
}
// If it requests Wifi connectivity, pretend it is fulfilled immediately if we have an active network.
public static void requestNetwork(ConnectivityManager connectivityManager, NetworkRequest request, ConnectivityManager.NetworkCallback networkCallback) {
Utils.networkCallback(
connectivityManager,
Utils.Option.of(request),
Utils.Option.of(networkCallback),
Utils.Option.empty(),
Utils.Option.empty(),
() -> connectivityManager.requestNetwork(request, networkCallback)
);
}
// If it requests Wifi connectivity, pretend it is fulfilled immediately if we have an active network.
@RequiresApi(api = Build.VERSION_CODES.O)
public static void requestNetwork(ConnectivityManager connectivityManager, NetworkRequest request, ConnectivityManager.NetworkCallback networkCallback, int timeoutMs) {
Utils.networkCallback(
connectivityManager,
Utils.Option.of(request),
Utils.Option.of(networkCallback),
Utils.Option.empty(),
Utils.Option.empty(),
() -> connectivityManager.requestNetwork(request, networkCallback, timeoutMs)
);
}
// If it requests Wifi connectivity, pretend it is fulfilled immediately if we have an active network.
@RequiresApi(api = Build.VERSION_CODES.O)
public static void requestNetwork(ConnectivityManager connectivityManager, NetworkRequest request, ConnectivityManager.NetworkCallback networkCallback, Handler handler) {
Utils.networkCallback(
connectivityManager,
Utils.Option.of(request),
Utils.Option.of(networkCallback),
Utils.Option.empty(),
Utils.Option.of(handler),
() -> connectivityManager.requestNetwork(request, networkCallback, handler)
);
}
// If it requests Wifi connectivity, pretend it is fulfilled immediately.
public static void requestNetwork(ConnectivityManager connectivityManager, NetworkRequest request, PendingIntent operation) {
Utils.networkCallback(
connectivityManager,
Utils.Option.of(request),
Utils.Option.empty(),
Utils.Option.of(operation),
Utils.Option.empty(),
() -> connectivityManager.requestNetwork(request, operation)
);
}
// If it requests Wifi connectivity, pretend it is fulfilled immediately if we have an active network.
@RequiresApi(api = Build.VERSION_CODES.O)
public static void requestNetwork(ConnectivityManager connectivityManager, NetworkRequest request, ConnectivityManager.NetworkCallback networkCallback, Handler handler, int timeoutMs) {
Utils.networkCallback(
connectivityManager,
Utils.Option.of(request),
Utils.Option.of(networkCallback),
Utils.Option.empty(),
Utils.Option.of(handler),
() -> connectivityManager.requestNetwork(request, networkCallback, handler, timeoutMs)
);
}
public static void unregisterNetworkCallback(ConnectivityManager connectivityManager, ConnectivityManager.NetworkCallback networkCallback) {
try {
connectivityManager.unregisterNetworkCallback(networkCallback);
} catch (IllegalArgumentException ignore) {
// ignore: NetworkCallback was not registered
}
}
public static void unregisterNetworkCallback(ConnectivityManager connectivityManager, PendingIntent operation) {
try {
connectivityManager.unregisterNetworkCallback(operation);
} catch (IllegalArgumentException ignore) {
// ignore: PendingIntent was not registered
}
}
private static class Utils {
private static class Option<T> {
private final T value;
private final boolean isPresent;
private Option(T value, boolean isPresent) {
this.value = value;
this.isPresent = isPresent;
}
private static <T> Option<T> of(T value) {
return new Option<>(value, true);
}
private static <T> Option<T> empty() {
return new Option<>(null, false);
}
}
private static void networkCallback(
ConnectivityManager connectivityManager,
Option<NetworkRequest> request,
Option<ConnectivityManager.NetworkCallback> networkCallback,
Option<PendingIntent> operation,
Option<Handler> handler,
Runnable fallback
) {
if(!request.isPresent || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && request.value != null && requestsWifiNetwork(request.value))) {
Runnable runnable = null;
if (networkCallback.isPresent && networkCallback.value != null) {
Network network = activeWifiNetwork(connectivityManager);
if (network != null) {
runnable = () -> networkCallback.value.onAvailable(network);
}
} else if (operation.isPresent && operation.value != null) {
runnable = () -> {
try {
operation.value.send();
} catch (PendingIntent.CanceledException ignore) {}
};
}
if (runnable != null) {
if (handler.isPresent) {
if (handler.value != null) {
handler.value.post(runnable);
return;
}
} else {
runnable.run();
return;
}
}
}
fallback.run();
}
// Returns an active (maybe fake) Wifi network if there is one, otherwise null.
private static Network activeWifiNetwork(ConnectivityManager connectivityManager) {
Network network = getActiveNetwork(connectivityManager);
NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(network);
if (networkCapabilities != null && hasTransport(networkCapabilities, NetworkCapabilities.TRANSPORT_WIFI)) {
return network;
}
return null;
}
// Whether a Wifi network with connection is requested.
@RequiresApi(api = Build.VERSION_CODES.P)
private static boolean requestsWifiNetwork(NetworkRequest request) {
return request.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
&& (request.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|| request.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED));
}
}
}
| 20,038 | Java | .java | ReVanced/revanced-integrations | 649 | 221 | 10 | 2022-03-15T20:37:24Z | 2024-05-08T22:30:33Z |
Main.java | /FileExtraction/Java_unseen/divestedcg_Simple_Hosts_Merger/src/Main.java | /*
Copyright (c) 2015-2019 Divested Computing Group
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.security.MessageDigest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
public class Main {
private static final String hostnameRegex = "^((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)+[A-Za-z]{2,6}$"; //Credit: http://www.mkyong.com/regular-expressions/domain-name-regular-expression-example/
private static final Pattern hostnamePattern = Pattern.compile(hostnameRegex);
private static final DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
public static final Set<String> arrWildcardExceptions = new HashSet<>();
public static final Set<String> arrWildcardBlock = new HashSet<>();
public static int RAW_COUNT = 0;
public static final HashMap<String, HashSet<String>> listMap = new HashMap<>();
public static boolean CACHE_ONLY = false; //For testing use
public static void main(String[] args) {
System.out.println("Simple Hosts Merger");
System.out.println("Copyright 2015-2021 Divested Computing Group");
System.out.println("License: GPLv3\n");
if (args.length != 4) {
System.out.println("Four arguments required: exclusion file, blocklists config (format: link,license;\\n), output file, cache dir");
System.exit(1);
}
//Get the allowlists
final Set<String> arrAllowlist = new HashSet<>();
File allowlist = new File(args[0]);
if (allowlist.exists()) {
arrAllowlist.addAll(readFileIntoArray(allowlist));
final Set<String> arrAllowlistWWW = new HashSet<>();
for(String domain : arrAllowlist) {
if (!domain.startsWith("www.")) {
arrAllowlistWWW.add("www." + domain);
}
}
arrAllowlist.addAll(arrAllowlistWWW);
System.out.println("Loaded " + arrAllowlist.size() + " excluded domains");
} else {
System.out.println("Allowlist file doesn't exist!");
System.exit(1);
}
File allowListWildcards = new File("allowlist-wildcards.txt"); //TODO: remove me, replaced by dnsrm
if (allowListWildcards.exists()) {
arrWildcardExceptions.addAll(readFileIntoArray(allowListWildcards));
}
File blockListWildcards = new File("blocklist-wildcards.txt");
if (blockListWildcards.exists()) {
arrWildcardBlock.addAll(readFileIntoArray(blockListWildcards));
}
File publicSuffixList = new File("public_suffix_list.dat");
if (publicSuffixList.exists()) {
arrWildcardExceptions.addAll(readFileIntoArray(publicSuffixList));
}
arrWildcardExceptions.addAll(arrAllowlist);
System.out.println("Loaded " + arrWildcardExceptions.size() + " excluded wildcards");
//Get the blocklists
ArrayList<String> arrBlocklists = new ArrayList<String>();
File blocklists = new File(args[1]);
if (blocklists.exists()) {
try {
Scanner scanner = new Scanner(blocklists);
while (scanner.hasNext()) {
String line = scanner.nextLine();
if (line.startsWith("http") && line.contains(",") && line.endsWith(";") && !line.startsWith("#")) {
arrBlocklists.add(line.replaceAll(";", ""));
}
}
scanner.close();
System.out.println("Loaded " + arrBlocklists.size() + " blocklist sources");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
System.out.println("Blocklists file doesn't exist!");
System.exit(1);
}
//Get the cache dir
File cacheDir = new File(args[3]);
if (!cacheDir.exists()) {
cacheDir.mkdirs();
}
//Process the blocklists
Set<String> arrDomains = new HashSet<>();
for (String list : arrBlocklists) {
String url = list.split(",")[0];
try {
//Download the file
String encodedName = byteArrayToHexString(MessageDigest.getInstance("MD5").digest(url.getBytes(StandardCharsets.UTF_8)));
System.out.println("Processing " + url + " / " + encodedName);
File out = new File(cacheDir, encodedName + identifyFileType(url));
downloadFile(url, out.toPath());
//Parse the file
HashSet<String> listResult = new HashSet<>();
listResult.addAll(readHostsFileIntoArray(out));
listMap.put(url, listResult);
arrDomains.addAll(listResult);
} catch (Exception e) {
e.printStackTrace();
}
}
//Remove excluded entries
int preSize = arrDomains.size();
ArrayList<String> arrDomainsRemoved = new ArrayList<>();
for (String domainToRemove : arrAllowlist) {
if (arrDomains.remove(domainToRemove)) {
arrDomainsRemoved.add(domainToRemove);
}
}
Collections.sort(arrDomainsRemoved);
System.out.println("Removed " + (preSize - arrDomains.size()) + " excluded entries");
//Sorting
ArrayList<String> arrDomainsSorted = new ArrayList<>(arrDomains);
Collections.sort(arrDomainsSorted);
ArrayList<String> arrDomainsWildcardsSorted = new ArrayList<>(wildcardOptimizer(arrDomains));
Collections.sort(arrDomainsWildcardsSorted);
System.out.println("Processed " + arrDomains.size() + " domains");
//Get the output file
writeOut(new File(args[2]), arrBlocklists, arrDomainsSorted, 0, arrDomainsSorted.size());
writeOut(new File(args[2] + "-domains"), arrBlocklists, arrDomainsSorted, 1, arrDomainsSorted.size());
writeOut(new File(args[2] + "-wildcards"), arrBlocklists, arrDomainsWildcardsSorted, 0, arrDomainsSorted.size());
writeOut(new File(args[2] + "-domains-wildcards"), arrBlocklists, arrDomainsWildcardsSorted, 1, arrDomainsSorted.size());
writeOut(new File(args[2] + "-dnsmasq"), arrBlocklists, arrDomainsWildcardsSorted, 2, arrDomainsSorted.size());
writeArrayToFile(new File(args[2] + "-removed"), arrDomainsRemoved);
generateCrossCheck(new File(args[2] + "-xcheck"));
}
public static void generateCrossCheck(File out) {
System.out.println("Generating crosscheck results");
ArrayList<String> xcheckResult = new ArrayList<>();
for (Map.Entry<String, HashSet<String>> entry : listMap.entrySet()) {
xcheckResult.add(entry.getKey());
xcheckResult.add("----------------------------------------------------------------");
boolean matchFound = false;
for (Map.Entry<String, HashSet<String>> recurseEntry : listMap.entrySet()) {
if (!recurseEntry.getKey().equals(entry.getKey())) {
int count = 0;
for (String domain : entry.getValue()) {
if (recurseEntry.getValue().contains(domain)) {
count++;
}
}
int percent = (int) ((100D / recurseEntry.getValue().size()) * count);
if (count != 0 && percent > 0) {
xcheckResult.add(count + "\t~" + percent + "%" + "\t\t" + recurseEntry.getKey());
matchFound = true;
}
}
}
if (!matchFound) {
xcheckResult.add("No significant number of entries found in any other lists.");
}
xcheckResult.add("\n");
}
writeArrayToFile(out, xcheckResult);
}
public static void writeOut(File fileOut, ArrayList<String> arrBlocklists, ArrayList<String> arrDomains, int mode, int trueCount) {
if (fileOut.exists()) {
fileOut.renameTo(new File(fileOut + ".bak"));
}
//Write the file
try {
PrintWriter writer = new PrintWriter(fileOut, "UTF-8");
writer.println("#");
writer.println("#Created using Simple Hosts Merger");
writer.println("#Last Updated: " + dateFormat.format(Calendar.getInstance().getTime()));
writer.println("#Number of Entries:");
writer.println("#\tInput Count: " + RAW_COUNT);
writer.println("#\tResult Count: " + trueCount);
if (trueCount != arrDomains.size()) {
writer.println("#\tAfter Wildcards: " + arrDomains.size());
}
writer.println("#");
writer.println("#Created from the following lists");
writer.println("#All attempts have been made to ensure accuracy of the corresponding license files and their compatibility.");
writer.println("#If you would like your list removed from this list please email us at webmaster@[THIS DOMAIN]");
writer.println("#");
for (String list : arrBlocklists) {
String[] listS = list.split(",");
writer.println("#" + listS[1] + "\t\t- " + listS[0]);
}
writer.println("#\n");
for (String line : arrDomains) {
switch (mode) {
case 0: //hosts
writer.println("0.0.0.0 " + line);
break;
case 1: //domains only
writer.println(line);
break;
case 2: //dnsmasq
if (!line.startsWith("*.")) {
writer.println("address=/" + line + "/#");
}
break;
}
}
writer.close();
System.out.println("Wrote out to " + fileOut);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void downloadFile(String url, Path out) {
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setConnectTimeout(45000);
connection.setReadTimeout(45000);
connection.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; rv:91.0) Gecko/20100101 Firefox/91.0");
if (out.toFile().exists()) {
connection.setIfModifiedSince(out.toFile().lastModified());
}
if (out.toFile().exists() && CACHE_ONLY) {
System.out.println("\tUsing cached version");
} else {
connection.connect();
int res = connection.getResponseCode();
if (res != 304 && (res == 200 || res == 301 || res == 302)) {
Files.copy(connection.getInputStream(), out, StandardCopyOption.REPLACE_EXISTING);
System.out.println("\tSuccessfully downloaded");
}
if (res == 304) {
System.out.println("\tFile not changed");
}
connection.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
}
//Credit (CC BY-SA 2.5): https://stackoverflow.com/a/4895572
public static String byteArrayToHexString(byte[] b) {
StringBuilder result = new StringBuilder();
for (byte aB : b)
result.append(Integer.toString((aB & 0xff) + 0x100, 16).substring(1));
return result.toString();
}
public static String identifyFileType(String url) {
String extension = ".txt";
if (url.contains("=zip") || url.endsWith(".zip"))
extension = ".zip";
else if (url.contains("=gz") || url.endsWith(".gz"))
extension = ".gz";
else if (url.contains("=7zip") || url.endsWith(".7zip"))
extension = ".7z";
else if (url.contains("=7z") || url.endsWith(".7z"))
extension = ".7z";
return extension;
}
public static void writeArrayToFile(File fileOut, ArrayList<String> contents) {
if (fileOut.exists()) {
fileOut.renameTo(new File(fileOut + ".bak"));
}
//Write the file
try {
PrintWriter writer = new PrintWriter(fileOut, "UTF-8");
for (String line : contents) {
writer.println(line);
}
writer.close();
System.out.println("Wrote out to " + fileOut);
} catch (Exception e) {
e.printStackTrace();
}
contents.clear();
}
public static ArrayList<String> readFileIntoArray(File in) {
ArrayList<String> out = new ArrayList<>();
try {
Scanner scanner = new Scanner(in);
while (scanner.hasNext()) {
String line = scanner.nextLine();
if (!line.startsWith("#") && !line.startsWith("//")) {
out.add(line);
}
}
scanner.close();
} catch (Exception e) {
e.printStackTrace();
}
return out;
}
public static ArrayList<String> readHostsFileIntoArray(File in) {
ArrayList<String> out = new ArrayList<>();
try {
Scanner fileIn = null;
if (identifyFileType(in.toString()).equals(".txt")) {//Plain text
fileIn = new Scanner(in);
}
if (identifyFileType(in.toString()).equals(".gz")) {//Decompress GunZip
fileIn = new Scanner(new GZIPInputStream(new FileInputStream(in)));
}
while (fileIn.hasNext()) {
out.addAll(getDomainsFromString(fileIn.nextLine()));
RAW_COUNT++;
}
System.out.println("\tAdded " + out.size() + " entries");
} catch (Exception e) {
e.printStackTrace();
}
return out;
}
public static Set<String> getDomainsFromString(String input) {
Set<String> domains = new HashSet<>();
String line = input.toLowerCase();
if (!shouldConsiderString(line)) {
return domains;
}
String[] blankSplit = line
.replaceAll("[\\s,;]", "~")
.split("~");
Matcher matcher;
for (String aSpaceSplit : blankSplit) {
if (shouldConsiderString(line)) {
aSpaceSplit = aSpaceSplit
.replaceAll("https://", "")
.replaceAll("http://", "")
.replaceAll("ftp://", "");
//.replaceAll("/.*", "");
matcher = hostnamePattern.matcher(aSpaceSplit);//Apply the pattern to the string
if (matcher.find()) {//Check if the string meets our requirements
String matchedDomain = matcher.group();
/* if(matchedDomain.startsWith("www.")) {
domains.add(matchedDomain.substring(4));
}*/
domains.add(matchedDomain);
} else if (aSpaceSplit.contains("xn--") && !aSpaceSplit.contains("/host/")) {//Ugly
domains.add(aSpaceSplit);
}
}
}
return domains;
}
public static boolean shouldConsiderString(String line) {
return !line.trim().equals("")
&& !line.startsWith("#")
&& !line.startsWith(";")
&& !line.startsWith("!")
&& !line.startsWith("//")
&& !line.startsWith("$")
&& !line.startsWith("@");
}
private static final ConcurrentLinkedQueue<Future<?>> futures = new ConcurrentLinkedQueue<>();
public static Set<String> wildcardOptimizer(Set<String> domains) {
Set<String> wildcards = new HashSet<>();
ConcurrentSkipListSet<String> domainsNew = new ConcurrentSkipListSet<>();
ConcurrentHashMap<String, AtomicInteger> occurrenceMap = new ConcurrentHashMap<>();
ThreadPoolExecutor threadPoolExecutorWork = new ThreadPoolExecutor(8, 8, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(4), new ThreadPoolExecutor.CallerRunsPolicy());
// Count the occurrence of each entry with one level removed
for (String domain : domains) {
futures.add(threadPoolExecutorWork.submit(() -> {
String[] domainSplit = domain.split("\\.");
for (int shift = 1; shift < 20; shift++) {
if (domainSplit.length > shift + 1) {
String shifted = jankSplit(domain, shift);
if (shifted.length() > 0) {
occurrenceMap.putIfAbsent(shifted, new AtomicInteger());
occurrenceMap.get(shifted).getAndIncrement();
}
}
}
}));
}
waitForThreadsComplete();
// Mark entries with count past X as a wildcard candidate
for (Map.Entry<String, AtomicInteger> domain : occurrenceMap.entrySet()) {
if (domain.getValue().get() >= 50) {
wildcards.add(domain.getKey());
}
}
wildcards.addAll(arrWildcardBlock);
//Exclude removal of certain domains
for (String exception : arrWildcardExceptions) {
wildcards.remove(exception);
}
//Remove redundant wildcards
Set<String> wildcardsNew = new HashSet<>();
wildcardsNew.addAll(wildcards);
for (String wildcard : wildcards) {
for (String wildcardCheck : wildcards) {
if (!wildcard.equals(wildcardCheck) && wildcardCheck.endsWith("." + wildcard)) {
wildcardsNew.remove(wildcardCheck);
}
}
}
wildcards = null; //set null to prevent accidental use
// Exclude all domains that would be matched by the wildcard and include the rest
domainsNew.addAll(domains);
for (String domain : domains) {
futures.add(threadPoolExecutorWork.submit(() -> {
for (String wildcard : wildcardsNew) {
if (domain.endsWith("." + wildcard)) {
domainsNew.remove(domain);
}
}
}));
}
waitForThreadsComplete();
//Add the wildcards
for (String wildcard : wildcardsNew) {
domainsNew.add("*." + wildcard);
domainsNew.add(wildcard);
}
threadPoolExecutorWork.shutdown();
System.out.println("Replaced " + (domains.size() - (domainsNew.size() - wildcardsNew.size())) + " domains with " + wildcardsNew.size() + " wildcards");
return domainsNew;
}
public static String jankSplit(String input, int afterOccurrence) {
StringBuilder result = new StringBuilder();
String[] split = input.split("\\.");
for (int count = 0; count < split.length; count++) {
if (count >= afterOccurrence) {
result.append(split[count]);
if (count != (split.length - 1)) {
result.append(".");
}
}
}
return result.toString();
}
private static void waitForThreadsComplete() {
try {
for (Future<?> future : futures) {
future.get();
futures.remove(future);
}
} catch (Exception e) {
e.printStackTrace();
}
futures.clear();
}
}
| 20,919 | Java | .java | divestedcg/Simple_Hosts_Merger | 12 | 5 | 1 | 2020-06-02T20:26:29Z | 2024-04-20T18:16:32Z |
BurpTab.java | /FileExtraction/Java_unseen/lorenzog_burpAddCustomHeader/burp/BurpTab.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package burp;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;
/**
*
* @author lor
*/
public class BurpTab extends javax.swing.JPanel {
/**
* Creates new form BurpTab
*/
public BurpTab() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
headerValueLabel = new javax.swing.JLabel();
headerNameLabel = new javax.swing.JLabel();
headerValuePrefixText = new javax.swing.JTextField();
headerValuePrefixLabel = new javax.swing.JLabel();
headerNameText = new javax.swing.JTextField();
finalResultLabel = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
hardCodedText = new javax.swing.JTextArea();
updatePreviewButton = new javax.swing.JButton();
regExpRadio = new javax.swing.JRadioButton();
hardCodedRadio = new javax.swing.JRadioButton();
regExpText = new javax.swing.JTextField();
jPanel1 = new javax.swing.JPanel();
jRadioButton1 = new javax.swing.JRadioButton();
headerValueLabel.setText("Header value");
headerNameLabel.setText("Header name");
headerValuePrefixText.setText("Bearer ");
headerValuePrefixText.setToolTipText("Don't forget the space");
headerValuePrefixText.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
headerValuePrefixTextActionPerformed(evt);
}
});
headerValuePrefixLabel.setText("Header value (prefix)");
headerNameText.setText("Authorization");
headerNameText.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
headerNameTextActionPerformed(evt);
}
});
finalResultLabel.setText("The new header will look like this");
finalResultLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP);
hardCodedText.setColumns(20);
hardCodedText.setRows(5);
jScrollPane1.setViewportView(hardCodedText);
updatePreviewButton.setText("Update Preview");
updatePreviewButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
updatePreviewButtonActionPerformed(evt);
}
});
buttonGroup1.add(regExpRadio);
regExpRadio.setText("Regular Expression");
regExpRadio.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
regExpRadioActionPerformed(evt);
}
});
buttonGroup1.add(hardCodedRadio);
hardCodedRadio.setText("Hard-Coded Value");
regExpText.setText("jTextField1");
regExpText.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
regExpTextActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
buttonGroup1.add(jRadioButton1);
jRadioButton1.setSelected(true);
jRadioButton1.setText("Disable custom header");
jRadioButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(headerValueLabel)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(headerValuePrefixLabel)
.addComponent(headerNameLabel))
.addGap(44, 44, 44)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(headerNameText, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(headerValuePrefixText, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(199, 199, 199)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(updatePreviewButton)
.addGap(44, 44, 44))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(hardCodedRadio)
.addComponent(regExpRadio)
.addComponent(jRadioButton1))
.addGap(18, 18, 18)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(finalResultLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 432, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 403, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(regExpText, javax.swing.GroupLayout.PREFERRED_SIZE, 273, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap(22, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(headerNameLabel)
.addComponent(headerNameText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(headerValuePrefixLabel)
.addComponent(headerValuePrefixText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(headerValueLabel))
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jRadioButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(regExpRadio)
.addComponent(regExpText, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(hardCodedRadio))
.addGroup(layout.createSequentialGroup()
.addGap(9, 9, 9)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(21, 21, 21)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(updatePreviewButton)
.addComponent(finalResultLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(45, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
private void headerNameTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_headerNameTextActionPerformed
updateFinalResultLabel();
}//GEN-LAST:event_headerNameTextActionPerformed
private void headerValuePrefixTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_headerValuePrefixTextActionPerformed
updateFinalResultLabel();
}//GEN-LAST:event_headerValuePrefixTextActionPerformed
private void updatePreviewButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updatePreviewButtonActionPerformed
updateFinalResultLabel();
}//GEN-LAST:event_updatePreviewButtonActionPerformed
private void regExpRadioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_regExpRadioActionPerformed
}//GEN-LAST:event_regExpRadioActionPerformed
private void regExpTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_regExpTextActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_regExpTextActionPerformed
private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jRadioButton1ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JLabel finalResultLabel;
private javax.swing.JRadioButton hardCodedRadio;
javax.swing.JTextArea hardCodedText;
private javax.swing.JLabel headerNameLabel;
javax.swing.JTextField headerNameText;
private javax.swing.JLabel headerValueLabel;
private javax.swing.JLabel headerValuePrefixLabel;
javax.swing.JTextField headerValuePrefixText;
private javax.swing.JPanel jPanel1;
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JRadioButton regExpRadio;
private javax.swing.JTextField regExpText;
private javax.swing.JButton updatePreviewButton;
// End of variables declaration//GEN-END:variables
void setHeaderName(String text) {
headerNameText.setText(text);
}
String getHeaderName() {
return headerNameText.getText();
}
void setHeaderValuePrefix(String text) {
headerValuePrefixText.setText(text);
}
String getHeaderValuePrefix() {
return headerValuePrefixText.getText();
}
public boolean useHardCoded() {
return hardCodedRadio.isSelected();
}
public boolean useRegExp() {
return regExpRadio.isSelected();
}
void setHardCodedText(String text) {
hardCodedText.setText(text);
}
String getHardCodedText() {
return hardCodedText.getText();
}
public String getRegExpText() {
return regExpText.getText();
}
public void setRegExpText(String regExpText) {
this.regExpText.setText(regExpText);
}
public void setUseHardCoded() {hardCodedRadio.setSelected(true);}
public void setUseRegExp() {regExpRadio.setSelected(true);}
// custom code
void updateFinalResultLabel() {
String finalText = headerNameText.getText() + ": " + headerValuePrefixText.getText();
if ( useHardCoded() ) finalText += getHardCodedText();
else if ( useRegExp()) finalText += "[regular expression: " + getRegExpText() + " ]";
else ;
finalResultLabel.setText(finalText);
}
}
| 13,775 | Java | .java | lorenzog/burpAddCustomHeader | 19 | 20 | 7 | 2018-05-07T08:01:10Z | 2021-12-09T20:39:19Z |
BurpExtender.java | /FileExtraction/Java_unseen/lorenzog_burpAddCustomHeader/burp/BurpExtender.java | package burp;
import javax.swing.SwingUtilities;
import java.awt.Component;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
public class BurpExtender implements IBurpExtender, ISessionHandlingAction, ITab, IExtensionStateListener {
IExtensionHelpers helpers = null;
Pattern p;
static String extensionName = "Add Custom Header";
IBurpExtenderCallbacks callbacks = null;
// some default values
final String DEFAULT_HEADER_NAME = "Authorization";
final String DEFAULT_HEADER_VALUE_PREFIX = "Bearer ";
final String DEFAULT_REGEXP = "access_token\":\"(.*?)\"";
final String DEFAULT_HARDCODED_VALUE = "<insert static JWT token here>";
//storage key for settings
final String KEY_REGEX = "setting_regex";
final String KEY_HARDCODED_VALUE = "setting_hardcoded_value";
final String KEY_MODE = "setting_mode";
final String KEY_HEADER_NAME = "settings_header_name";
final String KEY_HEADER_VALUE_PREFIX = "settings_header_value_prefix";
private BurpTab tab;
void useRegExp() {
}
@Override
public void registerExtenderCallbacks(IBurpExtenderCallbacks callbacks) {
this.callbacks = callbacks;
callbacks.setExtensionName(extensionName);
this.helpers = callbacks.getHelpers();
callbacks.registerSessionHandlingAction(this);
//Register the listener to trigger the auto storage of the settings
callbacks.registerExtensionStateListener(this);
// create our UI
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
tab = new BurpTab();
// set some default values
tab.setHeaderName(DEFAULT_HEADER_NAME);
tab.setHeaderValuePrefix(DEFAULT_HEADER_VALUE_PREFIX);
tab.setRegExpText(DEFAULT_REGEXP);
tab.setHardCodedText(DEFAULT_HARDCODED_VALUE);
//Loaded stored settings (if exists)
String headerName = callbacks.loadExtensionSetting(KEY_HEADER_NAME);
if(headerName != null && headerName.trim().length() > 0){
tab.setHeaderName(headerName);
}
String headerValuePrefix = callbacks.loadExtensionSetting(KEY_HEADER_VALUE_PREFIX);
if(headerValuePrefix != null && headerValuePrefix.trim().length() > 0){
tab.setHeaderValuePrefix(headerValuePrefix);
}
String regex = callbacks.loadExtensionSetting(KEY_REGEX);
if(regex != null && regex.trim().length() > 0){
tab.setRegExpText(regex);
}
String hardCodedText = callbacks.loadExtensionSetting(KEY_HARDCODED_VALUE);
if(hardCodedText != null && hardCodedText.trim().length() > 0){
tab.setHardCodedText(hardCodedText);
}
String mode = callbacks.loadExtensionSetting(KEY_MODE);
if("REGEX".equalsIgnoreCase(mode)){
tab.setUseRegExp();
}else if("HARD_CODED".equalsIgnoreCase(mode)){
tab.setUseHardCoded();
}
callbacks.printOutput("Mode loaded: " + mode);
// force update the example label
tab.updateFinalResultLabel();
// customize our UI components
callbacks.customizeUiComponent(tab);
callbacks.addSuiteTab(BurpExtender.this);
}
});
callbacks.printOutput("Add Header Extension loaded");
}
// methods below from ISessionHandlingAction
@Override
public String getActionName() {
return extensionName;
}
@Override
public void performAction(IHttpRequestResponse currentRequest,
IHttpRequestResponse[] macroItems) {
String token = null;
if (tab.useHardCoded()) {
// token has priority over regexp
token = tab.getHardCodedText();
} else if (tab.useRegExp()) {
if (macroItems.length == 0) {
this.callbacks.issueAlert("No macro configured or macro did not return any response");
return;
}
String regexp = tab.getRegExpText();
try {
p = Pattern.compile(regexp);
} catch (PatternSyntaxException e) {
this.callbacks.issueAlert("Syntax error in regular expression (see extension error window)");
callbacks.printError(e.toString());
return;
}
// go through all macros and run the regular expression on their body
for (int i = 0; i < macroItems.length; i++) {
byte[] _responseBody = macroItems[i].getResponse();
if (_responseBody == null) return;
IResponseInfo macroResponse = helpers.analyzeResponse(_responseBody);
if (macroResponse == null ) return;
String responseBody = helpers.bytesToString(_responseBody);
Matcher m = p.matcher(responseBody);
if (m.find()) {
token = m.group(1);
if (token != null && token.length() > 0) {
// found it
break;
}
}
}
} else {
// using the 'disable' button
return;
}
if (token == null) {
// nothing found: failing silently to avoid polluting the logs
callbacks.printError("No token found");
return;
}
String headerName = tab.getHeaderName();
String headerValuePrefix = tab.getHeaderValuePrefix();
IRequestInfo rqInfo = helpers.analyzeRequest(currentRequest);
// retrieve all headers
ArrayList<String> headers = (ArrayList<String>) rqInfo.getHeaders();
for (int i = 0; i < headers.size(); i++) {
if (((String) headers.get(i)).startsWith(headerName + ": " + headerValuePrefix)) {
// there could be more than one header like this; remove and continue
headers.remove(i);
}
}
String newHeader = headerName + ": " + headerValuePrefix + token;
headers.add(newHeader);
callbacks.printOutput("Added header: '" + newHeader + "'");
byte[] message = helpers.buildHttpMessage(headers, Arrays.copyOfRange(currentRequest.getRequest(), rqInfo.getBodyOffset(), currentRequest.getRequest().length));
currentRequest.setRequest(message);
}
// end ISessionHandlingAction methods
// ITab methods
@Override
public String getTabCaption() {
return extensionName;
}
@Override
public Component getUiComponent() {
return tab;
}
@Override
public void extensionUnloaded() {
//Save settings when burp close and extension is unloaded
callbacks.printOutput("Saving settings to project file...");
callbacks.saveExtensionSetting(KEY_HEADER_NAME, tab.getHeaderName());
callbacks.saveExtensionSetting(KEY_HEADER_VALUE_PREFIX, tab.getHeaderValuePrefix());
callbacks.saveExtensionSetting(KEY_REGEX, tab.getRegExpText());
callbacks.saveExtensionSetting(KEY_HARDCODED_VALUE, tab.getHardCodedText());
String mode = "DISABLED";
if(tab.useHardCoded()){
mode = "HARD_CODED";
}else if(tab.useRegExp()){
mode = "REGEX";
}
callbacks.saveExtensionSetting(KEY_MODE, mode);
callbacks.printOutput("Settings saved!");
}
// end ITab methods
}
| 7,842 | Java | .java | lorenzog/burpAddCustomHeader | 19 | 20 | 7 | 2018-05-07T08:01:10Z | 2021-12-09T20:39:19Z |
DatabaseCorruptException.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/leveldb/src/main/java/com/litl/leveldb/DatabaseCorruptException.java | package com.litl.leveldb;
public class DatabaseCorruptException extends LevelDBException {
private static final long serialVersionUID = -2110293580518875321L;
public DatabaseCorruptException() {
}
public DatabaseCorruptException(String error) {
super(error);
}
}
| 294 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
NativeObject.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/leveldb/src/main/java/com/litl/leveldb/NativeObject.java | package com.litl.leveldb;
import java.io.Closeable;
abstract class NativeObject implements Closeable {
protected long mPtr;
protected NativeObject() {
}
protected NativeObject(long ptr) {
this();
if (ptr == 0) {
throw new OutOfMemoryError("Failed to allocate native object");
}
mPtr = ptr;
}
synchronized protected long getPtr() {
return mPtr;
}
synchronized public boolean isClosed() {
return getPtr() == 0;
}
protected void assertOpen(String message) {
if (getPtr() == 0) {
throw new IllegalStateException(message);
}
}
protected abstract void closeNativeObject(long ptr);
@Override
public synchronized void close() {
closeNativeObject(mPtr);
mPtr = 0;
}
@Override
protected void finalize() throws Throwable {
if (mPtr != 0) closeNativeObject(mPtr);
mPtr = 0;
super.finalize();
}
}
| 998 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
LevelDBException.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/leveldb/src/main/java/com/litl/leveldb/LevelDBException.java | package com.litl.leveldb;
public class LevelDBException extends RuntimeException {
private static final long serialVersionUID = 2903013251786326801L;
public LevelDBException() {
}
public LevelDBException(String error) {
super(error);
}
public LevelDBException(String error, Throwable cause) {
super(error, cause);
}
}
| 366 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
WriteBatch.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/leveldb/src/main/java/com/litl/leveldb/WriteBatch.java | package com.litl.leveldb;
import java.nio.ByteBuffer;
public class WriteBatch extends NativeObject {
public WriteBatch() {
super(nativeCreate());
}
@Override
protected void closeNativeObject(long ptr) {
nativeDestroy(ptr);
}
public void delete(ByteBuffer key) {
assertOpen("WriteBatch is closed");
if (key == null) {
throw new NullPointerException("key");
}
nativeDelete(mPtr, key);
}
public void put(ByteBuffer key, ByteBuffer value) {
assertOpen("WriteBatch is closed");
if (key == null) {
throw new NullPointerException("key");
}
if (value == null) {
throw new NullPointerException("value");
}
nativePut(mPtr, key, value);
}
public void clear() {
assertOpen("WriteBatch is closed");
nativeClear(mPtr);
}
private static native long nativeCreate();
private static native void nativeDestroy(long ptr);
private static native void nativeDelete(long ptr, ByteBuffer key);
private static native void nativePut(long ptr, ByteBuffer key, ByteBuffer val);
private static native void nativeClear(long ptr);
}
| 1,226 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
DB.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/leveldb/src/main/java/com/litl/leveldb/DB.java | package com.litl.leveldb;
import java.io.File;
import java.nio.ByteBuffer;
public class DB extends NativeObject {
public abstract static class Snapshot extends NativeObject {
Snapshot(long ptr) {
super(ptr);
}
}
private final File mPath;
private boolean mDestroyOnClose = false;
public DB(File path) {
super();
if (path == null) {
throw new NullPointerException();
}
mPath = path;
}
public void open() {
mPtr = nativeOpen(mPath.getAbsolutePath());
}
@Override
protected void closeNativeObject(long ptr) {
nativeClose(ptr);
}
public void put(byte[] key, byte[] value) {
assertOpen("Database is closed");
if (key == null) {
throw new NullPointerException("key");
}
if (value == null) {
throw new NullPointerException("value");
}
nativePut(mPtr, key, value);
}
public byte[] get(byte[] key) {
return get(null, key);
}
public byte[] get(Snapshot snapshot, byte[] key) {
assertOpen("Database is closed");
if (key == null) {
throw new NullPointerException();
}
return nativeGet(mPtr, snapshot != null ? snapshot.getPtr() : 0, key);
}
public byte[] get(ByteBuffer key) {
return get(null, key);
}
public byte[] get(Snapshot snapshot, ByteBuffer key) {
assertOpen("Database is closed");
if (key == null) {
throw new NullPointerException();
}
return nativeGet(mPtr, snapshot != null ? snapshot.getPtr() : 0, key);
}
public void delete(byte[] key) {
assertOpen("Database is closed");
if (key == null) {
throw new NullPointerException();
}
nativeDelete(mPtr, key);
}
public void write(WriteBatch batch) {
assertOpen("Database is closed");
if (batch == null) {
throw new NullPointerException();
}
nativeWrite(mPtr, batch.getPtr());
}
public Iterator iterator() {
return iterator(null);
}
public Iterator iterator(final Snapshot snapshot) {
assertOpen("Database is closed");
return new Iterator(nativeIterator(mPtr, snapshot != null ? snapshot.getPtr() : 0)) {
@Override
protected void closeNativeObject(long ptr) {
super.closeNativeObject(ptr);
}
};
}
public Snapshot getSnapshot() {
assertOpen("Database is closed");
return new Snapshot(nativeGetSnapshot(mPtr)) {
protected void closeNativeObject(long ptr) {
nativeReleaseSnapshot(DB.this.getPtr(), getPtr());
}
};
}
public static native String fixLdb(String dbpath);
public static void destroy(File path) {
nativeDestroy(path.getAbsolutePath());
}
private static native long nativeOpen(String dbpath);
public File getPath() {
return mPath;
}
private static native void nativeClose(long dbPtr);
private static native void nativePut(long dbPtr, byte[] key, byte[] value);
private static native byte[] nativeGet(long dbPtr, long snapshotPtr, byte[] key);
private static native byte[] nativeGet(long dbPtr, long snapshotPtr, ByteBuffer key);
private static native void nativeDelete(long dbPtr, byte[] key);
private static native void nativeWrite(long dbPtr, long batchPtr);
private static native void nativeDestroy(String dbpath);
private static native long nativeIterator(long dbPtr, long snapshotPtr);
private static native long nativeGetSnapshot(long dbPtr);
private static native void nativeReleaseSnapshot(long dbPtr, long snapshotPtr);
public static native String stringFromJNI();
{
System.loadLibrary("leveldbjni");
}
}
| 3,925 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
NotFoundException.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/leveldb/src/main/java/com/litl/leveldb/NotFoundException.java | package com.litl.leveldb;
public class NotFoundException extends LevelDBException {
private static final long serialVersionUID = 6207999645579440001L;
public NotFoundException() {
}
public NotFoundException(String error) {
super(error);
}
}
| 272 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
Iterator.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/leveldb/src/main/java/com/litl/leveldb/Iterator.java | package com.litl.leveldb;
public class Iterator extends NativeObject {
Iterator(long iterPtr) {
super(iterPtr);
}
@Override
protected void closeNativeObject(long ptr) {
nativeDestroy(ptr);
}
public void seekToFirst() {
assertOpen("Iterator is closed");
nativeSeekToFirst(mPtr);
}
public void seekToLast() {
assertOpen("Iterator is closed");
nativeSeekToLast(mPtr);
}
public void seek(byte[] target) {
assertOpen("Iterator is closed");
if (target == null) {
throw new IllegalArgumentException();
}
nativeSeek(mPtr, target);
}
public boolean isValid() {
assertOpen("Iterator is closed");
return nativeValid(mPtr);
}
public void next() {
assertOpen("Iterator is closed");
nativeNext(mPtr);
}
public void prev() {
assertOpen("Iterator is closed");
nativePrev(mPtr);
}
public byte[] getKey() {
assertOpen("Iterator is closed");
return nativeKey(mPtr);
}
public byte[] getValue() {
assertOpen("Iterator is closed");
return nativeValue(mPtr);
}
private static native void nativeDestroy(long ptr);
private static native void nativeSeekToFirst(long ptr);
private static native void nativeSeekToLast(long ptr);
private static native void nativeSeek(long ptr, byte[] key);
private static native boolean nativeValid(long ptr);
private static native void nativeNext(long ptr);
private static native void nativePrev(long ptr);
private static native byte[] nativeKey(long dbPtr);
private static native byte[] nativeValue(long dbPtr);
}
| 1,732 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
TileView.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/tileview/src/main/java/com/qozix/tileview/TileView.java | package com.qozix.tileview;
import android.content.Context;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Region;
import android.os.Handler;
import android.os.Message;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import com.qozix.tileview.detail.DetailLevel;
import com.qozix.tileview.detail.DetailLevelManager;
import com.qozix.tileview.geom.CoordinateTranslater;
import com.qozix.tileview.geom.FloatMathHelper;
import com.qozix.tileview.graphics.BitmapProvider;
import com.qozix.tileview.hotspots.HotSpot;
import com.qozix.tileview.hotspots.HotSpotManager;
import com.qozix.tileview.markers.CalloutLayout;
import com.qozix.tileview.markers.MarkerLayout;
import com.qozix.tileview.paths.CompositePathView;
import com.qozix.tileview.tiles.TileCanvasViewGroup;
import com.qozix.tileview.widgets.ScalingLayout;
import com.qozix.tileview.widgets.ZoomPanLayout;
import java.lang.ref.WeakReference;
import java.util.List;
/**
* The TileView widget is a subclass of ViewGroup that supports:
* 1. Memory-managed tiled images with multiple levels of detail.
* 2. Panning by drag and fling.
* 3. Zooming by pinch and double-tap.
* 4. Markers and info windows.
* 5. Arbitrary coordinate systems.
* 6. Tappable hot spots.
* 7. Path drawing.
* <p>
* A minimal implementation might look like this:
*
* <pre>{@code
* TileView tileView = new TileView( this );
* tileView.setSize( 3000, 5000 );
* tileView.addDetailLevel( 1.0f, "path/to/tiles/%d-%d.jpg" );
* }</pre>
* <p>
* A more advanced implementation might look like:
*
* <pre>{@code
* TileView tileView = new TileView( this );
* tileView.setSize( 3000, 5000 );
* tileView.defineBounds( 42.379676, -71.094919, 42.346550, -71.040280 );
* tileView.addDetailLevel( 1.000f, "path/to/tiles/1000/%d-%d.jpg", 256, 256 );
* tileView.addDetailLevel( 0.500f, "path/to/tiles/500/%d-%d.jpg", 256, 256 );
* tileView.addDetailLevel( 0.250f, "path/to/tiles/250/%d-%d.jpg", 256, 256 );
* tileView.addDetailLevel( 0.125f, "path/to/tiles/125/%d-%d.jpg", 128, 128 );
* tileView.addMarker( someView, 42.35848, -71.063736, null, null );
* tileView.addMarker( anotherView, 42.3665, -71.05224, -1.0f, -0.5f );
* tileView.setMarkerTapListener( someMarkerTapListenerImplementation );
* }</pre>
*/
public class TileView extends ZoomPanLayout implements
ZoomPanLayout.ZoomPanListener,
TileCanvasViewGroup.TileRenderListener,
DetailLevelManager.DetailLevelChangeListener {
protected static final int DEFAULT_TILE_SIZE = 256;
private DetailLevelManager mDetailLevelManager = new DetailLevelManager();
private CoordinateTranslater mCoordinateTranslater = new CoordinateTranslater();
private HotSpotManager mHotSpotManager = new HotSpotManager();
private TileCanvasViewGroup mTileCanvasViewGroup;
private CompositePathView mCompositePathView;
private ScalingLayout mScalingLayout;
private MarkerLayout mMarkerLayout;
private CalloutLayout mCalloutLayout;
private RenderThrottleHandler mRenderThrottleHandler;
private boolean mShouldRenderWhilePanning = false;
private boolean mShouldUpdateDetailLevelWhileZooming = false;
/**
* Constructor to use when creating a TileView from code.
*
* @param context The Context the TileView is running in, through which it can access the current theme, resources, etc.
*/
public TileView(Context context) {
this(context, null);
}
public TileView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public TileView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mTileCanvasViewGroup = new TileCanvasViewGroup(context);
addView(mTileCanvasViewGroup);
mCompositePathView = new CompositePathView(context);
addView(mCompositePathView);
mScalingLayout = new ScalingLayout(context);
addView(mScalingLayout);
mMarkerLayout = new MarkerLayout(context);
addView(mMarkerLayout);
mCalloutLayout = new CalloutLayout(context);
addView(mCalloutLayout);
mDetailLevelManager.setDetailLevelChangeListener(this);
mTileCanvasViewGroup.setTileRenderListener(this);
addZoomPanListener(this);
mRenderThrottleHandler = new RenderThrottleHandler(this);
requestRender();
}
/**
* Returns the DetailLevelManager instance used by the TileView to coordinate DetailLevels.
*
* @return The DetailLevelManager instance.
*/
public DetailLevelManager getDetailLevelManager() {
return mDetailLevelManager;
}
/**
* Allows the use of a custom {@link DetailLevelManager}.
* <p>
* For example, to change the logic of {@link DetailLevel} choice for a given scale, you
* declare your own {@code DetailLevelMangerCustom} that extends {@link DetailLevelManager} :
* <pre>{@code
* private class DetailLevelManagerCustom extends DetailLevelManager{
* @literal @Override
* public DetailLevel getDetailLevelForScale(){
* // your logic here
* }
* }
* }
* </pre>
* Then you should use {@code TileView.setDetailLevelManager} before other method calls, especially
* {@code TileView.setSize} and {@code TileView.addDetailLevel}.
* </p>
*
* @param manager The DetailLevelManager instance used.
*/
public void setDetailLevelManager(DetailLevelManager manager) {
mDetailLevelManager = manager;
mDetailLevelManager.setDetailLevelChangeListener(this);
}
/**
* Returns the CoordinateTranslater instance used by the TileView to manage abritrary coordinate
* systems.
*
* @return The CoordinateTranslater instance.
*/
public CoordinateTranslater getCoordinateTranslater() {
return mCoordinateTranslater;
}
/**
* Returns the HotSpotManager instance used by the TileView to detect and react to touch events
* that intersect a user-defined region.
*
* @return The HotSpotManager instance.
*/
public HotSpotManager getHotSpotManager() {
return mHotSpotManager;
}
/**
* Returns the CompositePathView instance used by the TileView to draw and scale paths.
*
* @return The CompositePathView instance.
*/
public CompositePathView getCompositePathView() {
return mCompositePathView;
}
/**
* Returns the TileCanvasViewGroup instance used by the TileView to manage tile bitmap rendering.
*
* @return The TileCanvasViewGroup instance.
*/
public TileCanvasViewGroup getTileCanvasViewGroup() {
return mTileCanvasViewGroup;
}
/**
* Returns the MakerLayout instance used by the TileView to position and display Views used
* as markers.
*
* @return The MarkerLayout instance.
*/
public MarkerLayout getMarkerLayout() {
return mMarkerLayout;
}
/**
* Returns the CalloutLayout instance used by the TileView to position and display Views used
* as callouts.
*
* @return The CalloutLayout instance.
*/
public CalloutLayout getCalloutLayout() {
return mCalloutLayout;
}
/**
* Returns the ScalingLayout instance used by the TileView to allow insertion of arbitrary
* Views and ViewGroups that will scale visually with the TileView.
*
* @return The ScalingLayout instance.
*/
public ScalingLayout getScalingLayout() {
return mScalingLayout;
}
/**
* Add a ViewGroup to the TileView at a z-index above tiles and paths but beneath
* markers and callouts. The ViewGroup will be laid out to the full dimensions of the largest
* detail level, and will scale with the TileView.
* Note that only the drawing surface of the view is scaled, other operations that depend
* on dimensions are not (e.g., hit areas, invalidation tests).
*
* @param viewGroup The ViewGroup to be added to the TileView, that will scale visually.
*/
public void addScalingViewGroup(ViewGroup viewGroup) {
mScalingLayout.addView(viewGroup);
}
/**
* Request that the current tile set is re-examined and re-drawn.
* The request is added to a queue and is not guaranteed to be processed at any particular
* time, and will never be handled immediately.
*/
public void requestRender() {
mTileCanvasViewGroup.requestRender();
}
/**
* While all render operation requests are queued and batched, this method provides an additional
* throttle layer, so that any subsequent invocations cancel and pending invocations.
* <p>
* This is useful when requesting in a stream fashion, either in a loop or in response to a
* progressive action like an animation or touch move.
*/
public void requestThrottledRender() {
mRenderThrottleHandler.submit();
}
/**
* If flinging, defer render, otherwise request now.
* If a render operation starts at the beginning of a fling, a stutter can occur.
*/
protected void requestSafeRender() {
if (isFlinging()) {
requestThrottledRender();
} else {
requestRender();
}
}
/**
* Notify the TileView that it may stop rendering tiles. The rendering thread will be
* sent an interrupt request, but no guarantee is provided when the request will be responded to.
*/
public void cancelRender() {
mTileCanvasViewGroup.cancelRender();
}
/**
* Notify the TileView that it should continue to render any pending tiles, but should not
* accept new render tasks.
*/
public void suppressRender() {
mTileCanvasViewGroup.suppressRender();
}
/**
* Notify the TileView that it should resume tiles rendering.
*/
public void resumeRender() {
mTileCanvasViewGroup.resumeRender();
}
/**
* Sets a custom class to perform the getBitmap operation when tile bitmaps are requested for
* tile images only.
* By default, a BitmapDecoder implementation is provided that renders bitmaps from the context's
* Assets, but alternative implementations could be used that fetch images via HTTP, or from the
* SD card, or resources, SVG, etc.
*
* @param bitmapProvider A class instance that implements BitmapProvider, and must define a getBitmap method, which accepts a String file name and a Context object, and returns a Bitmap
*/
public void setBitmapProvider(BitmapProvider bitmapProvider) {
mTileCanvasViewGroup.setBitmapProvider(bitmapProvider);
}
/**
* Defines whether tile bitmaps should be rendered using an AlphaAnimation
*
* @param enabled True if the TileView should render tiles with fade transitions
*/
public void setTransitionsEnabled(boolean enabled) {
mTileCanvasViewGroup.setTransitionsEnabled(enabled);
}
/**
* Instructs Tile instances to recycle (or not). This can be useful if using a caching system
* that re-uses bitmaps and expects them to not have been recycled.
* <p>
* The default value is true.
*
* @param shouldRecycleBitmaps True if bitmaps should call Bitmap.recycle when they are removed from view.
* @deprecated This value is no longer considered - bitmaps are always recycled when they're no longer used.
*/
public void setShouldRecycleBitmaps(boolean shouldRecycleBitmaps) {
mTileCanvasViewGroup.setShouldRecycleBitmaps(shouldRecycleBitmaps);
}
/**
* Defines the total size, in pixels, of the tile set at 100% scale.
* The TileView wills pan within it's layout dimensions, with the content (scrollable)
* size defined by this method.
*
* @param width Total width of the tiled set.
* @param height Total height of the tiled set.
*/
@Override
public void setSize(int width, int height) {
super.setSize(width, height);
mDetailLevelManager.setSize(width, height);
mCoordinateTranslater.setSize(width, height);
}
/**
* Register a tile set to be used for a particular detail level.
* Each tile set to be used must be registered using this method,
* and at least one tile set must be registered for the TileView to render any tiles.
*
* @param detailScale Scale at which the TileView should use the tiles in this set.
* @param data An arbitrary object of any type that is passed to the BitmapProvider for each tile on this level.
*/
public void addDetailLevel(float detailScale, Object data) {
addDetailLevel(detailScale, data, DEFAULT_TILE_SIZE, DEFAULT_TILE_SIZE);
}
/**
* Register a tile set to be used for a particular detail level.
* Each tile set to be used must be registered using this method,
* and at least one tile set must be registered for the TileView to render any tiles.
*
* @param detailScale Scale at which the TileView should use the tiles in this set.
* @param data An arbitrary object of any type that is passed to the (Adapter|Decoder) for each tile on this level.
* @param tileWidth Size of each tiled column.
* @param tileHeight Size of each tiled row.
*/
public void addDetailLevel(float detailScale, Object data, int tileWidth, int tileHeight) {
mDetailLevelManager.addDetailLevel(detailScale, data, tileWidth, tileHeight);
}
/**
* Register a tile set to be used for a particular detail level.
* Each tile set to be used must be registered using this method,
* and at least one tile set must be registered for the TileView to render any tiles.
*
* @param detailScale Scale at which the TileView should use the tiles in this set.
* @param data An arbitrary object of any type that is passed to the (Adapter|Decoder) for each tile on this level.
* @param tileWidth Size of each tiled column.
* @param tileHeight Size of each tiled row.
* @param levelType Type of level, detail-levels can have the same scale but different looks.
*/
public void addDetailLevel(float detailScale, Object data, int tileWidth, int tileHeight, DetailLevelManager.LevelType levelType) {
mDetailLevelManager.addDetailLevel(detailScale, data, tileWidth, tileHeight, levelType);
}
/**
* Pads the viewport by the number of pixels passed. e.g., setViewportPadding( 100 ) instructs the
* TileView to interpret it's actual viewport offset by 100 pixels in each direction (top, left,
* right, bottom), so more tiles will qualify for "visible" status when intersections are calculated.
*
* @param padding The number of pixels to pad the viewport by
*/
public void setViewportPadding(int padding) {
mDetailLevelManager.setViewportPadding(padding);
}
/**
* Register a set of offset points to use when calculating position within the TileView.
* Any type of coordinate system can be used (any type of lat/lng, percentile-based, etc),
* and all positioned are calculated relatively. If relative bounds are defined, position parameters
* received by TileView methods will be translated to the the appropriate pixel value.
* To remove this process, use undefineBounds.
*
* @param left The left edge of the rectangle used when calculating position.
* @param top The top edge of the rectangle used when calculating position.
* @param right The right edge of the rectangle used when calculating position.
* @param bottom The bottom edge of the rectangle used when calculating position.
*/
public void defineBounds(double left, double top, double right, double bottom) {
mCoordinateTranslater.setBounds(left, top, right, bottom);
}
/**
* Unregisters arbitrary bounds and coordinate system. After invoking this method,
* TileView methods that receive position method parameters will use pixel values,
* relative to the TileView's registered size (at 1.0f scale).
*/
public void undefineBounds() {
mCoordinateTranslater.unsetBounds();
}
/**
* Scrolls (instantly) the TileView to the x and y positions provided. The is an overload
* of scrollTo( int x, int y ) that accepts doubles; if the TileView has relative bounds defined,
* those relative doubles will be converted to absolute pixel positions.
*
* @param x The relative x position to move to.
* @param y The relative y position to move to.
*/
public void scrollTo(double x, double y) {
scrollTo(
mCoordinateTranslater.translateAndScaleX(x, getScale()),
mCoordinateTranslater.translateAndScaleY(y, getScale())
);
}
/**
* Scrolls (instantly) the TileView to the x and y positions provided,
* then centers the viewport to the position.
*
* @param x The relative x position to move to.
* @param y The relative y position to move to.
*/
public void scrollToAndCenter(double x, double y) {
scrollToAndCenter(
mCoordinateTranslater.translateAndScaleX(x, getScale()),
mCoordinateTranslater.translateAndScaleY(y, getScale())
);
}
/**
* Scrolls (with animation) the TileView to the relative x and y positions provided.
*
* @param x The relative x position to move to.
* @param y The relative y position to move to.
*/
public void slideTo(double x, double y) {
slideTo(
mCoordinateTranslater.translateAndScaleX(x, getScale()),
mCoordinateTranslater.translateAndScaleY(y, getScale())
);
}
/**
* Scrolls (with animation) the TileView to the x and y positions provided,
* then centers the viewport to the position.
*
* @param x The relative x position to move to.
* @param y The relative y position to move to.
*/
public void slideToAndCenter(double x, double y) {
slideToAndCenter(
mCoordinateTranslater.translateAndScaleX(x, getScale()),
mCoordinateTranslater.translateAndScaleY(y, getScale())
);
}
/**
* Scrolls and scales (with animation) the TileView to the specified x, y and scale provided.
* The TileView will be centered to the coordinates passed.
*
* @param x The relative x position to move to.
* @param y The relative y position to move to.
* @param scale The scale the TileView should be at when the animation is complete.
*/
public void slideToAndCenterWithScale(double x, double y, float scale) {
slideToAndCenterWithScale(
mCoordinateTranslater.translateAndScaleX(x, scale),
mCoordinateTranslater.translateAndScaleY(y, scale),
scale
);
}
/**
* Markers added to this TileView will have anchor logic applied on the values provided here.
* E.g., setMarkerAnchorPoints(-0.5f, -1.0f) will have markers centered horizontally, and aligned
* along the bottom edge to the y value supplied.
* <p>
* Anchor values assigned to individual markers will override these default values.
*
* @param anchorX The x-axis position of a marker will be offset by a number equal to the width of the marker multiplied by this value.
* @param anchorY The y-axis position of a marker will be offset by a number equal to the height of the marker multiplied by this value.
*/
public void setMarkerAnchorPoints(Float anchorX, Float anchorY) {
mMarkerLayout.setAnchors(anchorX, anchorY);
}
/**
* Add a marker to the the TileView. The marker can be any View.
* No LayoutParams are required; the View will be laid out using WRAP_CONTENT for both width and height, and positioned based on the parameters.
*
* @param view View instance to be added to the TileView.
* @param x Relative x position the View instance should be positioned at.
* @param y Relative y position the View instance should be positioned at.
* @param anchorX The x-axis position of a marker will be offset by a number equal to the width of the marker multiplied by this value.
* @param anchorY The y-axis position of a marker will be offset by a number equal to the height of the marker multiplied by this value.
* @return The View instance added to the TileView.
*/
public View addMarker(View view, double x, double y, Float anchorX, Float anchorY) {
return mMarkerLayout.addMarker(view,
mCoordinateTranslater.translateX(x),
mCoordinateTranslater.translateY(y),
anchorX, anchorY
);
}
/**
* Removes a marker View from the TileView's view tree.
*
* @param view The marker View to be removed.
*/
public void removeMarker(View view) {
mMarkerLayout.removeMarker(view);
}
/**
* Moves an existing marker to another position.
*
* @param view The marker View to be repositioned.
* @param x Relative x position the View instance should be positioned at.
* @param y Relative y position the View instance should be positioned at.
*/
public void moveMarker(View view, double x, double y) {
mMarkerLayout.moveMarker(view,
mCoordinateTranslater.translateX(x),
mCoordinateTranslater.translateY(y));
}
/**
* Scroll the TileView so that the View passed is centered in the viewport.
*
* @param view The View marker that the TileView should center on.
* @param shouldAnimate True if the movement should use a transition effect.
*/
public void moveToMarker(View view, boolean shouldAnimate) {
if (mMarkerLayout.indexOfChild(view) == -1) {
throw new IllegalStateException("The view passed is not an existing marker");
}
ViewGroup.LayoutParams params = view.getLayoutParams();
if (params instanceof MarkerLayout.LayoutParams) {
MarkerLayout.LayoutParams anchorLayoutParams = (MarkerLayout.LayoutParams) params;
int scaledX = FloatMathHelper.scale(anchorLayoutParams.x, getScale());
int scaledY = FloatMathHelper.scale(anchorLayoutParams.y, getScale());
if (shouldAnimate) {
slideToAndCenter(scaledX, scaledY);
} else {
scrollToAndCenter(scaledX, scaledY);
}
}
}
/**
* Register a MarkerTapListener for the TileView instance (rather than on a single marker view).
* Unlike standard touch events attached to marker View's (e.g., View.OnClickListener),
* MarkerTapListener.onMarkerTapEvent does not consume the touch event, so will not interfere
* with scrolling.
*
* @param markerTapListener Listener to be added to the TileView's list of MarkerTapListener.
*/
public void setMarkerTapListener(MarkerLayout.MarkerTapListener markerTapListener) {
mMarkerLayout.setMarkerTapListener(markerTapListener);
}
/**
* Add a callout to the the TileView. The callout can be any View.
* No LayoutParams are required; the View will be laid out using WRAP_CONTENT for both
* width and height, and positioned according to the x and y values supplied.
* Callout views will always be positioned at the top of the view tree (at the highest z-index),
* and will always be removed during any touch event that is not consumed by the callout View.
*
* @param view View instance to be added to the TileView.
* @param x Relative x position the View instance should be positioned at.
* @param y Relative y position the View instance should be positioned at.
* @param anchorX The x-axis position of a callout view will be offset by a number equal to the width of the callout view multiplied by this value.
* @param anchorY The y-axis position of a callout view will be offset by a number equal to the height of the callout view multiplied by this value.
* @return The View instance added to the TileView.
*/
public View addCallout(View view, double x, double y, Float anchorX, Float anchorY) {
return mCalloutLayout.addMarker(view,
mCoordinateTranslater.translateX(x),
mCoordinateTranslater.translateY(y),
anchorX, anchorY
);
}
/**
* Removes a callout View from the TileView.
*
* @param view The callout View to be removed.
*/
public void removeCallout(View view) {
mCalloutLayout.removeMarker(view);
}
/**
* Register a HotSpot that should fire a listener when a touch event occurs that intersects the
* Region defined by the HotSpot.
* <p>
* The HotSpot virtually moves and scales with the TileView.
*
* @param hotSpot The hotspot that is tested against touch events that occur on the TileView.
* @return The HotSpot instance added.
*/
public HotSpot addHotSpot(HotSpot hotSpot) {
mHotSpotManager.addHotSpot(hotSpot);
return hotSpot;
}
/**
* Register a HotSpot that should fire a listener when a touch event occurs that intersects the
* Region defined by the HotSpot.
* <p>
* The HotSpot virtually moves and scales with the TileView.
*
* @param positions (List<double[]>) List of paired doubles that represents the region.
* @return HotSpot the hotspot created with this method.
*/
public HotSpot addHotSpot(List<double[]> positions, HotSpot.HotSpotTapListener listener) {
Path path = mCoordinateTranslater.pathFromPositions(positions, true);
RectF bounds = new RectF();
path.computeBounds(bounds, true);
Rect rect = new Rect();
bounds.round(rect);
Region clip = new Region(rect);
HotSpot hotSpot = new HotSpot();
hotSpot.setPath(path, clip);
hotSpot.setHotSpotTapListener(listener);
return addHotSpot(hotSpot);
}
/**
* Remove a HotSpot registered with addHotSpot.
*
* @param hotSpot The HotSpot instance to remove.
*/
public void removeHotSpot(HotSpot hotSpot) {
mHotSpotManager.removeHotSpot(hotSpot);
}
/**
* Register a HotSpotTapListener with the TileView. This listener will fire if any registered
* HotSpot's region intersects a Tap event.
*
* @param hotSpotTapListener The listener to be added.
*/
public void setHotSpotTapListener(HotSpot.HotSpotTapListener hotSpotTapListener) {
mHotSpotManager.setHotSpotTapListener(hotSpotTapListener);
}
/**
* Register a DrawablePath that will be drawn on a layer above the tiles, but below markers.
* The Path will be scaled with the TileView, but will always be as wide as the stroke set
* for the Paint instance associated with the DrawablePath.
*
* @param drawablePath DrawablePath instance to be drawn by the TileView.
* @return The DrawablePath instance passed to the TileView.
*/
public CompositePathView.DrawablePath drawPath(CompositePathView.DrawablePath drawablePath) {
return mCompositePathView.addPath(drawablePath);
}
/**
* Register a Path and Paint that will be drawn on a layer above the tiles, but below markers.
* The Path will be scaled with the TileView, but will always be as wide as the stroke set
* for the Paint.
*
* @param positions List of doubles that represent the points of the Path.
* @param paint The Paint instance that defines the style of the drawn path.
* @return The DrawablePath instance passed to the TileView.
*/
public CompositePathView.DrawablePath drawPath(List<double[]> positions, Paint paint) {
Path path = mCoordinateTranslater.pathFromPositions(positions, false);
return mCompositePathView.addPath(path, paint);
}
/**
* Removes a DrawablePath from the TileView's registry. This path will no longer be drawn by the
* TileView.
*
* @param drawablePath The DrawablePath instance to be removed.
*/
public void removePath(CompositePathView.DrawablePath drawablePath) {
mCompositePathView.removePath(drawablePath);
}
/**
* Returns the Paint instance used by the CompositePathView by default. This can be modified for
* future Path paint operations.
*
* @return The Paint instance used by default.
*/
public Paint getDefaultPathPaint() {
return mCompositePathView.getDefaultPaint();
}
/**
* Recycles bitmap image files, prevents path drawing, and clears pending Handler messages,
* appropriate for Activity.onPause.
*/
public void pause() {
mRenderThrottleHandler.clear();
mDetailLevelManager.invalidateAll();
setWillNotDraw(true);
}
/**
* Clear tile image files and remove all views, appropriate for Activity.onDestroy.
* After invoking this method, the TileView instance should be removed from any view trees,
* and references to it should be set to null.
*/
public void destroy() {
pause();
mTileCanvasViewGroup.destroy();
mCompositePathView.clear();
removeAllViews();
}
/**
* Restore visible state (generally after a call to pause).
* Appropriate for Activity.onResume.
*/
public void resume() {
setWillNotDraw(false);
updateViewport();
mTileCanvasViewGroup.updateTileSet(mDetailLevelManager.getCurrentDetailLevel());
requestRender();
requestLayout();
}
/**
* Allows the TileView to render tiles while panning.
*
* @param shouldRender True if it should render while panning.
*/
public void setShouldRenderWhilePanning(boolean shouldRender) {
mShouldRenderWhilePanning = shouldRender;
int buffer = shouldRender ? TileCanvasViewGroup.FAST_RENDER_BUFFER : TileCanvasViewGroup.DEFAULT_RENDER_BUFFER;
mTileCanvasViewGroup.setRenderBuffer(buffer);
}
/**
* By default, when a zoom begins, the current {@link DetailLevel} is locked so it is used to
* provide tiles until the zoom ends. This ensures that the {@link TileView} is updated
* consistently.
* <p>
* However, a zoom out may require a lot of tiles of the locked {@code DetailLevel} to be rendered.
* In worst case, it can cause {@link OutOfMemoryError}.
* Then, disabling the {@code DetailLevel} lock is a bandage to that issue. Using
* {@code setShouldUpdateDetailLevelWhileZooming( true )} is not advised unless you have that issue.
* </p>
*
* @param shouldUpdate True if it should lock {@link DetailLevel} when a zoom begins.
*/
public void setShouldUpdateDetailLevelWhileZooming(boolean shouldUpdate) {
mShouldUpdateDetailLevelWhileZooming = shouldUpdate;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
mCalloutLayout.removeAllViews();
return super.onTouchEvent(event);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
updateViewport();
requestRender();
}
protected void updateViewport() {
int left = getScrollX();
int top = getScrollY();
int right = left + getWidth();
int bottom = top + getHeight();
mDetailLevelManager.updateViewport(left, top, right, bottom);
}
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
updateViewport();
if (mShouldRenderWhilePanning) {
requestRender();
} else {
requestThrottledRender();
}
}
@Override
public void onScaleChanged(float scale, float previous) {
super.onScaleChanged(scale, previous);
mDetailLevelManager.setScale(scale);
mHotSpotManager.setScale(scale);
mTileCanvasViewGroup.setScale(scale);
mScalingLayout.setScale(scale);
mCompositePathView.setScale(scale);
mMarkerLayout.setScale(scale);
mCalloutLayout.setScale(scale);
}
@Override
public void onPanBegin(int x, int y, Origination origin) {
}
@Override
public void onPanUpdate(int x, int y, Origination origin) {
}
@Override
public void onPanEnd(int x, int y, Origination origin) {
requestRender();
}
@Override
public void onZoomBegin(float scale, Origination origin) {
if (origin == null) {
mTileCanvasViewGroup.suppressRender();
}
mDetailLevelManager.setScale(scale);
}
@Override
public void onZoomUpdate(float scale, Origination origin) {
}
@Override
public void onZoomEnd(float scale, Origination origin) {
if (origin == null) {
mTileCanvasViewGroup.resumeRender();
}
mDetailLevelManager.setScale(scale);
requestRender();
}
@Override
public void onDetailLevelChanged(DetailLevel detailLevel) {
requestRender();
mTileCanvasViewGroup.updateTileSet(detailLevel);
}
@Override
public boolean onSingleTapConfirmed(MotionEvent event) {
int x = getScrollX() + (int) event.getX() - getOffsetX();
int y = getScrollY() + (int) event.getY() - getOffsetY();
if (mMarkerLayout.processHit(x, y)) return true;
if (mHotSpotManager.processHit(x, y)) return true;
return super.onSingleTapConfirmed(event);
}
@Override
public void onRenderStart() {
}
@Override
public void onRenderCancelled() {
}
@Override
public void onRenderComplete() {
}
/**
* The default {@code super.onSaveInstanceState} and {@code onRestoreInstanceState} don't
* restore the position on the map as expected (if the instance of {@link TileView} remains the
* same). For this reason and if a new {@link TileView} instance is created, we have to save
* the current scale and position on the map, to restore them later when the {@link TileView} is
* recreated.
*/
@Override
public Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
ss.mScale = getScale();
ss.mSavedCenterX = getScrollX() + getHalfWidth();
ss.mSavedCenterY = getScrollY() + getHalfHeight();
return ss;
}
@Override
public void onRestoreInstanceState(Parcelable state) {
final SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
setScale(ss.mScale);
post(new Runnable() {
@Override
public void run() {
scrollToAndCenter(ss.mSavedCenterX, ss.mSavedCenterY);
}
});
}
private static class RenderThrottleHandler extends Handler {
private static final int MESSAGE = 0;
private static final int RENDER_THROTTLE_TIMEOUT = 100;
private final WeakReference<TileView> mTileViewWeakReference;
public RenderThrottleHandler(TileView tileView) {
super();
mTileViewWeakReference = new WeakReference<TileView>(tileView);
}
@Override
public void handleMessage(Message msg) {
TileView tileView = mTileViewWeakReference.get();
if (tileView != null) {
tileView.requestSafeRender();
}
}
public void clear() {
if (hasMessages(MESSAGE)) {
removeMessages(MESSAGE);
}
}
public void submit() {
clear();
sendEmptyMessageDelayed(MESSAGE, RENDER_THROTTLE_TIMEOUT);
}
}
/**
* Object used to keep some data when a configuration change happens and the activity is
* re-created.
* It's boiler-plate but this is how to save View state.
*/
private static class SavedState extends BaseSavedState {
public static final Parcelable.Creator<SavedState> CREATOR
= new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
/* This will store the current scale and position */
float mScale;
int mSavedCenterX;
int mSavedCenterY;
SavedState(Parcelable superState) {
super(superState);
}
private SavedState(Parcel in) {
super(in);
mScale = in.readFloat();
mSavedCenterX = in.readInt();
mSavedCenterY = in.readInt();
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeFloat(mScale);
out.writeInt(mSavedCenterX);
out.writeInt(mSavedCenterY);
}
}
} | 37,723 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
CalloutLayout.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/tileview/src/main/java/com/qozix/tileview/markers/CalloutLayout.java | package com.qozix.tileview.markers;
import android.content.Context;
/**
* @deprecated In the next major version, instances of this class will be replaced
* by instances of MarkerLayout
*/
public class CalloutLayout extends MarkerLayout {
public CalloutLayout( Context context ) {
super( context );
}
}
| 317 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
MarkerLayout.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/tileview/src/main/java/com/qozix/tileview/markers/MarkerLayout.java | package com.qozix.tileview.markers;
import android.content.Context;
import android.graphics.Rect;
import android.view.View;
import android.view.ViewGroup;
import com.qozix.tileview.geom.FloatMathHelper;
public class MarkerLayout extends ViewGroup {
private float mScale = 1;
private float mAnchorX;
private float mAnchorY;
private MarkerTapListener mMarkerTapListener;
public MarkerLayout(Context context) {
super(context);
setClipChildren(false);
}
/**
* Sets the anchor values used by this ViewGroup if it's children do not
* have anchor values supplied directly (via individual LayoutParams).
*
* @param aX x-axis anchor value (offset computed by multiplying this value by the child's width).
* @param aY y-axis anchor value (offset computed by multiplying this value by the child's height).
*/
public void setAnchors(float aX, float aY) {
mAnchorX = aX;
mAnchorY = aY;
requestLayout();
}
/**
* Retrieves the current scale of the MarkerLayout.
*
* @return The current scale of the MarkerLayout.
*/
public float getScale() {
return mScale;
}
/**
* Sets the scale (0-1) of the MarkerLayout.
*
* @param scale The new value of the MarkerLayout scale.
*/
public void setScale(float scale) {
mScale = scale;
requestLayout();
}
public View addMarker(View view, int x, int y, Float aX, Float aY) {
LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, x, y, aX, aY);
return addMarker(view, layoutParams);
}
public View addMarker(View view, LayoutParams params) {
addView(view, params);
return view;
}
public void moveMarker(View view, int x, int y) {
LayoutParams layoutParams = (LayoutParams) view.getLayoutParams();
layoutParams.x = x;
layoutParams.y = y;
moveMarker(view, layoutParams);
}
public void moveMarker(View view, LayoutParams params) {
if (indexOfChild(view) > -1) {
view.setLayoutParams(params);
requestLayout();
}
}
public void removeMarker(View view) {
removeView(view);
}
public void setMarkerTapListener(MarkerTapListener markerTapListener) {
mMarkerTapListener = markerTapListener;
}
private View getViewFromTap(int x, int y) {
for (int i = getChildCount() - 1; i >= 0; i--) {
View child = getChildAt(i);
LayoutParams layoutParams = (LayoutParams) child.getLayoutParams();
Rect hitRect = layoutParams.getHitRect();
if (hitRect.contains(x, y)) {
return child;
}
}
return null;
}
public boolean processHit(int x, int y) {
if (mMarkerTapListener != null) {
View view = getViewFromTap(x, y);
if (view != null) {
mMarkerTapListener.onMarkerTap(view, x, y);
return true;
}
}
return false;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
measureChildren(widthMeasureSpec, heightMeasureSpec);
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
if (child.getVisibility() != GONE) {
MarkerLayout.LayoutParams layoutParams = (MarkerLayout.LayoutParams) child.getLayoutParams();
// get anchor offsets
float widthMultiplier = (layoutParams.anchorX == null) ? mAnchorX : layoutParams.anchorX;
float heightMultiplier = (layoutParams.anchorY == null) ? mAnchorY : layoutParams.anchorY;
// actual sizes of children
int actualWidth = child.getMeasuredWidth();
int actualHeight = child.getMeasuredHeight();
// offset dimensions by anchor values
float widthOffset = actualWidth * widthMultiplier;
float heightOffset = actualHeight * heightMultiplier;
// get offset position
int scaledX = FloatMathHelper.scale(layoutParams.x, mScale);
int scaledY = FloatMathHelper.scale(layoutParams.y, mScale);
// save computed values
layoutParams.mLeft = (int) (scaledX + widthOffset);
layoutParams.mTop = (int) (scaledY + heightOffset);
layoutParams.mRight = layoutParams.mLeft + actualWidth;
layoutParams.mBottom = layoutParams.mTop + actualHeight;
}
}
int availableWidth = MeasureSpec.getSize(widthMeasureSpec);
int availableHeight = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(availableWidth, availableHeight);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
if (child.getVisibility() != GONE) {
LayoutParams layoutParams = (LayoutParams) child.getLayoutParams();
child.layout(layoutParams.mLeft, layoutParams.mTop, layoutParams.mRight, layoutParams.mBottom);
}
}
}
@Override
protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 0, 0);
}
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams layoutParams) {
return layoutParams instanceof LayoutParams;
}
@Override
protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams layoutParams) {
return new LayoutParams(layoutParams);
}
public interface MarkerTapListener {
void onMarkerTap(View view, int x, int y);
}
/**
* Per-child layout information associated with AnchorLayout.
*/
public static class LayoutParams extends ViewGroup.LayoutParams {
/**
* The absolute left position of the child in pixels.
*/
public int x = 0;
/**
* The absolute right position of the child in pixels.
*/
public int y = 0;
/**
* Float value to determine the child's horizontal offset.
* This float is multiplied by the child's width.
* If null, the containing AnchorLayout's anchor values will be used.
*/
public Float anchorX = null;
/**
* Float value to determine the child's vertical offset.
* This float is multiplied by the child's height.
* If null, the containing AnchorLayout's anchor values will be used.
*/
public Float anchorY = null;
private int mTop;
private int mLeft;
private int mBottom;
private int mRight;
private Rect mHitRect;
/**
* Copy constructor.
*
* @param source LayoutParams instance to copy properties from.
*/
public LayoutParams(ViewGroup.LayoutParams source) {
super(source);
}
/**
* Creates a new set of layout parameters with the specified values.
*
* @param width Information about how wide the view wants to be. This should generally be WRAP_CONTENT or a fixed value.
* @param height Information about how tall the view wants to be. This should generally be WRAP_CONTENT or a fixed value.
*/
public LayoutParams(int width, int height) {
super(width, height);
}
/**
* Creates a new set of layout parameters with the specified values.
*
* @param width Information about how wide the view wants to be. This should generally be WRAP_CONTENT or a fixed value.
* @param height Information about how tall the view wants to be. This should generally be WRAP_CONTENT or a fixed value.
* @param left Sets the absolute x value of the view's position in pixels.
* @param top Sets the absolute y value of the view's position in pixels.
*/
public LayoutParams(int width, int height, int left, int top) {
super(width, height);
x = left;
y = top;
}
/**
* Creates a new set of layout parameters with the specified values.
*
* @param width Information about how wide the view wants to be. This should generally be WRAP_CONTENT or a fixed value.
* @param height Information about how tall the view wants to be. This should generally be WRAP_CONTENT or a fixed value.
* @param left Sets the absolute x value of the view's position in pixels.
* @param top Sets the absolute y value of the view's position in pixels.
* @param anchorLeft Sets the relative horizontal offset of the view (multiplied by the view's width).
* @param anchorTop Sets the relative vertical offset of the view (multiplied by the view's height).
*/
public LayoutParams(int width, int height, int left, int top, Float anchorLeft, Float anchorTop) {
super(width, height);
x = left;
y = top;
anchorX = anchorLeft;
anchorY = anchorTop;
}
private Rect getHitRect() {
if (mHitRect == null) {
mHitRect = new Rect();
}
mHitRect.left = mLeft;
mHitRect.top = mTop;
mHitRect.right = mRight;
mHitRect.bottom = mBottom;
return mHitRect;
}
}
}
| 9,770 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
ZoomPanLayout.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/tileview/src/main/java/com/qozix/tileview/widgets/ZoomPanLayout.java | package com.qozix.tileview.widgets;
import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Interpolator;
import android.widget.Scroller;
import androidx.core.view.ViewCompat;
import com.qozix.tileview.geom.FloatMathHelper;
import com.qozix.tileview.view.TouchUpGestureDetector;
import java.lang.ref.WeakReference;
import java.util.HashSet;
/**
* ZoomPanLayout extends ViewGroup to provide support for scrolling and zooming.
* Fling, drag, pinch and double-tap events are supported natively.
* <p>
* Children of ZoomPanLayout are laid out to the sizes provided by setSize,
* and will always be positioned at 0,0.
*/
public class ZoomPanLayout extends ViewGroup implements
GestureDetector.OnGestureListener,
GestureDetector.OnDoubleTapListener,
ScaleGestureDetector.OnScaleGestureListener,
TouchUpGestureDetector.OnTouchUpListener {
private static final int DEFAULT_ZOOM_PAN_ANIMATION_DURATION = 400;
private int mBaseWidth;
private int mBaseHeight;
private int mScaledWidth;
private int mScaledHeight;
private float mScale = 1;
private float mMinScale = 0;
private float mMaxScale = 1;
private int mOffsetX;
private int mOffsetY;
private float mEffectiveMinScale = 0;
private boolean mShouldLoopScale = true;
private boolean mIsFlinging;
private boolean mIsDragging;
private boolean mIsScaling;
private boolean mIsSliding;
private int mAnimationDuration = DEFAULT_ZOOM_PAN_ANIMATION_DURATION;
private HashSet<ZoomPanListener> mZoomPanListeners = new HashSet<ZoomPanListener>();
private Scroller mScroller;
private ZoomPanAnimator mZoomPanAnimator;
private ScaleGestureDetector mScaleGestureDetector;
private GestureDetector mGestureDetector;
private TouchUpGestureDetector mTouchUpGestureDetector;
private MinimumScaleMode mMinimumScaleMode = MinimumScaleMode.FILL;
/**
* Constructor to use when creating a ZoomPanLayout from code.
*
* @param context The Context the ZoomPanLayout is running in, through which it can access the current theme, resources, etc.
*/
public ZoomPanLayout(Context context) {
this(context, null);
}
public ZoomPanLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ZoomPanLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setWillNotDraw(false);
setClipChildren(false);
mScroller = new Scroller(context);
mGestureDetector = new GestureDetector(context, this);
mScaleGestureDetector = new ScaleGestureDetector(context, this);
mTouchUpGestureDetector = new TouchUpGestureDetector(this);
}
// public void setOuterDoubleTapListener(GestureDetector.OnDoubleTapListener outerDoubleTapListener) {
// mOuterDoubleTapListener = outerDoubleTapListener;
// }
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// the container's children should be the size provided by setSize
// don't use measureChildren because that grabs the child's LayoutParams
int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(mScaledWidth, MeasureSpec.EXACTLY);
int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(mScaledHeight, MeasureSpec.EXACTLY);
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
// but the layout itself should report normal (on screen) dimensions
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
width = resolveSize(width, widthMeasureSpec);
height = resolveSize(height, heightMeasureSpec);
setMeasuredDimension(width, height);
}
/*
ZoomPanChildren will always be laid out with the scaled dimenions - what is visible during
scroll operations. Thus, a RelativeLayout added as a child that had views within it using
rules like ALIGN_PARENT_RIGHT would function as expected; similarly, an ImageView would be
stretched between the visible edges.
If children further operate on scale values, that should be accounted for
in the child's logic (see ScalingLayout).
*/
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int width = getWidth();
final int height = getHeight();
mOffsetX = mScaledWidth >= width ? 0 : width / 2 - mScaledWidth / 2;
mOffsetY = mScaledHeight >= height ? 0 : height / 2 - mScaledHeight / 2;
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
if (child.getVisibility() != GONE) {
child.layout(mOffsetX, mOffsetY, mScaledWidth + mOffsetX, mScaledHeight + mOffsetY);
}
}
calculateMinimumScaleToFit();
constrainScrollToLimits();
}
/**
* Determines whether the ZoomPanLayout should limit it's minimum scale to no less than what
* would be required to fill it's container.
*
* @param shouldScaleToFit True to limit minimum scale, false to allow arbitrary minimum scale.
*/
public void setShouldScaleToFit(boolean shouldScaleToFit) {
setMinimumScaleMode(shouldScaleToFit ? MinimumScaleMode.FILL : MinimumScaleMode.NONE);
}
/**
* Sets the minimum scale mode
*
* @param minimumScaleMode The minimum scale mode
*/
public void setMinimumScaleMode(MinimumScaleMode minimumScaleMode) {
mMinimumScaleMode = minimumScaleMode;
calculateMinimumScaleToFit();
}
/**
* Determines whether the ZoomPanLayout should go back to minimum scale after a double-tap at
* maximum scale.
*
* @param shouldLoopScale True to allow going back to minimum scale, false otherwise.
*/
public void setShouldLoopScale(boolean shouldLoopScale) {
mShouldLoopScale = shouldLoopScale;
}
/**
* Set minimum and maximum mScale values for this ZoomPanLayout.
* Note that if minimumScaleMode is set to {@link MinimumScaleMode#FIT} or {@link MinimumScaleMode#FILL}, the minimum value set here will be ignored
* Default values are 0 and 1.
*
* @param min Minimum scale the ZoomPanLayout should accept.
* @param max Maximum scale the ZoomPanLayout should accept.
*/
public void setScaleLimits(float min, float max) {
mMinScale = min;
mMaxScale = max;
setScale(mScale);
}
/**
* Sets the size (width and height) of the ZoomPanLayout
* as it should be rendered at a scale of 1f (100%).
*
* @param width Width of the underlying image, not the view or viewport.
* @param height Height of the underlying image, not the view or viewport.
*/
public void setSize(int width, int height) {
mBaseWidth = width;
mBaseHeight = height;
updateScaledDimensions();
calculateMinimumScaleToFit();
constrainScrollToLimits();
requestLayout();
}
/**
* Returns the base (not scaled) width of the underlying composite image.
*
* @return The base (not scaled) width of the underlying composite image.
*/
public int getBaseWidth() {
return mBaseWidth;
}
/**
* Returns the base (not scaled) height of the underlying composite image.
*
* @return The base (not scaled) height of the underlying composite image.
*/
public int getBaseHeight() {
return mBaseHeight;
}
/**
* Returns the scaled width of the underlying composite image.
*
* @return The scaled width of the underlying composite image.
*/
public int getScaledWidth() {
return mScaledWidth;
}
/**
* Returns the scaled height of the underlying composite image.
*
* @return The scaled height of the underlying composite image.
*/
public int getScaledHeight() {
return mScaledHeight;
}
/**
* Retrieves the current scale of the ZoomPanLayout.
*
* @return The current scale of the ZoomPanLayout.
*/
public float getScale() {
return mScale;
}
/**
* Sets the scale (0-1) of the ZoomPanLayout.
*
* @param scale The new value of the ZoomPanLayout scale.
*/
public void setScale(float scale) {
scale = getConstrainedDestinationScale(scale);
if (mScale != scale) {
float previous = mScale;
mScale = scale;
updateScaledDimensions();
constrainScrollToLimits();
onScaleChanged(scale, previous);
invalidate();
}
}
/**
* Returns the horizontal distance children are offset if the content is scaled smaller than width.
*
* @return
*/
public int getOffsetX() {
return mOffsetX;
}
/**
* Return the vertical distance children are offset if the content is scaled smaller than height.
*
* @return
*/
public int getOffsetY() {
return mOffsetY;
}
/**
* Returns whether the ZoomPanLayout is currently being flung.
*
* @return true if the ZoomPanLayout is currently flinging, false otherwise.
*/
public boolean isFlinging() {
return mIsFlinging;
}
/**
* Returns whether the ZoomPanLayout is currently being dragged.
*
* @return true if the ZoomPanLayout is currently dragging, false otherwise.
*/
public boolean isDragging() {
return mIsDragging;
}
/**
* Returns whether the ZoomPanLayout is currently operating a scroll tween.
*
* @return True if the ZoomPanLayout is currently scrolling, false otherwise.
*/
public boolean isSliding() {
return mIsSliding;
}
/**
* Returns whether the ZoomPanLayout is currently operating a scale tween.
*
* @return True if the ZoomPanLayout is currently scaling, false otherwise.
*/
public boolean isScaling() {
return mIsScaling;
}
/**
* Returns the Scroller instance used to manage dragging and flinging.
*
* @return The Scroller instance use to manage dragging and flinging.
*/
public Scroller getScroller() {
return mScroller;
}
/**
* Returns the duration zoom and pan animations will use.
*
* @return The duration zoom and pan animations will use.
*/
public int getAnimationDuration() {
return mAnimationDuration;
}
/**
* Set the duration zoom and pan animation will use.
*
* @param animationDuration The duration animations will use.
*/
public void setAnimationDuration(int animationDuration) {
mAnimationDuration = animationDuration;
if (mZoomPanAnimator != null) {
mZoomPanAnimator.setDuration(mAnimationDuration);
}
}
/**
* Adds a ZoomPanListener to the ZoomPanLayout, which will receive notification of actions
* relating to zoom and pan events.
*
* @param zoomPanListener ZoomPanListener implementation to add.
* @return True when the listener set did not already contain the Listener, false otherwise.
*/
public boolean addZoomPanListener(ZoomPanListener zoomPanListener) {
return mZoomPanListeners.add(zoomPanListener);
}
/**
* Removes a ZoomPanListener from the ZoomPanLayout
*
* @param listener ZoomPanListener to remove.
* @return True if the Listener was removed, false otherwise.
*/
public boolean removeZoomPanListener(ZoomPanListener listener) {
return mZoomPanListeners.remove(listener);
}
/**
* Scrolls and centers the ZoomPanLayout to the x and y values provided.
*
* @param x Horizontal destination point.
* @param y Vertical destination point.
*/
public void scrollToAndCenter(int x, int y) {
scrollTo(x - getHalfWidth(), y - getHalfHeight());
}
/**
* Set the scale of the ZoomPanLayout while maintaining the current center point.
*
* @param scale The new value of the ZoomPanLayout scale.
*/
public void setScaleFromCenter(float scale) {
setScaleFromPosition(getHalfWidth(), getHalfHeight(), scale);
}
/**
* Scrolls the ZoomPanLayout to the x and y values provided using scrolling animation.
*
* @param x Horizontal destination point.
* @param y Vertical destination point.
*/
public void slideTo(int x, int y) {
getAnimator().animatePan(x, y);
}
/**
* Scrolls and centers the ZoomPanLayout to the x and y values provided using scrolling animation.
*
* @param x Horizontal destination point.
* @param y Vertical destination point.
*/
public void slideToAndCenter(int x, int y) {
slideTo(x - getHalfWidth(), y - getHalfHeight());
}
/**
* Animates the ZoomPanLayout to the scale provided, and centers the viewport to the position
* supplied.
*
* @param x Horizontal destination point.
* @param y Vertical destination point.
* @param scale The final scale value the ZoomPanLayout should animate to.
*/
public void slideToAndCenterWithScale(int x, int y, float scale) {
getAnimator().animateZoomPan(x - getHalfWidth(), y - getHalfHeight(), scale);
}
/**
* Scales the ZoomPanLayout with animated progress, without maintaining scroll position.
*
* @param destination The final scale value the ZoomPanLayout should animate to.
*/
public void smoothScaleTo(float destination) {
getAnimator().animateZoom(destination);
}
/**
* Animates the ZoomPanLayout to the scale provided, while maintaining position determined by
* the focal point provided.
*
* @param focusX The horizontal focal point to maintain, relative to the screen (as supplied by MotionEvent.getX).
* @param focusY The vertical focal point to maintain, relative to the screen (as supplied by MotionEvent.getY).
* @param scale The final scale value the ZoomPanLayout should animate to.
*/
public void smoothScaleFromFocalPoint(int focusX, int focusY, float scale) {
scale = getConstrainedDestinationScale(scale);
if (scale == mScale) {
return;
}
int x = getOffsetScrollXFromScale(focusX, scale, mScale);
int y = getOffsetScrollYFromScale(focusY, scale, mScale);
getAnimator().animateZoomPan(x, y, scale);
}
/**
* Animate the scale of the ZoomPanLayout while maintaining the current center point.
*
* @param scale The final scale value the ZoomPanLayout should animate to.
*/
public void smoothScaleFromCenter(float scale) {
smoothScaleFromFocalPoint(getHalfWidth(), getHalfHeight(), scale);
}
/**
* Provide this method to be overriden by subclasses, e.g., onScrollChanged.
*/
public void onScaleChanged(float currentScale, float previousScale) {
// noop
}
private float getConstrainedDestinationScale(float scale) {
scale = Math.max(scale, mEffectiveMinScale);
scale = Math.min(scale, mMaxScale);
return scale;
}
private void constrainScrollToLimits() {
int x = getScrollX();
int y = getScrollY();
int constrainedX = getConstrainedScrollX(x);
int constrainedY = getConstrainedScrollY(y);
if (x != constrainedX || y != constrainedY) {
scrollTo(constrainedX, constrainedY);
}
}
private void updateScaledDimensions() {
mScaledWidth = FloatMathHelper.scale(mBaseWidth, mScale);
mScaledHeight = FloatMathHelper.scale(mBaseHeight, mScale);
}
protected ZoomPanAnimator getAnimator() {
if (mZoomPanAnimator == null) {
mZoomPanAnimator = new ZoomPanAnimator(this);
mZoomPanAnimator.setDuration(mAnimationDuration);
}
return mZoomPanAnimator;
}
private int getOffsetScrollXFromScale(int offsetX, float destinationScale, float currentScale) {
int scrollX = getScrollX() + offsetX;
float deltaScale = destinationScale / currentScale;
return (int) (scrollX * deltaScale) - offsetX;
}
private int getOffsetScrollYFromScale(int offsetY, float destinationScale, float currentScale) {
int scrollY = getScrollY() + offsetY;
float deltaScale = destinationScale / currentScale;
return (int) (scrollY * deltaScale) - offsetY;
}
public void setScaleFromPosition(int offsetX, int offsetY, float scale) {
scale = getConstrainedDestinationScale(scale);
if (scale == mScale) {
return;
}
int x = getOffsetScrollXFromScale(offsetX, scale, mScale);
int y = getOffsetScrollYFromScale(offsetY, scale, mScale);
setScale(scale);
x = getConstrainedScrollX(x);
y = getConstrainedScrollY(y);
scrollTo(x, y);
}
@Override
public boolean canScrollHorizontally(int direction) {
int position = getScrollX();
return direction > 0 ? position < getScrollLimitX() : direction < 0 && position > 0;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
boolean gestureIntercept = mGestureDetector.onTouchEvent(event);
boolean scaleIntercept = mScaleGestureDetector.onTouchEvent(event);
boolean touchIntercept = mTouchUpGestureDetector.onTouchEvent(event);
return gestureIntercept || scaleIntercept || touchIntercept || super.onTouchEvent(event);
}
@Override
public void scrollTo(int x, int y) {
x = getConstrainedScrollX(x);
y = getConstrainedScrollY(y);
super.scrollTo(x, y);
}
private void calculateMinimumScaleToFit() {
float minimumScaleX = getWidth() / (float) mBaseWidth;
float minimumScaleY = getHeight() / (float) mBaseHeight;
float recalculatedMinScale = calculatedMinScale(minimumScaleX, minimumScaleY);
if (recalculatedMinScale != mEffectiveMinScale) {
mEffectiveMinScale = recalculatedMinScale;
if (mScale < mEffectiveMinScale) {
setScale(mEffectiveMinScale);
}
}
}
private float calculatedMinScale(float minimumScaleX, float minimumScaleY) {
switch (mMinimumScaleMode) {
case FILL:
return Math.max(minimumScaleX, minimumScaleY);
case FIT:
return Math.min(minimumScaleX, minimumScaleY);
}
return mMinScale;
}
protected int getHalfWidth() {
return FloatMathHelper.scale(getWidth(), 0.5f);
}
protected int getHalfHeight() {
return FloatMathHelper.scale(getHeight(), 0.5f);
}
private int getConstrainedScrollX(int x) {
return Math.max(0, Math.min(x, getScrollLimitX()));
}
private int getConstrainedScrollY(int y) {
return Math.max(0, Math.min(y, getScrollLimitY()));
}
private int getScrollLimitX() {
return mScaledWidth - getWidth();
}
private int getScrollLimitY() {
return mScaledHeight - getHeight();
}
@Override
public void computeScroll() {
if (mScroller.computeScrollOffset()) {
int startX = getScrollX();
int startY = getScrollY();
int endX = getConstrainedScrollX(mScroller.getCurrX());
int endY = getConstrainedScrollY(mScroller.getCurrY());
if (startX != endX || startY != endY) {
scrollTo(endX, endY);
if (mIsFlinging) {
broadcastFlingUpdate();
}
}
if (mScroller.isFinished()) {
if (mIsFlinging) {
mIsFlinging = false;
broadcastFlingEnd();
}
} else {
ViewCompat.postInvalidateOnAnimation(this);
}
}
}
private void broadcastDragBegin() {
for (ZoomPanListener listener : mZoomPanListeners) {
listener.onPanBegin(getScrollX(), getScrollY(), ZoomPanListener.Origination.DRAG);
}
}
private void broadcastDragUpdate() {
for (ZoomPanListener listener : mZoomPanListeners) {
listener.onPanUpdate(getScrollX(), getScrollY(), ZoomPanListener.Origination.DRAG);
}
}
private void broadcastDragEnd() {
for (ZoomPanListener listener : mZoomPanListeners) {
listener.onPanEnd(getScrollX(), getScrollY(), ZoomPanListener.Origination.DRAG);
}
}
private void broadcastFlingBegin() {
for (ZoomPanListener listener : mZoomPanListeners) {
listener.onPanBegin(mScroller.getStartX(), mScroller.getStartY(), ZoomPanListener.Origination.FLING);
}
}
private void broadcastFlingUpdate() {
for (ZoomPanListener listener : mZoomPanListeners) {
listener.onPanUpdate(mScroller.getCurrX(), mScroller.getCurrY(), ZoomPanListener.Origination.FLING);
}
}
private void broadcastFlingEnd() {
for (ZoomPanListener listener : mZoomPanListeners) {
listener.onPanEnd(mScroller.getFinalX(), mScroller.getFinalY(), ZoomPanListener.Origination.FLING);
}
}
private void broadcastProgrammaticPanBegin() {
for (ZoomPanListener listener : mZoomPanListeners) {
listener.onPanBegin(getScrollX(), getScrollY(), null);
}
}
private void broadcastProgrammaticPanUpdate() {
for (ZoomPanListener listener : mZoomPanListeners) {
listener.onPanUpdate(getScrollX(), getScrollY(), null);
}
}
private void broadcastProgrammaticPanEnd() {
for (ZoomPanListener listener : mZoomPanListeners) {
listener.onPanEnd(getScrollX(), getScrollY(), null);
}
}
private void broadcastPinchBegin() {
for (ZoomPanListener listener : mZoomPanListeners) {
listener.onZoomBegin(mScale, ZoomPanListener.Origination.PINCH);
}
}
private void broadcastPinchUpdate() {
for (ZoomPanListener listener : mZoomPanListeners) {
listener.onZoomUpdate(mScale, ZoomPanListener.Origination.PINCH);
}
}
private void broadcastPinchEnd() {
for (ZoomPanListener listener : mZoomPanListeners) {
listener.onZoomEnd(mScale, ZoomPanListener.Origination.PINCH);
}
}
private void broadcastProgrammaticZoomBegin() {
for (ZoomPanListener listener : mZoomPanListeners) {
listener.onZoomBegin(mScale, null);
}
}
private void broadcastProgrammaticZoomUpdate() {
for (ZoomPanListener listener : mZoomPanListeners) {
listener.onZoomUpdate(mScale, null);
}
}
private void broadcastProgrammaticZoomEnd() {
for (ZoomPanListener listener : mZoomPanListeners) {
listener.onZoomEnd(mScale, null);
}
}
@Override
public boolean onDown(MotionEvent event) {
if (mIsFlinging && !mScroller.isFinished()) {
mScroller.forceFinished(true);
mIsFlinging = false;
broadcastFlingEnd();
}
return true;
}
@Override
public boolean onFling(MotionEvent event1, MotionEvent event2, float velocityX, float velocityY) {
mScroller.fling(getScrollX(), getScrollY(), (int) -velocityX, (int) -velocityY, 0, getScrollLimitX(), 0, getScrollLimitY());
mIsFlinging = true;
ViewCompat.postInvalidateOnAnimation(this);
broadcastFlingBegin();
return true;
}
@Override
public void onLongPress(MotionEvent event) {
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
int scrollEndX = getScrollX() + (int) distanceX;
int scrollEndY = getScrollY() + (int) distanceY;
scrollTo(scrollEndX, scrollEndY);
if (!mIsDragging) {
mIsDragging = true;
broadcastDragBegin();
} else {
broadcastDragUpdate();
}
return true;
}
@Override
public void onShowPress(MotionEvent event) {
}
@Override
public boolean onSingleTapUp(MotionEvent event) {
return true;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent event) {
return false;
}
@Override
public boolean onDoubleTap(MotionEvent event) {
// float destination = (float) (Math.pow(2, Math.floor(Math.log(mScale * 2) / Math.log(2))));
// float effectiveDestination = mShouldLoopScale && mScale >= mMaxScale ? mMinScale : destination;
// destination = getConstrainedDestinationScale(effectiveDestination);
// smoothScaleFromFocalPoint((int) event.getX(), (int) event.getY(), destination);
//if (mOuterDoubleTapListener != null) mOuterDoubleTapListener.onDoubleTap(event);
return true;
}
@Override
public boolean onDoubleTapEvent(MotionEvent event) {
return true;
}
@Override
public boolean onTouchUp(MotionEvent event) {
if (mIsDragging) {
mIsDragging = false;
if (!mIsFlinging) {
broadcastDragEnd();
}
}
return true;
}
@Override
public boolean onScaleBegin(ScaleGestureDetector scaleGestureDetector) {
mIsScaling = true;
broadcastPinchBegin();
return true;
}
@Override
public void onScaleEnd(ScaleGestureDetector scaleGestureDetector) {
mIsScaling = false;
broadcastPinchEnd();
}
@Override
public boolean onScale(ScaleGestureDetector scaleGestureDetector) {
float currentScale = mScale * mScaleGestureDetector.getScaleFactor();
setScaleFromPosition(
(int) scaleGestureDetector.getFocusX(),
(int) scaleGestureDetector.getFocusY(),
currentScale);
broadcastPinchUpdate();
return true;
}
public enum MinimumScaleMode {
/**
* Limit the minimum scale to no less than what
* would be required to fill the container
*/
FILL,
/**
* Limit the minimum scale to no less than what
* would be required to fit inside the container
*/
FIT,
/**
* Allow arbitrary minimum scale.
*/
NONE
}
public interface ZoomPanListener {
void onPanBegin(int x, int y, Origination origin);
void onPanUpdate(int x, int y, Origination origin);
void onPanEnd(int x, int y, Origination origin);
void onZoomBegin(float scale, Origination origin);
void onZoomUpdate(float scale, Origination origin);
void onZoomEnd(float scale, Origination origin);
enum Origination {
DRAG,
FLING,
PINCH
}
}
private static class ZoomPanAnimator extends ValueAnimator implements
ValueAnimator.AnimatorUpdateListener,
ValueAnimator.AnimatorListener {
private WeakReference<ZoomPanLayout> mZoomPanLayoutWeakReference;
private ZoomPanState mStartState = new ZoomPanState();
private ZoomPanState mEndState = new ZoomPanState();
private boolean mHasPendingZoomUpdates;
private boolean mHasPendingPanUpdates;
public ZoomPanAnimator(ZoomPanLayout zoomPanLayout) {
super();
addUpdateListener(this);
addListener(this);
setFloatValues(0f, 1f);
setInterpolator(new FastEaseInInterpolator());
mZoomPanLayoutWeakReference = new WeakReference<ZoomPanLayout>(zoomPanLayout);
}
private boolean setupPanAnimation(int x, int y) {
ZoomPanLayout zoomPanLayout = mZoomPanLayoutWeakReference.get();
if (zoomPanLayout != null) {
mStartState.x = zoomPanLayout.getScrollX();
mStartState.y = zoomPanLayout.getScrollY();
mEndState.x = x;
mEndState.y = y;
return mStartState.x != mEndState.x || mStartState.y != mEndState.y;
}
return false;
}
private boolean setupZoomAnimation(float scale) {
ZoomPanLayout zoomPanLayout = mZoomPanLayoutWeakReference.get();
if (zoomPanLayout != null) {
mStartState.scale = zoomPanLayout.getScale();
mEndState.scale = scale;
return mStartState.scale != mEndState.scale;
}
return false;
}
public void animateZoomPan(int x, int y, float scale) {
ZoomPanLayout zoomPanLayout = mZoomPanLayoutWeakReference.get();
if (zoomPanLayout != null) {
mHasPendingZoomUpdates = setupZoomAnimation(scale);
mHasPendingPanUpdates = setupPanAnimation(x, y);
if (mHasPendingPanUpdates || mHasPendingZoomUpdates) {
start();
}
}
}
public void animateZoom(float scale) {
ZoomPanLayout zoomPanLayout = mZoomPanLayoutWeakReference.get();
if (zoomPanLayout != null) {
mHasPendingZoomUpdates = setupZoomAnimation(scale);
if (mHasPendingZoomUpdates) {
start();
}
}
}
public void animatePan(int x, int y) {
ZoomPanLayout zoomPanLayout = mZoomPanLayoutWeakReference.get();
if (zoomPanLayout != null) {
mHasPendingPanUpdates = setupPanAnimation(x, y);
if (mHasPendingPanUpdates) {
start();
}
}
}
@Override
public void onAnimationUpdate(ValueAnimator animation) {
ZoomPanLayout zoomPanLayout = mZoomPanLayoutWeakReference.get();
if (zoomPanLayout != null) {
float progress = (float) animation.getAnimatedValue();
if (mHasPendingZoomUpdates) {
float scale = mStartState.scale + (mEndState.scale - mStartState.scale) * progress;
zoomPanLayout.setScale(scale);
zoomPanLayout.broadcastProgrammaticZoomUpdate();
}
if (mHasPendingPanUpdates) {
int x = (int) (mStartState.x + (mEndState.x - mStartState.x) * progress);
int y = (int) (mStartState.y + (mEndState.y - mStartState.y) * progress);
zoomPanLayout.scrollTo(x, y);
zoomPanLayout.broadcastProgrammaticPanUpdate();
}
}
}
@Override
public void onAnimationStart(Animator animator) {
ZoomPanLayout zoomPanLayout = mZoomPanLayoutWeakReference.get();
if (zoomPanLayout != null) {
if (mHasPendingZoomUpdates) {
zoomPanLayout.mIsScaling = true;
zoomPanLayout.broadcastProgrammaticZoomBegin();
}
if (mHasPendingPanUpdates) {
zoomPanLayout.mIsSliding = true;
zoomPanLayout.broadcastProgrammaticPanBegin();
}
}
}
@Override
public void onAnimationEnd(Animator animator) {
ZoomPanLayout zoomPanLayout = mZoomPanLayoutWeakReference.get();
if (zoomPanLayout != null) {
if (mHasPendingZoomUpdates) {
mHasPendingZoomUpdates = false;
zoomPanLayout.mIsScaling = false;
zoomPanLayout.broadcastProgrammaticZoomEnd();
}
if (mHasPendingPanUpdates) {
mHasPendingPanUpdates = false;
zoomPanLayout.mIsSliding = false;
zoomPanLayout.broadcastProgrammaticPanEnd();
}
}
}
@Override
public void onAnimationCancel(Animator animator) {
onAnimationEnd(animator);
}
@Override
public void onAnimationRepeat(Animator animator) {
}
private static class ZoomPanState {
public int x;
public int y;
public float scale;
}
private static class FastEaseInInterpolator implements Interpolator {
@Override
public float getInterpolation(float input) {
return (float) (1 - Math.pow(1 - input, 8));
}
}
}
}
| 33,217 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
ScalingLayout.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/tileview/src/main/java/com/qozix/tileview/widgets/ScalingLayout.java | package com.qozix.tileview.widgets;
import android.content.Context;
import android.graphics.Canvas;
import android.view.View;
import android.view.ViewGroup;
import com.qozix.tileview.geom.FloatMathHelper;
public class ScalingLayout extends ViewGroup {
private float mScale = 1;
/**
*
* @param context
*/
public ScalingLayout( Context context ) {
super( context );
setWillNotDraw( false );
}
/**
*
* @param scale
*/
public void setScale( float scale ) {
mScale = scale;
invalidate();
}
/**
*
* @return
*/
public float getScale() {
return mScale;
}
/*
* When scaling a canvas, as happens in onDraw, the clip area will be reduced at a small scale,
* thus decreasing the drawable surface, but when scaled up, the canvas is still constrained
* by the original width and height of the backing bitmap, which are not scaled. Offset those
* by dividing the measure and layout dimensions by the current scale.
*/
@Override
protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec ) {
int availableWidth = FloatMathHelper.unscale( MeasureSpec.getSize( widthMeasureSpec ), mScale );
int availableHeight = FloatMathHelper.unscale( MeasureSpec.getSize( heightMeasureSpec ), mScale );
// the container's children should be the size provided by setSize
// don't use measureChildren because that grabs the child's LayoutParams
int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec( availableWidth, MeasureSpec.EXACTLY );
int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec( availableHeight, MeasureSpec.EXACTLY );
for( int i = 0; i < getChildCount(); i++){
View child = getChildAt( i );
child.measure( childWidthMeasureSpec, childHeightMeasureSpec );
}
setMeasuredDimension( availableWidth, availableHeight );
}
@Override
protected void onLayout( boolean changed, int l, int t, int r, int b ) {
int availableWidth = FloatMathHelper.unscale( r - l, mScale );
int availableHeight = FloatMathHelper.unscale( b - t, mScale );
for( int i = 0; i < getChildCount(); i++ ) {
View child = getChildAt( i );
if( child.getVisibility() != GONE ) {
child.layout( 0, 0, availableWidth, availableHeight );
}
}
}
@Override
public void onDraw( Canvas canvas ) {
canvas.scale( mScale, mScale );
super.onDraw( canvas );
}
} | 2,403 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
TouchUpGestureDetector.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/tileview/src/main/java/com/qozix/tileview/view/TouchUpGestureDetector.java | package com.qozix.tileview.view;
import android.view.MotionEvent;
/**
* @author Mike Dunn, 10/6/15.
*/
public class TouchUpGestureDetector {
private OnTouchUpListener mOnTouchUpListener;
public TouchUpGestureDetector( OnTouchUpListener listener ) {
mOnTouchUpListener = listener;
}
public boolean onTouchEvent( MotionEvent event ) {
if( event.getActionMasked() == MotionEvent.ACTION_UP ) {
if( mOnTouchUpListener != null ) {
return mOnTouchUpListener.onTouchUp( event );
}
}
return true;
}
public interface OnTouchUpListener {
boolean onTouchUp( MotionEvent event );
}
}
| 634 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
CompositePathView.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/tileview/src/main/java/com/qozix/tileview/paths/CompositePathView.java | package com.qozix.tileview.paths;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.view.View;
import java.util.HashSet;
public class CompositePathView extends View {
private static final int DEFAULT_STROKE_COLOR = 0xFF000000;
private static final int DEFAULT_STROKE_WIDTH = 10;
private float mScale = 1;
private boolean mShouldDraw = true;
private Path mRecyclerPath = new Path();
private Matrix mMatrix = new Matrix();
private HashSet<DrawablePath> mDrawablePaths = new HashSet<DrawablePath>();
private Paint mDefaultPaint = new Paint();
{
mDefaultPaint.setStyle( Paint.Style.STROKE );
mDefaultPaint.setColor( DEFAULT_STROKE_COLOR );
mDefaultPaint.setStrokeWidth( DEFAULT_STROKE_WIDTH );
mDefaultPaint.setAntiAlias( true );
}
public CompositePathView( Context context ) {
super( context );
setWillNotDraw( false );
}
public float getScale() {
return mScale;
}
public void setScale( float scale ) {
mScale = scale;
mMatrix.setScale( mScale, mScale );
invalidate();
}
public Paint getDefaultPaint() {
return mDefaultPaint;
}
public DrawablePath addPath( Path path, Paint paint ) {
if( paint == null ) {
paint = mDefaultPaint;
}
DrawablePath DrawablePath = new DrawablePath();
DrawablePath.path = path;
DrawablePath.paint = paint;
return addPath( DrawablePath );
}
public DrawablePath addPath( DrawablePath DrawablePath ) {
mDrawablePaths.add( DrawablePath );
invalidate();
return DrawablePath;
}
public void removePath( DrawablePath path ) {
mDrawablePaths.remove( path );
invalidate();
}
public void clear() {
mDrawablePaths.clear();
invalidate();
}
public void setShouldDraw( boolean shouldDraw ) {
mShouldDraw = shouldDraw;
invalidate();
}
@Override
public void onDraw( Canvas canvas ) {
if( mShouldDraw ) {
for( DrawablePath drawablePath : mDrawablePaths ) {
mRecyclerPath.set( drawablePath.path );
mRecyclerPath.transform( mMatrix );
canvas.drawPath( mRecyclerPath, drawablePath.paint );
}
}
super.onDraw( canvas );
}
public static class DrawablePath {
/**
* The path that this drawable will follow.
*/
public Path path;
/**
* The paint to be used for this path.
*/
public Paint paint;
}
}
| 2,501 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
DetailLevelManager.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/tileview/src/main/java/com/qozix/tileview/detail/DetailLevelManager.java | package com.qozix.tileview.detail;
import android.graphics.Rect;
import com.qozix.tileview.geom.FloatMathHelper;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
public class DetailLevelManager {
public interface LevelType {
}
private Map<LevelType, LinkedList<DetailLevel>> mDetailLevelLinkedList = new HashMap<>();
private DetailLevelChangeListener mDetailLevelChangeListener;
protected float mScale = 1;
private int mBaseWidth;
private int mBaseHeight;
private int mScaledWidth;
private int mScaledHeight;
private boolean mDetailLevelLocked;
private int mPadding;
private Rect mViewport = new Rect();
private Rect mComputedViewport = new Rect();
private Rect mComputedScaledViewport = new Rect();
private boolean dirty;
private LevelType mCurrentLevelType;
private DetailLevel mCurrentDetailLevel;
public DetailLevelManager() {
update();
}
public float getScale() {
return mScale;
}
public void setScale( float scale ) {
mScale = scale;
update();
}
public int getBaseWidth() {
return mBaseWidth;
}
public int getBaseHeight() {
return mBaseHeight;
}
public int getScaledWidth() {
return mScaledWidth;
}
public int getScaledHeight() {
return mScaledHeight;
}
public void setSize( int width, int height ) {
mBaseWidth = width;
mBaseHeight = height;
update();
}
public void setLevelType(LevelType levelType) {
if( this.mCurrentLevelType == levelType ) return;
this.mCurrentLevelType = levelType;
this.dirty = true;
this.update();
}
public void setDetailLevelChangeListener( DetailLevelChangeListener detailLevelChangeListener ) {
mDetailLevelChangeListener = detailLevelChangeListener;
}
/**
* "pads" the viewport by the number of pixels passed. e.g., setViewportPadding( 100 ) instructs the
* DetailManager to interpret it's actual viewport offset by 100 pixels in each direction (top, left,
* right, bottom), so more tiles will qualify for "visible" status when intersections are calculated.
*
* @param pixels The number of pixels to pad the viewport by.
*/
public void setViewportPadding( int pixels ) {
mPadding = pixels;
updateComputedViewport();
}
public void updateViewport( int left, int top, int right, int bottom ) {
mViewport.set( left, top, right, bottom );
updateComputedViewport();
}
private void updateComputedViewport() {
mComputedViewport.set( mViewport );
mComputedViewport.top -= mPadding;
mComputedViewport.left -= mPadding;
mComputedViewport.bottom += mPadding;
mComputedViewport.right += mPadding;
}
public Rect getViewport() {
return mViewport;
}
public Rect getComputedViewport() {
return mComputedViewport;
}
public Rect getComputedScaledViewport(float scale){
mComputedScaledViewport.set(
(int) (mComputedViewport.left * scale),
(int) (mComputedViewport.top * scale),
(int) (mComputedViewport.right * scale),
(int) (mComputedViewport.bottom * scale)
);
return mComputedScaledViewport;
}
/**
* While the detail level is locked (after this method is invoked, and before unlockDetailLevel is invoked),
* the DetailLevel will not change, and the current DetailLevel will be scaled beyond the normal
* bounds. Normally, during any scale change the DetailManager searches for the DetailLevel with
* a registered scale closest to the defined mScale. While locked, this does not occur.
*/
public void lockDetailLevel() {
mDetailLevelLocked = true;
}
/**
* Unlocks a DetailLevel locked with lockDetailLevel.
*/
public void unlockDetailLevel() {
mDetailLevelLocked = false;
}
public boolean getIsLocked() {
return mDetailLevelLocked;
}
public void resetDetailLevels() {
mDetailLevelLinkedList.clear();
update();
}
public DetailLevel getCurrentDetailLevel() {
return mCurrentDetailLevel;
}
protected void update() {
if(this.dirty || !mDetailLevelLocked ) {
DetailLevel matchingLevel = getDetailLevelForScale();
if( matchingLevel != null ) {
this.dirty = !matchingLevel.equals( mCurrentDetailLevel );
mCurrentDetailLevel = matchingLevel;
}
}
mScaledWidth = FloatMathHelper.scale( mBaseWidth, mScale );
mScaledHeight = FloatMathHelper.scale( mBaseHeight, mScale );
if( this.dirty ) {
if( mDetailLevelChangeListener != null ) {
mDetailLevelChangeListener.onDetailLevelChanged( mCurrentDetailLevel );
}
this.dirty = false;
}
}
public void addDetailLevel( float scale, Object data, int tileWidth, int tileHeight) {
this.addDetailLevel(scale, data, tileWidth, tileHeight, null);
}
public void addDetailLevel( float scale, Object data, int tileWidth, int tileHeight, LevelType levelType) {
DetailLevel detailLevel = new DetailLevel( this, scale, data, tileWidth, tileHeight, levelType);
LinkedList<DetailLevel> levels = mDetailLevelLinkedList.get(levelType);
if( levels != null){
if(levels.contains( detailLevel ) ) {
return;
} else {
levels.add( detailLevel );
Collections.sort( levels );
}
} else {
//a list with one item does not need to be sorted, just add the new list to the map
levels = new LinkedList<>();
levels.add(detailLevel);
mDetailLevelLinkedList.put(levelType, levels);
}
update();
}
public DetailLevel getDetailLevelForScale() {
LinkedList<DetailLevel> levels = mDetailLevelLinkedList.get(mCurrentLevelType);
if( levels == null || levels.size() == 0 ) {
return null;
}
if( levels.size() == 1 ) {
return levels.get( 0 );
}
DetailLevel match = null;
int index = levels.size() - 1;
for( int i = index; i >= 0; i-- ) {
match = levels.get( i );
if( match.getScale() < mScale ) {
if( i < index ) {
match = levels.get( i + 1 );
}
break;
}
}
return match;
}
public void invalidateAll(){
for( LinkedList<DetailLevel> levels : mDetailLevelLinkedList.values() ) {
for (DetailLevel detailLevel : levels) {
detailLevel.invalidate();
}
}
}
public interface DetailLevelChangeListener {
void onDetailLevelChanged( DetailLevel detailLevel );
}
}
| 6,426 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
DetailLevel.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/tileview/src/main/java/com/qozix/tileview/detail/DetailLevel.java | package com.qozix.tileview.detail;
import android.graphics.Rect;
import com.qozix.tileview.tiles.Tile;
import java.util.HashSet;
import java.util.Set;
import androidx.annotation.NonNull;
public class DetailLevel implements Comparable<DetailLevel> {
private float mScale;
private int mTileWidth;
private int mTileHeight;
private Object mData;
private DetailLevelManager.LevelType mLevelType;
private DetailLevelManager mDetailLevelManager;
private StateSnapshot mLastStateSnapshot;
private Set<Tile> mTilesVisibleInViewport = new HashSet<>();
public DetailLevel(DetailLevelManager detailLevelManager, float scale, Object data, int tileWidth, int tileHeight, DetailLevelManager.LevelType levelType) {
mDetailLevelManager = detailLevelManager;
mScale = scale;
mData = data;
mTileWidth = tileWidth;
mTileHeight = tileHeight;
mLevelType = levelType;
}
public DetailLevel(DetailLevelManager detailLevelManager, float scale, Object data, int tileWidth, int tileHeight) {
mDetailLevelManager = detailLevelManager;
mScale = scale;
mData = data;
mTileWidth = tileWidth;
mTileHeight = tileHeight;
}
public DetailLevelManager getDetailLevelManager() {
return mDetailLevelManager;
}
/**
* Returns true if there has been a change, false otherwise.
*
* @return True if there has been a change, false otherwise.
*/
public boolean computeCurrentState() {
float relativeScale = getRelativeScale();
int drawableWidth = mDetailLevelManager.getScaledWidth();
int drawableHeight = mDetailLevelManager.getScaledHeight();
float offsetWidth = mTileWidth * relativeScale;
float offsetHeight = mTileHeight * relativeScale;
Rect viewport = new Rect(mDetailLevelManager.getComputedViewport());
viewport.top = Math.max(viewport.top, 0);
viewport.left = Math.max(viewport.left, 0);
viewport.right = Math.min(viewport.right, drawableWidth);
viewport.bottom = Math.min(viewport.bottom, drawableHeight);
int rowStart = (int) Math.floor(viewport.top / offsetHeight);
int rowEnd = (int) Math.ceil(viewport.bottom / offsetHeight);
int columnStart = (int) Math.floor(viewport.left / offsetWidth);
int columnEnd = (int) Math.ceil(viewport.right / offsetWidth);
StateSnapshot stateSnapshot = new StateSnapshot(this, rowStart, rowEnd, columnStart, columnEnd);
boolean sameState = stateSnapshot.equals(mLastStateSnapshot);
mLastStateSnapshot = stateSnapshot;
return !sameState;
}
/**
* Returns a list of Tile instances describing the currently visible viewport.
*
* @return List of Tile instances describing the currently visible viewport.
*/
public Set<Tile> getVisibleTilesFromLastViewportComputation() {
if (mLastStateSnapshot == null) {
throw new StateNotComputedException();
}
return mTilesVisibleInViewport;
}
public boolean hasComputedState() {
return mLastStateSnapshot != null;
}
public void computeVisibleTilesFromViewport() {
mTilesVisibleInViewport.clear();
for (int rowCurrent = mLastStateSnapshot.rowStart; rowCurrent < mLastStateSnapshot.rowEnd; rowCurrent++) {
for (int columnCurrent = mLastStateSnapshot.columnStart; columnCurrent < mLastStateSnapshot.columnEnd; columnCurrent++) {
Tile tile = new Tile(columnCurrent, rowCurrent, mTileWidth, mTileHeight, mData, this);
mTilesVisibleInViewport.add(tile);
}
}
}
/**
* Ensures that computeCurrentState will return true, indicating a change has occurred.
*/
public void invalidate() {
mLastStateSnapshot = null;
}
public float getScale() {
return mScale;
}
public float getRelativeScale() {
return mDetailLevelManager.getScale() / mScale;
}
public int getTileWidth() {
return mTileWidth;
}
public int getTileHeight() {
return mTileHeight;
}
public Object getData() {
return mData;
}
public DetailLevelManager.LevelType getLevelType() {
return mLevelType;
}
@Override
public int compareTo(@NonNull DetailLevel detailLevel) {
return (int) Math.signum(getScale() - detailLevel.getScale());
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object instanceof DetailLevel) {
DetailLevel detailLevel = (DetailLevel) object;
return mScale == detailLevel.getScale()
&& mData != null && mData.equals(detailLevel.getData())
&& mLevelType != null && mLevelType.equals(detailLevel.getLevelType());
}
return false;
}
@Override
public int hashCode() {
//TODO should this hashCode mix with the mLevelType hashcode?
long bits = (Double.doubleToLongBits(getScale()) * 43);
return (((int) bits) ^ ((int) (bits >> 32)));
}
public static class StateNotComputedException extends IllegalStateException {
public StateNotComputedException() {
super("Grid has not been computed; " +
"you must call computeCurrentState at some point prior to calling " +
"getVisibleTilesFromLastViewportComputation.");
}
}
private static class StateSnapshot {
public int rowStart;
public int rowEnd;
public int columnStart;
public int columnEnd;
public DetailLevel detailLevel;
public StateSnapshot(DetailLevel detailLevel, int rowStart, int rowEnd, int columnStart, int columnEnd) {
this.detailLevel = detailLevel;
this.rowStart = rowStart;
this.rowEnd = rowEnd;
this.columnStart = columnStart;
this.columnEnd = columnEnd;
}
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o instanceof StateSnapshot) {
StateSnapshot stateSnapshot = (StateSnapshot) o;
return detailLevel.equals(stateSnapshot.detailLevel)
&& rowStart == stateSnapshot.rowStart
&& columnStart == stateSnapshot.columnStart
&& rowEnd == stateSnapshot.rowEnd
&& columnEnd == stateSnapshot.columnEnd;
}
return false;
}
}
} | 6,688 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
CoordinateTranslater.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/tileview/src/main/java/com/qozix/tileview/geom/CoordinateTranslater.java | package com.qozix.tileview.geom;
import android.graphics.Path;
import java.util.List;
/**
* Helper class to translate relative coordinates into absolute pixels.
* Note that these methods always take arguments x and y in that order;
* this may be counter-intuitive since coordinates are often expressed as lat (y), lng (x).
* When using translation methods of this class, pass latitude and longitude in the reverse
* order: translationMethod( longitude, latitude )
*/
public class CoordinateTranslater {
private double mLeft;
private double mTop;
private double mRight;
private double mBottom;
private double mDiffX;
private double mDiffY;
private int mWidth;
private int mHeight;
private boolean mHasDefinedBounds;
/**
* Set size in pixels of the image at 100% scale.
*
* @param width Width of the tiled image in pixels.
* @param height Height of the tiled image in pixels.
*/
public void setSize( int width, int height ) {
mWidth = width;
mHeight = height;
}
/**
* Define arbitrary bound coordinates to the edges of the tiled image (e.g., latitude and longitude).
*
* @param left The left boundary (e.g., west longitude).
* @param top The top boundary (e.g., north latitude).
* @param right The right boundary (e.g., east longitude).
* @param bottom The bottom boundary (e.g., south latitude).
*/
public void setBounds( double left, double top, double right, double bottom ) {
mHasDefinedBounds = true;
mLeft = left;
mTop = top;
mRight = right;
mBottom = bottom;
mDiffX = mRight - mLeft;
mDiffY = mBottom - mTop;
}
public void unsetBounds() {
mHasDefinedBounds = false;
mLeft = 0;
mTop = 0;
mRight = mWidth;
mBottom = mHeight;
mDiffX = mWidth;
mDiffY = mHeight;
}
/**
* Translate a relative X position to an absolute pixel value.
*
* @param x The relative X position (e.g., longitude) to translate to absolute pixels.
* @return The translated position as a pixel value.
*/
public int translateX( double x ) {
if( !mHasDefinedBounds ) {
return (int) x;
}
double factor = (x - mLeft) / mDiffX;
return FloatMathHelper.scale( mWidth, (float) factor );
}
/**
* Translate a relative X position to an absolute pixel value, considering a scale value as well.
*
* @param x The relative X position (e.g., longitude) to translate to absolute pixels.
* @return The translated position as a pixel value.
*/
public int translateAndScaleX( double x, float scale ) {
return FloatMathHelper.scale( translateX( x ), scale );
}
/**
* Translate a relative Y position to an absolute pixel value.
*
* @param y The relative Y position (e.g., latitude) to translate to absolute pixels.
* @return The translated position as a pixel value.
*/
public int translateY( double y ) {
if( !mHasDefinedBounds ) {
return (int) y;
}
double factor = (y - mTop) / mDiffY;
return FloatMathHelper.scale( mHeight, (float) factor );
}
/**
* Translate a relative Y position to an absolute pixel value, considering a scale value as well.
*
* @param y The relative Y position (e.g., latitude) to translate to absolute pixels.
* @return The translated position as a pixel value.
*/
public int translateAndScaleY( double y, float scale ) {
return FloatMathHelper.scale( translateY( y ), scale );
}
/**
* Translate an absolute pixel value to a relative coordinate.
*
* @param x The x value to be translated.
* @return The relative value of the x coordinate supplied.
*/
public double translateAbsoluteToRelativeX( float x ) {
return mLeft + ( x * mDiffX / mWidth );
}
/**
* Pipes to {@link #translateAbsoluteToRelativeX( float )}
*/
public double translateAbsoluteToRelativeX( int x ) {
return translateAbsoluteToRelativeX( (float) x );
}
/**
* Convenience method to translate an absolute pixel value to a relative coordinate, while considering a scale value.
*
* @param x The x value to be translated.
* @param scale The scale to apply.
* @return The relative value of the x coordinate supplied.
*/
public double translateAndScaleAbsoluteToRelativeX( float x, float scale ) {
return translateAbsoluteToRelativeX( x / scale );
}
/**
* @see #translateAndScaleAbsoluteToRelativeX(float, float)
*/
public double translateAndScaleAbsoluteToRelativeX( int x, float scale ) {
return translateAbsoluteToRelativeX( x / scale );
}
/**
* Translate an absolute pixel value to a relative coordinate.
*
* @param y The y value to be translated.
* @return The relative value of the y coordinate supplied.
*/
public double translateAbsoluteToRelativeY( float y ) {
return mTop + ( y * mDiffY / mHeight );
}
/**
* Pipes to {@link #translateAbsoluteToRelativeY( float )}
*/
public double translateAbsoluteToRelativeY( int y ) {
return translateAbsoluteToRelativeY( (float) y );
}
/**
* Convenience method to translate an absolute pixel value to a relative coordinate, while considering a scale value.
*
* @param y The y value to be translated.
* @param scale The scale to apply.
* @return The relative value of the y coordinate supplied.
*/
public double translateAndScaleAbsoluteToRelativeY( float y, float scale ) {
return translateAbsoluteToRelativeY( y / scale );
}
/**
* @see #translateAndScaleAbsoluteToRelativeY(float, float)
*/
public double translateAndScaleAbsoluteToRelativeY( int y, float scale ) {
return translateAbsoluteToRelativeY( y / scale );
}
/**
* Determines if a given position (x, y) falls within the bounds defined, or the absolute pixel size of the image, if arbitrary bounds are nor supplied.
*
* @param x The x value of the coordinate to test.
* @param y The y value of the coordinate to test.
* @return True if the point falls within the defined area; false if not.
*/
public boolean contains( double x, double y ) {
double top = mTop;
double bottom = mBottom;
double left = mLeft;
double right = mRight;
if( mTop > mBottom ) {
top = mBottom;
bottom = mTop;
}
if( mLeft > mRight ) {
left = mRight;
right = mLeft;
}
return y >= top
&& y <= bottom
&& x >= left
&& x <= right;
}
/**
* Convenience method to convert a List of coordinates (pairs of doubles) to a Path instance.
*
* @param positions List of coordinates (pairs of doubles).
* @param shouldClose True if the path should be closed at the end of this operation.
* @return The Path instance created from the positions supplied.
*/
public Path pathFromPositions( List<double[]> positions, boolean shouldClose ) {
Path path = new Path();
double[] start = positions.get( 0 );
path.moveTo( translateX( start[0] ), translateY( start[1] ) );
for( int i = 1; i < positions.size(); i++ ) {
double[] position = positions.get( i );
path.lineTo( translateX( position[0] ), translateY( position[1] ) );
}
if( shouldClose ) {
path.close();
}
return path;
}
} | 7,229 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
FloatMathHelper.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/tileview/src/main/java/com/qozix/tileview/geom/FloatMathHelper.java | package com.qozix.tileview.geom;
/**
* @author Mike Dunn, 10/23/15.
*/
public class FloatMathHelper {
public static int scale( int base, float multiplier ) {
return (int) ((base * multiplier) + 0.5);
}
public static int unscale( int base, float multiplier ) {
return (int) ((base / multiplier) + 0.5);
}
}
| 325 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
TileRenderPoolExecutor.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/tileview/src/main/java/com/qozix/tileview/tiles/TileRenderPoolExecutor.java | package com.qozix.tileview.tiles;
import android.os.Handler;
import java.lang.ref.WeakReference;
import java.util.Set;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class TileRenderPoolExecutor extends ThreadPoolExecutor {
private static final int KEEP_ALIVE_TIME = 1;
private static final TimeUnit KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS;
private static final int AVAILABLE_PROCESSORS = Runtime.getRuntime().availableProcessors();
private static final int INITIAL_POOL_SIZE = AVAILABLE_PROCESSORS >> 1;
private static final int MAXIMUM_POOL_SIZE = AVAILABLE_PROCESSORS;
private WeakReference<TileCanvasViewGroup> mTileCanvasViewGroupWeakReference;
private TileRenderHandler mHandler = new TileRenderHandler();
public TileRenderPoolExecutor() {
super(
INITIAL_POOL_SIZE,
MAXIMUM_POOL_SIZE,
KEEP_ALIVE_TIME,
KEEP_ALIVE_TIME_UNIT,
new LinkedBlockingDeque<Runnable>()
);
}
public void queue( TileCanvasViewGroup tileCanvasViewGroup, Set<Tile> renderSet ) {
mTileCanvasViewGroupWeakReference = new WeakReference<>( tileCanvasViewGroup );
mHandler.setTileCanvasViewGroup( tileCanvasViewGroup );
tileCanvasViewGroup.onRenderTaskPreExecute();
for( Runnable runnable : getQueue() ) {
if( runnable instanceof TileRenderRunnable ) {
TileRenderRunnable tileRenderRunnable = (TileRenderRunnable) runnable;
if( tileRenderRunnable.isDone() || tileRenderRunnable.isCancelled() ) {
continue;
}
Tile tile = tileRenderRunnable.getTile();
if( tile != null && !renderSet.contains( tile ) ) {
tile.reset();
}
}
}
for( Tile tile : renderSet ) {
if( isShutdownOrTerminating() ) {
return;
}
tile.execute( this );
}
}
public Handler getHandler(){
return mHandler;
}
public TileCanvasViewGroup getTileCanvasViewGroup(){
if( mTileCanvasViewGroupWeakReference == null ) {
return null;
}
return mTileCanvasViewGroupWeakReference.get();
}
private void broadcastCancel() {
if( mTileCanvasViewGroupWeakReference != null ) {
TileCanvasViewGroup tileCanvasViewGroup = mTileCanvasViewGroupWeakReference.get();
if( tileCanvasViewGroup != null ) {
tileCanvasViewGroup.onRenderTaskCancelled();
}
}
}
public void cancel() {
for( Runnable runnable : getQueue() ) {
if( runnable instanceof TileRenderRunnable ) {
TileRenderRunnable tileRenderRunnable = (TileRenderRunnable) runnable;
tileRenderRunnable.cancel( true );
Tile tile = tileRenderRunnable.getTile();
if( tile != null ) {
tile.reset();
}
}
}
getQueue().clear();
broadcastCancel();
}
public boolean isShutdownOrTerminating() {
return isShutdown() || isTerminating() || isTerminated();
}
@Override
protected void afterExecute( Runnable runnable, Throwable throwable ) {
synchronized( this ) {
super.afterExecute( runnable, throwable );
if( getQueue().size() == 0 && getActiveCount() == 1 ) {
TileCanvasViewGroup tileCanvasViewGroup = mTileCanvasViewGroupWeakReference.get();
if( tileCanvasViewGroup != null ) {
tileCanvasViewGroup.onRenderTaskPostExecute();
}
}
}
}
}
| 3,416 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
TileCanvasViewGroup.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/tileview/src/main/java/com/qozix/tileview/tiles/TileCanvasViewGroup.java | package com.qozix.tileview.tiles;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.Region;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.ViewGroup;
import com.qozix.tileview.detail.DetailLevel;
import com.qozix.tileview.graphics.BitmapProvider;
import com.qozix.tileview.graphics.BitmapProviderAssets;
import java.lang.ref.WeakReference;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* This class extends ViewGroup for legacy reasons, and may be changed to extend View at
* some future point; consider all ViewGroup methods deprecated.
*/
public class TileCanvasViewGroup extends ViewGroup {
public static final int DEFAULT_RENDER_BUFFER = 250;
public static final int FAST_RENDER_BUFFER = 15;
private static final int RENDER_FLAG = 1;
private static final int DEFAULT_TRANSITION_DURATION = 200;
private float mScale = 1;
private BitmapProvider mBitmapProvider;
private DetailLevel mDetailLevelToRender;
private DetailLevel mLastRenderedDetailLevel;
private boolean mRenderIsCancelled = false;
private boolean mRenderIsSuppressed = false;
private boolean mIsRendering = false;
private boolean mShouldRecycleBitmaps = true;
private boolean mTransitionsEnabled = true;
private int mTransitionDuration = DEFAULT_TRANSITION_DURATION;
private TileRenderThrottleHandler mTileRenderThrottleHandler;
private TileRenderListener mTileRenderListener;
private TileRenderThrowableListener mTileRenderThrowableListener;
private int mRenderBuffer = DEFAULT_RENDER_BUFFER;
private TileRenderPoolExecutor mTileRenderPoolExecutor;
private Set<Tile> mTilesInCurrentViewport = new HashSet<>();
private Set<Tile> mPreviouslyDrawnTiles = new HashSet<>();
private Set<Tile> mDecodedTilesInCurrentViewport = new HashSet<>();
private Region mDirtyRegion = new Region();
private boolean mHasInvalidatedOnCleanOnce;
// This runnable is required to run on UI thread
private Runnable mRenderPostExecuteRunnable = new Runnable() {
@Override
public void run() {
cleanup();
if (mTileRenderListener != null) {
mTileRenderListener.onRenderComplete();
}
mLastRenderedDetailLevel = mDetailLevelToRender;
requestRender();
}
};
public TileCanvasViewGroup(Context context) {
super(context);
setWillNotDraw(false);
mTileRenderThrottleHandler = new TileRenderThrottleHandler(this);
mTileRenderPoolExecutor = new TileRenderPoolExecutor();
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
}
public float getScale() {
return mScale;
}
public void setScale(float factor) {
mScale = factor;
invalidate();
}
public float getInvertedScale() {
return 1f / mScale;
}
public boolean getTransitionsEnabled() {
return mTransitionsEnabled;
}
public void setTransitionsEnabled(boolean enabled) {
mTransitionsEnabled = enabled;
}
public int getTransitionDuration() {
return mTransitionDuration;
}
public void setTransitionDuration(int duration) {
mTransitionDuration = duration;
}
public BitmapProvider getBitmapProvider() {
if (mBitmapProvider == null) {
mBitmapProvider = new BitmapProviderAssets();
}
return mBitmapProvider;
}
public void setBitmapProvider(BitmapProvider bitmapProvider) {
mBitmapProvider = bitmapProvider;
}
public void setTileRenderListener(TileRenderListener tileRenderListener) {
mTileRenderListener = tileRenderListener;
}
public int getRenderBuffer() {
return mRenderBuffer;
}
public void setRenderBuffer(int renderBuffer) {
mRenderBuffer = renderBuffer;
}
/**
* @return True if tile bitmaps should be recycled.
* @deprecated This value is no longer considered - bitmaps are always recycled when they're no longer used.
*/
public boolean getShouldRecycleBitmaps() {
return mShouldRecycleBitmaps;
}
/**
* @param shouldRecycleBitmaps True if tile bitmaps should be recycled.
* @deprecated This value is no longer considered - bitmaps are always recycled when they're no longer used.
*/
public void setShouldRecycleBitmaps(boolean shouldRecycleBitmaps) {
mShouldRecycleBitmaps = shouldRecycleBitmaps;
}
public void setTileRenderThrowableListener(TileRenderThrowableListener tileRenderThrowableListener) {
mTileRenderThrowableListener = tileRenderThrowableListener;
}
/**
* The layout dimensions supplied to this ViewGroup will be exactly as large as the scaled
* width and height of the containing ZoomPanLayout (or TileView). However, when the canvas
* is scaled, it's clip area is also scaled - offset this by providing dimensions scaled as
* large as the smallest size the TileCanvasView might be.
*/
public void requestRender() {
mRenderIsCancelled = false;
if (mDetailLevelToRender == null) {
return;
}
if (!mTileRenderThrottleHandler.hasMessages(RENDER_FLAG)) {
mTileRenderThrottleHandler.sendEmptyMessageDelayed(RENDER_FLAG, mRenderBuffer);
}
}
/**
* Prevent new render tasks from starting, attempts to interrupt ongoing tasks, and will
* prevent queued tiles from begin decoded or rendered.
*/
public void cancelRender() {
mRenderIsCancelled = true;
if (mTileRenderPoolExecutor != null) {
mTileRenderPoolExecutor.cancel();
}
}
/**
* Prevent new render tasks from starting, but does not cancel any ongoing operations.
*/
public void suppressRender() {
mRenderIsSuppressed = true;
}
/**
* Enables new render tasks to start.
*/
public void resumeRender() {
mRenderIsSuppressed = false;
}
/**
* Returns true if the TileView has threads currently decoding tile Bitmaps.
*
* @return True if the TileView has threads currently decoding tile Bitmaps.
*/
public boolean getIsRendering() {
return mIsRendering;
}
/**
* Clears existing tiles and cancels any existing render tasks.
*/
public void clear() {
cancelRender();
mTilesInCurrentViewport.clear();
mPreviouslyDrawnTiles.clear();
invalidate();
}
/**
* This function is now a no-op
*
* @param recentlyComputedVisibleTileSet
* @deprecated
*/
public void reconcile(Set<Tile> recentlyComputedVisibleTileSet) {
// noop
}
void renderTiles() {
if (!mRenderIsCancelled && !mRenderIsSuppressed && mDetailLevelToRender != null) {
beginRenderTask();
}
}
private Rect getComputedViewport() {
if (mDetailLevelToRender == null) {
return null;
}
return mDetailLevelToRender.getDetailLevelManager().getComputedScaledViewport(getInvertedScale());
}
private boolean establishDirtyRegion() {
boolean shouldInvalidate = false;
mDirtyRegion.set(getComputedViewport());
for (Tile tile : mTilesInCurrentViewport) {
if (tile.getState() == Tile.State.DECODED) {
tile.computeProgress();
mDecodedTilesInCurrentViewport.add(tile);
if (tile.getIsDirty()) {
shouldInvalidate = true;
} else {
mDirtyRegion.op(tile.getRelativeRect(), Region.Op.DIFFERENCE);
}
}
}
return shouldInvalidate;
}
private boolean drawPreviousTiles(Canvas canvas) {
boolean shouldInvalidate = false;
Iterator<Tile> tilesFromLastDetailLevelIterator = mPreviouslyDrawnTiles.iterator();
while (tilesFromLastDetailLevelIterator.hasNext()) {
Tile tile = tilesFromLastDetailLevelIterator.next();
Rect rect = tile.getRelativeRect();
if (mDirtyRegion.quickReject(rect)) {
tilesFromLastDetailLevelIterator.remove();
} else {
tile.computeProgress();
tile.draw(canvas);
shouldInvalidate |= tile.getIsDirty();
}
}
return shouldInvalidate;
}
private boolean drawAndClearCurrentDecodedTiles(Canvas canvas) {
boolean shouldInvalidate = false;
for (Tile tile : mDecodedTilesInCurrentViewport) {
// these tiles should already have progress computed by the time they get here
tile.draw(canvas);
shouldInvalidate |= tile.getIsDirty();
}
mDecodedTilesInCurrentViewport.clear();
return shouldInvalidate;
}
private void handleInvalidation(boolean shouldInvalidate) {
if (shouldInvalidate) {
// there's more work to do, partially opaque tiles were drawn
mHasInvalidatedOnCleanOnce = false;
invalidate();
} else {
// if all tiles were fully opaque, we need another pass to clear our tiles from last level
if (!mHasInvalidatedOnCleanOnce) {
mHasInvalidatedOnCleanOnce = true;
invalidate();
}
}
}
private void drawTilesWithoutConsideringPreviouslyDrawnLevel(Canvas canvas) {
boolean shouldInvalidate = false;
for (Tile tile : mTilesInCurrentViewport) {
if (tile.getState() == Tile.State.DECODED) {
tile.computeProgress();
tile.draw(canvas);
shouldInvalidate |= tile.getIsDirty();
}
}
handleInvalidation(shouldInvalidate);
}
private void drawTilesConsideringPreviouslyDrawnLevel(Canvas canvas) {
// compute states, populate opaque region
boolean shouldInvalidate = establishDirtyRegion();
// draw any previous tiles that are in viewport and not under full opaque current tiles
shouldInvalidate |= drawPreviousTiles(canvas);
// draw the current tile set
shouldInvalidate |= drawAndClearCurrentDecodedTiles(canvas);
// depending on transition states and previous tile draw ops, add'l invalidation might be needed
handleInvalidation(shouldInvalidate);
}
/**
* Draw tile bitmaps into the surface canvas displayed by this View.
*
* @param canvas The Canvas instance to draw tile bitmaps into.
*/
private void drawTiles(Canvas canvas) {
if (mPreviouslyDrawnTiles.size() > 0) {
drawTilesConsideringPreviouslyDrawnLevel(canvas);
} else {
drawTilesWithoutConsideringPreviouslyDrawnLevel(canvas);
}
}
public void updateTileSet(DetailLevel detailLevel) {
if (detailLevel == null) {
return;
}
if (detailLevel.equals(mDetailLevelToRender)) {
return;
}
cancelRender();
markTilesAsPrevious();
mDetailLevelToRender = detailLevel;
requestRender();
}
private void markTilesAsPrevious() {
for (Tile tile : mTilesInCurrentViewport) {
if (tile.getState() == Tile.State.DECODED) {
mPreviouslyDrawnTiles.add(tile);
}
}
mTilesInCurrentViewport.clear();
}
private void beginRenderTask() {
// if visible columns and rows are same as previously computed, fast-fail
boolean changed = mDetailLevelToRender.computeCurrentState();
if (!changed && mDetailLevelToRender.equals(mLastRenderedDetailLevel)) {
return;
}
requiredBeginRenderTask();
}
public void requiredBeginRenderTask() {
// determine tiles are mathematically within the current viewport; force re-computation
mDetailLevelToRender.computeVisibleTilesFromViewport();
// get rid of anything outside, use previously computed intersections
cleanup();
// are there any new tiles the Executor isn't already aware of?
boolean wereTilesAdded = mTilesInCurrentViewport.addAll(mDetailLevelToRender.getVisibleTilesFromLastViewportComputation());
// if so, start up a new batch
if (wereTilesAdded) {
mTileRenderPoolExecutor.queue(this, mTilesInCurrentViewport);
}
}
/**
* This should seldom be necessary, as it's built into beginRenderTask
*/
public void cleanup() {
if (mDetailLevelToRender == null || !mDetailLevelToRender.hasComputedState()) {
return;
}
// these tiles are mathematically within the current viewport, and should be already computed
Set<Tile> recentlyComputedVisibleTileSet = mDetailLevelToRender.getVisibleTilesFromLastViewportComputation();
// use an iterator to avoid concurrent modification
Iterator<Tile> tilesInCurrentViewportIterator = mTilesInCurrentViewport.iterator();
while (tilesInCurrentViewportIterator.hasNext()) {
Tile tile = tilesInCurrentViewportIterator.next();
// this tile was visible previously, but is no longer, destroy and de-list it
if (!recentlyComputedVisibleTileSet.contains(tile)) {
tile.reset();
tilesInCurrentViewportIterator.remove();
}
}
}
// this tile has been decoded by the time it gets passed here
void addTileToCanvas(final Tile tile) {
if (mTilesInCurrentViewport.contains(tile)) {
invalidate();
}
}
void onRenderTaskPreExecute() {
mIsRendering = true;
if (mTileRenderListener != null) {
mTileRenderListener.onRenderStart();
}
}
void onRenderTaskCancelled() {
if (mTileRenderListener != null) {
mTileRenderListener.onRenderCancelled();
}
mIsRendering = false;
}
void onRenderTaskPostExecute() {
mIsRendering = false;
mTileRenderThrottleHandler.post(mRenderPostExecuteRunnable);
}
void handleTileRenderException(Throwable throwable) {
if (mTileRenderThrowableListener != null) {
mTileRenderThrowableListener.onRenderThrow(throwable);
}
}
boolean getRenderIsCancelled() {
return mRenderIsCancelled;
}
public void destroy() {
mTileRenderPoolExecutor.shutdownNow();
clear();
if (!mTileRenderThrottleHandler.hasMessages(RENDER_FLAG)) {
mTileRenderThrottleHandler.removeMessages(RENDER_FLAG);
}
}
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.save();
canvas.scale(mScale, mScale);
drawTiles(canvas);
canvas.restore();
}
/**
* Interface definition for callbacks to be invoked after render operations.
*/
public interface TileRenderListener {
void onRenderStart();
void onRenderCancelled();
void onRenderComplete();
}
// ideally this would be part of TileRenderListener, but that's a breaking change
public interface TileRenderThrowableListener {
void onRenderThrow(Throwable throwable);
}
private static class TileRenderThrottleHandler extends Handler {
private final WeakReference<TileCanvasViewGroup> mTileCanvasViewGroupWeakReference;
public TileRenderThrottleHandler(TileCanvasViewGroup tileCanvasViewGroup) {
super(Looper.getMainLooper());
mTileCanvasViewGroupWeakReference = new WeakReference<>(tileCanvasViewGroup);
}
@Override
public final void handleMessage(Message message) {
final TileCanvasViewGroup tileCanvasViewGroup = mTileCanvasViewGroupWeakReference.get();
if (tileCanvasViewGroup != null) {
tileCanvasViewGroup.renderTiles();
}
}
}
}
| 16,225 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
TileRenderRunnable.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/tileview/src/main/java/com/qozix/tileview/tiles/TileRenderRunnable.java | package com.qozix.tileview.tiles;
import android.os.Handler;
import android.os.Message;
import android.os.Process;
import java.lang.ref.WeakReference;
/**
* @author Mike Dunn, 3/10/16.
*/
class TileRenderRunnable implements Runnable {
private WeakReference<Tile> mTileWeakReference;
private WeakReference<TileRenderPoolExecutor> mTileRenderPoolExecutorWeakReference;
private boolean mCancelled = false;
private boolean mComplete = false;
private volatile Thread mThread;
private Throwable mThrowable;
public boolean cancel( boolean mayInterrupt ) {
if( mayInterrupt && mThread != null ) {
mThread.interrupt();
}
boolean cancelled = mCancelled;
mCancelled = true;
if( mTileRenderPoolExecutorWeakReference != null ) {
TileRenderPoolExecutor tileRenderPoolExecutor = mTileRenderPoolExecutorWeakReference.get();
if(tileRenderPoolExecutor != null){
tileRenderPoolExecutor.remove( this );
}
}
return !cancelled;
}
public boolean isCancelled() {
return mCancelled;
}
public boolean isDone() {
return mComplete;
}
public void setTileRenderPoolExecutor(TileRenderPoolExecutor tileRenderPoolExecutor ) {
mTileRenderPoolExecutorWeakReference = new WeakReference<>(tileRenderPoolExecutor);
}
public void setTile( Tile tile ) {
mTileWeakReference = new WeakReference<>( tile );
}
public Tile getTile() {
if( mTileWeakReference != null ) {
return mTileWeakReference.get();
}
return null;
}
public Throwable getThrowable() {
return mThrowable;
}
public TileRenderHandler.Status renderTile() {
if( mCancelled ) {
return TileRenderHandler.Status.INCOMPLETE;
}
android.os.Process.setThreadPriority( Process.THREAD_PRIORITY_BACKGROUND );
if( mThread.isInterrupted() ) {
return TileRenderHandler.Status.INCOMPLETE;
}
Tile tile = getTile();
if( tile == null ) {
return TileRenderHandler.Status.INCOMPLETE;
}
TileRenderPoolExecutor tileRenderPoolExecutor = mTileRenderPoolExecutorWeakReference.get();
if( tileRenderPoolExecutor == null ) {
return TileRenderHandler.Status.INCOMPLETE;
}
TileCanvasViewGroup tileCanvasViewGroup = tileRenderPoolExecutor.getTileCanvasViewGroup();
if(tileCanvasViewGroup == null ) {
return TileRenderHandler.Status.INCOMPLETE;
}
try {
tile.generateBitmap( tileCanvasViewGroup.getContext(), tileCanvasViewGroup.getBitmapProvider() );
} catch( Throwable throwable ) {
mThrowable = throwable;
return TileRenderHandler.Status.ERROR;
}
if( mCancelled || tile.getBitmap() == null || mThread.isInterrupted() ) {
tile.reset();
return TileRenderHandler.Status.INCOMPLETE;
}
return TileRenderHandler.Status.COMPLETE;
}
@Override
public void run() {
mThread = Thread.currentThread();
TileRenderHandler.Status status = renderTile();
if( status == TileRenderHandler.Status.INCOMPLETE ) {
return;
}
if( status == TileRenderHandler.Status.COMPLETE ) {
mComplete = true;
}
TileRenderPoolExecutor tileRenderPoolExecutor = mTileRenderPoolExecutorWeakReference.get();
if( tileRenderPoolExecutor != null ) {
TileCanvasViewGroup tileCanvasViewGroup = tileRenderPoolExecutor.getTileCanvasViewGroup();
if( tileCanvasViewGroup != null ) {
Tile tile = getTile();
if( tile != null ) {
Handler handler = tileRenderPoolExecutor.getHandler();
if( handler != null ) {
// need to stamp time now, since it'll be drawn before the handler posts
tile.setTransitionsEnabled( tileCanvasViewGroup.getTransitionsEnabled() );
tile.setTransitionDuration( tileCanvasViewGroup.getTransitionDuration() );
Message message = handler.obtainMessage( status.getMessageCode(), this );
message.sendToTarget();
}
}
}
}
}
}
| 3,966 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
TileRenderHandler.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/tileview/src/main/java/com/qozix/tileview/tiles/TileRenderHandler.java | package com.qozix.tileview.tiles;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import java.lang.ref.WeakReference;
/**
* @author Mike Dunn, 3/10/16.
*/
class TileRenderHandler extends Handler {
public static final int RENDER_ERROR = -1;
public static final int RENDER_INCOMPLETE = 0;
public static final int RENDER_COMPLETE = 1;
public enum Status {
ERROR( RENDER_ERROR ),
INCOMPLETE( RENDER_INCOMPLETE ),
COMPLETE( RENDER_COMPLETE );
private int mMessageCode;
Status( int messageCode ) {
mMessageCode = messageCode;
}
int getMessageCode() {
return mMessageCode;
}
}
private WeakReference<TileCanvasViewGroup> mTileCanvasViewGroupWeakReference;
public TileRenderHandler() {
this( Looper.getMainLooper() );
}
public TileRenderHandler( Looper looper ) {
super( looper );
}
public void setTileCanvasViewGroup( TileCanvasViewGroup tileCanvasViewGroup ) {
mTileCanvasViewGroupWeakReference = new WeakReference<>( tileCanvasViewGroup );
}
public TileCanvasViewGroup getTileCanvasViewGroup() {
if( mTileCanvasViewGroupWeakReference == null ) {
return null;
}
return mTileCanvasViewGroupWeakReference.get();
}
@Override
public void handleMessage( Message message ) {
TileRenderRunnable tileRenderRunnable = (TileRenderRunnable) message.obj;
TileCanvasViewGroup tileCanvasViewGroup = getTileCanvasViewGroup();
if( tileCanvasViewGroup == null ) {
return;
}
Tile tile = tileRenderRunnable.getTile();
if( tile == null ) {
return;
}
switch( message.what ) {
case RENDER_ERROR:
tileCanvasViewGroup.handleTileRenderException( tileRenderRunnable.getThrowable() );
break;
case RENDER_COMPLETE:
tileCanvasViewGroup.addTileToCanvas( tile );
break;
}
}
}
| 1,888 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
Tile.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/tileview/src/main/java/com/qozix/tileview/tiles/Tile.java | package com.qozix.tileview.tiles;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.animation.AnimationUtils;
import com.qozix.tileview.detail.DetailLevel;
import com.qozix.tileview.detail.DetailLevelManager;
import com.qozix.tileview.geom.FloatMathHelper;
import com.qozix.tileview.graphics.BitmapProvider;
import java.lang.ref.WeakReference;
import java.util.Objects;
public class Tile {
public enum State {
UNASSIGNED,
PENDING_DECODE,
DECODED
}
private static final int DEFAULT_TRANSITION_DURATION = 200;
private State mState = State.UNASSIGNED;
private int mWidth;
private int mHeight;
private int mLeft;
private int mTop;
private int mRight;
private int mBottom;
private float mProgress;
private int mRow;
private int mColumn;
private float mDetailLevelScale;
private Object mData;
private Bitmap mBitmap;
private Rect mIntrinsicRect = new Rect();
private Rect mBaseRect = new Rect();
private Rect mRelativeRect = new Rect();
private Rect mScaledRect = new Rect();
public Long mRenderTimeStamp;
private boolean mTransitionsEnabled;
private int mTransitionDuration = DEFAULT_TRANSITION_DURATION;
private Paint mPaint;
private DetailLevel mDetailLevel;
private WeakReference<TileRenderRunnable> mTileRenderRunnableWeakReference;
public Tile( int column, int row, int width, int height, Object data, DetailLevel detailLevel ) {
mRow = row;
mColumn = column;
mWidth = width;
mHeight = height;
mLeft = column * width;
mTop = row * height;
mRight = mLeft + mWidth;
mBottom = mTop + mHeight;
mData = data;
mDetailLevel = detailLevel;
mDetailLevelScale = mDetailLevel.getScale();
mIntrinsicRect.set( 0, 0, mWidth, mHeight );
mBaseRect.set( mLeft, mTop, mRight, mBottom );
mRelativeRect.set(
FloatMathHelper.unscale( mLeft, mDetailLevelScale ),
FloatMathHelper.unscale( mTop, mDetailLevelScale ),
FloatMathHelper.unscale( mRight, mDetailLevelScale ),
FloatMathHelper.unscale( mBottom, mDetailLevelScale )
);
mScaledRect.set( mRelativeRect );
}
public int getWidth() {
return mWidth;
}
public int getHeight() {
return mHeight;
}
public int getLeft() {
return mLeft;
}
public int getTop() {
return mTop;
}
public int getRow() {
return mRow;
}
public int getColumn() {
return mColumn;
}
public Object getData() {
return mData;
}
public Bitmap getBitmap() {
return mBitmap;
}
public boolean hasBitmap() {
return mBitmap != null;
}
public Rect getBaseRect() {
return mBaseRect;
}
public Rect getRelativeRect() {
return mRelativeRect;
}
/**
* @deprecated
* @return
*/
public float getRendered() {
return mProgress;
}
/**
* @deprecated
*/
public void stampTime() {
// no op
}
public Rect getScaledRect( float scale ) {
mScaledRect.set(
(int) (mRelativeRect.left * scale),
(int) (mRelativeRect.top * scale),
(int) (mRelativeRect.right * scale),
(int) (mRelativeRect.bottom * scale)
);
return mScaledRect;
}
public void setTransitionDuration( int transitionDuration ) {
mTransitionDuration = transitionDuration;
}
public State getState() {
return mState;
}
public void setState( State state ) {
mState = state;
}
public void execute( TileRenderPoolExecutor tileRenderPoolExecutor ) {
if(mState != State.UNASSIGNED){
return;
}
mState = State.PENDING_DECODE;
TileRenderRunnable runnable = new TileRenderRunnable();
mTileRenderRunnableWeakReference = new WeakReference<>( runnable );
runnable.setTile( this );
runnable.setTileRenderPoolExecutor( tileRenderPoolExecutor );
tileRenderPoolExecutor.execute( runnable );
}
public void computeProgress(){
if( !mTransitionsEnabled ) {
return;
}
if( mRenderTimeStamp == null ) {
mRenderTimeStamp = AnimationUtils.currentAnimationTimeMillis();
mProgress = 0;
return;
}
double elapsed = AnimationUtils.currentAnimationTimeMillis() - mRenderTimeStamp;
mProgress = (float) Math.min( 1, elapsed / mTransitionDuration );
if( mProgress == 1f ) {
mRenderTimeStamp = null;
mTransitionsEnabled = false;
}
}
public void setTransitionsEnabled( boolean enabled ) {
mTransitionsEnabled = enabled;
if( enabled ) {
mProgress = 0f;
}
}
public DetailLevel getDetailLevel() {
return mDetailLevel;
}
public boolean getIsDirty() {
return mTransitionsEnabled && mProgress < 1f;
}
public Paint getPaint() {
if( !mTransitionsEnabled ) {
return mPaint = null;
}
if( mPaint == null ) {
mPaint = new Paint();
}
mPaint.setAlpha( (int) (255 * mProgress) );
return mPaint;
}
void generateBitmap( Context context, BitmapProvider bitmapProvider ) {
if( mBitmap != null ) {
return;
}
mBitmap = bitmapProvider.getBitmap( this, context );
mState = State.DECODED;
}
/**
* Deprecated
* @param b
*/
void destroy( boolean b ) {
reset();
}
void reset() {
if( mState == State.PENDING_DECODE ) {
if ( mTileRenderRunnableWeakReference != null ) {
TileRenderRunnable runnable = mTileRenderRunnableWeakReference.get();
if( runnable != null ) {
runnable.cancel( true );
}
}
}
mState = State.UNASSIGNED;
mRenderTimeStamp = null;
if( mBitmap != null && !mBitmap.isRecycled() ) {
mBitmap.recycle();
}
mBitmap = null;
}
/**
* @param canvas The canvas the tile's bitmap should be drawn into
*/
public void draw( Canvas canvas ) {
if( mBitmap != null ) {
canvas.drawBitmap( mBitmap, mIntrinsicRect, mRelativeRect, getPaint() );
}
}
@Override
public int hashCode() {
int hash = 17;
hash = hash * 31 + getColumn();
hash = hash * 31 + getRow();
hash = hash * 31 + (int) ( 1000 * getDetailLevel().getScale() );
DetailLevelManager.LevelType levelType = getDetailLevel().getLevelType();
if( levelType != null ) hash = hash * 31 + levelType.hashCode();
return hash;
}
@Override
public boolean equals( Object o ) {
if( this == o ) {
return true;
}
if( o instanceof Tile ) {
Tile m = (Tile) o;
return m.getRow() == getRow()
&& m.getColumn() == getColumn()
&& m.getDetailLevel().getScale() == getDetailLevel().getScale()
&& ( m.getDetailLevel().getLevelType() == null
? getDetailLevel().getLevelType() == null
: m.getDetailLevel().getLevelType().equals( getDetailLevel().getLevelType() ) );
}
return false;
}
public String toShortString(){
return mColumn + ":" + mRow;
}
}
| 6,943 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
BitmapProvider.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/tileview/src/main/java/com/qozix/tileview/graphics/BitmapProvider.java | package com.qozix.tileview.graphics;
import android.content.Context;
import android.graphics.Bitmap;
import com.qozix.tileview.tiles.Tile;
/**
* This interface provides the bitmap data necessary to draw each tile. It will be run
* in a worker (non-UI) thread, so network operations are safe here. How the bitmap is generated
* is entirely up to you - assets, resources, file system, network access, SVG, drawn dynamically
* with Canvas instances, it doesn't matter - the method is passed a Tile instance (with information
* like column and row numbers, including the arbitrary data object passed for the detail level),
* and a Context instance to help with things like file i/o - as long as the
* getBitmap method returns a bitmap, everything will run along nicely.
*/
public interface BitmapProvider {
Bitmap getBitmap( Tile tile, Context context );
}
| 868 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
BitmapProviderAssets.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/tileview/src/main/java/com/qozix/tileview/graphics/BitmapProviderAssets.java | package com.qozix.tileview.graphics;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import com.qozix.tileview.tiles.Tile;
import java.io.InputStream;
/**
* This is a very simple implementation of BitmapProvider, using a formatted string to find
* an asset by filename, and built-in methods to decode the bitmap data.
*
* Feel free to use your own implementation here, where you might implement a favorite library like
* Picasso, or add your own disk-caching scheme, etc.
*/
public class BitmapProviderAssets implements BitmapProvider {
private static final BitmapFactory.Options OPTIONS = new BitmapFactory.Options();
static {
OPTIONS.inPreferredConfig = Bitmap.Config.RGB_565;
}
@Override
public Bitmap getBitmap( Tile tile, Context context ) {
Object data = tile.getData();
if( data instanceof String ) {
String unformattedFileName = (String) tile.getData();
String formattedFileName = String.format( unformattedFileName, tile.getColumn(), tile.getRow() );
AssetManager assetManager = context.getAssets();
try {
InputStream inputStream = assetManager.open( formattedFileName );
if( inputStream != null ) {
try {
return BitmapFactory.decodeStream( inputStream, null, OPTIONS );
} catch( OutOfMemoryError | Exception e ) {
// this is probably an out of memory error - you can try sleeping (this method won't be called in the UI thread) or try again (or give up)
}
}
} catch( Exception e ) {
// this is probably an IOException, meaning the file can't be found
}
}
return null;
}
}
| 1,747 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
HotSpot.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/tileview/src/main/java/com/qozix/tileview/hotspots/HotSpot.java | package com.qozix.tileview.hotspots;
import android.graphics.Region;
public class HotSpot extends Region {
private Object mTag;
private HotSpotTapListener mHotSpotTapListener;
public Object getTag() {
return mTag;
}
public void setTag( Object object ) {
mTag = object;
}
public void setHotSpotTapListener( HotSpotTapListener hotSpotTapListener ) {
mHotSpotTapListener = hotSpotTapListener;
}
public HotSpotTapListener getHotSpotTapListener() {
return mHotSpotTapListener;
}
public interface HotSpotTapListener {
void onHotSpotTap( HotSpot hotSpot, int x, int y );
}
@Override
public boolean equals( Object obj ) {
if( obj instanceof HotSpot ) {
HotSpot hotSpot = (HotSpot) obj;
return super.equals( hotSpot ) && hotSpot.mHotSpotTapListener == mHotSpotTapListener;
}
return false;
}
}
| 867 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
HotSpotManager.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/tileview/src/main/java/com/qozix/tileview/hotspots/HotSpotManager.java | package com.qozix.tileview.hotspots;
import com.qozix.tileview.geom.FloatMathHelper;
import java.util.Iterator;
import java.util.LinkedList;
public class HotSpotManager {
private float mScale = 1;
private HotSpot.HotSpotTapListener mHotSpotTapListener;
private LinkedList<HotSpot> mHotSpots = new LinkedList<HotSpot>();
public float getScale() {
return mScale;
}
public void setScale(float scale) {
mScale = scale;
}
public void addHotSpot(HotSpot hotSpot) {
mHotSpots.add(hotSpot);
}
public void removeHotSpot(HotSpot hotSpot) {
mHotSpots.remove(hotSpot);
}
public void setHotSpotTapListener(HotSpot.HotSpotTapListener hotSpotTapListener) {
mHotSpotTapListener = hotSpotTapListener;
}
public void clear() {
mHotSpots.clear();
}
private HotSpot getMatch(int x, int y) {
int scaledX = FloatMathHelper.unscale(x, mScale);
int scaledY = FloatMathHelper.unscale(y, mScale);
Iterator<HotSpot> iterator = mHotSpots.descendingIterator();
while (iterator.hasNext()) {
HotSpot hotSpot = iterator.next();
if (hotSpot.contains(scaledX, scaledY)) {
return hotSpot;
}
}
return null;
}
public boolean processHit(int x, int y) {
boolean ret = false;
HotSpot hotSpot = getMatch(x, y);
if (hotSpot != null) {
HotSpot.HotSpotTapListener spotListener = hotSpot.getHotSpotTapListener();
if (spotListener != null) {
spotListener.onHotSpotTap(hotSpot, x, y);
ret = true;
}
if (mHotSpotTapListener != null) {
mHotSpotTapListener.onHotSpotTap(hotSpot, x, y);
ret = true;
}
}
return ret;
}
}
| 1,869 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
WorldLevelData.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/app/src/main/java/io/vn/nguyenduck/blocktopograph/WorldLevelData.java | package io.vn.nguyenduck.blocktopograph;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.documentfile.provider.DocumentFile;
import io.vn.nguyenduck.blocktopograph.nbt.NbtInputStream;
import io.vn.nguyenduck.blocktopograph.nbt.Type;
import io.vn.nguyenduck.blocktopograph.nbt.tag.Tag;
import java.io.*;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import static io.vn.nguyenduck.blocktopograph.Constants.*;
import static io.vn.nguyenduck.blocktopograph.DocumentUtils.*;
import static io.vn.nguyenduck.blocktopograph.Logger.LOGGER;
import static io.vn.nguyenduck.blocktopograph.nbt.Type.*;
import static java.lang.Math.log10;
import static java.lang.Math.pow;
public class WorldLevelData {
private final DocumentFile root;
public String rawWorldName;
public Bundle dataBundle = new Bundle();
public Uri worldIconUri;
public long worldSizeRaw;
public String worldSizeFormated;
public WorldLevelData(@NonNull DocumentFile root) {
this.root = root;
readRawWorldName();
readAllTags();
setupWorldIconUri();
setupWorldSize();
}
private void setupWorldIconUri() {
DocumentFile doc = findFiles(root, WORLD_ICON_PREFIX);
if (doc != null) worldIconUri = doc.getUri();
}
private void setupWorldSize() {
worldSizeRaw = calculateFolderSize(root);
final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
int digitGroups = (int) (log10(worldSizeRaw) / log10(1024));
worldSizeFormated = new DecimalFormat("#,##0.#")
.format(worldSizeRaw / pow(1024, digitGroups)) + " " + units[digitGroups];
}
private long calculateFolderSize(DocumentFile folder) {
long totalSize = 0;
if (folder.isDirectory()) {
for (DocumentFile file : folder.listFiles()) {
if (file.isFile()) {
totalSize += file.length();
} else if (file.isDirectory()) {
totalSize += calculateFolderSize(file);
}
}
}
return totalSize;
}
private void readRawWorldName() {
try {
DocumentFile doc = DocumentUtils.getFileFromPath(root, WORLD_LEVELNAME_FILE);
if (doc == null) return;
InputStream is = contentResolver.openInputStream(doc.getUri());
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String name = reader.readLine();
if (name != null) rawWorldName = name;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void readAllTags() {
try {
DocumentFile doc = DocumentUtils.getFileFromPath(root, WORLD_LEVEL_DATA_FILE);
if (doc == null) return;
InputStream is = contentResolver.openInputStream(doc.getUri());
DataInputStream dataIS = new DataInputStream(is);
dataIS.skip(8);
NbtInputStream data = new NbtInputStream(dataIS);
Tag t = data.readTag();
// LOGGER.info(t.toString());
dataBundle = NbtUtils.toBundle(t);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| 3,340 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
DocumentUtils.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/app/src/main/java/io/vn/nguyenduck/blocktopograph/DocumentUtils.java | package io.vn.nguyenduck.blocktopograph;
import android.content.ContentResolver;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.documentfile.provider.DocumentFile;
import java.util.Objects;
import java.util.logging.Logger;
import static io.vn.nguyenduck.blocktopograph.Constants.SELF_APP_NAME;
public class DocumentUtils {
public static ContentResolver contentResolver;
@Nullable
public static DocumentFile getFileFromPath(@NonNull DocumentFile root, @NonNull String[] path) {
DocumentFile f = root;
for (String p : path) {
if (f == null) break;
f = f.findFile(p);
}
return f;
}
@Nullable
public static DocumentFile getFileFromPath(@NonNull DocumentFile root, @NonNull String path) {
return root.findFile(path);
}
public static DocumentFile findFiles(@NonNull DocumentFile root, @NonNull String startWiths) {
for (DocumentFile f : root.listFiles()) {
String name = f.getName();
if (name != null && name.startsWith(startWiths)) return f;
}
return null;
}
}
| 1,153 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
NbtUtils.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/app/src/main/java/io/vn/nguyenduck/blocktopograph/NbtUtils.java | package io.vn.nguyenduck.blocktopograph;
import android.os.Bundle;
import io.vn.nguyenduck.blocktopograph.nbt.Type;
import io.vn.nguyenduck.blocktopograph.nbt.tag.*;
import java.util.ArrayList;
public class NbtUtils {
public static Bundle toBundle(Tag tag) {
return toBundle(tag, new Bundle());
}
public static Bundle toBundle(Tag tag, Bundle b) {
Type type = tag.getType();
String name = tag.getName();
switch (type) {
case COMPOUND: {
if (name.isEmpty()) b = toBundle(((CompoundTag) tag).getValue());
else b.putBundle(name, toBundle(((CompoundTag) tag).getValue()));
break;
}
case LIST: {
Type childType = ((ListTag) tag).getChildNbtType();
switch (childType) {
case BYTE: {
ArrayList<Tag> a = ((ListTag) tag).getValue();
byte[] a2 = new byte[a.size()];
for (int i = 0; i < a.size(); i++) a2[i] = ((ByteTag) a.get(i)).getValue();
b.putByteArray(name, a2);
}
break;
case SHORT: {
ArrayList<Tag> a = ((ListTag) tag).getValue();
short[] a2 = new short[a.size()];
for (int i = 0; i < a.size(); i++) a2[i] = ((ShortTag) a.get(i)).getValue();
b.putShortArray(name, a2);
}
break;
case INT: {
ArrayList<Tag> a = ((ListTag) tag).getValue();
int[] a2 = new int[a.size()];
for (int i = 0; i < a.size(); i++) a2[i] = ((IntTag) a.get(i)).getValue();
b.putIntArray(name, a2);
}
break;
case LONG: {
ArrayList<Tag> a = ((ListTag) tag).getValue();
long[] a2 = new long[a.size()];
for (int i = 0; i < a.size(); i++) a2[i] = ((LongTag) a.get(i)).getValue();
b.putLongArray(name, a2);
}
break;
case FLOAT: {
ArrayList<Tag> a = ((ListTag) tag).getValue();
float[] a2 = new float[a.size()];
for (int i = 0; i < a.size(); i++) a2[i] = ((FloatTag) a.get(i)).getValue();
b.putFloatArray(name, a2);
}
break;
case DOUBLE: {
ArrayList<Tag> a = ((ListTag) tag).getValue();
double[] a2 = new double[a.size()];
for (int i = 0; i < a.size(); i++) a2[i] = ((DoubleTag) a.get(i)).getValue();
b.putDoubleArray(name, a2);
}
break;
}
break;
}
case BYTE:
b.putBoolean(name, (Byte) tag.getValue() == 1);
break;
case SHORT:
b.putShort(name, (Short) tag.getValue());
break;
case INT:
b.putInt(name, (Integer) tag.getValue());
break;
case LONG:
b.putLong(name, (Long) tag.getValue());
break;
case FLOAT:
b.putFloat(name, (Float) tag.getValue());
break;
case DOUBLE:
b.putDouble(name, (Double) tag.getValue());
break;
case BYTE_ARRAY:
b.putByteArray(name, (byte[]) tag.getValue());
break;
case STRING:
b.putString(name, (String) tag.getValue());
break;
case INT_ARRAY:
b.putIntArray(name, (int[]) tag.getValue());
break;
case SHORT_ARRAY:
b.putShortArray(name, (short[]) tag.getValue());
break;
}
return b;
}
private static Bundle toBundle(ArrayList<Tag> tag) {
Bundle b = new Bundle();
tag.forEach(v -> toBundle(v, b));
return b;
}
}
| 4,332 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
MainActivity.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/app/src/main/java/io/vn/nguyenduck/blocktopograph/MainActivity.java | package io.vn.nguyenduck.blocktopograph;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.documentfile.provider.DocumentFile;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.Objects;
import java.util.StringJoiner;
import static io.vn.nguyenduck.blocktopograph.Constants.*;
import static io.vn.nguyenduck.blocktopograph.Logger.LOGGER;
public class MainActivity extends AppCompatActivity {
private static final int REQ_FOLDER_PERMISSION = 0x00a;
private static final String ACCESS_URI = "access_uri";
private static SharedPreferences preferences;
private final WorldListAdapter adapter = new WorldListAdapter();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
preferences = getPreferences(MODE_PRIVATE);
DocumentUtils.contentResolver = getContentResolver();
setContentView(R.layout.world_list);
RecyclerView view = findViewById(R.id.world_list_layout);
view.setAdapter(adapter);
if (getCurrentRootFolder() != null) adapter.initAdapter(getCurrentRootFolder());
}
private DocumentFile getCurrentRootFolder() {
if (preferences.contains(ACCESS_URI)) {
Uri oldUri = Uri.parse(preferences.getString(ACCESS_URI, ""));
DocumentFile f = DocumentFile.fromTreeUri(this, oldUri);
if (f != null && f.canWrite()) return f;
}
return null;
}
private boolean hasPermission() {
return getCurrentRootFolder() != null;
}
private void displayStoragePermissionAlert() {
new AlertDialog.Builder(this, R.style.StoragePermission)
.setTitle(R.string.storage_permission_title)
.setMessage(R.string.storage_permission_description)
.setPositiveButton(
android.R.string.ok,
(DialogInterface dialog, int which) -> requestPermission())
.setCancelable(false)
.create()
.show();
}
@SuppressLint("NotifyDataSetChanged")
@Override
protected void onResume() {
super.onResume();
if (!hasPermission()) displayStoragePermissionAlert();
else {
RecyclerView view = findViewById(R.id.world_list_layout);
if (view.getAdapter() != null) {
((WorldListAdapter) view.getAdapter()).initAdapter(getCurrentRootFolder(), true);
view.requestLayout();
}
}
}
private void requestPermission() {
Uri uri = DocumentsContract.buildDocumentUri(
DOC_AUTHORITY,
new StringJoiner("/")
.add(DOC_DATA_PATH)
.add(MINECRAFT_APP_ID)
.toString());
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
.putExtra(DocumentsContract.EXTRA_INITIAL_URI, uri)
.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION)
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivityIfNeeded(intent, REQ_FOLDER_PERMISSION);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
super.onActivityResult(requestCode, resultCode, resultData);
if (resultCode == Activity.RESULT_OK && requestCode == REQ_FOLDER_PERMISSION) {
Uri uri = null;
if (resultData != null) uri = resultData.getData();
if (uri != null) {
if (!Objects.equals(uri.getPath(), "/tree/primary:Android/data/com.mojang.minecraftpe")) return;
getContentResolver().takePersistableUriPermission(uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
preferences.edit().putString(ACCESS_URI, uri.toString()).apply();
DocumentFile f = DocumentFile.fromTreeUri(this, uri);
if (f != null) adapter.initAdapter(f);
}
}
}
} | 4,700 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
WorldListAdapter.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/app/src/main/java/io/vn/nguyenduck/blocktopograph/WorldListAdapter.java | package io.vn.nguyenduck.blocktopograph;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.documentfile.provider.DocumentFile;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.Arrays;
import static io.vn.nguyenduck.blocktopograph.Constants.COM_MOJANG_FOLDER;
import static io.vn.nguyenduck.blocktopograph.Constants.WORLDS_FOLDER;
import static io.vn.nguyenduck.blocktopograph.TranslationUtils.translateGamemode;
public class WorldListAdapter extends RecyclerView.Adapter<WorldListAdapter.WorldItem> {
private DocumentFile rootFolder;
private final ArrayList<WorldLevelData> worldLevelData = new ArrayList<>();
public static class WorldItem extends RecyclerView.ViewHolder {
public final View view;
public final ImageView icon;
public final TextView name;
public final TextView gamemode;
public final TextView experimental;
public final TextView last_play;
public final TextView size;
public WorldItem(@NonNull View itemView) {
super(itemView);
view = itemView;
icon = view.findViewById(R.id.world_item_icon);
name = view.findViewById(R.id.world_item_name);
gamemode = view.findViewById(R.id.world_item_gamemode);
experimental = view.findViewById(R.id.world_item_experimental);
last_play = view.findViewById(R.id.world_item_last_play);
size = view.findViewById(R.id.world_item_size);
}
}
@NonNull
@Override
public WorldItem onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.world_item, viewGroup, false);
return new WorldItem(view);
}
@Override
public void onBindViewHolder(@NonNull WorldItem viewHolder, int i) {
WorldLevelData data = worldLevelData.get(i);
Bundle bundle = data.dataBundle;
String worldName = data.rawWorldName;
viewHolder.name.setText(worldName);
viewHolder.gamemode.setText(translateGamemode(bundle.getInt("GameType")));
viewHolder.size.setText(data.worldSizeFormated);
viewHolder.last_play.setText(
DateFormat.getDateFormat(viewHolder.view.getContext())
.format(bundle.getLong("LastPlayed") * 1000));
if (bundle.containsKey("experiments")) {
Bundle experiments = bundle.getBundle("experiments");
if (experiments != null) {
viewHolder.experimental.setVisibility(experiments.getBoolean("experiments_ever_used")
? View.VISIBLE : View.GONE);
}
}
if (data.worldIconUri != null) {
viewHolder.icon.setImageURI(data.worldIconUri);
} else {
viewHolder.icon.setImageResource(
viewHolder.experimental.getVisibility() == View.GONE ?
R.drawable.world_demo_screen_big :
R.drawable.world_demo_screen_big_grayscale
);
}
}
@Override
public int getItemCount() {
return worldLevelData.size();
}
public void initAdapter(DocumentFile appDataFolder) {
initAdapter(appDataFolder, false);
}
public void initAdapter(DocumentFile appDataFolder, boolean force) {
if (rootFolder == null || force) rootFolder = appDataFolder;
worldLevelData.clear();
DocumentFile f = DocumentUtils.getFileFromPath(rootFolder, new String[]{
"files",
"games",
COM_MOJANG_FOLDER,
WORLDS_FOLDER});
if (f != null) {
Arrays.stream(f.listFiles()).forEach(file -> worldLevelData.add(new WorldLevelData(file)));
worldLevelData.sort((a, b) -> Math.toIntExact(b.dataBundle.getLong("LastPlayed") - a.dataBundle.getLong("LastPlayed")));
}
}
}
| 4,213 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
TranslationUtils.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/app/src/main/java/io/vn/nguyenduck/blocktopograph/TranslationUtils.java | package io.vn.nguyenduck.blocktopograph;
public class TranslationUtils {
public static int translateGamemode(int gamemode) {
switch (gamemode) {
case 0:
return R.string.gamemode_survival;
case 1:
return R.string.gamemode_creative;
case 2:
return R.string.gamemode_adventure;
case 3:
return R.string.gamemode_spectator;
}
return R.string.gamemode_survival;
}
}
| 505 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
Constants.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/app/src/main/java/io/vn/nguyenduck/blocktopograph/Constants.java | package io.vn.nguyenduck.blocktopograph;
public class Constants {
static final String DOC_AUTHORITY = "com.android.externalstorage.documents";
static final String DOC_DATA_PATH = "primary:Android/data";
static final String SELF_APP_ID = "io.vn.nguyenduck.blocktopograph";
static final String SELF_APP_NAME = "Blocktopograph";
static final String MINECRAFT_APP_ID = "com.mojang.minecraftpe";
static final String COM_MOJANG_FOLDER = "com.mojang";
static final String WORLDS_FOLDER = "minecraftWorlds";
static final String WORLD_DATABASE_FOLDER = "db";
static final String WORLD_LEVEL_DATA_FILE = "level.dat";
static final String WORLD_LEVEL_DATA_BACKUP_FILE = "level.dat_old";
static final String WORLD_LEVELNAME_FILE = "levelname.txt";
static final String WORLD_ICON_PREFIX = "world_icon";
}
| 841 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
Logger.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/app/src/main/java/io/vn/nguyenduck/blocktopograph/Logger.java | package io.vn.nguyenduck.blocktopograph;
import static io.vn.nguyenduck.blocktopograph.Constants.SELF_APP_NAME;
public class Logger {
public static final java.util.logging.Logger LOGGER = java.util.logging.Logger.getLogger(SELF_APP_NAME);
}
| 247 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
NbtInputStream.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/app/src/main/java/io/vn/nguyenduck/blocktopograph/nbt/NbtInputStream.java | package io.vn.nguyenduck.blocktopograph.nbt;
import io.vn.nguyenduck.blocktopograph.nbt.tag.*;
import java.io.Closeable;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import static io.vn.nguyenduck.blocktopograph.nbt.Type.END;
public class NbtInputStream implements Closeable {
private final DataInputStream stream;
private final boolean isLittleEndian;
public NbtInputStream(InputStream is) {
this(is, true);
}
public NbtInputStream(DataInputStream is) {
stream = is;
isLittleEndian = true;
}
private NbtInputStream(InputStream is, boolean isLittleEndian) {
stream = new DataInputStream(is);
this.isLittleEndian = isLittleEndian;
}
public ArrayList<Tag> readAllTags() throws IOException {
ArrayList<Tag> tagsArray = new ArrayList<>();
while (stream.available() >= 8) {
tagsArray.add(readTag());
}
return tagsArray;
}
public Tag readTag() throws IOException {
Type type = Type.fromInt(stream.read());
String name = "";
if (type != END) {
byte[] nameByteArray = new byte[readShort()];
stream.readFully(nameByteArray);
name = new String(nameByteArray);
}
return readTagValue(type, name);
}
private Tag readTagValue(Type type, String name) throws IOException {
switch (type) {
case END:
return new EndTag();
case BYTE:
return new ByteTag(name, stream.readByte());
case SHORT:
return new ShortTag(name, readShort());
case INT:
return new IntTag(name, readInt());
case LONG:
return new LongTag(name, readLong());
case FLOAT:
return new FloatTag(name, readFloat());
case DOUBLE:
return new DoubleTag(name, readDouble());
case BYTE_ARRAY: {
Byte[] data = new Byte[readInt()];
for (int i = 0; i < data.length; i++) data[i] = stream.readByte();
return new ByteArrayTag(name, data);
}
case STRING: {
byte[] data = new byte[readShort()];
stream.readFully(data);
return new StringTag(name, new String(data));
}
case LIST: {
Type childNbtType = Type.fromInt(stream.readByte());
int length = readInt();
ArrayList<Tag> data = new ArrayList<>();
for (int i = 0; i < length; i++) data.add(readTagValue(childNbtType, null));
return new ListTag(name, data, childNbtType);
}
case COMPOUND: {
ArrayList<Tag> data = new ArrayList<>();
while (true) {
Tag tag = readTag();
if (tag.getType() == END) break;
else data.add(tag);
}
return new CompoundTag(name, data);
}
case INT_ARRAY: {
Integer[] data = new Integer[readInt()];
for (int i = 0; i < data.length; i++) data[i] = readInt();
return new IntArrayTag(name, data);
}
case SHORT_ARRAY: {
Short[] data = new Short[readInt()];
for (int i = 0; i < data.length; i++) data[i] = readShort();
return new ShortArrayTag(name, data);
}
}
return null;
}
private short readShort() throws IOException {
return isLittleEndian ? Short.reverseBytes(stream.readShort()) : stream.readShort();
}
private int readInt() throws IOException {
return isLittleEndian ? Integer.reverseBytes(stream.readInt()) : stream.readInt();
}
private long readLong() throws IOException {
return isLittleEndian ? Long.reverseBytes(stream.readLong()) : stream.readLong();
}
private float readFloat() throws IOException {
return isLittleEndian ? Float.intBitsToFloat(readInt()) : stream.readFloat();
}
private double readDouble() throws IOException {
return isLittleEndian ? Double.longBitsToDouble(readLong()) : stream.readDouble();
}
@Override
public void close() throws IOException {
stream.close();
}
}
| 4,458 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
Type.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/app/src/main/java/io/vn/nguyenduck/blocktopograph/nbt/Type.java | package io.vn.nguyenduck.blocktopograph.nbt;
public enum Type {
END(0),
BYTE(1),
SHORT(2),
INT(3),
LONG(4),
FLOAT(5),
DOUBLE(6),
BYTE_ARRAY(7),
STRING(8),
LIST(9),
COMPOUND(10),
INT_ARRAY(11),
SHORT_ARRAY(12);
private final int value;
Type(int value) {
this.value = value;
}
public static Type fromInt(int type) {
return values()[type];
}
public byte toByte() {
return (byte) this.value;
}
}
| 501 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
NbtOutputStream.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/app/src/main/java/io/vn/nguyenduck/blocktopograph/nbt/NbtOutputStream.java | package io.vn.nguyenduck.blocktopograph.nbt;
import io.vn.nguyenduck.blocktopograph.nbt.tag.*;
import java.io.Closeable;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
public class NbtOutputStream implements Closeable {
private final DataOutputStream stream;
private final boolean isLittleEndian;
public NbtOutputStream(OutputStream os) {
this(os, true);
}
public NbtOutputStream(DataOutputStream os) {
stream = os;
isLittleEndian = true;
}
private NbtOutputStream(OutputStream os, boolean isLittleEndian) {
stream = new DataOutputStream(os);
this.isLittleEndian = isLittleEndian;
}
public void writeTag(Tag tag) throws IOException {
Type type = tag.getType();
String name = tag.getName();
byte[] nameByteArray = name.getBytes();
stream.write(type.toByte());
writeShort((short) nameByteArray.length);
stream.write(nameByteArray);
writeTagValue(tag);
}
private void writeTagValue(Tag tag) throws IOException {
Type type = tag.getType();
switch (type) {
case END:
stream.write(0);
break;
case BYTE:
stream.write(((ByteTag) tag).getValue());
break;
case SHORT:
writeShort(((ShortTag) tag).getValue());
break;
case INT:
writeInt(((IntTag) tag).getValue());
break;
case LONG:
writeLong(((LongTag) tag).getValue());
break;
case FLOAT:
writeFloat(((FloatTag) tag).getValue());
break;
case DOUBLE:
writeDouble(((DoubleTag) tag).getValue());
break;
case BYTE_ARRAY: {
Byte[] data = ((ByteArrayTag) tag).getValue();
writeInt(data.length);
for (Byte d : data) stream.write(d);
break;
}
case STRING: {
String data = ((StringTag) tag).getValue();
writeShort((short) data.length());
stream.write(data.getBytes());
break;
}
case LIST: {
ArrayList<Tag> tags = ((ListTag) tag).getValue();
stream.write(tags.isEmpty() ? 0 : ((ListTag) tag).getChildNbtType().toByte());
writeInt(tags.size());
for (Tag t : tags) writeTagValue(t);
break;
}
case COMPOUND: {
for (Tag t : ((CompoundTag) tag).getValue()) writeTag(t);
stream.write(0);
break;
}
case INT_ARRAY: {
Integer[] data = ((IntArrayTag) tag).getValue();
writeInt(data.length);
for (Integer d : data) writeInt(d);
break;
}
case SHORT_ARRAY: {
Short[] data = ((ShortArrayTag) tag).getValue();
writeInt(data.length);
for (Short d : data) writeShort(d);
break;
}
}
}
private void writeShort(short data) throws IOException {
stream.writeShort(isLittleEndian ? Short.reverseBytes(data) : data);
}
private void writeInt(int data) throws IOException {
stream.writeInt(isLittleEndian ? Integer.reverseBytes(data) : data);
}
private void writeLong(long data) throws IOException {
stream.writeLong(isLittleEndian ? Long.reverseBytes(data) : data);
}
private void writeFloat(float data) throws IOException {
if (isLittleEndian) {
stream.writeInt(Integer.reverseBytes(Float.floatToIntBits(data)));
} else {
stream.writeFloat(data);
}
}
private void writeDouble(double data) throws IOException {
if (isLittleEndian) {
stream.writeLong(Long.reverseBytes(Double.doubleToLongBits(data)));
} else {
stream.writeDouble(data);
}
}
@Override
public void close() throws IOException {
stream.close();
}
}
| 4,286 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
CompoundTag.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/app/src/main/java/io/vn/nguyenduck/blocktopograph/nbt/tag/CompoundTag.java | package io.vn.nguyenduck.blocktopograph.nbt.tag;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.vn.nguyenduck.blocktopograph.nbt.Type;
import java.util.ArrayList;
import java.util.StringJoiner;
import java.util.stream.Stream;
import static io.vn.nguyenduck.blocktopograph.nbt.Type.COMPOUND;
public class CompoundTag implements Tag {
private final String name;
private final ArrayList<Tag> value;
public CompoundTag(String name, ArrayList<Tag> value) {
this.name = name != null ? name : "";
this.value = value;
}
@NonNull
@Override
public Type getType() {
return COMPOUND;
}
@NonNull
@Override
public String getName() {
return name;
}
@NonNull
@Override
public ArrayList<Tag> getValue() {
return value;
}
@NonNull
@Override
public String toString() {
ArrayList<String> a = new ArrayList<>();
for (Tag t : value) a.add(t.toString());
boolean isGreaterThan100 = (String.valueOf(a).length() + (a.size() - 1) * 2) > 100;
StringJoiner valueString = new StringJoiner(isGreaterThan100 ? ",\n" : ", ");
a.forEach(valueString::add);
return (name.isEmpty() ? "{" : ("\"" + name + "\": {")) +
((isGreaterThan100 ? "\n" : "") + valueString).replace("\n", "\n\t") +
(isGreaterThan100 ? "\n}" : "}");
}
}
| 1,435 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
ShortArrayTag.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/app/src/main/java/io/vn/nguyenduck/blocktopograph/nbt/tag/ShortArrayTag.java | package io.vn.nguyenduck.blocktopograph.nbt.tag;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.vn.nguyenduck.blocktopograph.nbt.Type;
import java.util.Arrays;
import static io.vn.nguyenduck.blocktopograph.nbt.Type.SHORT_ARRAY;
public class ShortArrayTag implements Tag {
private final String name;
private final Short[] value;
public ShortArrayTag(String name, Short[] value) {
this.name = name != null ? name : "";
this.value = value;
}
@NonNull
@Override
public Type getType() {
return SHORT_ARRAY;
}
@NonNull
@Override
public String getName() {
return name;
}
@NonNull
@Override
public Short[] getValue() {
return value;
}
@NonNull
@Override
public String toString() {
return name.isEmpty() ? "" : ("\"" + name + "\": ") + Arrays.toString(value);
}
}
| 928 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
ListTag.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/app/src/main/java/io/vn/nguyenduck/blocktopograph/nbt/tag/ListTag.java | package io.vn.nguyenduck.blocktopograph.nbt.tag;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.vn.nguyenduck.blocktopograph.nbt.Type;
import org.checkerframework.checker.units.qual.A;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringJoiner;
import java.util.stream.Stream;
import static io.vn.nguyenduck.blocktopograph.Logger.LOGGER;
import static io.vn.nguyenduck.blocktopograph.nbt.Type.LIST;
public class ListTag implements Tag {
private final String name;
private final ArrayList<Tag> value;
private final Type childNbtType;
public ListTag(String name, ArrayList<Tag> value, Type childNbtType) {
this.name = name != null ? name : "";
this.value = value;
this.childNbtType = childNbtType;
}
@NonNull
@Override
public Type getType() {
return LIST;
}
@NonNull
@Override
public String getName() {
return name;
}
@NonNull
@Override
public ArrayList<Tag> getValue() {
return value;
}
@NonNull
public Type getChildNbtType() {
return childNbtType;
}
@NonNull
@Override
public String toString() {
ArrayList<String> a = new ArrayList<>();
for (Tag t : value) a.add(t.toString());
boolean isGreaterThan100 = (String.valueOf(a).length() + (a.size() - 1) * 2) > 100;
StringJoiner valueString = new StringJoiner(isGreaterThan100 ? ",\n" : ", ");
a.forEach(valueString::add);
return (name.isEmpty() ? "[" : ("\"" + name + "\": [")) +
((isGreaterThan100 ? "\n" : "") + valueString).replace("\n", "\n\t") +
(isGreaterThan100 ? "\n]" : "]");
}
}
| 1,738 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
IntArrayTag.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/app/src/main/java/io/vn/nguyenduck/blocktopograph/nbt/tag/IntArrayTag.java | package io.vn.nguyenduck.blocktopograph.nbt.tag;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.vn.nguyenduck.blocktopograph.nbt.Type;
import java.util.Arrays;
import static io.vn.nguyenduck.blocktopograph.nbt.Type.INT_ARRAY;
public class IntArrayTag implements Tag {
private final String name;
private final Integer[] value;
public IntArrayTag(String name, Integer[] value) {
this.name = name != null ? name : "";
this.value = value;
}
@NonNull
@Override
public Type getType() {
return INT_ARRAY;
}
@NonNull
@Override
public String getName() {
return name;
}
@NonNull
@Override
public Integer[] getValue() {
return value;
}
@NonNull
@Override
public String toString() {
return (name.isEmpty() ? "" : ("\"" + name + "\": ")) + Arrays.toString(value);
}
}
| 928 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
IntTag.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/app/src/main/java/io/vn/nguyenduck/blocktopograph/nbt/tag/IntTag.java | package io.vn.nguyenduck.blocktopograph.nbt.tag;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.vn.nguyenduck.blocktopograph.nbt.Type;
import static io.vn.nguyenduck.blocktopograph.nbt.Type.INT;
public class IntTag implements Tag {
private final String name;
private final Integer value;
public IntTag(String name, Integer value) {
this.name = name != null ? name : "";
this.value = value;
}
@NonNull
@Override
public Type getType() {
return INT;
}
@NonNull
@Override
public String getName() {
return name;
}
@NonNull
@Override
public Integer getValue() {
return value;
}
@NonNull
@Override
public String toString() {
return (name.isEmpty() ? "" : ("\"" + name + "\": ")) + value;
}
}
| 857 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
FloatTag.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/app/src/main/java/io/vn/nguyenduck/blocktopograph/nbt/tag/FloatTag.java | package io.vn.nguyenduck.blocktopograph.nbt.tag;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.vn.nguyenduck.blocktopograph.nbt.Type;
import static io.vn.nguyenduck.blocktopograph.nbt.Type.FLOAT;
public class FloatTag implements Tag {
private final String name;
private final Float value;
public FloatTag(String name, Float value) {
this.name = name != null ? name : "";
this.value = value;
}
@NonNull
@Override
public Type getType() {
return FLOAT;
}
@NonNull
@Override
public String getName() {
return name;
}
@NonNull
@Override
public Float getValue() {
return value;
}
@NonNull
@Override
public String toString() {
return (name.isEmpty() ? "" : ("\"" + name + "\": ")) + value;
}
}
| 860 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
ShortTag.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/app/src/main/java/io/vn/nguyenduck/blocktopograph/nbt/tag/ShortTag.java | package io.vn.nguyenduck.blocktopograph.nbt.tag;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.vn.nguyenduck.blocktopograph.nbt.Type;
import static io.vn.nguyenduck.blocktopograph.nbt.Type.SHORT;
public class ShortTag implements Tag {
private final String name;
private final Short value;
public ShortTag(String name, Short value) {
this.name = name != null ? name : "";
this.value = value;
}
@NonNull
@Override
public Type getType() {
return SHORT;
}
@NonNull
@Override
public String getName() {
return name;
}
@NonNull
@Override
public Short getValue() {
return value;
}
@NonNull
@Override
public String toString() {
return (name.isEmpty() ? "" : ("\"" + name + "\": ")) + value;
}
}
| 859 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
EndTag.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/app/src/main/java/io/vn/nguyenduck/blocktopograph/nbt/tag/EndTag.java | package io.vn.nguyenduck.blocktopograph.nbt.tag;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.vn.nguyenduck.blocktopograph.nbt.Type;
import static io.vn.nguyenduck.blocktopograph.nbt.Type.END;
public class EndTag implements Tag {
@NonNull
@Override
public Type getType() {
return END;
}
@NonNull
@Override
public String getName() {
return "";
}
@NonNull
@Override
public Object getValue() {
return "";
}
@NonNull
@Override
public String toString() {
return "";
}
}
| 605 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
LongTag.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/app/src/main/java/io/vn/nguyenduck/blocktopograph/nbt/tag/LongTag.java | package io.vn.nguyenduck.blocktopograph.nbt.tag;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.vn.nguyenduck.blocktopograph.nbt.Type;
import static io.vn.nguyenduck.blocktopograph.nbt.Type.LONG;
public class LongTag implements Tag {
private final String name;
private final Long value;
public LongTag(String name, Long value) {
this.name = name != null ? name : "";
this.value = value;
}
@NonNull
@Override
public Type getType() {
return LONG;
}
@NonNull
@Override
public String getName() {
return name;
}
@NonNull
@Override
public Long getValue() {
return value;
}
@NonNull
@Override
public String toString() {
return (name.isEmpty() ? "" : ("\"" + name + "\": ")) + value;
}
}
| 852 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
DoubleTag.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/app/src/main/java/io/vn/nguyenduck/blocktopograph/nbt/tag/DoubleTag.java | package io.vn.nguyenduck.blocktopograph.nbt.tag;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.vn.nguyenduck.blocktopograph.nbt.Type;
import static io.vn.nguyenduck.blocktopograph.nbt.Type.DOUBLE;
public class DoubleTag implements Tag {
private final String name;
private final Double value;
public DoubleTag(String name, Double value) {
this.name = name != null ? name : "";
this.value = value;
}
@NonNull
@Override
public Type getType() {
return DOUBLE;
}
@NonNull
@Override
public String getName() {
return name;
}
@NonNull
@Override
public Double getValue() {
return value;
}
@NonNull
@Override
public String toString() {
return (name.isEmpty() ? "" : ("\"" + name + "\": ")) + value;
}
}
| 866 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
ByteTag.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/app/src/main/java/io/vn/nguyenduck/blocktopograph/nbt/tag/ByteTag.java | package io.vn.nguyenduck.blocktopograph.nbt.tag;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.vn.nguyenduck.blocktopograph.nbt.Type;
import static io.vn.nguyenduck.blocktopograph.nbt.Type.BYTE;
public class ByteTag implements Tag {
private final String name;
private final Byte value;
public ByteTag(String name, Byte value) {
this.name = name != null ? name : "";
this.value = value;
}
@NonNull
@Override
public Type getType() {
return BYTE;
}
@NonNull
@Override
public String getName() {
return name;
}
@NonNull
@Override
public Byte getValue() {
return value;
}
@NonNull
@Override
public String toString() {
return (name.isEmpty() ? "" : ("\"" + name + "\": ")) + (value == 1);
}
}
| 859 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
ByteArrayTag.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/app/src/main/java/io/vn/nguyenduck/blocktopograph/nbt/tag/ByteArrayTag.java | package io.vn.nguyenduck.blocktopograph.nbt.tag;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.vn.nguyenduck.blocktopograph.nbt.Type;
import java.util.Arrays;
import static io.vn.nguyenduck.blocktopograph.nbt.Type.BYTE_ARRAY;
public class ByteArrayTag implements Tag {
private final String name;
private final Byte[] value;
public ByteArrayTag(String name, Byte[] value) {
this.name = name != null ? name : "";
this.value = value;
}
@NonNull
@Override
public Type getType() {
return BYTE_ARRAY;
}
@NonNull
@Override
public String getName() {
return name;
}
@NonNull
@Override
public Byte[] getValue() {
return value;
}
@NonNull
@Override
public String toString() {
return name.isEmpty() ? "" : ("\"" + name + "\": ") + Arrays.toString(value);
}
}
| 921 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
Tag.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/app/src/main/java/io/vn/nguyenduck/blocktopograph/nbt/tag/Tag.java | package io.vn.nguyenduck.blocktopograph.nbt.tag;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.vn.nguyenduck.blocktopograph.nbt.Type;
public interface Tag {
@NonNull
String toString();
@NonNull
Type getType();
@NonNull
String getName();
@NonNull
Object getValue();
}
| 341 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
StringTag.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/app/src/main/java/io/vn/nguyenduck/blocktopograph/nbt/tag/StringTag.java | package io.vn.nguyenduck.blocktopograph.nbt.tag;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.vn.nguyenduck.blocktopograph.nbt.Type;
import static io.vn.nguyenduck.blocktopograph.nbt.Type.STRING;
public class StringTag implements Tag {
private final String name;
private final String value;
public StringTag(String name, String value) {
this.name = name != null ? name : "";
this.value = value;
}
@NonNull
@Override
public Type getType() {
return STRING;
}
@NonNull
@Override
public String getName() {
return name;
}
@NonNull
@Override
public String getValue() {
return value;
}
@NonNull
@Override
public String toString() {
return (name.isEmpty() ? "\"" : ("\"" + name + "\": \"")) + value.replace("\n", "\\n") + "\"";
}
}
| 898 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
WorldDetailActivity.java | /FileExtraction/Java_unseen/NguyenDuck_blocktopograph/app/src/main/java/io/vn/nguyenduck/blocktopograph/activity/WorldDetailActivity.java | package io.vn.nguyenduck.blocktopograph.activity;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class WorldDetailActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
} | 357 | Java | .java | NguyenDuck/blocktopograph | 17 | 0 | 4 | 2024-02-27T02:25:56Z | 2024-03-20T04:22:24Z |
ExampleUnitTest.java | /FileExtraction/Java_unseen/zoebchhatriwala_VPNTree/app/src/test/java/in/co/zoeb/vpntree/ExampleUnitTest.java | package in.co.zoeb.vpntree;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | 396 | Java | .java | zoebchhatriwala/VPNTree | 18 | 9 | 2 | 2017-02-06T11:07:11Z | 2017-03-26T06:58:30Z |
HomeFragment.java | /FileExtraction/Java_unseen/zoebchhatriwala_VPNTree/app/src/main/java/in/co/zoeb/vpntree/HomeFragment.java | package in.co.zoeb.vpntree;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.VpnService;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import static android.app.Activity.RESULT_OK;
/**
* A simple {@link Fragment} subclass.
*/
public class HomeFragment extends Fragment {
private View view;
private ImageView connect, connected, error;
private boolean onpurpose;
public HomeFragment() {
// Required empty public constructor
}
private void configureSettings() {
connect = (ImageView) view.findViewById(R.id.connect_view);
connected = (ImageView) view.findViewById(R.id.connected_view);
error = (ImageView) view.findViewById(R.id.errorconnect_view);
onpurpose = false; // Checks if VPN is disconnected On Purpose
connect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
connect.setVisibility(View.INVISIBLE);
connected.setVisibility(View.VISIBLE);
error.setVisibility(View.INVISIBLE);
Intent intent = VpnService.prepare(getActivity().getApplicationContext());
if (intent != null) {
startActivityForResult(intent, 0);
} else {
onActivityResult(0, RESULT_OK, null);
}
}
});
connected.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onpurpose = true;
stopVpn(true);
connect.setVisibility(View.VISIBLE);
connected.setVisibility(View.INVISIBLE);
error.setVisibility(View.INVISIBLE);
}
});
error.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
connect.setVisibility(View.VISIBLE);
connected.setVisibility(View.INVISIBLE);
error.setVisibility(View.INVISIBLE);
}
});
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_home, container, false);
configureSettings();
return view;
}
@Override
public void onResume() {
// This registers mMessageReceiver to receive messages.
LocalBroadcastManager.getInstance(getActivity())
.registerReceiver(mMessageReceiver,
new IntentFilter("status"));
super.onResume();
}
@Override
public void onPause() {
// Unregister since the activity is not visible
LocalBroadcastManager.getInstance(getActivity())
.unregisterReceiver(mMessageReceiver);
super.onPause();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Intent intent = new Intent(getActivity(), MyVpnService.class);
getActivity().startService(intent);
} else {
Toast.makeText(getActivity(), "A VPN is already connected", Toast.LENGTH_LONG).show();
}
}
@Override
public void onDestroy() {
try {
stopVpn(true);
} catch (NullPointerException ignored) {
}
super.onDestroy();
}
// Handling the received Intents
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Extract data included in the Intent
int status = intent.getIntExtra("status_code", 0);
if(status == 1) {
connect.setVisibility(View.VISIBLE);
connected.setVisibility(View.INVISIBLE);
error.setVisibility(View.INVISIBLE);
} else if(status == 2 && !onpurpose) {
connect.setVisibility(View.INVISIBLE);
connected.setVisibility(View.INVISIBLE);
error.setVisibility(View.VISIBLE);
}
onpurpose = false; // Resetting On Purpose
}
};
public void stopVpn(boolean stop) {
Intent intent = new Intent("stopvpn");
// Adding some data
intent.putExtra("stop_code", stop);
LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent);
}
}
| 4,930 | Java | .java | zoebchhatriwala/VPNTree | 18 | 9 | 2 | 2017-02-06T11:07:11Z | 2017-03-26T06:58:30Z |
AboutAppFragment.java | /FileExtraction/Java_unseen/zoebchhatriwala_VPNTree/app/src/main/java/in/co/zoeb/vpntree/AboutAppFragment.java | package in.co.zoeb.vpntree;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
/**
* A simple {@link Fragment} subclass.
*/
public class AboutAppFragment extends Fragment {
private View view;
public AboutAppFragment() {
// Required empty public constructor
}
private void renderWebView() {
String YourHtmlPage = "<html>\n" +
" <head>\n" +
" <title>VPNTree: About App</title>\n" +
" </head> \n" +
" <body style=\"margin:10px;\">\n" +
"<h3 style=\"text-align: center;\"><span style=\"color: #999999;\">VPNTree allows you to safely and anonymously connect to any network and access any app or site anywhere for free.</span></h3>\n" +
"<h3 style=\"text-align: center;\"><span style=\"color: #999999;\">Anytime you use the web on your phone, VPNTree first redirects your data to a secure network before transmission. We also hide your IP address so your location is un detectable. Whether you want to unblock YouTube or use as a shield proxy when surfing, your data, identity, and location are secure.</span></h3>\n" +
"<h3 style=\"text-align: center;\"><span style=\"color: #999999;\">This service is completely free for you.</span></h3>\n" +
"<h4> </h4>\n" +
"<h4><span style=\"color: #999999;\">Features:</span></h4>\n" +
"<h4><span style=\"color: #999999;\">No Premium and No Ads</span></h4>\n" +
"<h4><span style=\"color: #999999;\">We don't sell VPN, Its free and always be. </span></h4>\n" +
"<h4><span style=\"color: #999999;\">No Logging </span></h4>\n" +
"<h4><span style=\"color: #999999;\">All our servers are hosted in off-shore locations where logging user traffic is not required by any local laws. </span></h4>\n" +
"<h4><span style=\"color: #999999;\">Strong Encryption </span></h4>\n" +
"<h4><span style=\"color: #999999;\">Even after combining all the world’s super-computers together, it would take millions of years to crack AES encryption.</span></h4>\n" +
"<h4><span style=\"color: #999999;\">P2P Allowed </span></h4>\n" +
"<h4><span style=\"color: #999999;\">Download Torrents and use file sharing services safely and anonymously without fear of letters from CISPA or your ISP. </span></h4>\n" +
"<h4><span style=\"color: #999999;\">Unlimited Bandwidth </span></h4>\n" +
"<h4><span style=\"color: #999999;\">Wether you are an occasional web surfer, or a heavy downloader, you will always receive the best speeds possible with no bandwidth restrictions.</span></h4>\n" +
"<h4> </h4>\n" +
"<h2><span style=\"text-decoration: underline;\"><span style=\"color: #999999; text-decoration: underline;\">This application is just for learning purpose as we don't own any VPN server, So it doesn't work.</span></span></h2>\n" +
" </body>\n" +
" </html>";
WebView Data = (WebView) view.findViewById(R.id.about_app_text);
Data.loadDataWithBaseURL(null, YourHtmlPage, "text/html", "UTF-8", null);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_about_app, container, false);
renderWebView();
return view;
}
}
| 3,728 | Java | .java | zoebchhatriwala/VPNTree | 18 | 9 | 2 | 2017-02-06T11:07:11Z | 2017-03-26T06:58:30Z |
Activity_Loader.java | /FileExtraction/Java_unseen/zoebchhatriwala_VPNTree/app/src/main/java/in/co/zoeb/vpntree/Activity_Loader.java | package in.co.zoeb.vpntree;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class Activity_Loader extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity__loader);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.setCheckedItem(R.id.home);
FragmentManager FM = getSupportFragmentManager();
FragmentTransaction Transaction = FM.beginTransaction();
Transaction.replace(R.id.content_activity__loader, new HomeFragment());
Transaction.commit();
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity__loader, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.about_app) {
FragmentManager FM = getSupportFragmentManager();
FragmentTransaction Transaction = FM.beginTransaction();
Transaction.replace(R.id.content_activity__loader, new AboutAppFragment());
Transaction.commit();
} else if (id == R.id.home) {
FragmentManager FM = getSupportFragmentManager();
FragmentTransaction Transaction = FM.beginTransaction();
Transaction.replace(R.id.content_activity__loader, new HomeFragment());
Transaction.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
// End Class
}
| 3,336 | Java | .java | zoebchhatriwala/VPNTree | 18 | 9 | 2 | 2017-02-06T11:07:11Z | 2017-03-26T06:58:30Z |
MyVpnService.java | /FileExtraction/Java_unseen/zoebchhatriwala_VPNTree/app/src/main/java/in/co/zoeb/vpntree/MyVpnService.java | package in.co.zoeb.vpntree;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.VpnService;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
public class MyVpnService extends VpnService implements Handler.Callback, Runnable {
private static final String TAG = "VpnTreeService";
private String mServerAddress;
private String mServerPort;
@SuppressWarnings("unused")
private PendingIntent mConfigureIntent;
private byte[] mSharedSecret;
private Handler mHandler;
private Thread mThread;
private ParcelFileDescriptor mInterface;
private String mParameters;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
startReceiving();
// The handler is only used to show messages.
if (mHandler == null) {
mHandler = new Handler(this);
}
// Stop the previous session by interrupting the thread.
if (mThread != null) {
mThread.interrupt();
}
// Information about server
mServerAddress = "127.0.0.1";
mServerPort = "8087";
mSharedSecret = "test".getBytes();
// Start a new session by creating a new thread.
mThread = new Thread(this, "VPNTreeService");
mThread.start();
return START_STICKY;
}
@Override
public void onDestroy() {
if (mThread != null) {
mThread.interrupt();
}
stopReceiving();
}
@Override
public boolean handleMessage(Message message) {
if (message != null) {
Toast.makeText(this, message.what, Toast.LENGTH_SHORT).show();
}
return true;
}
@Override
public synchronized void run() {
try {
Log.i(TAG, "Starting");
// If anything needs to be obtained using the network, get it now.
// This greatly reduces the complexity of seamless handover, which
// tries to recreate the tunnel without shutting down everything.
// In this demo, all we need to know is the server address.
InetSocketAddress server = new InetSocketAddress(
mServerAddress, Integer.parseInt(mServerPort));
// We try to create the tunnel for several times. The better way
// is to work with ConnectivityManager, such as trying only when
// the network is available. Here we just use a counter to keep
// things simple.
for (int attempt = 0; attempt < 5; ++attempt) {
sendStatus(0);
mHandler.sendEmptyMessage(R.string.connecting);
// Reset the counter if we were connected.
if (run(server)) {
attempt = 0;
}
// Sleep for a while. This also checks if we got interrupted.
Thread.sleep(3000);
}
Log.i(TAG, "Giving up");
} catch (Exception e) {
Log.e(TAG, "Got " + e.toString());
} finally {
try {
mInterface.close();
} catch (Exception e) {
// ignore
}
mInterface = null;
mParameters = null;
sendStatus(2);
mHandler.sendEmptyMessage(R.string.disconnected);
Log.i(TAG, "Exiting");
}
}
private boolean run(InetSocketAddress server) throws Exception {
DatagramChannel tunnel = null;
boolean connected = false;
try {
// Create a DatagramChannel as the VPN tunnel.
tunnel = DatagramChannel.open();
// Protect the tunnel before connecting to avoid loopback.
if (!protect(tunnel.socket())) {
throw new IllegalStateException("Cannot protect the tunnel");
}
// Connect to the server.
tunnel.connect(server);
// For simplicity, we use the same thread for both reading and
// writing. Here we put the tunnel into non-blocking mode.
tunnel.configureBlocking(false);
// Authenticate and configure the virtual network interface.
handshake(tunnel);
// Now we are connected. Set the flag and show the message.
connected = true;
sendStatus(1);
mHandler.sendEmptyMessage(R.string.connected);
// Packets to be sent are queued in this input stream.
FileInputStream in = new FileInputStream(mInterface.getFileDescriptor());
// Packets received need to be written to this output stream.
FileOutputStream out = new FileOutputStream(mInterface.getFileDescriptor());
// Allocate the buffer for a single packet.
ByteBuffer packet = ByteBuffer.allocate(32767);
// We use a timer to determine the status of the tunnel. It
// works on both sides. A positive value means sending, and
// any other means receiving. We start with receiving.
int timer = 0;
// We keep forwarding packets till something goes wrong.
//noinspection InfiniteLoopStatement
while (true) {
// Assume that we did not make any progress in this iteration.
boolean idle = true;
// Read the outgoing packet from the input stream.
int length = in.read(packet.array());
if (length > 0) {
// Write the outgoing packet to the tunnel.
packet.limit(length);
tunnel.write(packet);
packet.clear();
// There might be more outgoing packets.
idle = false;
// If we were receiving, switch to sending.
if (timer < 1) {
timer = 1;
}
}
// Read the incoming packet from the tunnel.
length = tunnel.read(packet);
if (length > 0) {
// Ignore control messages, which start with zero.
if (packet.get(0) != 0) {
// Write the incoming packet to the output stream.
out.write(packet.array(), 0, length);
}
packet.clear();
// There might be more incoming packets.
idle = false;
// If we were sending, switch to receiving.
if (timer > 0) {
timer = 0;
}
}
// If we are idle or waiting for the network, sleep for a
// fraction of time to avoid busy looping.
if (idle) {
Thread.sleep(100);
// Increase the timer. This is inaccurate but good enough,
// since everything is operated in non-blocking mode.
timer += (timer > 0) ? 100 : -100;
// We are receiving for a long time but not sending.
if (timer < -15000) {
// Send empty control messages.
packet.put((byte) 0).limit(1);
for (int i = 0; i < 3; ++i) {
packet.position(0);
tunnel.write(packet);
}
packet.clear();
// Switch to sending.
timer = 1;
}
// We are sending for a long time but not receiving.
if (timer > 20000) {
throw new IllegalStateException("Timed out");
}
}
}
} catch (InterruptedException e) {
throw e;
} catch (Exception e) {
Log.e(TAG, "Got " + e.toString());
} finally {
try {
assert tunnel != null;
tunnel.close();
} catch (Exception e) {
// ignore
}
}
return connected;
}
private void handshake(DatagramChannel tunnel) throws Exception {
// To build a secured tunnel, we should perform mutual authentication
// and exchange session keys for encryption. To keep things simple in
// this demo, we just send the shared secret in plaintext and wait
// for the server to send the parameters.
// Allocate the buffer for handshaking.
ByteBuffer packet = ByteBuffer.allocate(1024);
// Control messages always start with zero.
packet.put((byte) 0).put(mSharedSecret).flip();
// Send the secret several times in case of packet loss.
for (int i = 0; i < 3; ++i) {
packet.position(0);
tunnel.write(packet);
}
packet.clear();
// Wait for the parameters within a limited time.
for (int i = 0; i < 50; ++i) {
Thread.sleep(100);
// Normally we should not receive random packets.
int length = tunnel.read(packet);
if (length > 0 && packet.get(0) == 0) {
configure(new String(packet.array(), 1, length - 1).trim());
return;
}
}
throw new IllegalStateException("Timed out");
}
private void configure(String parameters) throws Exception {
// If the old interface has exactly the same parameters, use it!
if (mInterface != null && parameters.equals(mParameters)) {
Log.i(TAG, "Using the previous interface");
return;
}
// Configure a builder while parsing the parameters.
Builder builder = new Builder();
for (String parameter : parameters.split(" ")) {
String[] fields = parameter.split(",");
try {
switch (fields[0].charAt(0)) {
case 'm':
builder.setMtu(Short.parseShort(fields[1]));
break;
case 'a':
builder.addAddress(fields[1], Integer.parseInt(fields[2]));
break;
case 'r':
builder.addRoute(fields[1], Integer.parseInt(fields[2]));
break;
case 'd':
builder.addDnsServer(fields[1]);
break;
case 's':
builder.addSearchDomain(fields[1]);
break;
}
} catch (Exception e) {
throw new IllegalArgumentException("Bad parameter: " + parameter);
}
}
// Close the old interface since the parameters have been changed.
try {
mInterface.close();
} catch (Exception e) {
// ignore
}
// Create a new interface using the builder and save the parameters.
mInterface = builder.setSession(mServerAddress)
.setConfigureIntent(mConfigureIntent)
.establish();
mParameters = parameters;
Log.i(TAG, "New interface: " + parameters);
}
public void stopVpn() {
if (mThread != null) {
mThread.interrupt();
}
stopReceiving();
stopSelf();
}
public void sendStatus(int status) {
Intent intent = new Intent("status");
// Adding some data
intent.putExtra("status_code", status);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
// Handling the received Intents
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Extract data included in the Intent
boolean status = intent.getBooleanExtra("stop_code", false);
if(status) {
stopVpn();
}
}
};
private void startReceiving() {
// This registers mMessageReceiver to receive messages.
LocalBroadcastManager.getInstance(this)
.registerReceiver(mMessageReceiver,
new IntentFilter("stopvpn"));
}
public void stopReceiving() {
// Unregister since the activity is not visible
LocalBroadcastManager.getInstance(this)
.unregisterReceiver(mMessageReceiver);
}
} | 13,082 | Java | .java | zoebchhatriwala/VPNTree | 18 | 9 | 2 | 2017-02-06T11:07:11Z | 2017-03-26T06:58:30Z |
ExampleInstrumentedTest.java | /FileExtraction/Java_unseen/zoebchhatriwala_VPNTree/app/src/androidTest/java/in/co/zoeb/vpntree/ExampleInstrumentedTest.java | package in.co.zoeb.vpntree;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("in.co.zoeb.vpntree", appContext.getPackageName());
}
}
| 740 | Java | .java | zoebchhatriwala/VPNTree | 18 | 9 | 2 | 2017-02-06T11:07:11Z | 2017-03-26T06:58:30Z |
PBStreamDeckTest.java | /FileExtraction/Java_unseen/IllusionaryOne_PBStreamDeck/pbstreamdeck/src/test/java/tv/phantombot/pbstreamdeck/PBStreamDeckTest.java | package tv.phantombot.pbstreamdeck;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class PBStreamDeckTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public PBStreamDeckTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( PBStreamDeckTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}
| 719 | Java | .java | IllusionaryOne/PBStreamDeck | 9 | 3 | 2 | 2018-04-10T22:40:23Z | 2020-05-05T09:31:33Z |
PBStreamDeckProperties.java | /FileExtraction/Java_unseen/IllusionaryOne_PBStreamDeck/pbstreamdeck/src/main/java/tv/phantombot/pbstreamdeck/PBStreamDeckProperties.java | /*
* Copyright (C) 2018 phantombot.tv
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package tv.phantombot.pbstreamdeck;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
/**
* Handles the properties file for the application. Responsible for
* processing the properties file.
*
* @author IllusionaryOne
*/
public class PBStreamDeckProperties {
private Properties appProperties;
/**
* Constructor. Creates the Properties object.
*/
public PBStreamDeckProperties() {
appProperties = new Properties();
}
/**
* Loads the configuration file, if one is not found, calls the
* skeleton creation method.
*
* @return false on failure and true on success
*/
public boolean loadPropertiesFile(String pathToFile) throws SecurityException, FileNotFoundException, IOException {
FileInputStream inputStream = new FileInputStream(pathToFile + "/streamdeck.properties.txt");
appProperties.load(inputStream);
inputStream.close();
return true;
}
/**
* Returns the name of the PhantomBot from properties.
*
* @return Name of the PhantomBot.
*/
public String getBotName() {
return appProperties.getProperty("botname");
}
/**
* Returns the host that PhantomBot is running from.
*
* @return The URL that the REST API is hosted on.
*/
public String getURL() {
return appProperties.getProperty("boturl");
}
/**
* Returns the API authorization key for calling the REST API.
*
* @return The API authorization key.
*/
public String getAPIAuthKey() {
return appProperties.getProperty("botapiauthkey");
}
/**
* Returns the setting for disabling SSL CA verification.
*
* @return Disable/enable SSL CA verification.
*/
public String getSSLCACheck() {
return appProperties.getProperty("sslcacheck") == null ? "enable" : appProperties.getProperty("sslcacheck");
}
/**
* Returns the data to pass to the PhantomBot REST API.
*
* @return The command or text to place into chat.
*/
public String getCommandOrText(String key) {
return appProperties.getProperty(key);
}
}
| 2,839 | Java | .java | IllusionaryOne/PBStreamDeck | 9 | 3 | 2 | 2018-04-10T22:40:23Z | 2020-05-05T09:31:33Z |
ElgatoStreamDeckConfig.java | /FileExtraction/Java_unseen/IllusionaryOne_PBStreamDeck/pbstreamdeck/src/main/java/tv/phantombot/pbstreamdeck/ElgatoStreamDeckConfig.java | /*
* Copyright (C) 2018 phantombot.tv
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package tv.phantombot.pbstreamdeck;
import java.util.Map;
import java.util.stream.Stream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;
/**
* Interfaces with the Elgato JSON configuration files to automaticelly
* update items in the Stream Deck interface.
*
* @author IllusionaryOne
*
*/
/**
* Notes:
*
* Files are stored in:
* AppData/Roaming/Elgato/StreamDeck/ProfilesV2/<hash>.sdProfile
*
* Location is Column, Row
*
* Format: { "Actions": { "2,2": { "Name": "Open", "Settings": {
* "openInBrowser": true, "path": "D:\\pbs\\PBStreamDeck.exe d:\\pbs skipsong"
* }, "State": 0, "States": [ { "Image": "state0.png", "Title": "Skipsong",
* "TitleAlignment": "" } ], "UUID": "com.elgato.streamdeck.system.open" }, },
* "DeviceUUID": "@(1)[4057/96/]", "Name": "Default Profile", "Version": "1.0" }
*
*/
public class ElgatoStreamDeckConfig {
/* x,y -> True/False */
private Map<String, Boolean> locationMap = new HashMap<String, Boolean>();
/* UUID -> Description in file */
private Map<String, String> uuidToNameMap = new HashMap<String, String>();
/* UUID -> JSON */
private Map<String, JSONObject> jsonMap = new HashMap<String, JSONObject>();
/**
* Constructor.
*/
public ElgatoStreamDeckConfig() {
initializeLocationMap();
}
/**
* Loads the profiles for the Stream Deck.
*/
public void loadProfiles(String elgatoDir) throws IOException {
Stream<Path> jsonFiles = Files.find(Paths.get(elgatoDir), 10, (path, basicFileAttributes) -> {
File file = path.toFile();
return !file.isDirectory() && file.getName().contains("manifest.json");
});
jsonFiles.forEach((jsonFilePath) -> {
try {
byte[] fileData = Files.readAllBytes(jsonFilePath);
JSONObject jsonObject = new JSONObject(new String(fileData, "UTF-8"));
String[] filePathSplit = jsonFilePath.getParent().toString().split("\\\\");
String uuid = filePathSplit[filePathSplit.length - 1];
String[] uuidSplit = uuid.split("\\.");
uuid = uuidSplit[0];
String description = jsonObject.getString("Name");
uuidToNameMap.put(uuid, description);
jsonMap.put(uuid, jsonObject);
} catch (IOException ex) {
System.out.println("IOException: " + ex.getMessage());
}
});
jsonFiles.close();
}
/**
* Initializes the locationMap HashMap.
*/
private void initializeLocationMap() {
for (int x = 0; x < 5; x++) {
for (int y = 0; y < 3; y++) {
String locationStr = Integer.toString(x) + "," + Integer.toString(y);
locationMap.put(locationStr, Boolean.FALSE);
}
}
}
} | 3,560 | Java | .java | IllusionaryOne/PBStreamDeck | 9 | 3 | 2 | 2018-04-10T22:40:23Z | 2020-05-05T09:31:33Z |
PBStreamDeck.java | /FileExtraction/Java_unseen/IllusionaryOne_PBStreamDeck/pbstreamdeck/src/main/java/tv/phantombot/pbstreamdeck/PBStreamDeck.java | /*
* Copyright (C) 2018 phantombot.tv
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package tv.phantombot.pbstreamdeck;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import com.github.sarxos.winreg.HKey;
import com.github.sarxos.winreg.RegistryException;
import com.github.sarxos.winreg.WindowsRegistry;
/**
* Main class for PBStreamDeck. To run this without the application being fully
* installed via InnoSetup run with the parameters of [execute key] [path to config]
*/
public class PBStreamDeck {
/**
* Main function for PBStreamDeck.
*
* @param args
* Command line arguments.
*/
public static void main(String[] args) {
String configDir = "";
String elgatoConfigDir = "";
String fileKey = "";
PBStreamDeckProperties properties = new PBStreamDeckProperties();
// ElgatoStreamDeckConfig streamDeck = new ElgatoStreamDeckConfig();
if (args.length < 2) {
try {
WindowsRegistry registry = WindowsRegistry.getInstance();
configDir = registry.readString(HKey.HKCU, "SOFTWARE\\PhantomBot\\StreamDeck", "ConfigDir");
// elgatoConfigDir = registry.readString(HKey.HKCU, "SOFTWARE\\PhantomBot\\StreamDeck", "ElgatoConfigDir");
} catch (RegistryException ex) {
throwErrorGUI("error accessing registry: " + ex.getMessage());
return;
}
} else {
configDir = args[1];
}
/**
* Remove support for this for now. Still a work in progress and need to release
* a patch for Let's Encrypt.
*
try {
streamDeck.loadProfiles(elgatoConfigDir);
} catch (IOException ex) {
throwErrorGUI("error loading Elgato profiles: " + ex.getMessage());
return;
}
**/
if (args.length == 0) {
throwErrorGUI("usage: PBStreamDeck [execute key]");
return;
}
try {
if (!properties.loadPropertiesFile(configDir)) {
return;
}
} catch (SecurityException ex) {
throwErrorGUI("Cannot access " + configDir + "/streamdeck.properties.txt due to security permissions.");
return;
} catch (FileNotFoundException ex) {
throwErrorGUI("Properties file does not exist: " + configDir + "/streamdeck.properties.txt");
return;
} catch (IOException ex) {
throwErrorGUI("Error loading properties file: " + ex.getMessage());
return;
}
fileKey = args[0];
String commandOrText = properties.getCommandOrText(fileKey);
if (commandOrText == null) {
throwErrorGUI("That key does not seem to exist in the properties file: " + fileKey);
return;
}
PhantomBotRESTAPI restAPI = new PhantomBotRESTAPI(properties.getURL(), properties.getBotName(),
properties.getAPIAuthKey(), properties.getSSLCACheck().equals("enable"));
String restAPIResult = restAPI.callAPI(commandOrText);
if (!restAPIResult.contains("event posted")) {
throwErrorGUI(restAPIResult);
}
}
/**
* Throws an error window up with an error message.
*
* @param errorMessage
* The error message to display in the window.
*/
private static void throwErrorGUI(String errorMessage) {
JLabel label = new JLabel(errorMessage);
label.setFont(new Font(label.getFont().getName(), Font.PLAIN, 18));
JOptionPane.showMessageDialog(null, label, "PBStreamDeck Error", JOptionPane.PLAIN_MESSAGE);
}
}
| 4,039 | Java | .java | IllusionaryOne/PBStreamDeck | 9 | 3 | 2 | 2018-04-10T22:40:23Z | 2020-05-05T09:31:33Z |
PhantomBotRESTAPI.java | /FileExtraction/Java_unseen/IllusionaryOne_PBStreamDeck/pbstreamdeck/src/main/java/tv/phantombot/pbstreamdeck/PhantomBotRESTAPI.java | /*
* Copyright (C) 2018 phantombot.tv
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package tv.phantombot.pbstreamdeck;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
* Responsible for interacting with the PhantomBot REST API.
*
* @author IllusionaryOne
*/
public class PhantomBotRESTAPI {
private String botURL;
private String botName;
private String botAPIAuthKey;
private Boolean sslCACheck = Boolean.TRUE;
/**
* Constructor for PhantomBotRESTAPI
*
* @param botURL
* The URL that PhantomBot is hosting the REST API service on.
* @param botName
* The name of the PhantomBot instance, will be used as the actor.
* @param botAPIAuthKey
* The webauth key from botlogin.txt.
*/
public PhantomBotRESTAPI(String botURL, String botName, String botAPIAuthKey, Boolean sslCACheck) {
this.botURL = botURL;
this.botName = botName;
this.botAPIAuthKey = botAPIAuthKey;
this.sslCACheck = sslCACheck;
}
/**
* Calls the PhantomBot REST API
*
* @param message
* The message/command to send to the REST API.
* @return A String object that contains the value back from REST or another
* error message.
*/
public String callAPI(String message) {
URL url;
InputStream inputStream = null;
HttpsURLConnection httpsUrlConn;
HttpURLConnection httpUrlConn;
/**
* Disable the CA verification on SSL certificates. Some certificates, such as Let's
* Encrypt, can have problems with Java. While this is not recommended for accessing
* sites in general, the assumption is that the operator of this program trusts the
* certificate and server that PhantomBot is running on.
*/
if (sslCACheck == Boolean.FALSE) {
TrustManager[] trustManager = new TrustManager[] {
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[] {};
}
@Override
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
}
};
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustManager, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception ex) {
return "exception trying to override SSL CA check: " + ex.getMessage();
}
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
}
try {
url = new URL(botURL);
if (botURL.startsWith("https://")) {
httpsUrlConn = (HttpsURLConnection) url.openConnection();
httpsUrlConn.setDoInput(true);
httpsUrlConn.setDoOutput(true);
httpsUrlConn.setRequestMethod("PUT");
httpsUrlConn.addRequestProperty("webauth", botAPIAuthKey);
httpsUrlConn.addRequestProperty("user", botName);
httpsUrlConn.addRequestProperty("message", message);
httpsUrlConn.connect();
if (httpsUrlConn.getResponseCode() == 200) {
inputStream = httpsUrlConn.getInputStream();
} else {
inputStream = httpsUrlConn.getErrorStream();
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream, Charset.forName("UTF-8")));
return "API Returned: " + readAll(reader);
} else {
httpUrlConn = (HttpURLConnection) url.openConnection();
httpUrlConn.setDoInput(true);
httpUrlConn.setDoOutput(true);
httpUrlConn.setRequestMethod("PUT");
httpUrlConn.addRequestProperty("webauth", botAPIAuthKey);
httpUrlConn.addRequestProperty("user", botName);
httpUrlConn.addRequestProperty("message", message);
httpUrlConn.connect();
if (httpUrlConn.getResponseCode() == 200) {
inputStream = httpUrlConn.getInputStream();
} else {
inputStream = httpUrlConn.getErrorStream();
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream, Charset.forName("UTF-8")));
return "API Returned: " + readAll(reader);
}
} catch (UnsupportedEncodingException ex) {
return "Failed to decode data from API.";
} catch (NullPointerException ex) {
return "Null pointer encounted.";
} catch (MalformedURLException ex) {
return "Bad URL was provided.";
} catch (SocketTimeoutException ex) {
return "Timed out trying to access API.";
} catch (IOException ex) {
return "An IO exception has occurred: " + ex.getMessage();
} catch (Exception ex) {
return "A general exception has occurred: " + ex.getMessage();
}
}
/**
* Reads data from a stream.
*
* @return A String representing the data read from the stream.
*/
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
}
| 6,608 | Java | .java | IllusionaryOne/PBStreamDeck | 9 | 3 | 2 | 2018-04-10T22:40:23Z | 2020-05-05T09:31:33Z |
module-info.java | /FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird-api/src/main/java/module-info.java | open module lyrebird.api {
exports moe.lyrebird.api.model;
exports moe.lyrebird.api.conf;
requires slf4j.api;
requires spring.beans;
requires spring.context;
requires spring.core;
requires spring.web;
requires spring.boot.autoconfigure;
requires com.fasterxml.jackson.databind;
requires jackson.annotations;
requires java.annotation;
requires java.sql;
requires org.immutables.value;
requires immutables.styles;
}
| 475 | Java | .java | Tristan971/Lyrebird | 34 | 9 | 10 | 2017-02-05T19:44:00Z | 2020-09-27T21:13:06Z |
Endpoints.java | /FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird-api/src/main/java/moe/lyrebird/api/conf/Endpoints.java | /*
* Lyrebird, a free open-source cross-platform twitter client.
* Copyright (C) 2017-2018, Tristan Deloche
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package moe.lyrebird.api.conf;
public final class Endpoints {
public static final String VERSIONS_CONTROLLER = "versions";
public static final String VERSIONS_LATEST = "latest";
public static final String VERSIONS_CHANGENOTES = "changenotes/{buildVersion}";
private Endpoints() {
}
}
| 1,120 | Java | .java | Tristan971/Lyrebird | 34 | 9 | 10 | 2017-02-05T19:44:00Z | 2020-09-27T21:13:06Z |
TargetPlatform.java | /FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird-api/src/main/java/moe/lyrebird/api/model/TargetPlatform.java | /*
* Lyrebird, a free open-source cross-platform twitter client.
* Copyright (C) 2017-2018, Tristan Deloche
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package moe.lyrebird.api.model;
public enum TargetPlatform {
WINDOWS("win", "Windows"),
MACOS("mac", "macOS"),
LINUX_DEB("deb", "Debian & derivatives (Ubuntu...)"),
LINUX_RPM("rpm", "RPM-based distributions"),
UNIVERSAL_JAVA("java", "Universal distribution (JDK required)");
private final String codename;
private final String readableName;
TargetPlatform(final String codename, final String readableName) {
this.codename = codename;
this.readableName = readableName;
}
public String getCodename() {
return codename;
}
public String getReadableName() {
return readableName;
}
}
| 1,481 | Java | .java | Tristan971/Lyrebird | 34 | 9 | 10 | 2017-02-05T19:44:00Z | 2020-09-27T21:13:06Z |
AbstractLyrebirdVersion.java | /FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird-api/src/main/java/moe/lyrebird/api/model/AbstractLyrebirdVersion.java | /*
* Lyrebird, a free open-source cross-platform twitter client.
* Copyright (C) 2017-2018, Tristan Deloche
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package moe.lyrebird.api.model;
import java.util.List;
import org.immutables.value.Value.Immutable;
import com.treatwell.immutables.styles.ValueObjectStyle;
@Immutable
@ValueObjectStyle
abstract class AbstractLyrebirdVersion {
public abstract String getVersion();
public abstract int getBuildVersion();
public abstract String getReleaseUrl();
public abstract List<LyrebirdPackage> getPackages();
}
| 1,235 | Java | .java | Tristan971/Lyrebird | 34 | 9 | 10 | 2017-02-05T19:44:00Z | 2020-09-27T21:13:06Z |
AbstractLyrebirdPackage.java | /FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird-api/src/main/java/moe/lyrebird/api/model/AbstractLyrebirdPackage.java | /*
* Lyrebird, a free open-source cross-platform twitter client.
* Copyright (C) 2017-2018, Tristan Deloche
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package moe.lyrebird.api.model;
import java.net.URL;
import org.immutables.value.Value.Immutable;
import com.treatwell.immutables.styles.ValueObjectStyle;
@Immutable
@ValueObjectStyle
abstract class AbstractLyrebirdPackage {
public abstract TargetPlatform getTargetPlatform();
public abstract URL getPackageUrl();
}
| 1,143 | Java | .java | Tristan971/Lyrebird | 34 | 9 | 10 | 2017-02-05T19:44:00Z | 2020-09-27T21:13:06Z |
module-info.java | /FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird-api-server/src/main/java/module-info.java | open module lyrebird.server {
exports moe.lyrebird.api.server;
exports moe.lyrebird.api.server.model;
exports moe.lyrebird.api.server.controllers;
requires slf4j.api;
requires spring.beans;
requires spring.boot;
requires spring.boot.autoconfigure;
requires spring.context;
requires spring.core;
requires spring.security.config;
requires spring.web;
requires com.fasterxml.jackson.databind;
requires lyrebird.api;
requires io.vavr;
}
| 495 | Java | .java | Tristan971/Lyrebird | 34 | 9 | 10 | 2017-02-05T19:44:00Z | 2020-09-27T21:13:06Z |
LyrebirdApiSecurityAdapter.java | /FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird-api-server/src/main/java/moe/lyrebird/api/server/LyrebirdApiSecurityAdapter.java | package moe.lyrebird.api.server;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import moe.lyrebird.api.conf.Endpoints;
@Configuration
@EnableWebSecurity
public class LyrebirdApiSecurityAdapter extends WebSecurityConfigurerAdapter {
@Override
protected void configure(final HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/" + Endpoints.VERSIONS_CONTROLLER + "/**").permitAll()
.antMatchers("/actuator/**").hasRole("admin")
.and()
.httpBasic()
.and()
.headers().httpStrictTransportSecurity();
}
}
| 910 | Java | .java | Tristan971/Lyrebird | 34 | 9 | 10 | 2017-02-05T19:44:00Z | 2020-09-27T21:13:06Z |
LyrebirdApi.java | /FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird-api-server/src/main/java/moe/lyrebird/api/server/LyrebirdApi.java | /*
* Lyrebird, a free open-source cross-platform twitter client.
* Copyright (C) 2017-2018, Tristan Deloche
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package moe.lyrebird.api.server;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class LyrebirdApi {
public static void main(final String[] args) {
SpringApplication.run(LyrebirdApi.class, args);
}
}
| 1,134 | Java | .java | Tristan971/Lyrebird | 34 | 9 | 10 | 2017-02-05T19:44:00Z | 2020-09-27T21:13:06Z |
VersionController.java | /FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird-api-server/src/main/java/moe/lyrebird/api/server/controllers/VersionController.java | /*
* Lyrebird, a free open-source cross-platform twitter client.
* Copyright (C) 2017-2018, Tristan Deloche
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package moe.lyrebird.api.server.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import moe.lyrebird.api.model.LyrebirdVersion;
import moe.lyrebird.api.server.model.VersionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import static moe.lyrebird.api.conf.Endpoints.VERSIONS_CHANGENOTES;
import static moe.lyrebird.api.conf.Endpoints.VERSIONS_CONTROLLER;
import static moe.lyrebird.api.conf.Endpoints.VERSIONS_LATEST;
@RestController
@RequestMapping(VERSIONS_CONTROLLER)
public class VersionController {
private static final Logger LOG = LoggerFactory.getLogger(VersionController.class);
private final VersionService versionService;
@Autowired
public VersionController(final VersionService versionService) {
this.versionService = versionService;
}
@GetMapping(value = VERSIONS_LATEST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public LyrebirdVersion getLatestVersion() {
return versionService.getLatestVersion();
}
@GetMapping(value = VERSIONS_CHANGENOTES, produces = MediaType.TEXT_MARKDOWN_VALUE)
public String getChangeNotes(@PathVariable final int buildVersion) {
try (final InputStream fis = getClass().getClassLoader().getResourceAsStream("versions/" + buildVersion + ".md")) {
return StreamUtils.copyToString(fis, StandardCharsets.UTF_8);
} catch (final IOException e) {
LOG.error("Could not load changenotes for build version "+buildVersion, e);
return "Could not load changenotes.";
}
}
}
| 2,825 | Java | .java | Tristan971/Lyrebird | 34 | 9 | 10 | 2017-02-05T19:44:00Z | 2020-09-27T21:13:06Z |
VersionService.java | /FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird-api-server/src/main/java/moe/lyrebird/api/server/model/VersionService.java | /*
* Lyrebird, a free open-source cross-platform twitter client.
* Copyright (C) 2017-2018, Tristan Deloche
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package moe.lyrebird.api.server.model;
import static io.vavr.API.unchecked;
import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.ObjectMapper;
import moe.lyrebird.api.model.LyrebirdVersion;
@Component
public class VersionService {
private static final String VERSIONS_PATTERN = "classpath:versions/*.json";
private final ObjectMapper objectMapper;
@Autowired
public VersionService(final ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Cacheable("latestVersion")
public LyrebirdVersion getLatestVersion() {
return getAllVersions().stream()
.max(Comparator.comparingInt(LyrebirdVersion::getBuildVersion))
.orElse(null);
}
@Cacheable("availableVersions")
public List<LyrebirdVersion> getAllVersions() {
final PathMatchingResourcePatternResolver versionsResourcesResolver = new PathMatchingResourcePatternResolver();
try {
final Resource[] versionResources = versionsResourcesResolver.getResources(VERSIONS_PATTERN);
return Arrays.stream(versionResources)
.map(unchecked(Resource::getInputStream))
.map(unchecked(is -> objectMapper.readValue(is, LyrebirdVersion.class)))
.sorted(Comparator.comparing(LyrebirdVersion::getBuildVersion).reversed())
.collect(Collectors.toList());
} catch (final IOException e) {
throw new IllegalStateException("Can not load releases!", e);
}
}
}
| 2,823 | Java | .java | Tristan971/Lyrebird | 34 | 9 | 10 | 2017-02-05T19:44:00Z | 2020-09-27T21:13:06Z |
module-info.java | /FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/module-info.java | open module lyrebird {
requires lyrebird.api;
requires org.twitter4j.core;
requires java.persistence;
requires java.prefs;
requires moe.tristan.easyfxml;
requires java.desktop;
requires javafx.controls;
requires javafx.fxml;
requires javafx.graphics;
requires javafx.media;
requires SystemTray;
requires jackson.annotations;
requires com.fasterxml.jackson.databind;
requires io.vavr;
requires net.bytebuddy;
requires oshi.core;
requires prettytime;
requires slf4j.api;
requires spring.beans;
requires spring.boot.autoconfigure;
requires spring.context;
requires spring.core;
requires spring.data.jpa;
requires spring.boot;
requires spring.web;
requires java.sql;
requires liquibase.core;
}
| 805 | Java | .java | Tristan971/Lyrebird | 34 | 9 | 10 | 2017-02-05T19:44:00Z | 2020-09-27T21:13:06Z |
Lyrebird.java | /FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/Lyrebird.java | /*
* Lyrebird, a free open-source cross-platform twitter client.
* Copyright (C) 2017-2018, Tristan Deloche
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package moe.lyrebird;
import java.awt.Toolkit;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import javafx.application.Application;
import javafx.stage.Stage;
import moe.lyrebird.model.interrupts.CleanupService;
import moe.lyrebird.model.update.compatibility.PostUpdateCompatibilityHelper;
import moe.lyrebird.view.LyrebirdUiManager;
import moe.tristan.easyfxml.FxApplication;
import moe.tristan.easyfxml.FxUiManager;
/**
* This class is the entry point for Lyrebird. It bootstraps JavaFX, Spring Boot and AWT and then delegates
* that work to the {@link LyrebirdUiManager}.
* <p>
* More precisely:
* <p>
* From the fact that {@link FxApplication} extends {@link Application}, the {@link
* FxApplication#start(Stage)} method is called with the main stage as argument.
* <p>
* This makes it so the spring application context {@link #springContext} fetches the default {@link FxUiManager} whose
* {@code onStageCreated(Stage)} method will be called with the main stage generated by JavaFX.
* <p>
* The {@link Toolkit#getDefaultToolkit()} call is because AWT needs to be instantiated before JavaFX has been started
* and this only can be done in the {@link #main(String[])} method with the architecture of Lyrebird.
*
* @see LyrebirdUiManager
*/
@SpringBootApplication
@EnableCaching
public class Lyrebird extends FxApplication {
/**
* Main method called on JAR execution.
* <p>
* It bootstraps AWT then JavaFX with the Spring delegation left for {@link LyrebirdUiManager} to do.
*
* @param args The command line arguments given on JAR execution. Usually empty.
*/
public static void main(final String[] args) {
PostUpdateCompatibilityHelper.executeCompatibilityTasks();
launch(args);
}
/**
* Called by the JavaFX platform (through {@link Application#stop()}) on application closure request.
* We execute all the operations to be executed on shutdown (with {@link CleanupService}) then shutdown
* the virtual machine with {@link Runtime#halt(int)}.
* <p>
* This shutdown is not a good practice and is only there due to bad practices from the Twitter4J project regarding
* thread management.
*/
@Override
public void stop() {
springContext.getBean(CleanupService.class).executeCleanupOperations();
super.stop();
System.exit(0);
}
}
| 3,279 | Java | .java | Tristan971/Lyrebird | 34 | 9 | 10 | 2017-02-05T19:44:00Z | 2020-09-27T21:13:06Z |
PersistenceConfiguration.java | /FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/persistence/PersistenceConfiguration.java | package moe.lyrebird.persistence;
import org.springframework.context.annotation.Configuration;
@Configuration
public class PersistenceConfiguration {
}
| 155 | Java | .java | Tristan971/Lyrebird | 34 | 9 | 10 | 2017-02-05T19:44:00Z | 2020-09-27T21:13:06Z |
LyrebirdUiManager.java | /FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/LyrebirdUiManager.java | /*
* Lyrebird, a free open-source cross-platform twitter client.
* Copyright (C) 2017-2018, Tristan Deloche
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package moe.lyrebird.view;
import java.util.concurrent.atomic.AtomicBoolean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import javafx.application.Platform;
import javafx.stage.Stage;
import moe.lyrebird.model.notifications.Notification;
import moe.lyrebird.model.notifications.NotificationService;
import moe.lyrebird.model.settings.Setting;
import moe.lyrebird.model.settings.SettingsUtils;
import moe.lyrebird.view.screens.root.RootScreenComponent;
import moe.tristan.easyfxml.FxUiManager;
import moe.tristan.easyfxml.api.FxmlComponent;
import moe.tristan.easyfxml.model.beanmanagement.StageManager;
/**
* The {@link LyrebirdUiManager} is responsible for bootstrapping the GUI of the application correctly.
* <p>
* To do so, it serves as the entry point for the JavaFX side of things and uses overriding from {@link FxUiManager} for root view configuration.
*/
@Component
public class LyrebirdUiManager extends FxUiManager {
private final StageManager stageManager;
private final Environment environment;
private final NotificationService notificationService;
private final AtomicBoolean informedUserOfCloseBehavior;
private final RootScreenComponent rootScreenComponent;
/**
* The constructor of this class, called by Spring automatically.
*
* @param stageManager The instance of {@link StageManager} that will be used to register the root view for later retrieval.
* @param environment The spring environment to use property keys for minimal size and main stage title.
* @param notificationService The notification service that will be used to notify user of the custom behavior of this main stage's closure view {@link
* #handleMainStageClosure(Stage)}.
* @param rootScreenComponent The root component to load
*/
@Autowired
public LyrebirdUiManager(
final StageManager stageManager,
final Environment environment,
final NotificationService notificationService,
RootScreenComponent rootScreenComponent) {
this.stageManager = stageManager;
this.environment = environment;
this.notificationService = notificationService;
this.rootScreenComponent = rootScreenComponent;
this.informedUserOfCloseBehavior = new AtomicBoolean(SettingsUtils.get(
Setting.NOTIFICATION_MAIN_STAGE_TRAY_SEEN,
false
));
}
/**
* @return the title of the main window
*/
@Override
protected String title() {
return String.format(
"%s [%s]",
environment.getRequiredProperty("app.promo.name"),
environment.getRequiredProperty("app.version")
);
}
/**
* This method is called by {@link FxUiManager} and is the first call that is made after {@link FxUiManager#startGui(Stage)} is called.
* <p>
* Here we mostly do some post-processing to:
* <ul>
* <li>Disable closure of the application on closure of main stage</li>
* <li>Treating closure of main stage as a request to hide it</li>
* <li>Set-up minimum stage size constraints</li>
* <li>Register it again {@link StageManager} for retrieval in various places</li>
* </ul>
*
* @param mainStage The application's main stage.
*/
@Override
protected void onStageCreated(final Stage mainStage) {
Platform.setImplicitExit(false);
mainStage.setOnCloseRequest(e -> handleMainStageClosure(mainStage));
mainStage.setMinHeight(environment.getRequiredProperty("mainStage.minHeight", Integer.class));
mainStage.setMinWidth(environment.getRequiredProperty("mainStage.minWidth", Integer.class));
mainStage.setWidth(600.0);
mainStage.setHeight(500.0);
stageManager.registerSingle(rootScreenComponent, mainStage);
}
/**
* @return The root {@link FxmlComponent} of the application to put inside the main stage as sole node of the main scene.
*/
@Override
protected FxmlComponent mainComponent() {
return rootScreenComponent;
}
/**
* This method is called when the main stage is closed (i.e. the user clicks on the close window button).
*
* @param mainStage A reference to the main stage. Mostly here to avoid creating a field only for this method.
*/
private void handleMainStageClosure(final Stage mainStage) {
mainStage.hide();
if (!informedUserOfCloseBehavior.getAcquire()) {
notificationService.sendNotification(new Notification(
"Lyrebird's main window closed",
"Exiting the main window does not close Lyrebird, use the icon in the system tray."
));
informedUserOfCloseBehavior.setRelease(true);
SettingsUtils.set(Setting.NOTIFICATION_MAIN_STAGE_TRAY_SEEN, true);
}
}
}
| 5,869 | Java | .java | Tristan971/Lyrebird | 34 | 9 | 10 | 2017-02-05T19:44:00Z | 2020-09-27T21:13:06Z |
TweetContentTokenizer.java | /FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/viewmodel/tokenization/TweetContentTokenizer.java | package moe.lyrebird.view.viewmodel.tokenization;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javafx.scene.text.Text;
import moe.lyrebird.model.util.URLMatcher;
import moe.lyrebird.view.viewmodel.javafx.ClickableText;
import twitter4j.Status;
/**
* This class helps with tokenization of Tweet content to make sure elements expected to be clickable are not
* rendered as simple {@link Text} but really as proper links (i.e. {@link ClickableText}), that is to say
* {@link Text} elements (because {@link javafx.scene.control.Hyperlink} does not wrap properly) that will open
* a browser on click.
*
* @see Status#getURLEntities()
* @see URLMatcher
* @see Token
*/
@Component
public class TweetContentTokenizer {
private static final Logger LOGGER = LoggerFactory.getLogger(TweetContentTokenizer.class);
private static final int MAX_TOKEN_CACHE = 1024;
private final Map<Status, List<Token>> tokenizations = new LinkedHashMap<>() {
@Override
protected boolean removeEldestEntry(final Map.Entry<Status, List<Token>> eldest) {
return size() > MAX_TOKEN_CACHE;
}
};
private final List<TokensExtractor> tokensExtractors;
@Autowired
public TweetContentTokenizer(final List<TokensExtractor> tokensExtractors) {
this.tokensExtractors = tokensExtractors;
}
/**
* Computes the appropriate {@link Text} elements to represent the given {@link Status}' text content in a {@link
* javafx.scene.text.TextFlow}.
*
* @param status The {@link Status}' whose text will be presented in a {@link javafx.scene.text.TextFlow}.
*
* @return The {@link List} of {@link Text} elements that will be put into the {@link javafx.scene.text.TextFlow} that
* represents the content of a Tweet.
*/
public List<Text> asTextFlowTokens(final Status status) {
return tokenizations.computeIfAbsent(status, this::tokenize)
.stream()
.map(Token::asTextElement)
.collect(Collectors.toList());
}
/**
* Tokenizes a given {@link Status} as a {@link List} of {@link Token}s.
* <p>
* Calls {@link TokensExtractor#extractTokens(Status)} on all the supported {@link TokensExtractor}s to compute
* the special {@link Token}s and collects the "leftover" text elements via {@link
* SimpleTextTokensCollector#collectLeftovers(Status, List)}.
* <p>
* Caches the tokenization results via {@link Map#computeIfAbsent(Object, Function)} on {@link #tokenizations}.
*
* @param status The status to tokenize.
*
* @return The {@link Token}ized representation of the given {@link Status}.
*/
private List<Token> tokenize(final Status status) {
LOGGER.trace("Tokenizing status {}", status.getId());
final List<Token> clickableTokens = tokensExtractors.stream()
.map(extractor -> extractor.extractTokens(status))
.flatMap(List::stream)
.collect(Collectors.toList());
final List<Token> simpleTextTokens = SimpleTextTokensCollector.collectLeftovers(status, clickableTokens);
final List<Token> tokenization = Stream.of(clickableTokens, simpleTextTokens)
.flatMap(List::stream)
.sorted(Comparator.comparingInt(Token::getBegin))
.collect(Collectors.toList());
LOGGER.trace("Tokenized status {} as : {}", status.getId(), tokenizationStringValue(tokenization));
return tokenization;
}
/**
* Simple helper for debugging. Prints a list of token as a String-convertible representation.
*
* @param tokens The tokens that will be printed.
*
* @return The string-convertible list of the tokens given as parameter.
*/
private static List<String> tokenizationStringValue(final List<Token> tokens) {
return tokens.stream().map(Token::getTextRepresentation).collect(Collectors.toList());
}
}
| 4,588 | Java | .java | Tristan971/Lyrebird | 34 | 9 | 10 | 2017-02-05T19:44:00Z | 2020-09-27T21:13:06Z |
Token.java | /FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/viewmodel/tokenization/Token.java | package moe.lyrebird.view.viewmodel.tokenization;
import javafx.scene.text.Text;
import moe.lyrebird.view.viewmodel.javafx.ClickableText;
/**
* This class represents a String-convertible token that can either represent some {@link TokenType#SIMPLE_TEXT} or
* a {@link TokenType#CLICKABLE} element.
*/
public final class Token {
private final String textRepresentation;
private final int begin;
private final int end;
private final TokenType tokenType;
private final Runnable onClick;
public Token(
final String textRepresentation,
final int begin,
final int end,
final TokenType tokenType,
final Runnable onClick
) {
this.textRepresentation = textRepresentation;
this.begin = begin;
this.end = end;
this.tokenType = tokenType;
this.onClick = onClick;
}
public Text asTextElement() {
if (TokenType.SIMPLE_TEXT.equals(tokenType)) {
return new Text(textRepresentation);
} else {
return new ClickableText(textRepresentation, onClick);
}
}
public String getTextRepresentation() {
return textRepresentation;
}
public int getBegin() {
return begin;
}
public int getEnd() {
return end;
}
/**
* Simple enum flag for whether a given {@link Token} is actually plain text or a URL.
*/
public enum TokenType {
SIMPLE_TEXT,
CLICKABLE
}
}
| 1,512 | Java | .java | Tristan971/Lyrebird | 34 | 9 | 10 | 2017-02-05T19:44:00Z | 2020-09-27T21:13:06Z |
TokensExtractor.java | /FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/viewmodel/tokenization/TokensExtractor.java | package moe.lyrebird.view.viewmodel.tokenization;
import java.util.List;
import twitter4j.Status;
public interface TokensExtractor {
List<Token> extractTokens(final Status status);
}
| 192 | Java | .java | Tristan971/Lyrebird | 34 | 9 | 10 | 2017-02-05T19:44:00Z | 2020-09-27T21:13:06Z |
SimpleTextTokensCollector.java | /FileExtraction/Java_unseen/Tristan971_Lyrebird/lyrebird/src/main/java/moe/lyrebird/view/viewmodel/tokenization/SimpleTextTokensCollector.java | package moe.lyrebird.view.viewmodel.tokenization;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import twitter4j.Status;
public final class SimpleTextTokensCollector {
private SimpleTextTokensCollector() {
}
public static List<Token> collectLeftovers(final Status status, final List<Token> tokens) {
final String text = status.getText();
if (tokens.isEmpty()) {
return Collections.singletonList(asToken(text, 0, text.length()));
}
tokens.sort(Comparator.comparingInt(Token::getBegin));
final List<Token> textTokens = new ArrayList<>(tokens.size() * 2);
int cursorLeft = 0;
int cursorRight = 0;
for (final Token token : tokens) {
final int tokenBegin = token.getBegin();
final int tokenEnd = token.getEnd();
cursorRight = tokenBegin;
if (cursorRight > cursorLeft) {
textTokens.add(asToken(text.substring(cursorLeft, cursorRight), cursorLeft, cursorRight));
}
cursorRight = tokenEnd;
cursorLeft = tokenEnd;
}
if (cursorRight < text.length() - 1) {
textTokens.add(asToken(text.substring(cursorLeft), cursorLeft, text.length()));
}
return textTokens;
}
private static Token asToken(final String text, final int begin, final int end) {
return new Token(
text,
begin,
end,
Token.TokenType.SIMPLE_TEXT,
() -> {
}
);
}
}
| 1,647 | Java | .java | Tristan971/Lyrebird | 34 | 9 | 10 | 2017-02-05T19:44:00Z | 2020-09-27T21:13:06Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.