repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
akshetpandey/react-native-cronet
https://github.com/akshetpandey/react-native-cronet/blob/486391286a328f760ee620157f2c10859307d6fd/android/src/main/java/com/akshetpandey/rncronet/RNCronetOkHttpNetworkFetcher.java
android/src/main/java/com/akshetpandey/rncronet/RNCronetOkHttpNetworkFetcher.java
package com.akshetpandey.rncronet; import android.net.Uri; import android.os.SystemClock; import com.facebook.imagepipeline.backends.okhttp3.OkHttpNetworkFetcher; import com.facebook.imagepipeline.producers.NetworkFetcher; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.ReadableMapKeySetIterator; import com.facebook.react.modules.fresco.ReactNetworkImageRequest; import java.util.Collections; import java.util.HashMap; import java.util.Map; import okhttp3.CacheControl; import okhttp3.Headers; import okhttp3.OkHttpClient; import okhttp3.Request; class RNCronetOkHttpNetworkFetcher extends OkHttpNetworkFetcher { /** * @param okHttpClient client to use */ RNCronetOkHttpNetworkFetcher(OkHttpClient okHttpClient) { super(new RNCronetOkHttpCallFactory(okHttpClient), okHttpClient.dispatcher().executorService()); } private Map<String, String> getHeaders(ReadableMap readableMap) { if (readableMap == null) { return null; } ReadableMapKeySetIterator iterator = readableMap.keySetIterator(); Map<String, String> map = new HashMap<>(); while (iterator.hasNextKey()) { String key = iterator.nextKey(); String value = readableMap.getString(key); if (value != null) { map.put(key, value); } } return map; } @Override public void fetch( final OkHttpNetworkFetcher.OkHttpNetworkFetchState fetchState, final NetworkFetcher.Callback callback) { fetchState.submitTime = SystemClock.elapsedRealtime(); final Uri uri = fetchState.getUri(); Map<String, String> requestHeaders = null; if (fetchState.getContext().getImageRequest() instanceof ReactNetworkImageRequest) { ReactNetworkImageRequest networkImageRequest = (ReactNetworkImageRequest) fetchState.getContext().getImageRequest(); requestHeaders = getHeaders(networkImageRequest.getHeaders()); } if (requestHeaders == null) { requestHeaders = Collections.emptyMap(); } final Request request = new Request.Builder() .cacheControl(new CacheControl.Builder().noStore().build()) .url(uri.toString()) .headers(Headers.of(requestHeaders)) .get() .build(); fetchWithRequest(fetchState, callback, request); } }
java
MIT
486391286a328f760ee620157f2c10859307d6fd
2026-01-05T02:41:19.160773Z
false
akshetpandey/react-native-cronet
https://github.com/akshetpandey/react-native-cronet/blob/486391286a328f760ee620157f2c10859307d6fd/android/src/main/java/com/akshetpandey/rncronet/RNCronetOkHttpCallFactory.java
android/src/main/java/com/akshetpandey/rncronet/RNCronetOkHttpCallFactory.java
package com.akshetpandey.rncronet; import org.chromium.net.CronetEngine; import okhttp3.Call; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.internal.annotations.EverythingIsNonNull; @EverythingIsNonNull public class RNCronetOkHttpCallFactory implements Call.Factory { private final OkHttpClient client; RNCronetOkHttpCallFactory(OkHttpClient client) { this.client = client; } @Override public Call newCall(Request request) { CronetEngine engine = RNCronetNetworkingModule.cronetEngine(); if (engine != null) { return new RNCronetOkHttpCall(client, engine, request); } else { return client.newCall(request); } } }
java
MIT
486391286a328f760ee620157f2c10859307d6fd
2026-01-05T02:41:19.160773Z
false
akshetpandey/react-native-cronet
https://github.com/akshetpandey/react-native-cronet/blob/486391286a328f760ee620157f2c10859307d6fd/android/src/main/java/com/akshetpandey/rncronet/RNCronetFrescoImagePipelineConfig.java
android/src/main/java/com/akshetpandey/rncronet/RNCronetFrescoImagePipelineConfig.java
package com.akshetpandey.rncronet; import android.content.Context; import com.facebook.imagepipeline.backends.okhttp3.OkHttpImagePipelineConfigFactory; import com.facebook.imagepipeline.core.ImagePipelineConfig; import com.facebook.imagepipeline.listener.RequestListener; import com.facebook.react.modules.fresco.SystraceRequestListener; import com.facebook.react.modules.network.OkHttpClientProvider; import java.util.HashSet; import okhttp3.OkHttpClient; public class RNCronetFrescoImagePipelineConfig { public static ImagePipelineConfig build(Context context) { HashSet<RequestListener> requestListeners = new HashSet<>(); requestListeners.add(new SystraceRequestListener()); OkHttpClient client = OkHttpClientProvider.createClient(); return OkHttpImagePipelineConfigFactory.newBuilder(context.getApplicationContext(), client) .setNetworkFetcher(new RNCronetOkHttpNetworkFetcher(client)) .setDownsampleEnabled(false) .setRequestListeners(requestListeners) .build(); } }
java
MIT
486391286a328f760ee620157f2c10859307d6fd
2026-01-05T02:41:19.160773Z
false
akshetpandey/react-native-cronet
https://github.com/akshetpandey/react-native-cronet/blob/486391286a328f760ee620157f2c10859307d6fd/android/src/main/java/com/akshetpandey/rncronet/RNCronetNetworkingModule.java
android/src/main/java/com/akshetpandey/rncronet/RNCronetNetworkingModule.java
package com.akshetpandey.rncronet; import androidx.annotation.NonNull; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.modules.network.OkHttpClientFactory; import com.facebook.react.modules.network.OkHttpClientProvider; import com.facebook.react.modules.network.ReactCookieJarContainer; import com.facebook.soloader.SoLoader; import com.google.android.gms.net.CronetProviderInstaller; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import org.chromium.net.CronetEngine; import org.chromium.net.UploadDataProviders; import org.chromium.net.UrlRequest; import java.io.File; import java.io.IOException; import java.net.URL; import java.security.Provider; import java.security.Security; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import okhttp3.Headers; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okio.Buffer; public class RNCronetNetworkingModule extends ReactContextBaseJavaModule { private static OkHttpClient sharedClient; private static CustomCronetBuilder customCronetBuilder; private static CronetEngine cronetEngine; private static ExecutorService executorService = Executors.newSingleThreadExecutor(); static { OkHttpClientProvider.setOkHttpClientFactory(new OkHttpClientFactory() { @Override public OkHttpClient createNewNetworkModuleClient() { if (sharedClient != null) { return sharedClient; } OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder() .connectTimeout(0, TimeUnit.MILLISECONDS) .readTimeout(0, TimeUnit.MILLISECONDS) .writeTimeout(0, TimeUnit.MILLISECONDS) .cookieJar(new ReactCookieJarContainer()) .addInterceptor(new RNCronetInterceptor()); try { Class ConscryptProvider = Class.forName("org.conscrypt.OpenSSLProvider"); Security.insertProviderAt((Provider) ConscryptProvider.newInstance(), 1); sharedClient = clientBuilder.build(); } catch (Exception e) { sharedClient = OkHttpClientProvider.enableTls12OnPreLollipop(clientBuilder).build(); } return sharedClient; } }); } private final ReactApplicationContext mReactContext; RNCronetNetworkingModule(ReactApplicationContext reactContext) { super(reactContext); mReactContext = reactContext; CronetProviderInstaller.installProvider(reactContext).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { initializeCronetEngine(mReactContext); } } }); } public static void setCustomCronetBuilder(CustomCronetBuilder builder) { customCronetBuilder = builder; } public static CronetEngine cronetEngine() { return cronetEngine; } private static synchronized void initializeCronetEngine(ReactApplicationContext reactContext) { if (cronetEngine == null) { if (customCronetBuilder != null) { cronetEngine = customCronetBuilder.build(reactContext); } else { File cacheDir = new File(reactContext.getCacheDir(), "cronet-cache"); //noinspection ResultOfMethodCallIgnored cacheDir.mkdirs(); cronetEngine = new CronetEngine.Builder(reactContext) .enableBrotli(true) .enableHttp2(true) .enableQuic(true) .setLibraryLoader(new CronetEngine.Builder.LibraryLoader() { @Override public void loadLibrary(String libName) { SoLoader.loadLibrary(libName); } }) .setStoragePath(cacheDir.getAbsolutePath()) .enableHttpCache(CronetEngine.Builder.HTTP_CACHE_DISK, 10 * 1024 * 1024) // 10 MegaBytes .build(); URL.setURLStreamHandlerFactory(cronetEngine.createURLStreamHandlerFactory()); } } } static UrlRequest buildRequest(Request request, UrlRequest.Callback callback) throws IOException { String url = request.url().toString(); UrlRequest.Builder requestBuilder = cronetEngine.newUrlRequestBuilder(url, callback, executorService); requestBuilder.setHttpMethod(request.method()); Headers headers = request.headers(); for (int i = 0; i < headers.size(); i += 1) { requestBuilder.addHeader(headers.name(i), headers.value(i)); } RequestBody requestBody = request.body(); if (requestBody != null) { MediaType contentType = requestBody.contentType(); if (contentType != null) { requestBuilder.addHeader("Content-Type", contentType.toString()); } Buffer buffer = new Buffer(); requestBody.writeTo(buffer); requestBuilder.setUploadDataProvider(UploadDataProviders.create(buffer.readByteArray()), executorService); } return requestBuilder.build(); } @Override @NonNull public String getName() { return "RNCronet"; } public interface CustomCronetBuilder { CronetEngine build(ReactApplicationContext context); } }
java
MIT
486391286a328f760ee620157f2c10859307d6fd
2026-01-05T02:41:19.160773Z
false
akshetpandey/react-native-cronet
https://github.com/akshetpandey/react-native-cronet/blob/486391286a328f760ee620157f2c10859307d6fd/android/src/main/java/com/akshetpandey/rncronet/RNCronetNetworkingPackage.java
android/src/main/java/com/akshetpandey/rncronet/RNCronetNetworkingPackage.java
package com.akshetpandey.rncronet; import androidx.annotation.NonNull; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import java.util.Arrays; import java.util.Collections; import java.util.List; public class RNCronetNetworkingPackage implements ReactPackage { @NonNull @Override public List<NativeModule> createNativeModules(@NonNull ReactApplicationContext reactContext) { return Arrays.<NativeModule>asList(new RNCronetNetworkingModule(reactContext)); } @NonNull @Override public List<ViewManager> createViewManagers(@NonNull ReactApplicationContext reactContext) { return Collections.emptyList(); } }
java
MIT
486391286a328f760ee620157f2c10859307d6fd
2026-01-05T02:41:19.160773Z
false
akshetpandey/react-native-cronet
https://github.com/akshetpandey/react-native-cronet/blob/486391286a328f760ee620157f2c10859307d6fd/android/src/main/java/com/akshetpandey/rncronet/RNCronetOkHttpCall.java
android/src/main/java/com/akshetpandey/rncronet/RNCronetOkHttpCall.java
package com.akshetpandey.rncronet; import androidx.annotation.Nullable; import org.chromium.net.CronetEngine; import org.chromium.net.UrlRequest; import java.io.IOException; import java.util.concurrent.TimeUnit; import okhttp3.Call; import okhttp3.Callback; import okhttp3.EventListener; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.internal.annotations.EverythingIsNonNull; import okio.AsyncTimeout; import okio.Timeout; @EverythingIsNonNull final public class RNCronetOkHttpCall implements Call { private final OkHttpClient client; private final EventListener eventListener; private Request originalRequest; private CronetEngine engine; @Nullable private UrlRequest mRequest; private boolean executed; private boolean canceled; private Timeout timeout = new AsyncTimeout() { @Override protected void timedOut() { cancel(); } }; RNCronetOkHttpCall(OkHttpClient client, CronetEngine engine, Request originalRequest) { this.client = client; this.engine = engine; this.originalRequest = originalRequest; eventListener = client.eventListenerFactory().create(this); this.timeout.timeout(client.callTimeoutMillis(), TimeUnit.MILLISECONDS); } @Override public Request request() { return originalRequest; } @Override public Response execute() throws IOException { synchronized (this) { if (executed) throw new IllegalStateException("Already Executed"); executed = true; } eventListener.callStart(this); RNCronetUrlRequestCallback callback = new RNCronetUrlRequestCallback(originalRequest, this, eventListener, null); mRequest = RNCronetNetworkingModule.buildRequest(originalRequest, callback); mRequest.start(); return callback.waitForDone(); } @Override public void enqueue(Callback responseCallback) { synchronized (this) { if (executed) throw new IllegalStateException("Already Executed"); executed = true; } eventListener.callStart(this); try { RNCronetUrlRequestCallback callback = new RNCronetUrlRequestCallback(originalRequest, this, eventListener, responseCallback); mRequest = RNCronetNetworkingModule.buildRequest(originalRequest, callback); mRequest.start(); } catch (IOException e) { responseCallback.onFailure(this, e); } } @Override public void cancel() { if (mRequest != null && !mRequest.isDone()) { canceled = true; mRequest.cancel(); } } @Override public boolean isExecuted() { return executed; } @Override public boolean isCanceled() { return canceled; } @Override public Timeout timeout() { return timeout; } @SuppressWarnings("CloneDoesntCallSuperClone") // We are a final type & this saves clearing state. @Override public Call clone() { return new RNCronetOkHttpCall(client, engine, originalRequest); } }
java
MIT
486391286a328f760ee620157f2c10859307d6fd
2026-01-05T02:41:19.160773Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/CoordinateConverter.java
alpha/MyBox/src/main/java/thridparty/CoordinateConverter.java
package thridparty; import mara.mybox.tools.DoubleTools; /** * @Author https://www.jianshu.com/p/c39a2c72dc65?from=singlemessage * * Changed by Mara */ public class CoordinateConverter { public static boolean outOfChina(double lon, double lat) { return lon < 72.004 || lon > 137.8347 || lat < 0.8293 || lat > 55.8271; } public static double[] offsets(double lon, double lat) { double a = 6378245.0; double ee = 0.00669342162296594323; double x = lon - 105.0, y = lat - 35.0; double dLon = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x)); dLon += (20.0 * Math.sin(6.0 * x * Math.PI) + 20.0 * Math.sin(2.0 * x * Math.PI)) * 2.0 / 3.0; dLon += (20.0 * Math.sin(x * Math.PI) + 40.0 * Math.sin(x / 3.0 * Math.PI)) * 2.0 / 3.0; dLon += (150.0 * Math.sin(x / 12.0 * Math.PI) + 300.0 * Math.sin(x / 30.0 * Math.PI)) * 2.0 / 3.0; double dLat = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x)); dLat += (20.0 * Math.sin(6.0 * x * Math.PI) + 20.0 * Math.sin(2.0 * x * Math.PI)) * 2.0 / 3.0; dLat += (20.0 * Math.sin(y * Math.PI) + 40.0 * Math.sin(y / 3.0 * Math.PI)) * 2.0 / 3.0; dLat += (160.0 * Math.sin(y / 12.0 * Math.PI) + 320 * Math.sin(y * Math.PI / 30.0)) * 2.0 / 3.0; double radLat = lat / 180.0 * Math.PI; double magic = Math.sin(radLat); magic = 1 - ee * magic * magic; double sqrtMagic = Math.sqrt(magic); dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * Math.PI); dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * Math.PI); double[] offsets = {dLon, dLat}; return offsets; } public static double[] GCJ02ToWGS84(double lon, double lat) { double longitude, latitude; if (outOfChina(lon, lat)) { longitude = lon; latitude = lat; } else { double[] offsets = offsets(lon, lat); longitude = lon - offsets[0]; latitude = lat - offsets[1]; } double[] coordinate = {DoubleTools.scale(longitude, 6), DoubleTools.scale(latitude, 6)}; return coordinate; } public static double[] WGS84ToGCJ02(double lon, double lat) { double longitude, latitude; if (outOfChina(lon, lat)) { longitude = lon; latitude = lat; } else { double[] offsets = offsets(lon, lat); longitude = lon + offsets[0]; latitude = lat + offsets[1]; } double[] coordinate = {DoubleTools.scale(longitude, 6), DoubleTools.scale(latitude, 6)}; return coordinate; } public static double[] BD09ToGCJ02(double bd_lon, double bd_lat) { double x = bd_lon - 0.0065, y = bd_lat - 0.006; double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * Math.PI); double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * Math.PI); double longitude = z * Math.cos(theta); double latitude = z * Math.sin(theta); double[] coordinate = {DoubleTools.scale(longitude, 6), DoubleTools.scale(latitude, 6)}; return coordinate; } public static double[] GCJ02ToBD09(double gg_lon, double gg_lat) { double x = gg_lon, y = gg_lat; double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * Math.PI); double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * Math.PI); double longitude = z * Math.cos(theta) + 0.0065; double latitude = z * Math.sin(theta) + 0.006; double[] coordinate = {DoubleTools.scale(longitude, 6), DoubleTools.scale(latitude, 6)}; return coordinate; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/QRCodeWriter.java
alpha/MyBox/src/main/java/thridparty/QRCodeWriter.java
package thridparty; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.Writer; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import com.google.zxing.qrcode.encoder.ByteMatrix; import com.google.zxing.qrcode.encoder.Encoder; import com.google.zxing.qrcode.encoder.QRCode; import java.util.Map; /** * Original class: com.google.zxing.qrcode.QRCodeWriter * * @Author dswitkin@google.com (Daniel Switkin) * @License Apache License Version 2.0 * * Updated by Mara * Update Date 2019-9-26 * ===> Original class is final so I have to modify it by copying all codes here */ public class QRCodeWriter implements Writer { protected static final int QUIET_ZONE_SIZE = 4; protected QRCode code; protected int leftPadding, topPadding; @Override public BitMatrix encode(String contents, BarcodeFormat format, int width, int height) throws WriterException { return encode(contents, format, width, height, null); } @Override public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, Map<EncodeHintType, ?> hints) throws WriterException { if (contents.isEmpty()) { throw new IllegalArgumentException("Found empty contents"); } if (format != BarcodeFormat.QR_CODE) { throw new IllegalArgumentException("Can only encode QR_CODE, but got " + format); } if (width < 0 || height < 0) { throw new IllegalArgumentException("Requested dimensions are too small: " + width + 'x' + height); } ErrorCorrectionLevel errorCorrectionLevel = ErrorCorrectionLevel.L; int quietZone = QUIET_ZONE_SIZE; if (hints != null) { if (hints.containsKey(EncodeHintType.ERROR_CORRECTION)) { errorCorrectionLevel = ErrorCorrectionLevel.valueOf(hints.get(EncodeHintType.ERROR_CORRECTION).toString()); } if (hints.containsKey(EncodeHintType.MARGIN)) { quietZone = Integer.parseInt(hints.get(EncodeHintType.MARGIN).toString()); } } code = Encoder.encode(contents, errorCorrectionLevel, hints); return renderResult(width, height, quietZone); } // Note that the input matrix uses 0 == white, 1 == black, while the output matrix uses // 0 == black, 255 == white (i.e. an 8 bit greyscale bitmap). public BitMatrix renderResult(int width, int height, int quietZone) { ByteMatrix input = code.getMatrix(); if (input == null) { throw new IllegalStateException(); } int inputWidth = input.getWidth(); int inputHeight = input.getHeight(); int qrWidth = inputWidth + (quietZone * 2); int qrHeight = inputHeight + (quietZone * 2); int outputWidth = Math.max(width, qrWidth); int outputHeight = Math.max(height, qrHeight); int multiple = Math.min(outputWidth / qrWidth, outputHeight / qrHeight); // Padding includes both the quiet zone and the extra white pixels to accommodate the requested // dimensions. For example, if input is 25x25 the QR will be 33x33 including the quiet zone. // If the requested size is 200x160, the multiple will be 4, for a QR of 132x132. These will // handle all the padding from 100x100 (the actual QR) up to 200x160. leftPadding = (outputWidth - (inputWidth * multiple)) / 2; topPadding = (outputHeight - (inputHeight * multiple)) / 2; BitMatrix output = new BitMatrix(outputWidth, outputHeight); for (int inputY = 0, outputY = topPadding; inputY < inputHeight; inputY++, outputY += multiple) { // Write the contents of this row of the barcode for (int inputX = 0, outputX = leftPadding; inputX < inputWidth; inputX++, outputX += multiple) { if (input.get(inputX, inputY) == 1) { output.setRegion(outputX, outputY, multiple, multiple); } } } return output; } /** * get/set -- to help to expose the values */ public QRCode getCode() { return code; } public void setCode(QRCode code) { this.code = code; } public int getLeftPadding() { return leftPadding; } public void setLeftPadding(int leftPadding) { this.leftPadding = leftPadding; } public int getTopPadding() { return topPadding; } public void setTopPadding(int topPadding) { this.topPadding = topPadding; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/EncodingDetect.java
alpha/MyBox/src/main/java/thridparty/EncodingDetect.java
package thridparty; /** * @Author https://www.cnblogs.com/ChurchYim/p/8427373.html * * Changed by Mara * My updates are marked with #####. */ import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.net.URL; public class EncodingDetect { public static int MAX_CHECK_BYTES = 20000000; // ##### Added by Mara public static String detect(String path) { BytesEncodingDetect s = new BytesEncodingDetect(); String fileCode = BytesEncodingDetect.javaname[s.detectEncoding(new File(path))]; return fileCode; } public static String detect(File file) { BytesEncodingDetect s = new BytesEncodingDetect(); String fileCode = BytesEncodingDetect.javaname[s.detectEncoding(file)]; return fileCode; } public static String detect(byte[] contents) { BytesEncodingDetect s = new BytesEncodingDetect(); String fileCode = BytesEncodingDetect.javaname[s.detectEncoding(contents)]; return fileCode; } public static String detect(URL url) { BytesEncodingDetect s = new BytesEncodingDetect(); String fileCode = BytesEncodingDetect.javaname[s.detectEncoding(url)]; return fileCode; } static class BytesEncodingDetect extends Encoding { int GBFreq[][]; int GBKFreq[][]; int Big5Freq[][]; int Big5PFreq[][]; int EUC_TWFreq[][]; int KRFreq[][]; int JPFreq[][]; public boolean debug; public BytesEncodingDetect() { super(); debug = false; GBFreq = new int[94][94]; GBKFreq = new int[126][191]; Big5Freq = new int[94][158]; Big5PFreq = new int[126][191]; EUC_TWFreq = new int[94][94]; KRFreq = new int[94][94]; JPFreq = new int[94][94]; initialize_frequencies(); } public int detectEncoding(URL testurl) { byte[] rawtext = new byte[10000]; int bytesread = 0, byteoffset = 0; int guess = OTHER; InputStream is; try { is = testurl.openStream(); while ((bytesread = is.read(rawtext, byteoffset, rawtext.length - byteoffset)) > 0) { byteoffset += bytesread; } is.close(); guess = detectEncoding(rawtext); } catch (Exception e) { System.err.println("Error loading or using URL " + e.toString()); guess = -1; } return guess; } public int detectEncoding(File testfile) { byte[] rawtext = new byte[MAX_CHECK_BYTES]; // ##### Updated by Mara try ( FileInputStream fileis = new FileInputStream(testfile)) { fileis.read(rawtext); } catch (Exception e) { return OTHER; } return detectEncoding(rawtext); } public int detectEncoding(byte[] rawtext) { int[] scores; int index, maxscore = 0; int encoding_guess = OTHER; scores = new int[TOTALTYPES]; // Assign Scores scores[GB2312] = gb2312_probability(rawtext); scores[GBK] = gbk_probability(rawtext); scores[GB18030] = gb18030_probability(rawtext); scores[HZ] = hz_probability(rawtext); scores[BIG5] = big5_probability(rawtext); scores[CNS11643] = euc_tw_probability(rawtext); scores[ISO2022CN] = iso_2022_cn_probability(rawtext); scores[UTF8] = utf8_probability(rawtext); scores[UNICODE] = utf16_probability(rawtext); scores[EUC_KR] = euc_kr_probability(rawtext); scores[CP949] = cp949_probability(rawtext); scores[JOHAB] = 0; scores[ISO2022KR] = iso_2022_kr_probability(rawtext); scores[ASCII] = ascii_probability(rawtext); scores[SJIS] = sjis_probability(rawtext); scores[EUC_JP] = euc_jp_probability(rawtext); scores[ISO2022JP] = iso_2022_jp_probability(rawtext); scores[UNICODET] = 0; scores[UNICODES] = 0; scores[ISO2022CN_GB] = 0; scores[ISO2022CN_CNS] = 0; scores[OTHER] = 0; // Tabulate Scores for (index = 0; index < TOTALTYPES; index++) { if (debug) { System.err.println("Encoding " + nicename[index] + " score " + scores[index]); } if (scores[index] > maxscore) { encoding_guess = index; maxscore = scores[index]; } } // Return OTHER if nothing scored above 50 if (maxscore <= 50) { encoding_guess = OTHER; } return encoding_guess; } /* * Function: gb2312_probability Argument: pointer to byte array Returns : number from 0 to 100 representing * probability text in array uses GB-2312 encoding */ int gb2312_probability(byte[] rawtext) { int i, rawtextlen = 0; int dbchars = 1, gbchars = 1; long gbfreq = 0, totalfreq = 1; float rangeval = 0, freqval = 0; int row, column; // Stage 1: Check to see if characters fit into acceptable ranges rawtextlen = rawtext.length; for (i = 0; i < rawtextlen - 1; ++i) { // System.err.println(rawtext[i]); if (rawtext[i] >= 0) { // asciichars++; } else { dbchars++; if ((byte) 0xA1 <= rawtext[i] && rawtext[i] <= (byte) 0xF7 && (byte) 0xA1 <= rawtext[i + 1] && rawtext[i + 1] <= (byte) 0xFE) { gbchars++; totalfreq += 500; row = rawtext[i] + 256 - 0xA1; column = rawtext[i + 1] + 256 - 0xA1; if (GBFreq[row][column] != 0) { gbfreq += GBFreq[row][column]; } else if (15 <= row && row < 55) { // In GB high-freq character range gbfreq += 200; } } i++; } } rangeval = 50 * ((float) gbchars / (float) dbchars); freqval = 50 * ((float) gbfreq / (float) totalfreq); return (int) (rangeval + freqval); } /* * Function: gbk_probability Argument: pointer to byte array Returns : number from 0 to 100 representing * probability text in array uses GBK encoding */ int gbk_probability(byte[] rawtext) { int i, rawtextlen = 0; int dbchars = 1, gbchars = 1; long gbfreq = 0, totalfreq = 1; float rangeval = 0, freqval = 0; int row, column; // Stage 1: Check to see if characters fit into acceptable ranges rawtextlen = rawtext.length; for (i = 0; i < rawtextlen - 1; ++i) { // System.err.println(rawtext[i]); if (rawtext[i] >= 0) { // asciichars++; } else { dbchars++; if ((byte) 0xA1 <= rawtext[i] && rawtext[i] <= (byte) 0xF7 && // Original GB range (byte) 0xA1 <= rawtext[i + 1] && rawtext[i + 1] <= (byte) 0xFE) { gbchars++; totalfreq += 500; row = rawtext[i] + 256 - 0xA1; column = rawtext[i + 1] + 256 - 0xA1; // System.out.println("original row " + row + " column " + // column); if (GBFreq[row][column] != 0) { gbfreq += GBFreq[row][column]; } else if (15 <= row && row < 55) { gbfreq += 200; } } else if ((byte) 0x81 <= rawtext[i] && rawtext[i] <= (byte) 0xFE && // Extended GB range (((byte) 0x80 <= rawtext[i + 1] && rawtext[i + 1] <= (byte) 0xFE) || ((byte) 0x40 <= rawtext[i + 1] && rawtext[i + 1] <= (byte) 0x7E))) { gbchars++; totalfreq += 500; row = rawtext[i] + 256 - 0x81; if (0x40 <= rawtext[i + 1] && rawtext[i + 1] <= 0x7E) { column = rawtext[i + 1] - 0x40; } else { column = rawtext[i + 1] + 256 - 0x40; } // System.out.println("extended row " + row + " column " + // column + " rawtext[i] " + rawtext[i]); if (GBKFreq[row][column] != 0) { gbfreq += GBKFreq[row][column]; } } i++; } } rangeval = 50 * ((float) gbchars / (float) dbchars); freqval = 50 * ((float) gbfreq / (float) totalfreq); // For regular GB files, this would give the same score, so I handicap // it slightly return (int) (rangeval + freqval) - 1; } /* * Function: gb18030_probability Argument: pointer to byte array Returns : number from 0 to 100 representing * probability text in array uses GBK encoding */ int gb18030_probability(byte[] rawtext) { int i, rawtextlen = 0; int dbchars = 1, gbchars = 1; long gbfreq = 0, totalfreq = 1; float rangeval = 0, freqval = 0; int row, column; // Stage 1: Check to see if characters fit into acceptable ranges rawtextlen = rawtext.length; for (i = 0; i < rawtextlen - 1; ++i) { // System.err.println(rawtext[i]); if (rawtext[i] >= 0) { // asciichars++; } else { dbchars++; if ((byte) 0xA1 <= rawtext[i] && rawtext[i] <= (byte) 0xF7 && // Original GB range i + 1 < rawtextlen && (byte) 0xA1 <= rawtext[i + 1] && rawtext[i + 1] <= (byte) 0xFE) { gbchars++; totalfreq += 500; row = rawtext[i] + 256 - 0xA1; column = rawtext[i + 1] + 256 - 0xA1; // System.out.println("original row " + row + " column " + // column); if (GBFreq[row][column] != 0) { gbfreq += GBFreq[row][column]; } else if (15 <= row && row < 55) { gbfreq += 200; } } else if ((byte) 0x81 <= rawtext[i] && rawtext[i] <= (byte) 0xFE && // Extended GB range i + 1 < rawtextlen && (((byte) 0x80 <= rawtext[i + 1] && rawtext[i + 1] <= (byte) 0xFE) || ((byte) 0x40 <= rawtext[i + 1] && rawtext[i + 1] <= (byte) 0x7E))) { gbchars++; totalfreq += 500; row = rawtext[i] + 256 - 0x81; if (0x40 <= rawtext[i + 1] && rawtext[i + 1] <= 0x7E) { column = rawtext[i + 1] - 0x40; } else { column = rawtext[i + 1] + 256 - 0x40; } // System.out.println("extended row " + row + " column " + // column + " rawtext[i] " + rawtext[i]); if (GBKFreq[row][column] != 0) { gbfreq += GBKFreq[row][column]; } } else if ((byte) 0x81 <= rawtext[i] && rawtext[i] <= (byte) 0xFE && // Extended GB range i + 3 < rawtextlen && (byte) 0x30 <= rawtext[i + 1] && rawtext[i + 1] <= (byte) 0x39 && (byte) 0x81 <= rawtext[i + 2] && rawtext[i + 2] <= (byte) 0xFE && (byte) 0x30 <= rawtext[i + 3] && rawtext[i + 3] <= (byte) 0x39) { gbchars++; /* * totalfreq += 500; row = rawtext[i] + 256 - 0x81; if (0x40 <= rawtext[i+1] && rawtext[i+1] <= * 0x7E) { column = rawtext[i+1] - 0x40; } else { column = rawtext[i+1] + 256 - 0x40; } * //System.out.println("extended row " + row + " column " + column + " rawtext[i] " + * rawtext[i]); if (GBKFreq[row][column] != 0) { gbfreq += GBKFreq[row][column]; } */ } i++; } } rangeval = 50 * ((float) gbchars / (float) dbchars); freqval = 50 * ((float) gbfreq / (float) totalfreq); // For regular GB files, this would give the same score, so I handicap // it slightly return (int) (rangeval + freqval) - 1; } /* * Function: hz_probability Argument: byte array Returns : number from 0 to 100 representing probability text in * array uses HZ encoding */ int hz_probability(byte[] rawtext) { int i, rawtextlen; int hzchars = 0, dbchars = 1; long hzfreq = 0, totalfreq = 1; float rangeval = 0, freqval = 0; int hzstart = 0, hzend = 0; int row, column; rawtextlen = rawtext.length; for (i = 0; i < rawtextlen; ++i) { if (rawtext[i] == '~') { if (rawtext[i + 1] == '{') { hzstart++; i += 2; while (i < rawtextlen - 1) { if (rawtext[i] == 0x0A || rawtext[i] == 0x0D) { break; } else if (rawtext[i] == '~' && rawtext[i + 1] == '}') { hzend++; i++; break; } else if ((0x21 <= rawtext[i] && rawtext[i] <= 0x77) && (0x21 <= rawtext[i + 1] && rawtext[i + 1] <= 0x77)) { hzchars += 2; row = rawtext[i] - 0x21; column = rawtext[i + 1] - 0x21; totalfreq += 500; if (GBFreq[row][column] != 0) { hzfreq += GBFreq[row][column]; } else if (15 <= row && row < 55) { hzfreq += 200; } } else if ((0xA1 <= rawtext[i] && rawtext[i] <= 0xF7) && (0xA1 <= rawtext[i + 1] && rawtext[i + 1] <= 0xF7)) { hzchars += 2; row = rawtext[i] + 256 - 0xA1; column = rawtext[i + 1] + 256 - 0xA1; totalfreq += 500; if (GBFreq[row][column] != 0) { hzfreq += GBFreq[row][column]; } else if (15 <= row && row < 55) { hzfreq += 200; } } dbchars += 2; i += 2; } } else if (rawtext[i + 1] == '}') { hzend++; i++; } else if (rawtext[i + 1] == '~') { i++; } } } if (hzstart > 4) { rangeval = 50; } else if (hzstart > 1) { rangeval = 41; } else if (hzstart > 0) { // Only 39 in case the sequence happened to // occur rangeval = 39; // in otherwise non-Hz text } else { rangeval = 0; } freqval = 50 * ((float) hzfreq / (float) totalfreq); return (int) (rangeval + freqval); } /** * Function: big5_probability Argument: byte array Returns : number from * 0 to 100 representing probability text in array uses Big5 encoding */ int big5_probability(byte[] rawtext) { int i, rawtextlen = 0; int dbchars = 1, bfchars = 1; float rangeval = 0, freqval = 0; long bffreq = 0, totalfreq = 1; int row, column; // Check to see if characters fit into acceptable ranges rawtextlen = rawtext.length; for (i = 0; i < rawtextlen - 1; ++i) { if (rawtext[i] >= 0) { // asciichars++; } else { dbchars++; if ((byte) 0xA1 <= rawtext[i] && rawtext[i] <= (byte) 0xF9 && (((byte) 0x40 <= rawtext[i + 1] && rawtext[i + 1] <= (byte) 0x7E) || ((byte) 0xA1 <= rawtext[i + 1] && rawtext[i + 1] <= (byte) 0xFE))) { bfchars++; totalfreq += 500; row = rawtext[i] + 256 - 0xA1; if (0x40 <= rawtext[i + 1] && rawtext[i + 1] <= 0x7E) { column = rawtext[i + 1] - 0x40; } else { column = rawtext[i + 1] + 256 - 0x61; } if (Big5Freq[row][column] != 0) { bffreq += Big5Freq[row][column]; } else if (3 <= row && row <= 37) { bffreq += 200; } } i++; } } rangeval = 50 * ((float) bfchars / (float) dbchars); freqval = 50 * ((float) bffreq / (float) totalfreq); return (int) (rangeval + freqval); } /* * Function: big5plus_probability Argument: pointer to unsigned char array Returns : number from 0 to 100 * representing probability text in array uses Big5+ encoding */ int big5plus_probability(byte[] rawtext) { int i, rawtextlen = 0; int dbchars = 1, bfchars = 1; long bffreq = 0, totalfreq = 1; float rangeval = 0, freqval = 0; int row, column; // Stage 1: Check to see if characters fit into acceptable ranges rawtextlen = rawtext.length; for (i = 0; i < rawtextlen - 1; ++i) { // System.err.println(rawtext[i]); if (rawtext[i] >= 128) { // asciichars++; } else { dbchars++; if (0xA1 <= rawtext[i] && rawtext[i] <= 0xF9 && // Original Big5 range ((0x40 <= rawtext[i + 1] && rawtext[i + 1] <= 0x7E) || (0xA1 <= rawtext[i + 1] && rawtext[i + 1] <= 0xFE))) { bfchars++; totalfreq += 500; row = rawtext[i] - 0xA1; if (0x40 <= rawtext[i + 1] && rawtext[i + 1] <= 0x7E) { column = rawtext[i + 1] - 0x40; } else { column = rawtext[i + 1] - 0x61; } // System.out.println("original row " + row + " column " + // column); if (Big5Freq[row][column] != 0) { bffreq += Big5Freq[row][column]; } else if (3 <= row && row < 37) { bffreq += 200; } } else if (0x81 <= rawtext[i] && rawtext[i] <= 0xFE && // Extended Big5 range ((0x40 <= rawtext[i + 1] && rawtext[i + 1] <= 0x7E) || (0x80 <= rawtext[i + 1] && rawtext[i + 1] <= 0xFE))) { bfchars++; totalfreq += 500; row = rawtext[i] - 0x81; if (0x40 <= rawtext[i + 1] && rawtext[i + 1] <= 0x7E) { column = rawtext[i + 1] - 0x40; } else { column = rawtext[i + 1] - 0x40; } // System.out.println("extended row " + row + " column " + // column + " rawtext[i] " + rawtext[i]); if (Big5PFreq[row][column] != 0) { bffreq += Big5PFreq[row][column]; } } i++; } } rangeval = 50 * ((float) bfchars / (float) dbchars); freqval = 50 * ((float) bffreq / (float) totalfreq); // For regular Big5 files, this would give the same score, so I handicap // it slightly return (int) (rangeval + freqval) - 1; } /* * Function: euc_tw_probability Argument: byte array Returns : number from 0 to 100 representing probability * text in array uses EUC-TW (CNS 11643) encoding */ int euc_tw_probability(byte[] rawtext) { int i, rawtextlen = 0; int dbchars = 1, cnschars = 1; long cnsfreq = 0, totalfreq = 1; float rangeval = 0, freqval = 0; int row, column; // Check to see if characters fit into acceptable ranges // and have expected frequency of use rawtextlen = rawtext.length; for (i = 0; i < rawtextlen - 1; ++i) { if (rawtext[i] >= 0) { // in ASCII range // asciichars++; } else { // high bit set dbchars++; if (i + 3 < rawtextlen && (byte) 0x8E == rawtext[i] && (byte) 0xA1 <= rawtext[i + 1] && rawtext[i + 1] <= (byte) 0xB0 && (byte) 0xA1 <= rawtext[i + 2] && rawtext[i + 2] <= (byte) 0xFE && (byte) 0xA1 <= rawtext[i + 3] && rawtext[i + 3] <= (byte) 0xFE) { // Planes 1 - 16 cnschars++; // System.out.println("plane 2 or above CNS char"); // These are all less frequent chars so just ignore freq i += 3; } else if ((byte) 0xA1 <= rawtext[i] && rawtext[i] <= (byte) 0xFE && // Plane 1 (byte) 0xA1 <= rawtext[i + 1] && rawtext[i + 1] <= (byte) 0xFE) { cnschars++; totalfreq += 500; row = rawtext[i] + 256 - 0xA1; column = rawtext[i + 1] + 256 - 0xA1; if (EUC_TWFreq[row][column] != 0) { cnsfreq += EUC_TWFreq[row][column]; } else if (35 <= row && row <= 92) { cnsfreq += 150; } i++; } } } rangeval = 50 * ((float) cnschars / (float) dbchars); freqval = 50 * ((float) cnsfreq / (float) totalfreq); return (int) (rangeval + freqval); } /* * Function: iso_2022_cn_probability Argument: byte array Returns : number from 0 to 100 representing * probability text in array uses ISO 2022-CN encoding WORKS FOR BASIC CASES, BUT STILL NEEDS MORE WORK */ int iso_2022_cn_probability(byte[] rawtext) { int i, rawtextlen = 0; int dbchars = 1, isochars = 1; long isofreq = 0, totalfreq = 1; float rangeval = 0, freqval = 0; int row, column; // Check to see if characters fit into acceptable ranges // and have expected frequency of use rawtextlen = rawtext.length; for (i = 0; i < rawtextlen - 1; ++i) { if (rawtext[i] == (byte) 0x1B && i + 3 < rawtextlen) { // Escape // char ESC if (rawtext[i + 1] == (byte) 0x24 && rawtext[i + 2] == 0x29 && rawtext[i + 3] == (byte) 0x41) { // GB // Escape // $ // ) // A i += 4; while (rawtext[i] != (byte) 0x1B) { dbchars++; if ((0x21 <= rawtext[i] && rawtext[i] <= 0x77) && (0x21 <= rawtext[i + 1] && rawtext[i + 1] <= 0x77)) { isochars++; row = rawtext[i] - 0x21; column = rawtext[i + 1] - 0x21; totalfreq += 500; if (GBFreq[row][column] != 0) { isofreq += GBFreq[row][column]; } else if (15 <= row && row < 55) { isofreq += 200; } i++; } i++; } } else if (i + 3 < rawtextlen && rawtext[i + 1] == (byte) 0x24 && rawtext[i + 2] == (byte) 0x29 && rawtext[i + 3] == (byte) 0x47) { // CNS Escape $ ) G i += 4; while (rawtext[i] != (byte) 0x1B) { dbchars++; if ((byte) 0x21 <= rawtext[i] && rawtext[i] <= (byte) 0x7E && (byte) 0x21 <= rawtext[i + 1] && rawtext[i + 1] <= (byte) 0x7E) { isochars++; totalfreq += 500; row = rawtext[i] - 0x21; column = rawtext[i + 1] - 0x21; if (EUC_TWFreq[row][column] != 0) { isofreq += EUC_TWFreq[row][column]; } else if (35 <= row && row <= 92) { isofreq += 150; } i++; } i++; } } if (rawtext[i] == (byte) 0x1B && i + 2 < rawtextlen && rawtext[i + 1] == (byte) 0x28 && rawtext[i + 2] == (byte) 0x42) { // ASCII: // ESC // ( B i += 2; } } } rangeval = 50 * ((float) isochars / (float) dbchars); freqval = 50 * ((float) isofreq / (float) totalfreq); // System.out.println("isochars dbchars isofreq totalfreq " + isochars + // " " + dbchars + " " + isofreq + " " + totalfreq + " // " + rangeval + " " + freqval); return (int) (rangeval + freqval); // return 0; } /* * Function: utf8_probability Argument: byte array Returns : number from 0 to 100 representing probability text * in array uses UTF-8 encoding of Unicode */ int utf8_probability(byte[] rawtext) { int score = 0; int i, rawtextlen = 0; int goodbytes = 0, asciibytes = 0; // Maybe also use UTF8 Byte Order Mark: EF BB BF // Check to see if characters fit into acceptable ranges rawtextlen = rawtext.length; for (i = 0; i < rawtextlen; ++i) { if ((rawtext[i] & (byte) 0x7F) == rawtext[i]) { // One byte asciibytes++; // Ignore ASCII, can throw off count } else if (-64 <= rawtext[i] && rawtext[i] <= -33 && // Two bytes i + 1 < rawtextlen && -128 <= rawtext[i + 1] && rawtext[i + 1] <= -65) { goodbytes += 2; i++; } else if (-32 <= rawtext[i] && rawtext[i] <= -17 && // Three bytes i + 2 < rawtextlen && -128 <= rawtext[i + 1] && rawtext[i + 1] <= -65 && -128 <= rawtext[i + 2] && rawtext[i + 2] <= -65) { goodbytes += 3; i += 2; } } if (asciibytes == rawtextlen) { return 0; } score = (int) (100 * ((float) goodbytes / (float) (rawtextlen - asciibytes))); // System.out.println("rawtextlen " + rawtextlen + " goodbytes " + // goodbytes + " asciibytes " + asciibytes + " score " + // score); // If not above 98, reduce to zero to prevent coincidental matches // Allows for some (few) bad formed sequences if (score > 98) { return score; } else if (score > 95 && goodbytes > 30) { return score; } else { return 0; } } /* * Function: utf16_probability Argument: byte array Returns : number from 0 to 100 representing probability text * in array uses UTF-16 encoding of Unicode, guess based on BOM // NOT VERY GENERAL, NEEDS MUCH MORE WORK */ int utf16_probability(byte[] rawtext) { // int score = 0; // int i, rawtextlen = 0; // int goodbytes = 0, asciibytes = 0; if (rawtext.length > 1 && ((byte) 0xFE == rawtext[0] && (byte) 0xFF == rawtext[1]) || // Big-endian ((byte) 0xFF == rawtext[0] && (byte) 0xFE == rawtext[1])) { // Little-endian return 100; } return 0; /* * // Check to see if characters fit into acceptable ranges rawtextlen = rawtext.length; for (i = 0; i < * rawtextlen; i++) { if ((rawtext[i] & (byte)0x7F) == rawtext[i]) { // One byte goodbytes += 1; * asciibytes++; } else if ((rawtext[i] & (byte)0xDF) == rawtext[i]) { // Two bytes if (i+1 < rawtextlen && * (rawtext[i+1] & (byte)0xBF) == rawtext[i+1]) { goodbytes += 2; i++; } } else if ((rawtext[i] & * (byte)0xEF) == rawtext[i]) { // Three bytes if (i+2 < rawtextlen && (rawtext[i+1] & (byte)0xBF) == * rawtext[i+1] && (rawtext[i+2] & (byte)0xBF) == rawtext[i+2]) { goodbytes += 3; i+=2; } } } * * score = (int)(100 * ((float)goodbytes/(float)rawtext.length)); // An all ASCII file is also a good UTF8 * file, but I'd rather it // get identified as ASCII. Can delete following 3 lines otherwise if (goodbytes * == asciibytes) { score = 0; } // If not above 90, reduce to zero to prevent coincidental matches if * (score > 90) { return score; } else { return 0; } */ } /* * Function: ascii_probability Argument: byte array Returns : number from 0 to 100 representing probability text * in array uses all ASCII Description: Sees if array has any characters not in ASCII range, if so, score is * reduced */ int ascii_probability(byte[] rawtext) { int score = 75; int i, rawtextlen; rawtextlen = rawtext.length; for (i = 0; i < rawtextlen; ++i) { if (rawtext[i] < 0) { score = score - 5; } else if (rawtext[i] == (byte) 0x1B) { // ESC (used by ISO 2022)
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
true
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/ColorTemperature.java
alpha/MyBox/src/main/java/thridparty/ColorTemperature.java
package thridparty; /** * @Author http://brucelindbloom.com/index.html?Eqn_XYZ_to_T.html * http://brucelindbloom.com/index.html?Eqn_T_to_xy.html * */ public class ColorTemperature { public static double[] rt = { /* reciprocal temperature (K) */ -Double.MAX_VALUE, 10.0e-6, 20.0e-6, 30.0e-6, 40.0e-6, 50.0e-6, 60.0e-6, 70.0e-6, 80.0e-6, 90.0e-6, 100.0e-6, 125.0e-6, 150.0e-6, 175.0e-6, 200.0e-6, 225.0e-6, 250.0e-6, 275.0e-6, 300.0e-6, 325.0e-6, 350.0e-6, 375.0e-6, 400.0e-6, 425.0e-6, 450.0e-6, 475.0e-6, 500.0e-6, 525.0e-6, 550.0e-6, 575.0e-6, 600.0e-6 }; public static double[][] uvt = { {0.18006, 0.26352, -0.24341}, {0.18066, 0.26589, -0.25479}, {0.18133, 0.26846, -0.26876}, {0.18208, 0.27119, -0.28539}, {0.18293, 0.27407, -0.30470}, {0.18388, 0.27709, -0.32675}, {0.18494, 0.28021, -0.35156}, {0.18611, 0.28342, -0.37915}, {0.18740, 0.28668, -0.40955}, {0.18880, 0.28997, -0.44278}, {0.19032, 0.29326, -0.47888}, {0.19462, 0.30141, -0.58204}, {0.19962, 0.30921, -0.70471}, {0.20525, 0.31647, -0.84901}, {0.21142, 0.32312, -1.0182}, {0.21807, 0.32909, -1.2168}, {0.22511, 0.33439, -1.4512}, {0.23247, 0.33904, -1.7298}, {0.24010, 0.34308, -2.0637}, {0.24792, 0.34655, -2.4681}, /* Note: 0.24792 is a corrected value for the error found in W&S as 0.24702 */ {0.25591, 0.34951, -2.9641}, {0.26400, 0.35200, -3.5814}, {0.27218, 0.35407, -4.3633}, {0.28039, 0.35577, -5.3762}, {0.28863, 0.35714, -6.7262}, {0.29685, 0.35823, -8.5955}, {0.30505, 0.35907, -11.324}, {0.31320, 0.35968, -15.628}, {0.32129, 0.36011, -23.325}, {0.32931, 0.36038, -40.770}, {0.33724, 0.36051, -116.45} }; // xyz are tristimulus values public static double xyz2ColorTemp(double[] xyz) { if ((xyz[0] < 1.0e-20) && (xyz[1] < 1.0e-20) && (xyz[2] < 1.0e-20)) { return (-1); /* protect against possible divide-by-zero failure */ } double us = (4.0 * xyz[0]) / (xyz[0] + 15.0 * xyz[1] + 3.0 * xyz[2]); double vs = (6.0 * xyz[1]) / (xyz[0] + 15.0 * xyz[1] + 3.0 * xyz[2]); double di = 0.0, dm = 0.0; int i; for (i = 0; i < uvt.length; ++i) { di = (vs - uvt[i][1]) - uvt[i][2] * (us - uvt[i][0]); if ((i > 0) && (((di < 0.0) && (dm >= 0.0)) || ((di >= 0.0) && (dm < 0.0)))) { break; /* found lines bounding (us, vs) : i-1 and i */ } dm = di; } if (i == 31) { return (-1); /* bad XYZ input, color temp would be less than minimum of 1666.7 degrees, or too far towards blue */ } di = di / Math.sqrt(1.0 + uvt[i][2] * uvt[i][2]); dm = dm / Math.sqrt(1.0 + uvt[i - 1][2] * uvt[i - 1][2]); double temp = dm / (dm - di); /* temp = interpolation parameter, 0.0 : i-1, 1.0 : i */ temp = 1.0 / ((rt[i] - rt[i - 1]) * temp + rt[i - 1]); return temp; } public static double[] colorTemp2xy(double temp) { if (temp < 4000 || temp > 25000) { return null; } double[] xy = new double[2]; if (temp <= 7000) { xy[0] = -4.6070 * Math.pow(10, 9) / Math.pow(temp, 3) + 2.9678 * Math.pow(10, 6) / Math.pow(temp, 2) + 0.09911 * Math.pow(10, 3) / temp + 0.244063; } else { xy[0] = -2.0064 * Math.pow(10, 9) / Math.pow(temp, 3) + 1.9018 * Math.pow(10, 6) / Math.pow(temp, 2) + 0.24748 * Math.pow(10, 3) / temp + 0.237040; } xy[1] = -3.000 * Math.pow(xy[0], 2) + 2.870 * xy[0] - 0.275; return xy; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/GifDecoder.java
alpha/MyBox/src/main/java/thridparty/GifDecoder.java
package thridparty; import static java.lang.System.arraycopy; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; /* * Copyright 2014 Dhyan Blum * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * <p> * A decoder capable of processing a GIF data stream to render the graphics * contained in it. This implementation follows the official * <A HREF="http://www.w3.org/Graphics/GIF/spec-gif89a.txt">GIF * specification</A>. * </p> * * <p> * Example usage: * </p> * * <p> * * <pre> * final GifImage gifImage = GifDecoder.read(int[] data); * final int width = gifImage.getWidth(); * final int height = gifImage.getHeight(); * final int frameCount = gifImage.getFrameCount(); * for (int i = 0; i < frameCount; ++i) { * final BufferedImage image = gifImage.getFrame(i); * final int delay = gif.getDelay(i); * } * </pre> * * </p> * * @author Dhyan Blum * @version 1.09 November 2017 * */ public final class GifDecoder { static final class BitReader { private int bitPos; // Next bit to read private int numBits; // Number of bits to read private int bitMask; // Use to kill unwanted higher bits private byte[] in; // Data array // To avoid costly bounds checks, 'in' needs 2 more 0-bytes at the end private final void init(final byte[] in) { this.in = in; bitPos = 0; } private final int read() { // Byte indices: (bitPos / 8), (bitPos / 8) + 1, (bitPos / 8) + 2 int i = bitPos >>> 3; // Byte = bit / 8 // Bits we'll shift to the right, AND 7 is the same as MODULO 8 final int rBits = bitPos & 7; // Byte 0 to 2, AND to get their unsigned values final int b0 = in[i++] & 0xFF, b1 = in[i++] & 0xFF, b2 = in[i] & 0xFF; // Glue the bytes together, don't do more shifting than necessary final int buf = ((b2 << 8 | b1) << 8 | b0) >>> rBits; bitPos += numBits; return buf & bitMask; // Kill the unwanted higher bits } private final void setNumBits(final int numBits) { this.numBits = numBits; bitMask = (1 << numBits) - 1; } } static final class CodeTable { private final int[][] tbl; // Maps codes to lists of colors private int initTableSize; // Number of colors +2 for CLEAR + EOI private int initCodeSize; // Initial code size private int initCodeLimit; // First code limit private int codeSize; // Current code size, maximum is 12 bits private int nextCode; // Next available code for a new entry private int nextCodeLimit; // Increase codeSize when nextCode == limit private BitReader br; // Notify when code sizes increases public CodeTable() { tbl = new int[4096][1]; } private final int add(final int[] indices) { if (nextCode < 4096) { if (nextCode == nextCodeLimit && codeSize < 12) { codeSize++; // Max code size is 12 br.setNumBits(codeSize); nextCodeLimit = (1 << codeSize) - 1; // 2^codeSize - 1 } tbl[nextCode++] = indices; } return codeSize; } private final int clear() { codeSize = initCodeSize; br.setNumBits(codeSize); nextCodeLimit = initCodeLimit; nextCode = initTableSize; // Don't recreate table, reset pointer return codeSize; } private final void init(final GifFrame fr, final int[] activeColTbl, final BitReader br) { this.br = br; final int numColors = activeColTbl.length; initCodeSize = fr.firstCodeSize; initCodeLimit = (1 << initCodeSize) - 1; // 2^initCodeSize - 1 initTableSize = fr.endOfInfoCode + 1; nextCode = initTableSize; for (int c = numColors - 1; c >= 0; c--) { tbl[c][0] = activeColTbl[c]; // Translated color } // A gap may follow with no colors assigned if numCols < CLEAR tbl[fr.clearCode] = new int[]{fr.clearCode}; // CLEAR tbl[fr.endOfInfoCode] = new int[]{fr.endOfInfoCode}; // EOI // Locate transparent color in code table and set to 0 if (fr.transpColFlag && fr.transpColIndex < numColors) { tbl[fr.transpColIndex][0] = 0; } } } final class GifFrame { // Graphic control extension (optional) // Disposal: 0=NO_ACTION, 1=NO_DISPOSAL, 2=RESTORE_BG, 3=RESTORE_PREV private int disposalMethod; // 0-3 as above, 4-7 undefined private boolean transpColFlag; // 1 Bit private int delay; // Unsigned, LSByte first, n * 1/100 * s private int transpColIndex; // 1 Byte // Image descriptor private int x; // Position on the canvas from the left private int y; // Position on the canvas from the top private int w; // May be smaller than the base image private int h; // May be smaller than the base image private int wh; // width * height private boolean hasLocColTbl; // Has local color table? 1 Bit private boolean interlaceFlag; // Is an interlace image? 1 Bit @SuppressWarnings("unused") private boolean sortFlag; // True if local colors are sorted, 1 Bit private int sizeOfLocColTbl; // Size of the local color table, 3 Bits private int[] localColTbl; // Local color table (optional) // Image data private int firstCodeSize; // LZW minimum code size + 1 for CLEAR & EOI private int clearCode; private int endOfInfoCode; private byte[] data; // Holds LZW encoded data private BufferedImage img; // Full drawn image, not just the frame area } public final class GifImage { public String header; // Bytes 0-5, GIF87a or GIF89a private int w; // Unsigned 16 Bit, least significant byte first private int h; // Unsigned 16 Bit, least significant byte first private int wh; // Image width * image height public boolean hasGlobColTbl; // 1 Bit public int colorResolution; // 3 Bits public boolean sortFlag; // True if global colors are sorted, 1 Bit public int sizeOfGlobColTbl; // 2^(val(3 Bits) + 1), see spec public int bgColIndex; // Background color index, 1 Byte public int pxAspectRatio; // Pixel aspect ratio, 1 Byte public int[] globalColTbl; // Global color table private final List<GifFrame> frames = new ArrayList<>(64); public String appId = ""; // 8 Bytes at in[i+3], usually "NETSCAPE" public String appAuthCode = ""; // 3 Bytes at in[i+11], usually "2.0" public int repetitions = 0; // 0: infinite loop, N: number of loops private BufferedImage img = null; // Currently drawn frame private int[] prevPx = null; // Previous frame's pixels private final BitReader bits = new BitReader(); private final CodeTable codes = new CodeTable(); private Graphics2D g; private final int[] decode(final GifFrame fr, final int[] activeColTbl) { codes.init(fr, activeColTbl, bits); bits.init(fr.data); // Incoming codes final int clearCode = fr.clearCode, endCode = fr.endOfInfoCode; final int[] out = new int[wh]; // Target image pixel array final int[][] tbl = codes.tbl; // Code table int outPos = 0; // Next pixel position in the output image array codes.clear(); // Init code table bits.read(); // Skip leading clear code int code = bits.read(); // Read first code int[] pixels = tbl[code]; // Output pixel for first code arraycopy(pixels, 0, out, outPos, pixels.length); outPos += pixels.length; try { while (true) { final int prevCode = code; code = bits.read(); // Get next code in stream if (code == clearCode) { // After a CLEAR table, there is codes.clear(); // no previous code, we need to read code = bits.read(); // a new one pixels = tbl[code]; // Output pixels arraycopy(pixels, 0, out, outPos, pixels.length); outPos += pixels.length; continue; // Back to the loop with a valid previous code } else if (code == endCode) { break; } final int[] prevVals = tbl[prevCode]; final int[] prevValsAndK = new int[prevVals.length + 1]; arraycopy(prevVals, 0, prevValsAndK, 0, prevVals.length); if (code < codes.nextCode) { // Code table contains code pixels = tbl[code]; // Output pixels arraycopy(pixels, 0, out, outPos, pixels.length); outPos += pixels.length; prevValsAndK[prevVals.length] = tbl[code][0]; // K } else { prevValsAndK[prevVals.length] = prevVals[0]; // K arraycopy(prevValsAndK, 0, out, outPos, prevValsAndK.length); outPos += prevValsAndK.length; } codes.add(prevValsAndK); // Previous indices + K } } catch (final ArrayIndexOutOfBoundsException e) { } return out; } private final int[] deinterlace(final int[] src, final GifFrame fr) { final int w = fr.w, h = fr.h, wh = fr.wh; final int[] dest = new int[src.length]; // Interlaced images are organized in 4 sets of pixel lines final int set2Y = (h + 7) >>> 3; // Line no. = ceil(h/8.0) final int set3Y = set2Y + ((h + 3) >>> 3); // ceil(h-4/8.0) final int set4Y = set3Y + ((h + 1) >>> 2); // ceil(h-2/4.0) // Sets' start indices in source array final int set2 = w * set2Y, set3 = w * set3Y, set4 = w * set4Y; // Line skips in destination array final int w2 = w << 1, w4 = w2 << 1, w8 = w4 << 1; // Group 1 contains every 8th line starting from 0 int from = 0, to = 0; for (; from < set2; from += w, to += w8) { arraycopy(src, from, dest, to, w); } // Group 2 contains every 8th line starting from 4 for (to = w4; from < set3; from += w, to += w8) { arraycopy(src, from, dest, to, w); } // Group 3 contains every 4th line starting from 2 for (to = w2; from < set4; from += w, to += w4) { arraycopy(src, from, dest, to, w); } // Group 4 contains every 2nd line starting from 1 (biggest group) for (to = w; from < wh; from += w, to += w2) { arraycopy(src, from, dest, to, w); } return dest; // All pixel lines have now been rearranged } private final void drawFrame(final GifFrame fr) { // Determine the color table that will be active for this frame final int[] activeColTbl = fr.hasLocColTbl ? fr.localColTbl : globalColTbl; // Get pixels from data stream int[] pixels = decode(fr, activeColTbl); if (fr.interlaceFlag) { pixels = deinterlace(pixels, fr); // Rearrange pixel lines } // Create image of type 2=ARGB for frame area final BufferedImage frame = new BufferedImage(fr.w, fr.h, 2); arraycopy(pixels, 0, ((DataBufferInt) frame.getRaster().getDataBuffer()).getData(), 0, fr.wh); // Draw frame area on top of working image g.drawImage(frame, fr.x, fr.y, null); // Visualize frame boundaries during testing // if (DEBUG_MODE) { // if (prev != null) { // g.setColor(Color.RED); // Previous frame color // g.drawRect(prev.x, prev.y, prev.w - 1, prev.h - 1); // } // g.setColor(Color.GREEN); // New frame color // g.drawRect(fr.x, fr.y, fr.w - 1, fr.h - 1); // } // Keep one copy as "previous frame" in case we need to restore it prevPx = new int[wh]; arraycopy(((DataBufferInt) img.getRaster().getDataBuffer()).getData(), 0, prevPx, 0, wh); // Create another copy for the end user to not expose internal state fr.img = new BufferedImage(w, h, 2); // 2 = ARGB arraycopy(prevPx, 0, ((DataBufferInt) fr.img.getRaster().getDataBuffer()).getData(), 0, wh); // Handle disposal of current frame if (fr.disposalMethod == 2) { // Restore to background color (clear frame area only) g.clearRect(fr.x, fr.y, fr.w, fr.h); } else if (fr.disposalMethod == 3 && prevPx != null) { // Restore previous frame arraycopy(prevPx, 0, ((DataBufferInt) img.getRaster().getDataBuffer()).getData(), 0, wh); } } /** * Returns the background color of the first frame in this GIF image. If * the frame has a local color table, the returned color will be from * that table. If not, the color will be from the global color table. * Returns 0 if there is neither a local nor a global color table. * * @param index Index of the current frame, 0 to N-1 * @return 32 bit ARGB color in the form 0xAARRGGBB */ public final int getBackgroundColor() { final GifFrame frame = frames.get(0); if (frame.hasLocColTbl) { return frame.localColTbl[bgColIndex]; } else if (hasGlobColTbl) { return globalColTbl[bgColIndex]; } return 0; } /** * If not 0, the delay specifies how many hundredths (1/100) of a second * to wait before displaying the frame <i>after</i> the current frame. * * @param index Index of the current frame, 0 to N-1 * @return Delay as number of hundredths (1/100) of a second */ public final int getDelay(final int index) { return frames.get(index).delay; } /** * @param index Index of the frame to return as image, starting from 0. * For incremental calls such as [0, 1, 2, ...] the method's run time is * O(1) as only one frame is drawn per call. For random access calls * such as [7, 12, ...] the run time is O(N+1) with N being the number * of previous frames that need to be drawn before N+1 can be drawn on * top. Once a frame has been drawn it is being cached and the run time * is more or less O(0) to retrieve it from the list. * @return A BufferedImage for the specified frame. */ public final BufferedImage getFrame(final int index) { if (img == null) { // Init img = new BufferedImage(w, h, 2); // 2 = ARGB g = img.createGraphics(); g.setBackground(new Color(0, true)); // Transparent color } GifFrame fr = frames.get(index); if (fr.img == null) { // Draw all frames until and including the requested frame for (int i = 0; i <= index; ++i) { fr = frames.get(i); if (fr.img == null) { drawFrame(fr); } } } return fr.img; } /** * @return The number of frames contained in this GIF image */ public final int getFrameCount() { return frames.size(); } /** * @return The height of the GIF image */ public final int getHeight() { return h; } /** * @return The width of the GIF image */ public final int getWidth() { return w; } } static final boolean DEBUG_MODE = false; /** * @param in Raw image data as a byte[] array * @return A GifImage object exposing the properties of the GIF image. * @throws IOException If the image violates the GIF specification or is * truncated. */ public static final GifImage read(final byte[] in) throws IOException { final GifDecoder decoder = new GifDecoder(); final GifImage img = decoder.new GifImage(); GifFrame frame = null; // Currently open frame int pos = readHeader(in, img); // Read header, get next byte position pos = readLogicalScreenDescriptor(img, in, pos); if (img.hasGlobColTbl) { img.globalColTbl = new int[img.sizeOfGlobColTbl]; pos = readColTbl(in, img.globalColTbl, pos); } while (pos < in.length) { final int block = in[pos] & 0xFF; switch (block) { case 0x21: // Extension introducer if (pos + 1 >= in.length) { throw new IOException("Unexpected end of file."); } switch (in[pos + 1] & 0xFF) { case 0xFE: // Comment extension pos = readTextExtension(in, pos); break; case 0xFF: // Application extension pos = readAppExt(img, in, pos); break; case 0x01: // Plain text extension frame = null; // End of current frame pos = readTextExtension(in, pos); break; case 0xF9: // Graphic control extension if (frame == null) { frame = decoder.new GifFrame(); img.frames.add(frame); } pos = readGraphicControlExt(frame, in, pos); break; default: throw new IOException("Unknown extension at " + pos); } break; case 0x2C: // Image descriptor if (frame == null) { frame = decoder.new GifFrame(); img.frames.add(frame); } pos = readImgDescr(frame, in, pos); if (frame.hasLocColTbl) { frame.localColTbl = new int[frame.sizeOfLocColTbl]; pos = readColTbl(in, frame.localColTbl, pos); } pos = readImgData(frame, in, pos); frame = null; // End of current frame break; case 0x3B: // GIF Trailer return img; // Found trailer, finished reading. default: // Unknown block. The image is corrupted. Strategies: a) Skip // and wait for a valid block. Experience: It'll get worse. b) // Throw exception. c) Return gracefully if we are almost done // processing. The frames we have so far should be error-free. final double progress = 1.0 * pos / in.length; if (progress < 0.9) { throw new IOException("Unknown block at: " + pos); } pos = in.length; // Exit loop } } return img; } /** * @param is Image data as input stream. This method will read from the * input stream's current position. It will not reset the position before * reading and won't reset or close the stream afterwards. Call these * methods before and after calling this method as needed. * @return A GifImage object exposing the properties of the GIF image. * @throws IOException If an I/O error occurs, the image violates the GIF * specification or the GIF is truncated. */ public static final GifImage read(final InputStream is) throws IOException { final byte[] data = new byte[is.available()]; is.read(data, 0, data.length); return read(data); } /** * @param ext Empty application extension object * @param in Raw data * @param i Index of the first byte of the application extension * @return Index of the first byte after this extension */ static final int readAppExt(final GifImage img, final byte[] in, int i) { img.appId = new String(in, i + 3, 8); // should be "NETSCAPE" img.appAuthCode = new String(in, i + 11, 3); // should be "2.0" i += 14; // Go to sub-block size, it's value should be 3 final int subBlockSize = in[i] & 0xFF; // The only app extension widely used is NETSCAPE, it's got 3 data bytes if (subBlockSize == 3) { // in[i+1] should have value 01, in[i+5] should be block terminator img.repetitions = in[i + 2] & 0xFF | in[i + 3] & 0xFF << 8; // Short return i + 5; } // Skip unknown application extensions while ((in[i] & 0xFF) != 0) { // While sub-block size != 0 i += (in[i] & 0xFF) + 1; // Skip to next sub-block } return i + 1; } /** * @param in Raw data * @param colors Pre-initialized target array to store ARGB colors * @param i Index of the color table's first byte * @return Index of the first byte after the color table */ static final int readColTbl(final byte[] in, final int[] colors, int i) { final int numColors = colors.length; for (int c = 0; c < numColors; c++) { final int a = 0xFF; // Alpha 255 (opaque) final int r = in[i++] & 0xFF; // 1st byte is red final int g = in[i++] & 0xFF; // 2nd byte is green final int b = in[i++] & 0xFF; // 3rd byte is blue colors[c] = ((a << 8 | r) << 8 | g) << 8 | b; } return i; } /** * @param ext Graphic control extension object * @param in Raw data * @param i Index of the extension introducer * @return Index of the first byte after this block */ static final int readGraphicControlExt(final GifFrame fr, final byte[] in, final int i) { fr.disposalMethod = (in[i + 3] & 0b00011100) >>> 2; // Bits 4-2 fr.transpColFlag = (in[i + 3] & 1) == 1; // Bit 0 fr.delay = in[i + 4] & 0xFF | (in[i + 5] & 0xFF) << 8; // 16 bit LSB fr.transpColIndex = in[i + 6] & 0xFF; // Byte 6 return i + 8; // Skipped byte 7 (blockTerminator), as it's always 0x00 } /** * @param in Raw data * @param img The GifImage object that is currently read * @return Index of the first byte after this block * @throws IOException If the GIF header/trailer is missing, incomplete or * unknown */ static final int readHeader(final byte[] in, final GifImage img) throws IOException { if (in.length < 6) { // Check first 6 bytes throw new IOException("Image is truncated."); } img.header = new String(in, 0, 6); if (!img.header.equals("GIF87a") && !img.header.equals("GIF89a")) { throw new IOException("Invalid GIF header."); } return 6; } /** * @param fr The GIF frame to whom this image descriptor belongs * @param in Raw data * @param i Index of the first byte of this block, i.e. the minCodeSize * @return */ static final int readImgData(final GifFrame fr, final byte[] in, int i) { final int fileSize = in.length; final int minCodeSize = in[i++] & 0xFF; // Read code size, go to block final int clearCode = 1 << minCodeSize; // CLEAR = 2^minCodeSize fr.firstCodeSize = minCodeSize + 1; // Add 1 bit for CLEAR and EOI fr.clearCode = clearCode; fr.endOfInfoCode = clearCode + 1; final int imgDataSize = readImgDataSize(in, i); final byte[] imgData = new byte[imgDataSize + 2]; int imgDataPos = 0; int subBlockSize = in[i] & 0xFF; while (subBlockSize > 0) { // While block has data try { // Next line may throw exception if sub-block size is fake final int nextSubBlockSizePos = i + subBlockSize + 1; final int nextSubBlockSize = in[nextSubBlockSizePos] & 0xFF; arraycopy(in, i + 1, imgData, imgDataPos, subBlockSize); imgDataPos += subBlockSize; // Move output data position i = nextSubBlockSizePos; // Move to next sub-block size subBlockSize = nextSubBlockSize; } catch (final Exception e) { // Sub-block exceeds file end, only use remaining bytes subBlockSize = fileSize - i - 1; // Remaining bytes arraycopy(in, i + 1, imgData, imgDataPos, subBlockSize); imgDataPos += subBlockSize; // Move output data position i += subBlockSize + 1; // Move to next sub-block size break; } } fr.data = imgData; // Holds LZW encoded data i++; // Skip last sub-block size, should be 0 return i; } static final int readImgDataSize(final byte[] in, int i) { final int fileSize = in.length; int imgDataPos = 0; int subBlockSize = in[i] & 0xFF; while (subBlockSize > 0) { // While block has data try { // Next line may throw exception if sub-block size is fake final int nextSubBlockSizePos = i + subBlockSize + 1; final int nextSubBlockSize = in[nextSubBlockSizePos] & 0xFF; imgDataPos += subBlockSize; // Move output data position i = nextSubBlockSizePos; // Move to next sub-block size subBlockSize = nextSubBlockSize; } catch (final Exception e) { // Sub-block exceeds file end, only use remaining bytes subBlockSize = fileSize - i - 1; // Remaining bytes imgDataPos += subBlockSize; // Move output data position break; } } return imgDataPos; } /** * @param fr The GIF frame to whom this image descriptor belongs * @param in Raw data * @param i Index of the image separator, i.e. the first block byte * @return Index of the first byte after this block */ static final int readImgDescr(final GifFrame fr, final byte[] in, int i) { fr.x = in[++i] & 0xFF | (in[++i] & 0xFF) << 8; // Byte 1-2: left fr.y = in[++i] & 0xFF | (in[++i] & 0xFF) << 8; // Byte 3-4: top fr.w = in[++i] & 0xFF | (in[++i] & 0xFF) << 8; // Byte 5-6: width fr.h = in[++i] & 0xFF | (in[++i] & 0xFF) << 8; // Byte 7-8: height fr.wh = fr.w * fr.h; final byte b = in[++i]; // Byte 9 is a packed byte fr.hasLocColTbl = (b & 0b10000000) >>> 7 == 1; // Bit 7 fr.interlaceFlag = (b & 0b01000000) >>> 6 == 1; // Bit 6 fr.sortFlag = (b & 0b00100000) >>> 5 == 1; // Bit 5 final int colTblSizePower = (b & 7) + 1; // Bits 2-0 fr.sizeOfLocColTbl = 1 << colTblSizePower; // 2^(N+1), As per the spec return ++i; } /** * @param img * @param i Start index of this block. * @return Index of the first byte after this block. */ static final int readLogicalScreenDescriptor(final GifImage img, final byte[] in, final int i) { img.w = in[i] & 0xFF | (in[i + 1] & 0xFF) << 8; // 16 bit, LSB 1st img.h = in[i + 2] & 0xFF | (in[i + 3] & 0xFF) << 8; // 16 bit img.wh = img.w * img.h; final byte b = in[i + 4]; // Byte 4 is a packed byte img.hasGlobColTbl = (b & 0b10000000) >>> 7 == 1; // Bit 7 final int colResPower = ((b & 0b01110000) >>> 4) + 1; // Bits 6-4 img.colorResolution = 1 << colResPower; // 2^(N+1), As per the spec img.sortFlag = (b & 0b00001000) >>> 3 == 1; // Bit 3 final int globColTblSizePower = (b & 7) + 1; // Bits 0-2 img.sizeOfGlobColTbl = 1 << globColTblSizePower; // 2^(N+1), see spec img.bgColIndex = in[i + 5] & 0xFF; // 1 Byte img.pxAspectRatio = in[i + 6] & 0xFF; // 1 Byte return i + 7; } /** * @param in Raw data * @param pos Index of the extension introducer * @return Index of the first byte after this block */ static final int readTextExtension(final byte[] in, final int pos) { int i = pos + 2; // Skip extension introducer and label int subBlockSize = in[i++] & 0xFF; while (subBlockSize != 0 && i < in.length) { i += subBlockSize; subBlockSize = in[i++] & 0xFF; } return i; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/miguelemosreverte/Quantize.java
alpha/MyBox/src/main/java/thridparty/miguelemosreverte/Quantize.java
package thridparty.miguelemosreverte; /* * @(#)Quantize.java 0.90 9/19/00 Adam Doppelt */ /** * An efficient color quantization algorithm, adapted from the C++ * implementation quantize.c in <a * href="http://www.imagemagick.org/">ImageMagick</a>. The pixels for * an image are placed into an oct tree. The oct tree is reduced in * size, and the pixels from the original image are reassigned to the * nodes in the reduced tree.<p> * * Here is the copyright notice from ImageMagick: * * <pre> %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Permission is hereby granted, free of charge, to any person obtaining a % % copy of this software and associated documentation files ("ImageMagick"), % % to deal in ImageMagick without restriction, including without limitation % % the rights to use, copy, modify, merge, publish, distribute, sublicense, % % and/or sell copies of ImageMagick, and to permit persons to whom the % % ImageMagick is furnished to do so, subject to the following conditions: % % % % The above copyright notice and this permission notice shall be included in % % all copies or substantial portions of ImageMagick. % % % % The software is provided "as is", without warranty of any kind, express or % % implied, including but not limited to the warranties of merchantability, % % fitness for a particular purpose and noninfringement. In no event shall % % E. I. du Pont de Nemours and Company be liable for any claim, damages or % % other liability, whether in an action of contract, tort or otherwise, % % arising from, out of or in connection with ImageMagick or the use or other % % dealings in ImageMagick. % % % % Except as contained in this notice, the name of the E. I. du Pont de % % Nemours and Company shall not be used in advertising or otherwise to % % promote the sale, use or other dealings in ImageMagick without prior % % written authorization from the E. I. du Pont de Nemours and Company. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% </pre> * * * @version 0.90 19 Sep 2000 * @author <a href="http://www.gurge.com/amd/">Adam Doppelt</a> */ public class Quantize { /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % QQQ U U AAA N N TTTTT IIIII ZZZZZ EEEEE % % Q Q U U A A NN N T I ZZ E % % Q Q U U AAAAA N N N T I ZZZ EEEEE % % Q QQ U U A A N NN T I ZZ E % % QQQQ UUU A A N N T IIIII ZZZZZ EEEEE % % % % % % Reduce the Number of Unique Colors in an Image % % % % % % Software Design % % John Cristy % % July 1992 % % % % % % Copyright 1998 E. I. du Pont de Nemours and Company % % % % Permission is hereby granted, free of charge, to any person obtaining a % % copy of this software and associated documentation files ("ImageMagick"), % % to deal in ImageMagick without restriction, including without limitation % % the rights to use, copy, modify, merge, publish, distribute, sublicense, % % and/or sell copies of ImageMagick, and to permit persons to whom the % % ImageMagick is furnished to do so, subject to the following conditions: % % % % The above copyright notice and this permission notice shall be included in % % all copies or substantial portions of ImageMagick. % % % % The software is provided "as is", without warranty of any kind, express or % % implied, including but not limited to the warranties of merchantability, % % fitness for a particular purpose and noninfringement. In no event shall % % E. I. du Pont de Nemours and Company be liable for any claim, damages or % % other liability, whether in an action of contract, tort or otherwise, % % arising from, out of or in connection with ImageMagick or the use or other % % dealings in ImageMagick. % % % % Except as contained in this notice, the name of the E. I. du Pont de % % Nemours and Company shall not be used in advertising or otherwise to % % promote the sale, use or other dealings in ImageMagick without prior % % written authorization from the E. I. du Pont de Nemours and Company. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Realism in computer graphics typically requires using 24 bits/pixel to % generate an image. Yet many graphic display devices do not contain % the amount of memory necessary to match the spatial and color % resolution of the human eye. The QUANTIZE program takes a 24 bit % image and reduces the number of colors so it can be displayed on % raster device with less bits per pixel. In most instances, the % quantized image closely resembles the original reference image. % % A reduction of colors in an image is also desirable for image % transmission and real-time animation. % % Function Quantize takes a standard RGB or monochrome images and quantizes % them down to some fixed number of colors. % % For purposes of color allocation, an image is a set of n pixels, where % each pixel is a point in RGB space. RGB space is a 3-dimensional % vector space, and each pixel, pi, is defined by an ordered triple of % red, green, and blue coordinates, (ri, gi, bi). % % Each primary color component (red, green, or blue) represents an % intensity which varies linearly from 0 to a maximum value, cmax, which % corresponds to full saturation of that color. Color allocation is % defined over a domain consisting of the cube in RGB space with % opposite vertices at (0,0,0) and (cmax,cmax,cmax). QUANTIZE requires % cmax = 255. % % The algorithm maps this domain onto a tree in which each node % represents a cube within that domain. In the following discussion % these cubes are defined by the coordinate of two opposite vertices: % The vertex nearest the origin in RGB space and the vertex farthest % from the origin. % % The tree's root node represents the the entire domain, (0,0,0) through % (cmax,cmax,cmax). Each lower level in the tree is generated by % subdividing one node's cube into eight smaller cubes of equal size. % This corresponds to bisecting the parent cube with planes passing % through the midpoints of each edge. % % The basic algorithm operates in three phases: Classification, % Reduction, and Assignment. Classification builds a color % description tree for the image. Reduction collapses the tree until % the number it represents, at most, the number of colors desired in the % output image. Assignment defines the output image's color map and % sets each pixel's color by reclassification in the reduced tree. % Our goal is to minimize the numerical discrepancies between the original % colors and quantized colors (quantization error). % % Classification begins by initializing a color description tree of % sufficient depth to represent each possible input color in a leaf. % However, it is impractical to generate a fully-formed color % description tree in the classification phase for realistic values of % cmax. If colors components in the input image are quantized to k-bit % precision, so that cmax= 2k-1, the tree would need k levels below the % root node to allow representing each possible input color in a leaf. % This becomes prohibitive because the tree's total number of nodes is % 1 + sum(i=1,k,8k). % % A complete tree would require 19,173,961 nodes for k = 8, cmax = 255. % Therefore, to avoid building a fully populated tree, QUANTIZE: (1) % Initializes data structures for nodes only as they are needed; (2) % Chooses a maximum depth for the tree as a function of the desired % number of colors in the output image (currently log2(colormap size)). % % For each pixel in the input image, classification scans downward from % the root of the color description tree. At each level of the tree it % identifies the single node which represents a cube in RGB space % containing the pixel's color. It updates the following data for each % such node: % % n1: Number of pixels whose color is contained in the RGB cube % which this node represents; % % n2: Number of pixels whose color is not represented in a node at % lower depth in the tree; initially, n2 = 0 for all nodes except % leaves of the tree. % % Sr, Sg, Sb: Sums of the red, green, and blue component values for % all pixels not classified at a lower depth. The combination of % these sums and n2 will ultimately characterize the mean color of a % set of pixels represented by this node. % % E: The distance squared in RGB space between each pixel contained % within a node and the nodes' center. This represents the quantization % error for a node. % % Reduction repeatedly prunes the tree until the number of nodes with % n2 > 0 is less than or equal to the maximum number of colors allowed % in the output image. On any given iteration over the tree, it selects % those nodes whose E count is minimal for pruning and merges their % color statistics upward. It uses a pruning threshold, Ep, to govern % node selection as follows: % % Ep = 0 % while number of nodes with (n2 > 0) > required maximum number of colors % prune all nodes such that E <= Ep % Set Ep to minimum E in remaining nodes % % This has the effect of minimizing any quantization error when merging % two nodes together. % % When a node to be pruned has offspring, the pruning procedure invokes % itself recursively in order to prune the tree from the leaves upward. % n2, Sr, Sg, and Sb in a node being pruned are always added to the % corresponding data in that node's parent. This retains the pruned % node's color characteristics for later averaging. % % For each node, n2 pixels exist for which that node represents the % smallest volume in RGB space containing those pixel's colors. When n2 % > 0 the node will uniquely define a color in the output image. At the % beginning of reduction, n2 = 0 for all nodes except a the leaves of % the tree which represent colors present in the input image. % % The other pixel count, n1, indicates the total number of colors % within the cubic volume which the node represents. This includes n1 - % n2 pixels whose colors should be defined by nodes at a lower level in % the tree. % % Assignment generates the output image from the pruned tree. The % output image consists of two parts: (1) A color map, which is an % array of color descriptions (RGB triples) for each color present in % the output image; (2) A pixel array, which represents each pixel as % an index into the color map array. % % First, the assignment phase makes one pass over the pruned color % description tree to establish the image's color map. For each node % with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the % mean color of all pixels that classify no lower than this node. Each % of these colors becomes an entry in the color map. % % Finally, the assignment phase reclassifies each pixel in the pruned % tree to identify the deepest node containing the pixel's color. The % pixel's value in the pixel array becomes the index of this node's mean % color in the color map. % % With the permission of USC Information Sciences Institute, 4676 Admiralty % Way, Marina del Rey, California 90292, this code was adapted from module % ALCOLS written by Paul Raveling. % % The names of ISI and USC are not used in advertising or publicity % pertaining to distribution of the software without prior specific % written permission from ISI. % */ final static boolean QUICK = true; final static int MAX_RGB = 255; final static int MAX_NODES = 266817; final static int MAX_TREE_DEPTH = 8; // these are precomputed in advance static int SQUARES[]; static int SHIFT[]; static { SQUARES = new int[MAX_RGB + MAX_RGB + 1]; for (int i= -MAX_RGB; i <= MAX_RGB; i++) { SQUARES[i + MAX_RGB] = i * i; } SHIFT = new int[MAX_TREE_DEPTH + 1]; for (int i = 0; i < MAX_TREE_DEPTH + 1; ++i) { SHIFT[i] = 1 << (15 - i); } } /** * Reduce the image to the given number of colors. The pixels are * reduced in place. * @return The new color palette. */ public static int[] quantizeImage(int pixels[][], int max_colors) { Cube cube = new Cube(pixels, max_colors); cube.classification(); cube.reduction(); cube.assignment(); return cube.colormap; } static class Cube { int pixels[][]; int max_colors; int colormap[]; Node root; int depth; // counter for the number of colors in the cube. this gets // recalculated often. int colors; // counter for the number of nodes in the tree int nodes; Cube(int pixels[][], int max_colors) { this.pixels = pixels; this.max_colors = max_colors; int i = max_colors; // tree_depth = log max_colors // 4 for (depth = 1; i != 0; depth++) { i /= 4; } if (depth > 1) { --depth; } if (depth > MAX_TREE_DEPTH) { depth = MAX_TREE_DEPTH; } else if (depth < 2) { depth = 2; } root = new Node(this); } /* * Procedure Classification begins by initializing a color * description tree of sufficient depth to represent each * possible input color in a leaf. However, it is impractical * to generate a fully-formed color description tree in the * classification phase for realistic values of cmax. If * colors components in the input image are quantized to k-bit * precision, so that cmax= 2k-1, the tree would need k levels * below the root node to allow representing each possible * input color in a leaf. This becomes prohibitive because the * tree's total number of nodes is 1 + sum(i=1,k,8k). * * A complete tree would require 19,173,961 nodes for k = 8, * cmax = 255. Therefore, to avoid building a fully populated * tree, QUANTIZE: (1) Initializes data structures for nodes * only as they are needed; (2) Chooses a maximum depth for * the tree as a function of the desired number of colors in * the output image (currently log2(colormap size)). * * For each pixel in the input image, classification scans * downward from the root of the color description tree. At * each level of the tree it identifies the single node which * represents a cube in RGB space containing It updates the * following data for each such node: * * number_pixels : Number of pixels whose color is contained * in the RGB cube which this node represents; * * unique : Number of pixels whose color is not represented * in a node at lower depth in the tree; initially, n2 = 0 * for all nodes except leaves of the tree. * * total_red/green/blue : Sums of the red, green, and blue * component values for all pixels not classified at a lower * depth. The combination of these sums and n2 will * ultimately characterize the mean color of a set of pixels * represented by this node. */ void classification() { int pixels[][] = this.pixels; int width = pixels.length; int height = pixels[0].length; // convert to indexed color for (int x = width; x-- > 0; ) { for (int y = height; y-- > 0; ) { int pixel = pixels[x][y]; int red = (pixel >> 16) & 0xFF; int green = (pixel >> 8) & 0xFF; int blue = (pixel >> 0) & 0xFF; // a hard limit on the number of nodes in the tree if (nodes > MAX_NODES) { //System.out.println("pruning"); root.pruneLevel(); --depth; } // walk the tree to depth, increasing the // number_pixels count for each node Node node = root; for (int level = 1; level <= depth; ++level) { int id = (((red > node.mid_red ? 1 : 0) << 0) | ((green > node.mid_green ? 1 : 0) << 1) | ((blue > node.mid_blue ? 1 : 0) << 2)); if (node.child[id] == null) { new Node(node, id, level); } node = node.child[id]; node.number_pixels += SHIFT[level]; } ++node.unique; node.total_red += red; node.total_green += green; node.total_blue += blue; } } } /* * reduction repeatedly prunes the tree until the number of * nodes with unique > 0 is less than or equal to the maximum * number of colors allowed in the output image. * * When a node to be pruned has offspring, the pruning * procedure invokes itself recursively in order to prune the * tree from the leaves upward. The statistics of the node * being pruned are always added to the corresponding data in * that node's parent. This retains the pruned node's color * characteristics for later averaging. */ void reduction() { int threshold = 1; while (colors > max_colors) { colors = 0; threshold = root.reduce(threshold, Integer.MAX_VALUE); } } /** * The result of a closest color search. */ static class Search { int distance; int color_number; } /* * Procedure assignment generates the output image from the * pruned tree. The output image consists of two parts: (1) A * color map, which is an array of color descriptions (RGB * triples) for each color present in the output image; (2) A * pixel array, which represents each pixel as an index into * the color map array. * * First, the assignment phase makes one pass over the pruned * color description tree to establish the image's color map. * For each node with n2 > 0, it divides Sr, Sg, and Sb by n2. * This produces the mean color of all pixels that classify no * lower than this node. Each of these colors becomes an entry * in the color map. * * Finally, the assignment phase reclassifies each pixel in * the pruned tree to identify the deepest node containing the * pixel's color. The pixel's value in the pixel array becomes * the index of this node's mean color in the color map. */ void assignment() { colormap = new int[colors]; colors = 0; root.colormap(); int pixels[][] = this.pixels; int width = pixels.length; int height = pixels[0].length; Search search = new Search(); // convert to indexed color for (int x = width; x-- > 0; ) { for (int y = height; y-- > 0; ) { int pixel = pixels[x][y]; int red = (pixel >> 16) & 0xFF; int green = (pixel >> 8) & 0xFF; int blue = (pixel >> 0) & 0xFF; // walk the tree to find the cube containing that color Node node = root; for ( ; ; ) { int id = (((red > node.mid_red ? 1 : 0) << 0) | ((green > node.mid_green ? 1 : 0) << 1) | ((blue > node.mid_blue ? 1 : 0) << 2) ); if (node.child[id] == null) { break; } node = node.child[id]; } if (QUICK) { // if QUICK is set, just use that // node. Strictly speaking, this isn't // necessarily best match. pixels[x][y] = node.color_number; } else { // Find the closest color. search.distance = Integer.MAX_VALUE; node.parent.closestColor(red, green, blue, search); pixels[x][y] = search.color_number; } } } } /** * A single Node in the tree. */ static class Node { Cube cube; // parent node Node parent; // child nodes Node child[]; int nchild; // our index within our parent int id; // our level within the tree int level; // our color midpoint int mid_red; int mid_green; int mid_blue; // the pixel count for this node and all children int number_pixels; // the pixel count for this node int unique; // the sum of all pixels contained in this node int total_red; int total_green; int total_blue; // used to build the colormap int color_number; Node(Cube cube) { this.cube = cube; this.parent = this; this.child = new Node[8]; this.id = 0; this.level = 0; this.number_pixels = Integer.MAX_VALUE; this.mid_red = (MAX_RGB + 1) >> 1; this.mid_green = (MAX_RGB + 1) >> 1; this.mid_blue = (MAX_RGB + 1) >> 1; } Node(Node parent, int id, int level) { this.cube = parent.cube; this.parent = parent; this.child = new Node[8]; this.id = id; this.level = level; // add to the cube ++cube.nodes; if (level == cube.depth) { ++cube.colors; } // add to the parent ++parent.nchild; parent.child[id] = this; // figure out our midpoint int bi = (1 << (MAX_TREE_DEPTH - level)) >> 1; mid_red = parent.mid_red + ((id & 1) > 0 ? bi : -bi); mid_green = parent.mid_green + ((id & 2) > 0 ? bi : -bi); mid_blue = parent.mid_blue + ((id & 4) > 0 ? bi : -bi); } /** * Remove this child node, and make sure our parent * absorbs our pixel statistics. */ void pruneChild() { --parent.nchild; parent.unique += unique; parent.total_red += total_red; parent.total_green += total_green; parent.total_blue += total_blue; parent.child[id] = null; --cube.nodes; cube = null; parent = null; } /** * Prune the lowest layer of the tree. */ void pruneLevel() { if (nchild != 0) { for (int id = 0; id < 8; id++) { if (child[id] != null) { child[id].pruneLevel(); } } } if (level == cube.depth) { pruneChild(); } } /** * Remove any nodes that have fewer than threshold * pixels. Also, as long as we're walking the tree: * * - figure out the color with the fewest pixels * - recalculate the total number of colors in the tree */ int reduce(int threshold, int next_threshold) { if (nchild != 0) { for (int id = 0; id < 8; id++) { if (child[id] != null) { next_threshold = child[id].reduce(threshold, next_threshold); } } } if (number_pixels <= threshold) { pruneChild(); } else { if (unique != 0) { cube.colors++; } if (number_pixels < next_threshold) { next_threshold = number_pixels; } } return next_threshold; } /* * colormap traverses the color cube tree and notes each * colormap entry. A colormap entry is any node in the * color cube tree where the number of unique colors is * not zero. */ void colormap() { if (nchild != 0) { for (int id = 0; id < 8; id++) { if (child[id] != null) { child[id].colormap(); } } } if (unique != 0) { int r = ((total_red + (unique >> 1)) / unique); int g = ((total_green + (unique >> 1)) / unique); int b = ((total_blue + (unique >> 1)) / unique); cube.colormap[cube.colors] = ((( 0xFF) << 24) | ((r & 0xFF) << 16) | ((g & 0xFF) << 8) | ((b & 0xFF) << 0)); color_number = cube.colors++; } } /* ClosestColor traverses the color cube tree at a * particular node and determines which colormap entry * best represents the input color. */ void closestColor(int red, int green, int blue, Search search) { if (nchild != 0) { for (int id = 0; id < 8; id++) { if (child[id] != null) { child[id].closestColor(red, green, blue, search); } } } if (unique != 0) { int color = cube.colormap[color_number]; int distance = distance(color, red, green, blue); if (distance < search.distance) { search.distance = distance; search.color_number = color_number; } } } /** * Figure out the distance between this node and som color. */ final static int distance(int color, int r, int g, int b) { return (SQUARES[((color >> 16) & 0xFF) - r + MAX_RGB] + SQUARES[((color >> 8) & 0xFF) - g + MAX_RGB] + SQUARES[((color >> 0) & 0xFF) - b + MAX_RGB]); } public String toString() { StringBuffer buf = new StringBuffer(); if (parent == this) { buf.append("root"); } else { buf.append("node"); } buf.append(' '); buf.append(level); buf.append(" ["); buf.append(mid_red); buf.append(','); buf.append(mid_green); buf.append(','); buf.append(mid_blue); buf.append(']'); return new String(buf); } } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/miguelemosreverte/PDFUtils.java
alpha/MyBox/src/main/java/thridparty/miguelemosreverte/PDFUtils.java
package thridparty.miguelemosreverte; import java.awt.*; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; import java.awt.geom.Path2D; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; import de.erichseifert.vectorgraphics2d.Document; import de.erichseifert.vectorgraphics2d.VectorGraphics2D; import de.erichseifert.vectorgraphics2d.intermediate.CommandSequence; import de.erichseifert.vectorgraphics2d.pdf.PDFProcessor; import de.erichseifert.vectorgraphics2d.util.PageSize; import thridparty.miguelemosreverte.ImageTracer.IndexedImage; public class PDFUtils { public static String getPDFString(IndexedImage ii, HashMap<String, Float> options) { // Document setup int w = (int) (ii.width * options.get("scale")), h = (int) (ii.height * options.get("scale")); VectorGraphics2D vg2d = new VectorGraphics2D(); // creating Z-index TreeMap<Double, Integer[]> zindex = new TreeMap<Double, Integer[]>(); double label; // Layer loop for (int k = 0; k < ii.layers.size(); k++) { // Path loop for (int pcnt = 0; pcnt < ii.layers.get(k).size(); pcnt++) { // Label (Z-index key) is the startpoint of the path, linearized label = (ii.layers.get(k).get(pcnt).get(0)[2] * w) + ii.layers.get(k).get(pcnt).get(0)[1]; // Creating new list if required if (!zindex.containsKey(label)) { zindex.put(label, new Integer[2]); } // Adding layer and path number to list zindex.get(label)[0] = new Integer(k); zindex.get(label)[1] = new Integer(pcnt); }// End of path loop }// End of layer loop // Drawing // Z-index loop String thisdesc = ""; for (Map.Entry<Double, Integer[]> entry : zindex.entrySet()) { byte[] c = ii.palette[entry.getValue()[0]]; if (options.get("desc") != 0) { thisdesc = "desc=\"l " + entry.getValue()[0] + " p " + entry.getValue()[1] + "\" "; } else { thisdesc = ""; } drawPdfPath(vg2d, thisdesc, ii.layers.get(entry.getValue()[0]).get(entry.getValue()[1]), new Color(c[0] + 128, c[1] + 128, c[2] + 128), options); } // Write result PDFProcessor pdfProcessor = new PDFProcessor(false); CommandSequence commands = vg2d.getCommands(); Document doc = pdfProcessor.getDocument(commands, new PageSize(0.0, 0.0, w, h)); ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { doc.writeTo(bos); } catch (IOException e) { e.printStackTrace(); } return bos.toString(); } public static void drawPdfPath(VectorGraphics2D graphics, String desc, ArrayList<Double[]> segments, Color color, HashMap<String, Float> options) { float scale = options.get("scale"), lcpr = options.get("lcpr"), qcpr = options.get("qcpr"), roundcoords = (float) Math.floor(options.get("roundcoords")); graphics.setColor(color); final Path2D path = new Path2D.Double(); path.moveTo(segments.get(0)[1] * scale, segments.get(0)[2] * scale); if (roundcoords == -1) { for (int pcnt = 0; pcnt < segments.size(); pcnt++) { if (segments.get(pcnt)[0] == 1.0) { path.lineTo(segments.get(pcnt)[3] * scale, segments.get(pcnt)[4] * scale); } else { path.quadTo( segments.get(pcnt)[3] * scale, segments.get(pcnt)[4] * scale, segments.get(pcnt)[5] * scale, segments.get(pcnt)[6] * scale ); } } } else { for (int pcnt = 0; pcnt < segments.size(); pcnt++) { if (segments.get(pcnt)[0] == 1.0) { path.lineTo( roundtodec((float) (segments.get(pcnt)[3] * scale), roundcoords), roundtodec((float) (segments.get(pcnt)[4] * scale), roundcoords) ); } else { path.quadTo( roundtodec((float) (segments.get(pcnt)[3] * scale), roundcoords), roundtodec((float) (segments.get(pcnt)[4] * scale), roundcoords), roundtodec((float) (segments.get(pcnt)[5] * scale), roundcoords), roundtodec((float) (segments.get(pcnt)[6] * scale), roundcoords)); } } } graphics.fill(path); graphics.draw(path); // Rendering control points for (int pcnt = 0; pcnt < segments.size(); pcnt++) { if ((lcpr > 0) && (segments.get(pcnt)[0] == 1.0)) { graphics.setColor(Color.BLACK); graphics.fill(new Ellipse2D.Double(segments.get(pcnt)[3] * scale, segments.get(pcnt)[4] * scale, lcpr, lcpr)); } if ((qcpr > 0) && (segments.get(pcnt)[0] == 2.0)) { graphics.setColor(Color.CYAN); graphics.setStroke(new BasicStroke((float) (qcpr * 0.2), BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0F, (float[]) null, 0.0F)); graphics.fill(new Ellipse2D.Double(segments.get(pcnt)[3] * scale, segments.get(pcnt)[4] * scale, qcpr, qcpr)); graphics.fill(new Ellipse2D.Double(segments.get(pcnt)[5] * scale, segments.get(pcnt)[6] * scale, qcpr, qcpr)); graphics.draw(new Line2D.Double(segments.get(pcnt)[1] * scale, segments.get(pcnt)[2] * scale, segments.get(pcnt)[3] * scale, segments.get(pcnt)[4] * scale)); graphics.draw(new Line2D.Double(segments.get(pcnt)[3] * scale, segments.get(pcnt)[4] * scale, segments.get(pcnt)[5] * scale, segments.get(pcnt)[6] * scale)); }// End of quadratic control points } } public static float roundtodec(float val, float places) { return (float) (Math.round(val * Math.pow(10, places)) / Math.pow(10, places)); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/miguelemosreverte/VectorizingUtils.java
alpha/MyBox/src/main/java/thridparty/miguelemosreverte/VectorizingUtils.java
package thridparty.miguelemosreverte; import java.util.ArrayList; import java.util.HashMap; import thridparty.miguelemosreverte.ImageTracer.ImageData; import thridparty.miguelemosreverte.ImageTracer.IndexedImage; public class VectorizingUtils { //////////////////////////////////////////////////////////// // // Vectorizing functions // //////////////////////////////////////////////////////////// // 1. Color quantization repeated "cycles" times, based on K-means clustering // https://en.wikipedia.org/wiki/Color_quantization https://en.wikipedia.org/wiki/K-means_clustering public static IndexedImage colorquantization(ImageData imgd, byte[][] palette, HashMap<String, Float> options) { // Selective Gaussian blur preprocessing if (options.get("blurradius") > 0) { imgd = SelectiveBlur.blur(imgd, options.get("blurradius"), options.get("blurdelta")); } int cycles = (int) Math.floor(options.get("colorquantcycles")); // Creating indexed color array arr which has a boundary filled with -1 in every direction int[][] arr = new int[imgd.height + 2][imgd.width + 2]; for (int j = 0; j < (imgd.height + 2); j++) { arr[j][0] = -1; arr[j][imgd.width + 1] = -1; } for (int i = 0; i < (imgd.width + 2); i++) { arr[0][i] = -1; arr[imgd.height + 1][i] = -1; } int idx = 0, cd, cdl, ci, c1, c2, c3, c4; byte[][] original_palette_backup = palette; long[][] paletteacc = new long[palette.length][5]; // Repeat clustering step "cycles" times for (int cnt = 0; cnt < cycles; cnt++) { // Average colors from the second iteration if (cnt > 0) { // averaging paletteacc for palette //float ratio; for (int k = 0; k < palette.length; k++) { // averaging if (paletteacc[k][3] > 0) { palette[k][0] = (byte) (-128 + (paletteacc[k][0] / paletteacc[k][4])); palette[k][1] = (byte) (-128 + (paletteacc[k][1] / paletteacc[k][4])); palette[k][2] = (byte) (-128 + (paletteacc[k][2] / paletteacc[k][4])); palette[k][3] = (byte) (-128 + (paletteacc[k][3] / paletteacc[k][4])); } //ratio = (float)( (double)(paletteacc[k][4]) / (double)(imgd.width*imgd.height) ); /*// Randomizing a color, if there are too few pixels and there will be a new cycle if( (ratio<minratio) && (cnt<(cycles-1)) ){ palette[k][0] = (byte) (-128+Math.floor(Math.random()*255)); palette[k][1] = (byte) (-128+Math.floor(Math.random()*255)); palette[k][2] = (byte) (-128+Math.floor(Math.random()*255)); palette[k][3] = (byte) (-128+Math.floor(Math.random()*255)); }*/ }// End of palette loop }// End of Average colors from the second iteration // Reseting palette accumulator for averaging for (int i = 0; i < palette.length; i++) { paletteacc[i][0] = 0; paletteacc[i][1] = 0; paletteacc[i][2] = 0; paletteacc[i][3] = 0; paletteacc[i][4] = 0; } // loop through all pixels for (int j = 0; j < imgd.height; j++) { for (int i = 0; i < imgd.width; i++) { idx = ((j * imgd.width) + i) * 4; // find closest color from original_palette_backup by measuring (rectilinear) // color distance between this pixel and all palette colors cdl = 256 + 256 + 256 + 256; ci = 0; for (int k = 0; k < original_palette_backup.length; k++) { // In my experience, https://en.wikipedia.org/wiki/Rectilinear_distance works better than https://en.wikipedia.org/wiki/Euclidean_distance c1 = Math.abs(original_palette_backup[k][0] - imgd.data[idx]); c2 = Math.abs(original_palette_backup[k][1] - imgd.data[idx + 1]); c3 = Math.abs(original_palette_backup[k][2] - imgd.data[idx + 2]); c4 = Math.abs(original_palette_backup[k][3] - imgd.data[idx + 3]); cd = c1 + c2 + c3 + (c4 * 4); // weighted alpha seems to help images with transparency // Remember this color if this is the closest yet if (cd < cdl) { cdl = cd; ci = k; } }// End of palette loop // add to palettacc paletteacc[ci][0] += 128 + imgd.data[idx]; paletteacc[ci][1] += 128 + imgd.data[idx + 1]; paletteacc[ci][2] += 128 + imgd.data[idx + 2]; paletteacc[ci][3] += 128 + imgd.data[idx + 3]; paletteacc[ci][4]++; arr[j + 1][i + 1] = ci; }// End of i loop }// End of j loop }// End of Repeat clustering step "cycles" times return new IndexedImage(arr, original_palette_backup); }// End of colorquantization // 2. Layer separation and edge detection // Edge node types ( ▓:light or 1; ░:dark or 0 ) // 12 ░░ ▓░ ░▓ ▓▓ ░░ ▓░ ░▓ ▓▓ ░░ ▓░ ░▓ ▓▓ ░░ ▓░ ░▓ ▓▓ // 48 ░░ ░░ ░░ ░░ ░▓ ░▓ ░▓ ░▓ ▓░ ▓░ ▓░ ▓░ ▓▓ ▓▓ ▓▓ ▓▓ // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // public static int[][][] layering(IndexedImage ii) { // Creating layers for each indexed color in arr int val = 0, aw = ii.array[0].length, ah = ii.array.length, n1, n2, n3, n4, n5, n6, n7, n8; int[][][] layers = new int[ii.palette.length][ah][aw]; // Looping through all pixels and calculating edge node type for (int j = 1; j < (ah - 1); j++) { for (int i = 1; i < (aw - 1); i++) { // This pixel's indexed color val = ii.array[j][i]; // Are neighbor pixel colors the same? n1 = ii.array[j - 1][i - 1] == val ? 1 : 0; n2 = ii.array[j - 1][i] == val ? 1 : 0; n3 = ii.array[j - 1][i + 1] == val ? 1 : 0; n4 = ii.array[j][i - 1] == val ? 1 : 0; n5 = ii.array[j][i + 1] == val ? 1 : 0; n6 = ii.array[j + 1][i - 1] == val ? 1 : 0; n7 = ii.array[j + 1][i] == val ? 1 : 0; n8 = ii.array[j + 1][i + 1] == val ? 1 : 0; // this pixel"s type and looking back on previous pixels layers[val][j + 1][i + 1] = 1 + (n5 * 2) + (n8 * 4) + (n7 * 8); if (n4 == 0) { layers[val][j + 1][i] = 0 + 2 + (n7 * 4) + (n6 * 8); } if (n2 == 0) { layers[val][j][i + 1] = 0 + (n3 * 2) + (n5 * 4) + 8; } if (n1 == 0) { layers[val][j][i] = 0 + (n2 * 2) + 4 + (n4 * 8); } }// End of i loop }// End of j loop return layers; }// End of layering() // Lookup tables for pathscan static byte[] pathscan_dir_lookup = {0, 0, 3, 0, 1, 0, 3, 0, 0, 3, 3, 1, 0, 3, 0, 0}; static boolean[] pathscan_holepath_lookup = {false, false, false, false, false, false, false, true, false, false, false, true, false, true, true, false}; // pathscan_combined_lookup[ arr[py][px] ][ dir ] = [nextarrpypx, nextdir, deltapx, deltapy]; static byte[][][] pathscan_combined_lookup = { {{-1, -1, -1, -1}, {-1, -1, -1, -1}, {-1, -1, -1, -1}, {-1, -1, -1, -1}},// arr[py][px]==0 is invalid {{0, 1, 0, -1}, {-1, -1, -1, -1}, {-1, -1, -1, -1}, {0, 2, -1, 0}}, {{-1, -1, -1, -1}, {-1, -1, -1, -1}, {0, 1, 0, -1}, {0, 0, 1, 0}}, {{0, 0, 1, 0}, {-1, -1, -1, -1}, {0, 2, -1, 0}, {-1, -1, -1, -1}}, {{-1, -1, -1, -1}, {0, 0, 1, 0}, {0, 3, 0, 1}, {-1, -1, -1, -1}}, {{13, 3, 0, 1}, {13, 2, -1, 0}, {7, 1, 0, -1}, {7, 0, 1, 0}}, {{-1, -1, -1, -1}, {0, 1, 0, -1}, {-1, -1, -1, -1}, {0, 3, 0, 1}}, {{0, 3, 0, 1}, {0, 2, -1, 0}, {-1, -1, -1, -1}, {-1, -1, -1, -1}}, {{0, 3, 0, 1}, {0, 2, -1, 0}, {-1, -1, -1, -1}, {-1, -1, -1, -1}}, {{-1, -1, -1, -1}, {0, 1, 0, -1}, {-1, -1, -1, -1}, {0, 3, 0, 1}}, {{11, 1, 0, -1}, {14, 0, 1, 0}, {14, 3, 0, 1}, {11, 2, -1, 0}}, {{-1, -1, -1, -1}, {0, 0, 1, 0}, {0, 3, 0, 1}, {-1, -1, -1, -1}}, {{0, 0, 1, 0}, {-1, -1, -1, -1}, {0, 2, -1, 0}, {-1, -1, -1, -1}}, {{-1, -1, -1, -1}, {-1, -1, -1, -1}, {0, 1, 0, -1}, {0, 0, 1, 0}}, {{0, 1, 0, -1}, {-1, -1, -1, -1}, {-1, -1, -1, -1}, {0, 2, -1, 0}}, {{-1, -1, -1, -1}, {-1, -1, -1, -1}, {-1, -1, -1, -1}, {-1, -1, -1, -1}}// arr[py][px]==15 is invalid }; // 3. Walking through an edge node array, discarding edge node types 0 and 15 and creating paths from the rest. // Walk directions (dir): 0 > ; 1 ^ ; 2 < ; 3 v // Edge node types ( ▓:light or 1; ░:dark or 0 ) // ░░ ▓░ ░▓ ▓▓ ░░ ▓░ ░▓ ▓▓ ░░ ▓░ ░▓ ▓▓ ░░ ▓░ ░▓ ▓▓ // ░░ ░░ ░░ ░░ ░▓ ░▓ ░▓ ░▓ ▓░ ▓░ ▓░ ▓░ ▓▓ ▓▓ ▓▓ ▓▓ // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // public static ArrayList<ArrayList<Integer[]>> pathscan(int[][] arr, float pathomit) { ArrayList<ArrayList<Integer[]>> paths = new ArrayList<ArrayList<Integer[]>>(); ArrayList<Integer[]> thispath; int px = 0, py = 0, w = arr[0].length, h = arr.length, dir = 0; boolean pathfinished = true, holepath = false; byte[] lookuprow; for (int j = 0; j < h; j++) { for (int i = 0; i < w; i++) { if ((arr[j][i] != 0) && (arr[j][i] != 15)) { // Init px = i; py = j; paths.add(new ArrayList<Integer[]>()); thispath = paths.get(paths.size() - 1); pathfinished = false; // fill paths will be drawn, but hole paths are also required to remove unnecessary edge nodes dir = pathscan_dir_lookup[arr[py][px]]; holepath = pathscan_holepath_lookup[arr[py][px]]; // Path points loop while (!pathfinished) { // New path point thispath.add(new Integer[3]); thispath.get(thispath.size() - 1)[0] = px - 1; thispath.get(thispath.size() - 1)[1] = py - 1; thispath.get(thispath.size() - 1)[2] = arr[py][px]; // Next: look up the replacement, direction and coordinate changes = clear this cell, turn if required, walk forward lookuprow = pathscan_combined_lookup[arr[py][px]][dir]; arr[py][px] = lookuprow[0]; dir = lookuprow[1]; px += lookuprow[2]; py += lookuprow[3]; // Close path if (((px - 1) == thispath.get(0)[0]) && ((py - 1) == thispath.get(0)[1])) { pathfinished = true; // Discarding 'hole' type paths and paths shorter than pathomit if ((holepath) || (thispath.size() < pathomit)) { paths.remove(thispath); } } }// End of Path points loop }// End of Follow path }// End of i loop }// End of j loop return paths; }// End of pathscan() // 3. Batch pathscan public static ArrayList<ArrayList<ArrayList<Integer[]>>> batchpathscan(int[][][] layers, float pathomit) { ArrayList<ArrayList<ArrayList<Integer[]>>> bpaths = new ArrayList<ArrayList<ArrayList<Integer[]>>>(); for (int[][] layer : layers) { bpaths.add(pathscan(layer, pathomit)); } return bpaths; } // 4. interpolating between path points for nodes with 8 directions ( East, SouthEast, S, SW, W, NW, N, NE ) public static ArrayList<ArrayList<Double[]>> internodes(ArrayList<ArrayList<Integer[]>> paths) { ArrayList<ArrayList<Double[]>> ins = new ArrayList<ArrayList<Double[]>>(); ArrayList<Double[]> thisinp; Double[] thispoint, nextpoint = new Double[2]; Integer[] pp1, pp2, pp3; int palen = 0, nextidx = 0, nextidx2 = 0; // paths loop for (int pacnt = 0; pacnt < paths.size(); pacnt++) { ins.add(new ArrayList<Double[]>()); thisinp = ins.get(ins.size() - 1); palen = paths.get(pacnt).size(); // pathpoints loop for (int pcnt = 0; pcnt < palen; pcnt++) { // interpolate between two path points nextidx = (pcnt + 1) % palen; nextidx2 = (pcnt + 2) % palen; thisinp.add(new Double[3]); thispoint = thisinp.get(thisinp.size() - 1); pp1 = paths.get(pacnt).get(pcnt); pp2 = paths.get(pacnt).get(nextidx); pp3 = paths.get(pacnt).get(nextidx2); thispoint[0] = (pp1[0] + pp2[0]) / 2.0; thispoint[1] = (pp1[1] + pp2[1]) / 2.0; nextpoint[0] = (pp2[0] + pp3[0]) / 2.0; nextpoint[1] = (pp2[1] + pp3[1]) / 2.0; // line segment direction to the next point if (thispoint[0] < nextpoint[0]) { if (thispoint[1] < nextpoint[1]) { thispoint[2] = 1.0; }// SouthEast else if (thispoint[1] > nextpoint[1]) { thispoint[2] = 7.0; }// NE else { thispoint[2] = 0.0; } // E } else if (thispoint[0] > nextpoint[0]) { if (thispoint[1] < nextpoint[1]) { thispoint[2] = 3.0; }// SW else if (thispoint[1] > nextpoint[1]) { thispoint[2] = 5.0; }// NW else { thispoint[2] = 4.0; }// W } else { if (thispoint[1] < nextpoint[1]) { thispoint[2] = 2.0; }// S else if (thispoint[1] > nextpoint[1]) { thispoint[2] = 6.0; }// N else { thispoint[2] = 8.0; }// center, this should not happen } }// End of pathpoints loop }// End of paths loop return ins; }// End of internodes() // 4. Batch interpollation public static ArrayList<ArrayList<ArrayList<Double[]>>> batchinternodes(ArrayList<ArrayList<ArrayList<Integer[]>>> bpaths) { ArrayList<ArrayList<ArrayList<Double[]>>> binternodes = new ArrayList<ArrayList<ArrayList<Double[]>>>(); for (int k = 0; k < bpaths.size(); k++) { binternodes.add(internodes(bpaths.get(k))); } return binternodes; } // 5. tracepath() : recursively trying to fit straight and quadratic spline segments on the 8 direction internode path // 5.1. Find sequences of points with only 2 segment types // 5.2. Fit a straight line on the sequence // 5.3. If the straight line fails (an error>ltreshold), find the point with the biggest error // 5.4. Fit a quadratic spline through errorpoint (project this to get controlpoint), then measure errors on every point in the sequence // 5.5. If the spline fails (an error>qtreshold), find the point with the biggest error, set splitpoint = (fitting point + errorpoint)/2 // 5.6. Split sequence and recursively apply 5.2. - 5.7. to startpoint-splitpoint and splitpoint-endpoint sequences // 5.7. TODO? If splitpoint-endpoint is a spline, try to add new points from the next sequence // This returns an SVG Path segment as a double[7] where // segment[0] ==1.0 linear ==2.0 quadratic interpolation // segment[1] , segment[2] : x1 , y1 // segment[3] , segment[4] : x2 , y2 ; middle point of Q curve, endpoint of L line // segment[5] , segment[6] : x3 , y3 for Q curve, should be 0.0 , 0.0 for L line // // path type is discarded, no check for path.size < 3 , which should not happen public static ArrayList<Double[]> tracepath(ArrayList<Double[]> path, float ltreshold, float qtreshold) { int pcnt = 0, seqend = 0; double segtype1, segtype2; ArrayList<Double[]> smp = new ArrayList<Double[]>(); //Double [] thissegment; int pathlength = path.size(); while (pcnt < pathlength) { // 5.1. Find sequences of points with only 2 segment types segtype1 = path.get(pcnt)[2]; segtype2 = -1; seqend = pcnt + 1; while (((path.get(seqend)[2] == segtype1) || (path.get(seqend)[2] == segtype2) || (segtype2 == -1)) && (seqend < (pathlength - 1))) { if ((path.get(seqend)[2] != segtype1) && (segtype2 == -1)) { segtype2 = path.get(seqend)[2]; } seqend++; } if (seqend == (pathlength - 1)) { seqend = 0; } // 5.2. - 5.6. Split sequence and recursively apply 5.2. - 5.6. to startpoint-splitpoint and splitpoint-endpoint sequences smp.addAll(fitseq(path, ltreshold, qtreshold, pcnt, seqend)); // 5.7. TODO? If splitpoint-endpoint is a spline, try to add new points from the next sequence // forward pcnt; if (seqend > 0) { pcnt = seqend; } else { pcnt = pathlength; } }// End of pcnt loop return smp; }// End of tracepath() // 5.2. - 5.6. recursively fitting a straight or quadratic line segment on this sequence of path nodes, // called from tracepath() public static ArrayList<Double[]> fitseq(ArrayList<Double[]> path, float ltreshold, float qtreshold, int seqstart, int seqend) { ArrayList<Double[]> segment = new ArrayList<Double[]>(); Double[] thissegment; int pathlength = path.size(); // return if invalid seqend if ((seqend > pathlength) || (seqend < 0)) { return segment; } int errorpoint = seqstart; boolean curvepass = true; double px, py, dist2, errorval = 0; double tl = (seqend - seqstart); if (tl < 0) { tl += pathlength; } double vx = (path.get(seqend)[0] - path.get(seqstart)[0]) / tl, vy = (path.get(seqend)[1] - path.get(seqstart)[1]) / tl; // 5.2. Fit a straight line on the sequence int pcnt = (seqstart + 1) % pathlength; double pl; while (pcnt != seqend) { pl = pcnt - seqstart; if (pl < 0) { pl += pathlength; } px = path.get(seqstart)[0] + (vx * pl); py = path.get(seqstart)[1] + (vy * pl); dist2 = ((path.get(pcnt)[0] - px) * (path.get(pcnt)[0] - px)) + ((path.get(pcnt)[1] - py) * (path.get(pcnt)[1] - py)); if (dist2 > ltreshold) { curvepass = false; } if (dist2 > errorval) { errorpoint = pcnt; errorval = dist2; } pcnt = (pcnt + 1) % pathlength; } // return straight line if fits if (curvepass) { segment.add(new Double[7]); thissegment = segment.get(segment.size() - 1); thissegment[0] = 1.0; thissegment[1] = path.get(seqstart)[0]; thissegment[2] = path.get(seqstart)[1]; thissegment[3] = path.get(seqend)[0]; thissegment[4] = path.get(seqend)[1]; thissegment[5] = 0.0; thissegment[6] = 0.0; return segment; } // 5.3. If the straight line fails (an error>ltreshold), find the point with the biggest error int fitpoint = errorpoint; curvepass = true; errorval = 0; // 5.4. Fit a quadratic spline through this point, measure errors on every point in the sequence // helpers and projecting to get control point double t = (fitpoint - seqstart) / tl, t1 = (1.0 - t) * (1.0 - t), t2 = 2.0 * (1.0 - t) * t, t3 = t * t; double cpx = (((t1 * path.get(seqstart)[0]) + (t3 * path.get(seqend)[0])) - path.get(fitpoint)[0]) / -t2, cpy = (((t1 * path.get(seqstart)[1]) + (t3 * path.get(seqend)[1])) - path.get(fitpoint)[1]) / -t2; // Check every point pcnt = seqstart + 1; while (pcnt != seqend) { t = (pcnt - seqstart) / tl; t1 = (1.0 - t) * (1.0 - t); t2 = 2.0 * (1.0 - t) * t; t3 = t * t; px = (t1 * path.get(seqstart)[0]) + (t2 * cpx) + (t3 * path.get(seqend)[0]); py = (t1 * path.get(seqstart)[1]) + (t2 * cpy) + (t3 * path.get(seqend)[1]); dist2 = ((path.get(pcnt)[0] - px) * (path.get(pcnt)[0] - px)) + ((path.get(pcnt)[1] - py) * (path.get(pcnt)[1] - py)); if (dist2 > qtreshold) { curvepass = false; } if (dist2 > errorval) { errorpoint = pcnt; errorval = dist2; } pcnt = (pcnt + 1) % pathlength; } // return spline if fits if (curvepass) { segment.add(new Double[7]); thissegment = segment.get(segment.size() - 1); thissegment[0] = 2.0; thissegment[1] = path.get(seqstart)[0]; thissegment[2] = path.get(seqstart)[1]; thissegment[3] = cpx; thissegment[4] = cpy; thissegment[5] = path.get(seqend)[0]; thissegment[6] = path.get(seqend)[1]; return segment; } // 5.5. If the spline fails (an error>qtreshold), find the point with the biggest error, // set splitpoint = (fitting point + errorpoint)/2 int splitpoint = (fitpoint + errorpoint) / 2; // 5.6. Split sequence and recursively apply 5.2. - 5.6. to startpoint-splitpoint and splitpoint-endpoint sequences segment = fitseq(path, ltreshold, qtreshold, seqstart, splitpoint); segment.addAll(fitseq(path, ltreshold, qtreshold, splitpoint, seqend)); return segment; }// End of fitseq() // 5. Batch tracing paths public static ArrayList<ArrayList<Double[]>> batchtracepaths(ArrayList<ArrayList<Double[]>> internodepaths, float ltres, float qtres) { ArrayList<ArrayList<Double[]>> btracedpaths = new ArrayList<ArrayList<Double[]>>(); for (int k = 0; k < internodepaths.size(); k++) { btracedpaths.add(tracepath(internodepaths.get(k), ltres, qtres)); } return btracedpaths; } // 5. Batch tracing layers public static ArrayList<ArrayList<ArrayList<Double[]>>> batchtracelayers(ArrayList<ArrayList<ArrayList<Double[]>>> binternodes, float ltres, float qtres) { ArrayList<ArrayList<ArrayList<Double[]>>> btbis = new ArrayList<ArrayList<ArrayList<Double[]>>>(); for (int k = 0; k < binternodes.size(); k++) { btbis.add(batchtracepaths(binternodes.get(k), ltres, qtres)); } return btbis; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/miguelemosreverte/ImageTracer.java
alpha/MyBox/src/main/java/thridparty/miguelemosreverte/ImageTracer.java
// https://github.com/miguelemosreverte/imagetracerjava package thridparty.miguelemosreverte; import java.awt.Color; import java.awt.image.BufferedImage; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.HashMap; import javax.imageio.ImageIO; public class ImageTracer { public static String versionnumber = "1.1.3"; private static int[] rawdata; public ImageTracer() { } public static void main(String[] args) { try { if (args.length < 1) { System.out.println("ERROR: there's no input filename. Basic usage: \r\n\r\njava -jar ImageTracer.jar <filename>" + "\r\n\r\nor\r\n\r\njava -jar ImageTracer.jar help"); //System.out.println("Starting anyway with default value for testing purposes."); //saveString("output.svg",imageToSVG("input.jpg",new HashMap<String,Float>())); } else if (arraycontains(args, "help") > -1) { System.out.println("Example usage:\r\n\r\njava -jar ImageTracer.jar <filename> outfilename test.svg " + "ltres 1 qtres 1 pathomit 1 numberofcolors 128 colorquantcycles 15 " + "scale 1 roundcoords 1 lcpr 0 qcpr 0 desc 1 viewbox 0 blurradius 0 blurdelta 20 \r\n" + "\r\nOnly <filename> is mandatory, if some of the other optional parameters are missing, they will be set to these defaults. " + "\r\nWarning: if outfilename is not specified, then <filename>.svg will be overwritten." + "\r\nSee https://github.com/jankovicsandras/imagetracerjava for details. \r\nThis is version " + versionnumber); } else { // Parameter parsing String outfilename = args[0]; HashMap<String, Float> options = new HashMap<String, Float>(); String[] parameternames = {"ltres", "qtres", "pathomit", "numberofcolors", "colorquantcycles", "format", "scale", "roundcoords", "lcpr", "qcpr", "desc", "viewbox", "outfilename", "blurammount"}; int j = -1; float f = -1; for (String parametername : parameternames) { j = arraycontains(args, parametername); if (j > -1) { if (parametername == "outfilename") { if (j < (args.length - 1)) { outfilename = args[j + 1]; } } else { f = parsenext(args, j); if (f > -1) { options.put(parametername, new Float(f)); } } } }// End of parameternames loop options = checkoptions(options); // Loading image, tracing, rendering, saving output file if (options.get("format") == 0) { saveString(outfilename + ".svg", imageToSVG(args[0], options)); } else if (options.get("format") == 1) { saveString(outfilename + ".pdf", imageToPDF(args[0], options)); } else { System.out.println("ERROR: Incorrect output format. Options: 0 - SVG, 1 - PDF"); } }// End of parameter parsing and processing } catch (Exception e) { e.printStackTrace(); } }// End of main() public static int arraycontains(String[] arr, String str) { for (int j = 0; j < arr.length; j++) { if (arr[j].toLowerCase().equals(str)) { return j; } } return -1; } public static float parsenext(String[] arr, int i) { if (i < (arr.length - 1)) { try { return Float.parseFloat(arr[i + 1]); } catch (Exception e) { } } return -1; } // Container for the color-indexed image before and tracedata after vectorizing public static class IndexedImage { public int width, height; public int[][] array; // array[x][y] of palette colors public byte[][] palette;// array[palettelength][4] RGBA color palette public ArrayList<ArrayList<ArrayList<Double[]>>> layers;// tracedata public IndexedImage(int[][] marray, byte[][] mpalette) { array = marray; palette = mpalette; width = marray[0].length - 2; height = marray.length - 2;// Color quantization adds +2 to the original width and height } } // https://developer.mozilla.org/en-US/docs/Web/API/ImageData public static class ImageData { public int width, height; public byte[] data; // raw byte data: R G B A R G B A ... public ImageData(int mwidth, int mheight, byte[] mdata) { width = mwidth; height = mheight; data = mdata; } } // Saving a String as a file public static void saveString(String filename, String str) throws Exception { File file = new File(filename); // if file doesnt exists, then create it if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(str); bw.close(); } // Loading a file to ImageData, ARGB byte order public static ImageData loadImageData(String filename, HashMap<String, Float> options) throws Exception { BufferedImage image = ImageIO.read(new File(filename)); return loadImageData(image); } public static ImageData loadImageData(BufferedImage image) throws Exception { int width = image.getWidth(); int height = image.getHeight(); rawdata = image.getRGB(0, 0, width, height, null, 0, width); byte[] data = new byte[rawdata.length * 4]; for (int i = 0; i < rawdata.length; i++) { data[(i * 4) + 3] = bytetrans((byte) (rawdata[i] >>> 24)); data[i * 4] = bytetrans((byte) (rawdata[i] >>> 16)); data[(i * 4) + 1] = bytetrans((byte) (rawdata[i] >>> 8)); data[(i * 4) + 2] = bytetrans((byte) (rawdata[i])); } return new ImageData(width, height, data); } // The bitshift method in loadImageData creates signed bytes where -1 -> 255 unsigned ; -128 -> 128 unsigned ; // 127 -> 127 unsigned ; 0 -> 0 unsigned ; These will be converted to -128 (representing 0 unsigned) ... // 127 (representing 255 unsigned) and tosvgcolorstr will add +128 to create RGB values 0..255 public static byte bytetrans(byte b) { if (b < 0) { return (byte) (b + 128); } else { return (byte) (b - 128); } } public static byte[][] getPalette(BufferedImage image, HashMap<String, Float> options) { int numberofcolors = options.get("numberofcolors").intValue(); int[][] pixels = new int[image.getWidth()][image.getHeight()]; for (int i = 0; i < image.getWidth(); i++) { for (int j = 0; j < image.getHeight(); j++) { pixels[i][j] = image.getRGB(i, j); } } int[] palette = Quantize.quantizeImage(pixels, numberofcolors); byte[][] bytepalette = new byte[numberofcolors][4]; for (int i = 0; i < palette.length; i++) { Color c = new Color(palette[i]); bytepalette[i][0] = (byte) c.getRed(); bytepalette[i][1] = (byte) c.getGreen(); bytepalette[i][2] = (byte) c.getBlue(); bytepalette[i][3] = 0; } return bytepalette; } //////////////////////////////////////////////////////////// // // User friendly functions // //////////////////////////////////////////////////////////// // Loading an image from a file, tracing when loaded, then returning the SVG String public static String imageToSVG(String filename, HashMap<String, Float> options) throws Exception { System.out.println(options.toString()); ImageData imgd = loadImageData(filename, options); return imagedataToSVG(imgd, options, getPalette(ImageIO.read(new File(filename)), options)); }// End of imageToSVG() // Tracing ImageData, then returning the SVG String public static String imagedataToSVG(ImageData imgd, HashMap<String, Float> options, byte[][] palette) { IndexedImage ii = imagedataToTracedata(imgd, options, palette); return SVGUtils.getsvgstring(ii, options); }// End of imagedataToSVG() // Loading an image from a file, tracing when loaded, then returning PDF String public static String imageToPDF(String filename, HashMap<String, Float> options) throws Exception { ImageData imgd = loadImageData(filename, options); IndexedImage ii = imagedataToTracedata(imgd, options, getPalette(ImageIO.read(new File(filename)), options)); return PDFUtils.getPDFString(ii, options); }// End of imagedataToSVG() // Loading an image from a file, tracing when loaded, then returning IndexedImage with tracedata in layers public IndexedImage imageToTracedata(String filename, HashMap<String, Float> options, byte[][] palette) throws Exception { ImageData imgd = loadImageData(filename, options); return imagedataToTracedata(imgd, options, palette); }// End of imageToTracedata() public IndexedImage imageToTracedata(BufferedImage image, HashMap<String, Float> options, byte[][] palette) throws Exception { ImageData imgd = loadImageData(image); return imagedataToTracedata(imgd, options, palette); }// End of imageToTracedata() // Tracing ImageData, then returning IndexedImage with tracedata in layers public static IndexedImage imagedataToTracedata(ImageData imgd, HashMap<String, Float> options, byte[][] palette) { // 1. Color quantization IndexedImage ii = VectorizingUtils.colorquantization(imgd, palette, options); // 2. Layer separation and edge detection int[][][] rawlayers = VectorizingUtils.layering(ii); // 3. Batch pathscan ArrayList<ArrayList<ArrayList<Integer[]>>> bps = VectorizingUtils.batchpathscan(rawlayers, (int) (Math.floor(options.get("pathomit")))); // 4. Batch interpollation ArrayList<ArrayList<ArrayList<Double[]>>> bis = VectorizingUtils.batchinternodes(bps); // 5. Batch tracing ii.layers = VectorizingUtils.batchtracelayers(bis, options.get("ltres"), options.get("qtres")); return ii; }// End of imagedataToTracedata() // creating options object, setting defaults for missing values public static HashMap<String, Float> checkoptions(HashMap<String, Float> options) { if (options == null) { options = new HashMap<String, Float>(); } // Tracing if (!options.containsKey("ltres")) { options.put("ltres", 10f); } if (!options.containsKey("qtres")) { options.put("qtres", 10f); } if (!options.containsKey("pathomit")) { options.put("pathomit", 1f); } // Color quantization if (!options.containsKey("numberofcolors")) { options.put("numberofcolors", 128f); } if (!options.containsKey("colorquantcycles")) { options.put("colorquantcycles", 15f); } // Output rendering if (!options.containsKey("format")) { options.put("format", 0f); } if (!options.containsKey("scale")) { options.put("scale", 1f); } if (!options.containsKey("roundcoords")) { options.put("roundcoords", 1f); } if (!options.containsKey("lcpr")) { options.put("lcpr", 0f); } if (!options.containsKey("qcpr")) { options.put("qcpr", 0f); } if (!options.containsKey("desc")) { options.put("desc", 1f); } if (!options.containsKey("viewbox")) { options.put("viewbox", 0f); } // Blur if (!options.containsKey("blurradius")) { options.put("blurradius", 5f); } if (!options.containsKey("blurdelta")) { options.put("blurdelta", 50f); } return options; }// End of checkoptions() }// End of ImageTracer class
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/miguelemosreverte/SelectiveBlur.java
alpha/MyBox/src/main/java/thridparty/miguelemosreverte/SelectiveBlur.java
package thridparty.miguelemosreverte; import thridparty.miguelemosreverte.ImageTracer.ImageData; public class SelectiveBlur { // Gaussian kernels for blur static double[][] gks = {{0.27901, 0.44198, 0.27901}, {0.135336, 0.228569, 0.272192, 0.228569, 0.135336}, {0.086776, 0.136394, 0.178908, 0.195843, 0.178908, 0.136394, 0.086776}, {0.063327, 0.093095, 0.122589, 0.144599, 0.152781, 0.144599, 0.122589, 0.093095, 0.063327}, {0.049692, 0.069304, 0.089767, 0.107988, 0.120651, 0.125194, 0.120651, 0.107988, 0.089767, 0.069304, 0.049692}}; // Selective Gaussian blur for preprocessing static ImageData blur(ImageData imgd, float rad, float del) { int i, j, k, d, idx; double racc, gacc, bacc, aacc, wacc; ImageData imgd2 = new ImageData(imgd.width, imgd.height, new byte[imgd.width * imgd.height * 4]); // radius and delta limits, this kernel int radius = (int) Math.floor(rad); if (radius < 1) { return imgd; } if (radius > 5) { radius = 5; } int delta = (int) Math.abs(del); if (delta > 1024) { delta = 1024; } double[] thisgk = gks[radius - 1]; // loop through all pixels, horizontal blur for (j = 0; j < imgd.height; j++) { for (i = 0; i < imgd.width; i++) { racc = 0; gacc = 0; bacc = 0; aacc = 0; wacc = 0; // gauss kernel loop for (k = -radius; k < (radius + 1); k++) { // add weighted color values if (((i + k) > 0) && ((i + k) < imgd.width)) { idx = ((j * imgd.width) + i + k) * 4; racc += imgd.data[idx] * thisgk[k + radius]; gacc += imgd.data[idx + 1] * thisgk[k + radius]; bacc += imgd.data[idx + 2] * thisgk[k + radius]; aacc += imgd.data[idx + 3] * thisgk[k + radius]; wacc += thisgk[k + radius]; } } // The new pixel idx = ((j * imgd.width) + i) * 4; imgd2.data[idx] = (byte) Math.floor(racc / wacc); imgd2.data[idx + 1] = (byte) Math.floor(gacc / wacc); imgd2.data[idx + 2] = (byte) Math.floor(bacc / wacc); imgd2.data[idx + 3] = (byte) Math.floor(aacc / wacc); }// End of width loop }// End of horizontal blur // copying the half blurred imgd2 byte[] himgd = imgd2.data.clone(); // loop through all pixels, vertical blur for (j = 0; j < imgd.height; j++) { for (i = 0; i < imgd.width; i++) { racc = 0; gacc = 0; bacc = 0; aacc = 0; wacc = 0; // gauss kernel loop for (k = -radius; k < (radius + 1); k++) { // add weighted color values if (((j + k) > 0) && ((j + k) < imgd.height)) { idx = (((j + k) * imgd.width) + i) * 4; racc += himgd[idx] * thisgk[k + radius]; gacc += himgd[idx + 1] * thisgk[k + radius]; bacc += himgd[idx + 2] * thisgk[k + radius]; aacc += himgd[idx + 3] * thisgk[k + radius]; wacc += thisgk[k + radius]; } } // The new pixel idx = ((j * imgd.width) + i) * 4; imgd2.data[idx] = (byte) Math.floor(racc / wacc); imgd2.data[idx + 1] = (byte) Math.floor(gacc / wacc); imgd2.data[idx + 2] = (byte) Math.floor(bacc / wacc); imgd2.data[idx + 3] = (byte) Math.floor(aacc / wacc); }// End of width loop }// End of vertical blur // Selective blur: loop through all pixels for (j = 0; j < imgd.height; j++) { for (i = 0; i < imgd.width; i++) { idx = ((j * imgd.width) + i) * 4; // d is the difference between the blurred and the original pixel d = Math.abs(imgd2.data[idx] - imgd.data[idx]) + Math.abs(imgd2.data[idx + 1] - imgd.data[idx + 1]) + Math.abs(imgd2.data[idx + 2] - imgd.data[idx + 2]) + Math.abs(imgd2.data[idx + 3] - imgd.data[idx + 3]); // selective blur: if d>delta, put the original pixel back if (d > delta) { imgd2.data[idx] = imgd.data[idx]; imgd2.data[idx + 1] = imgd.data[idx + 1]; imgd2.data[idx + 2] = imgd.data[idx + 2]; imgd2.data[idx + 3] = imgd.data[idx + 3]; } } }// End of Selective blur return imgd2; }// End of blur() }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/miguelemosreverte/SVGUtils.java
alpha/MyBox/src/main/java/thridparty/miguelemosreverte/SVGUtils.java
package thridparty.miguelemosreverte; import java.util.ArrayList; import java.util.HashMap; import java.util.Map.Entry; import java.util.TreeMap; import thridparty.miguelemosreverte.ImageTracer.IndexedImage; public class SVGUtils { //////////////////////////////////////////////////////////// // // SVG Drawing functions // //////////////////////////////////////////////////////////// public static float roundtodec(float val, float places) { return (float) (Math.round(val * Math.pow(10, places)) / Math.pow(10, places)); } // Getting SVG path element string from a traced path public static void svgpathstring(StringBuilder sb, String desc, ArrayList<Double[]> segments, String colorstr, HashMap<String, Float> options) { float scale = options.get("scale"), lcpr = options.get("lcpr"), qcpr = options.get("qcpr"), roundcoords = (float) Math.floor(options.get("roundcoords")); // Path sb.append("<path ").append(desc).append(colorstr).append("d=\"").append("M ").append(segments.get(0)[1] * scale).append(" ").append(segments.get(0)[2] * scale).append(" "); if (roundcoords == -1) { for (int pcnt = 0; pcnt < segments.size(); pcnt++) { if (segments.get(pcnt)[0] == 1.0) { sb.append("L ").append(segments.get(pcnt)[3] * scale).append(" ").append(segments.get(pcnt)[4] * scale).append(" "); } else { sb.append("Q ").append(segments.get(pcnt)[3] * scale).append(" ").append(segments.get(pcnt)[4] * scale).append(" ").append(segments.get(pcnt)[5] * scale).append(" ").append(segments.get(pcnt)[6] * scale).append(" "); } } } else { for (int pcnt = 0; pcnt < segments.size(); pcnt++) { if (segments.get(pcnt)[0] == 1.0) { sb.append("L ").append(roundtodec((float) (segments.get(pcnt)[3] * scale), roundcoords)).append(" ") .append(roundtodec((float) (segments.get(pcnt)[4] * scale), roundcoords)).append(" "); } else { sb.append("Q ").append(roundtodec((float) (segments.get(pcnt)[3] * scale), roundcoords)).append(" ") .append(roundtodec((float) (segments.get(pcnt)[4] * scale), roundcoords)).append(" ") .append(roundtodec((float) (segments.get(pcnt)[5] * scale), roundcoords)).append(" ") .append(roundtodec((float) (segments.get(pcnt)[6] * scale), roundcoords)).append(" "); } } }// End of roundcoords check sb.append("Z\" />"); // Rendering control points for (int pcnt = 0; pcnt < segments.size(); pcnt++) { if ((lcpr > 0) && (segments.get(pcnt)[0] == 1.0)) { sb.append("<circle cx=\"").append(segments.get(pcnt)[3] * scale).append("\" cy=\"").append(segments.get(pcnt)[4] * scale).append("\" r=\"").append(lcpr).append("\" fill=\"white\" stroke-width=\"").append(lcpr * 0.2).append("\" stroke=\"black\" />"); } if ((qcpr > 0) && (segments.get(pcnt)[0] == 2.0)) { sb.append("<circle cx=\"").append(segments.get(pcnt)[3] * scale).append("\" cy=\"").append(segments.get(pcnt)[4] * scale).append("\" r=\"").append(qcpr).append("\" fill=\"cyan\" stroke-width=\"").append(qcpr * 0.2).append("\" stroke=\"black\" />"); sb.append("<circle cx=\"").append(segments.get(pcnt)[5] * scale).append("\" cy=\"").append(segments.get(pcnt)[6] * scale).append("\" r=\"").append(qcpr).append("\" fill=\"white\" stroke-width=\"").append(qcpr * 0.2).append("\" stroke=\"black\" />"); sb.append("<line x1=\"").append(segments.get(pcnt)[1] * scale).append("\" y1=\"").append(segments.get(pcnt)[2] * scale).append("\" x2=\"").append(segments.get(pcnt)[3] * scale).append("\" y2=\"").append(segments.get(pcnt)[4] * scale).append("\" stroke-width=\"").append(qcpr * 0.2).append("\" stroke=\"cyan\" />"); sb.append("<line x1=\"").append(segments.get(pcnt)[3] * scale).append("\" y1=\"").append(segments.get(pcnt)[4] * scale).append("\" x2=\"").append(segments.get(pcnt)[5] * scale).append("\" y2=\"").append(segments.get(pcnt)[6] * scale).append("\" stroke-width=\"").append(qcpr * 0.2).append("\" stroke=\"cyan\" />"); }// End of quadratic control points } }// End of svgpathstring() // Converting tracedata to an SVG string, paths are drawn according to a Z-index // the optional lcpr and qcpr are linear and quadratic control point radiuses public static String getsvgstring(IndexedImage ii, HashMap<String, Float> options) { // SVG start int w = (int) (ii.width * options.get("scale")), h = (int) (ii.height * options.get("scale")); String viewboxorviewport = options.get("viewbox") != 0 ? "viewBox=\"0 0 " + w + " " + h + "\" " : "width=\"" + w + "\" height=\"" + h + "\" "; StringBuilder svgstr = new StringBuilder("<svg " + viewboxorviewport + "version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" "); if (options.get("desc") != 0) { svgstr.append("desc=\"Created with ImageTracer.java version " + ImageTracer.versionnumber + "\" "); } svgstr.append(">"); // creating Z-index TreeMap<Double, Integer[]> zindex = new TreeMap<Double, Integer[]>(); double label; // Layer loop for (int k = 0; k < ii.layers.size(); k++) { // Path loop for (int pcnt = 0; pcnt < ii.layers.get(k).size(); pcnt++) { // Label (Z-index key) is the startpoint of the path, linearized label = (ii.layers.get(k).get(pcnt).get(0)[2] * w) + ii.layers.get(k).get(pcnt).get(0)[1]; // Creating new list if required if (!zindex.containsKey(label)) { zindex.put(label, new Integer[2]); } // Adding layer and path number to list zindex.get(label)[0] = new Integer(k); zindex.get(label)[1] = new Integer(pcnt); }// End of path loop }// End of layer loop // Sorting Z-index is not required, TreeMap is sorted automatically // Drawing // Z-index loop String thisdesc = ""; for (Entry<Double, Integer[]> entry : zindex.entrySet()) { if (options.get("desc") != 0) { thisdesc = "desc=\"l " + entry.getValue()[0] + " p " + entry.getValue()[1] + "\" "; } else { thisdesc = ""; } svgpathstring(svgstr, thisdesc, ii.layers.get(entry.getValue()[0]).get(entry.getValue()[1]), tosvgcolorstr(ii.palette[entry.getValue()[0]]), options); } // SVG End svgstr.append("</svg>"); return svgstr.toString(); }// End of getsvgstring() static String tosvgcolorstr(byte[] c) { return "fill=\"rgb(" + (c[0] + 128) + "," + (c[1] + 128) + "," + (c[2] + 128) + ")\" stroke=\"rgb(" + (c[0] + 128) + "," + (c[1] + 128) + "," + (c[2] + 128) + ")\" stroke-width=\"1\" opacity=\"" + ((c[3] + 128) / 255.0) + "\" "; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/image4j/LittleEndianRandomAccessFile.java
alpha/MyBox/src/main/java/thridparty/image4j/LittleEndianRandomAccessFile.java
/* * LittleEndianRandomAccessFile.java * * Created on 07 November 2006, 03:04 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package thridparty.image4j; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; /** * Provides endian conversions for input and output with a <tt>RandomAccessFile</tt>. * * This class is currently not in use and has not been tested. * * @author Ian McDonagh */ public class LittleEndianRandomAccessFile extends RandomAccessFile { public LittleEndianRandomAccessFile(java.io.File file, String mode) throws FileNotFoundException { super(file, mode); } public LittleEndianRandomAccessFile(String name, String mode) throws FileNotFoundException { super(name, mode); } public short readShortLE() throws IOException { short ret = super.readShort(); ret = EndianUtils.swapShort(ret); return ret; } public int readIntLE() throws IOException { int ret = super.readInt(); ret = EndianUtils.swapInteger(ret); return ret; } public float readFloatLE() throws IOException { float ret = super.readFloat(); ret = EndianUtils.swapFloat(ret); return ret; } public long readLongLE() throws IOException { long ret = super.readLong(); ret = EndianUtils.swapLong(ret); return ret; } public double readDoubleLE() throws IOException { double ret = super.readDouble(); ret = EndianUtils.swapDouble(ret); return ret; } public void writeShortLE(short value) throws IOException { value = EndianUtils.swapShort(value); super.writeShort(value); } public void writeIntLE(int value) throws IOException { value = EndianUtils.swapInteger(value); super.writeInt(value); } public void writeFloatLE(float value) throws IOException { value = EndianUtils.swapFloat(value); super.writeFloat(value); } public void writeLongLE(long value) throws IOException { value = EndianUtils.swapLong(value); super.writeLong(value); } public void writeDoubleLE(double value) throws IOException { value = EndianUtils.swapDouble(value); super.writeDouble(value); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/image4j/ICOEncoder.java
alpha/MyBox/src/main/java/thridparty/image4j/ICOEncoder.java
/* * ICOEncoder.java * * Created on 12 May 2006, 04:08 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package thridparty.image4j; import java.awt.image.BufferedImage; import java.awt.image.IndexColorModel; import java.awt.image.Raster; import java.awt.image.WritableRaster; import java.io.*; import java.util.List; import javax.imageio.ImageWriter; import thridparty.image4j.BMPEncoder; import thridparty.image4j.InfoHeader; /** * Encodes images in ICO format. * @author Ian McDonagh */ public class ICOEncoder { /** Creates a new instance of ICOEncoder */ private ICOEncoder() { } /** * Encodes and writes a single image to file without colour depth conversion. * @param image the source image to encode * @param file the output file to which the encoded image will be written * @throws java.io.IOException if an exception occurs */ public static void write(BufferedImage image, java.io.File file) throws IOException { write(image, -1, file); } /** * Encodes and writes a single image without colour depth conversion. * @param image the source image to encode * @param os the output to which the encoded image will be written * @throws java.io.IOException if an exception occurs */ public static void write(BufferedImage image, java.io.OutputStream os) throws IOException { write(image, -1, os); } /** * Encodes and writes multiple images without colour depth conversion. * @param images the list of source images to be encoded * @param os the output to which the encoded image will be written * @throws java.io.IOException if an error occurs */ public static void write(List<BufferedImage> images, java.io.OutputStream os) throws IOException { write(images, null, null, os); } /** * Encodes and writes multiple images to file without colour depth conversion. * @param images the list of source images to encode * @param file the file to which the encoded images will be written * @throws java.io.IOException if an exception occurs */ public static void write(List<BufferedImage> images, java.io.File file) throws IOException { write(images, null, file); } /** * Encodes and writes multiple images to file with the colour depth conversion using the specified values. * @param images the list of source images to encode * @param bpp array containing desired colour depths for colour depth conversion * @param file the output file to which the encoded images will be written * @throws java.io.IOException if an error occurs */ public static void write(List<BufferedImage> images, int[] bpp, java.io.File file) throws IOException { write(images, bpp, new java.io.FileOutputStream(file)); } /** * Encodes and outputs a list of images in ICO format. The first image in the list will be at index #0 in the ICO file, the second at index #1, and so on. * @param images List of images to encode, which will be output in the order supplied in the list. * @param bpp Array containing the color depth (bits per pixel) for encoding the corresponding image at each index in the <tt>images</tt> list. If the array is <tt>null</tt>, no colour depth conversion will be performed. A colour depth value of <tt>-1</tt> at a particular index indicates that no colour depth conversion should be performed for that image. * @param compress Array containing the compression flag for the corresponding image at each index in the <tt>images</tt> list. If the array is <tt>null</tt>, no compression will be peformed. A value of <tt>true</tt> specifies that compression should be performed, while a value of <tt>false</tt> specifies that no compression should be performed. * @param file the file to which the encoded images will be written. * @throws java.io.IOException if an error occurred. * @since 0.6 */ public static void write(List<BufferedImage> images, int[] bpp, boolean[] compress, java.io.File file) throws IOException { write(images, bpp, compress, new java.io.FileOutputStream(file)); } /** * Encodes and writes a single image to file with colour depth conversion using the specified value. * @param image the source image to encode * @param bpp the colour depth (bits per pixel) for the colour depth conversion, or <tt>-1</tt> if no colour depth conversion should be performed * @param file the output file to which the encoded image will be written * @throws java.io.IOException if an error occurs */ public static void write(BufferedImage image, int bpp, java.io.File file) throws IOException { java.io.FileOutputStream fout = new java.io.FileOutputStream(file); try { BufferedOutputStream out = new BufferedOutputStream(fout); write(image, bpp, out); out.flush(); } finally { try { fout.close(); } catch (IOException ex) { } } } /** * Encodes and outputs a single image in ICO format. * Convenience method, which calls {@link #write(java.util.List,int[],java.io.OutputStream) write(java.util.List,int[],java.io.OutputStream)}. * @param image The image to encode. * @param bpp Colour depth (in bits per pixel) for the colour depth conversion, or <tt>-1</tt> if no colour depth conversion should be performed. * @param os The output to which the encoded image will be written. * @throws java.io.IOException if an error occurs when trying to write the output. */ public static void write(BufferedImage image, int bpp, java.io.OutputStream os) throws IOException { List<BufferedImage> list = new java.util.ArrayList<BufferedImage>(1); list.add(image); write(list, new int[] { bpp }, new boolean[] { false }, os); } /** * Encodes and outputs a list of images in ICO format. The first image in the list will be at index #0 in the ICO file, the second at index #1, and so on. * @param images List of images to encode, which will be output in the order supplied in the list. * @param bpp Array containing the color depth (bits per pixel) for encoding the corresponding image at each index in the <tt>images</tt> list. If the array is <tt>null</tt>, no colour depth conversion will be performed. A colour depth value of <tt>-1</tt> at a particular index indicates that no colour depth conversion should be performed for that image. * @param os The output to which the encoded images will be written. * @throws java.io.IOException if an error occurred. */ public static void write(List<BufferedImage> images, int[] bpp, java.io.OutputStream os) throws IOException { write(images, bpp, null, os); } /** * Encodes and outputs a list of images in ICO format. The first image in the list will be at index #0 in the ICO file, the second at index #1, and so on. * @param images List of images to encode, which will be output in the order supplied in the list. * @param bpp Array containing the color depth (bits per pixel) for encoding the corresponding image at each index in the <tt>images</tt> list. If the array is <tt>null</tt>, no colour depth conversion will be performed. A colour depth value of <tt>-1</tt> at a particular index indicates that no colour depth conversion should be performed for that image. * @param compress Array containing the compression flag for the corresponding image at each index in the <tt>images</tt> list. If the array is <tt>null</tt>, no compression will be peformed. A value of <tt>true</tt> specifies that compression should be performed, while a value of <tt>false</tt> specifies that no compression should be performed. * @param os The output to which the encoded images will be written. * @throws java.io.IOException if an error occurred. * @since 0.6 */ public static void write(List<BufferedImage> images, int[] bpp, boolean[] compress, java.io.OutputStream os) throws IOException { LittleEndianOutputStream out = new LittleEndianOutputStream(os); int count = images.size(); //file header 6 writeFileHeader(count, ICOConstants.TYPE_ICON, out); //file offset where images start int fileOffset = 6 + count * 16; List<InfoHeader> infoHeaders = new java.util.ArrayList<InfoHeader>(count); List<BufferedImage> converted = new java.util.ArrayList<BufferedImage>(count); List<byte[]> compressedImages = null; if (compress != null) { compressedImages = new java.util.ArrayList<byte[]>(count); } javax.imageio.ImageWriter pngWriter = null; //icon entries 16 * count for (int i = 0; i < count; i++) { BufferedImage img = images.get(i); int b = bpp == null ? -1 : bpp[i]; //convert image BufferedImage imgc = b == -1 ? img : convert(img, b); converted.add(imgc); //create info header InfoHeader ih = BMPEncoder.createInfoHeader(imgc); //create icon entry IconEntry e = createIconEntry(ih); if (compress != null) { if (compress[i]) { if (pngWriter == null) { pngWriter = getPNGImageWriter(); } byte[] compressedImage = encodePNG(pngWriter, imgc); compressedImages.add(compressedImage); e.iSizeInBytes = compressedImage.length; } else { compressedImages.add(null); } } ih.iHeight *= 2; e.iFileOffset = fileOffset; fileOffset += e.iSizeInBytes; e.write(out); infoHeaders.add(ih); } //images for (int i = 0; i < count; i++) { BufferedImage img = images.get(i); BufferedImage imgc = converted.get(i); if (compress == null || !compress[i]) { //info header InfoHeader ih = infoHeaders.get(i); ih.write(out); //color map if (ih.sBitCount <= 8) { IndexColorModel icm = (IndexColorModel) imgc.getColorModel(); BMPEncoder.writeColorMap(icm, out); } //xor bitmap writeXorBitmap(imgc, ih, out); //and bitmap writeAndBitmap(img, out); } else { byte[] compressedImage = compressedImages.get(i); out.write(compressedImage); } //javax.imageio.ImageIO.write(imgc, "png", new java.io.File("test_"+i+".png")); } } /** * Writes the ICO file header for an ICO containing the given number of images. * @param count the number of images in the ICO * @param type one of {@link net.sf.image4j.codec.ico.ICOConstants#TYPE_ICON TYPE_ICON} or * {@link net.sf.image4j.codec.ico.ICOConstants#TYPE_CURSOR TYPE_CURSOR} * @param out the output to which the file header will be written * @throws java.io.IOException if an error occurs */ public static void writeFileHeader(int count, int type, LittleEndianOutputStream out) throws IOException { //reserved 2 out.writeShortLE((short) 0); //type 2 out.writeShortLE((short) type); //count 2 out.writeShortLE((short) count); } /** * Constructs an <tt>IconEntry</tt> from the given <tt>InfoHeader</tt> * structure. * @param ih the <tt>InfoHeader</tt> structure from which to construct the <tt>IconEntry</tt> structure. * @return the <tt>IconEntry</tt> structure constructed from the <tt>IconEntry</tt> structure. */ public static IconEntry createIconEntry(InfoHeader ih) { IconEntry ret = new IconEntry(); //width 1 ret.bWidth = ih.iWidth == 256 ? 0 : ih.iWidth; //height 1 ret.bHeight = ih.iHeight == 256 ? 0 : ih.iHeight; //color count 1 ret.bColorCount = ih.iNumColors >= 256 ? 0 : ih.iNumColors; //reserved 1 ret.bReserved = 0; //planes 2 = 1 ret.sPlanes = 1; //bit count 2 ret.sBitCount = ih.sBitCount; //sizeInBytes 4 - size of infoHeader + xor bitmap + and bitbmap int cmapSize = BMPEncoder.getColorMapSize(ih.sBitCount); int xorSize = BMPEncoder.getBitmapSize(ih.iWidth, ih.iHeight, ih.sBitCount); int andSize = BMPEncoder.getBitmapSize(ih.iWidth, ih.iHeight, 1); int size = ih.iSize + cmapSize + xorSize + andSize; ret.iSizeInBytes = size; //fileOffset 4 ret.iFileOffset = 0; return ret; } /** * Encodes the <em>AND</em> bitmap for the given image according the its alpha channel (transparency) and writes it to the given output. * @param img the image to encode as the <em>AND</em> bitmap. * @param out the output to which the <em>AND</em> bitmap will be written * @throws java.io.IOException if an error occurs. */ public static void writeAndBitmap(BufferedImage img, thridparty.image4j.LittleEndianOutputStream out) throws IOException { WritableRaster alpha = img.getAlphaRaster(); //indexed transparency (eg. GIF files) if (img.getColorModel() instanceof IndexColorModel && img.getColorModel().hasAlpha()) { int w = img.getWidth(); int h = img.getHeight(); int bytesPerLine = BMPEncoder.getBytesPerLine1(w); byte[] line = new byte[bytesPerLine]; IndexColorModel icm = (IndexColorModel) img.getColorModel(); Raster raster = img.getRaster(); for (int y = h - 1; y >= 0; y--) { for (int x = 0; x < w; x++) { int bi = x / 8; int i = x % 8; //int a = alpha.getSample(x, y, 0); int p = raster.getSample(x, y, 0); int a = icm.getAlpha(p); //invert bit since and mask is applied to xor mask int b = ~a & 1; line[bi] = setBit(line[bi], i, b); } out.write(line); } } //no transparency else if (alpha == null) { int h = img.getHeight(); int w = img.getWidth(); //calculate number of bytes per line, including 32-bit padding int bytesPerLine = BMPEncoder.getBytesPerLine1(w); byte[] line = new byte[bytesPerLine]; for (int i = 0; i < bytesPerLine; i++) { line[i] = (byte) 0; } for (int y = h - 1; y >= 0; y--) { out.write(line); } } //transparency (ARGB, etc. eg. PNG) else { //BMPEncoder.write1(alpha, cmap, out); int w = img.getWidth(); int h = img.getHeight(); int bytesPerLine = BMPEncoder.getBytesPerLine1(w); byte[] line = new byte[bytesPerLine]; for (int y = h - 1; y >= 0; y--) { for (int x = 0; x < w; x++) { int bi = x / 8; int i = x % 8; int a = alpha.getSample(x, y, 0); //invert bit since and mask is applied to xor mask int b = ~a & 1; line[bi] = setBit(line[bi], i, b); } out.write(line); } } } private static byte setBit(byte bits, int index, int bit) { int mask = 1 << (7 - index); bits &= ~mask; bits |= bit << (7 - index); return bits; } private static void writeXorBitmap(BufferedImage img, InfoHeader ih, LittleEndianOutputStream out) throws IOException { Raster raster = img.getRaster(); switch (ih.sBitCount) { case 1: BMPEncoder.write1(raster, out); break; case 4: BMPEncoder.write4(raster, out); break; case 8: BMPEncoder.write8(raster, out); break; case 24: BMPEncoder.write24(raster, out); break; case 32: Raster alpha = img.getAlphaRaster(); BMPEncoder.write32(raster, alpha, out); break; } } /** * Utility method, which converts the given image to the specified colour depth. * @param img the image to convert. * @param bpp the target colour depth (bits per pixel) for the conversion. * @return the given image converted to the specified colour depth. */ public static BufferedImage convert(BufferedImage img, int bpp) { BufferedImage ret = null; switch (bpp) { case 1: ret = ConvertUtil.convert1(img); break; case 4: ret = ConvertUtil.convert4(img); break; case 8: ret = ConvertUtil.convert8(img); break; case 24: int b = img.getColorModel().getPixelSize(); if (b == 24 || b == 32) { ret = img; } else { ret = ConvertUtil.convert24(img); } break; case 32: int b2 = img.getColorModel().getPixelSize(); if (b2 == 24 || b2 == 32) { ret = img; } else { ret = ConvertUtil.convert32(img); } break; } return ret; } /** * @since 0.6 */ private static javax.imageio.ImageWriter getPNGImageWriter() { javax.imageio.ImageWriter ret = null; java.util.Iterator<javax.imageio.ImageWriter> itr = javax.imageio.ImageIO.getImageWritersByFormatName("png"); if (itr.hasNext()) { ret = itr.next(); } return ret; } /** * @since 0.6 */ private static byte[] encodePNG(ImageWriter pngWriter, BufferedImage img) throws IOException { java.io.ByteArrayOutputStream bout = new java.io.ByteArrayOutputStream(); javax.imageio.stream.ImageOutputStream output = javax.imageio.ImageIO.createImageOutputStream(bout); pngWriter.setOutput(output); pngWriter.write(img); bout.flush(); byte[] ret = bout.toByteArray(); return ret; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/image4j/CountingInput.java
alpha/MyBox/src/main/java/thridparty/image4j/CountingInput.java
package thridparty.image4j; public interface CountingInput { int getCount(); }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/image4j/BMPEncoder.java
alpha/MyBox/src/main/java/thridparty/image4j/BMPEncoder.java
/* * BMPEncoder.java * * Created on 11 May 2006, 04:19 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package thridparty.image4j; import java.awt.image.BufferedImage; import java.awt.image.IndexColorModel; import java.awt.image.Raster; import java.io.*; /** * Encodes images in BMP format. * @author Ian McDonagh */ public class BMPEncoder { /** Creates a new instance of BMPEncoder */ private BMPEncoder() { } /** * Encodes and writes BMP data the output file * @param img the image to encode * @param file the file to which encoded data will be written * @throws java.io.IOException if an error occurs */ public static void write(BufferedImage img, java.io.File file) throws IOException { java.io.FileOutputStream fout = new java.io.FileOutputStream(file); try { BufferedOutputStream out = new BufferedOutputStream(fout); write(img, out); out.flush(); } finally { try { fout.close(); } catch (IOException ex) { } } } /** * Encodes and writes BMP data to the output * @param img the image to encode * @param os the output to which encoded data will be written * @throws java.io.IOException if an error occurs */ public static void write(BufferedImage img, java.io.OutputStream os) throws IOException { // create info header InfoHeader ih = createInfoHeader(img); // Create colour map if the image uses an indexed colour model. // Images with colour depth of 8 bits or less use an indexed colour model. int mapSize = 0; IndexColorModel icm = null; if (ih.sBitCount <= 8) { icm = (IndexColorModel) img.getColorModel(); mapSize = icm.getMapSize(); } // Calculate header size int headerSize = 14 //file header + ih.iSize //info header ; // Calculate map size int mapBytes = 4 * mapSize; // Calculate data offset int dataOffset = headerSize + mapBytes; // Calculate bytes per line int bytesPerLine = 0; switch (ih.sBitCount) { case 1: bytesPerLine = getBytesPerLine1(ih.iWidth); break; case 4: bytesPerLine = getBytesPerLine4(ih.iWidth); break; case 8: bytesPerLine = getBytesPerLine8(ih.iWidth); break; case 24: bytesPerLine = getBytesPerLine24(ih.iWidth); break; case 32: bytesPerLine = ih.iWidth * 4; break; } // calculate file size int fileSize = dataOffset + bytesPerLine * ih.iHeight; // output little endian byte order LittleEndianOutputStream out = new LittleEndianOutputStream(os); //write file header writeFileHeader(fileSize, dataOffset, out); //write info header ih.write(out); //write color map (bit count <= 8) if (ih.sBitCount <= 8) { writeColorMap(icm, out); } //write raster data switch (ih.sBitCount) { case 1: write1(img.getRaster(), out); break; case 4: write4(img.getRaster(), out); break; case 8: write8(img.getRaster(), out); break; case 24: write24(img.getRaster(), out); break; case 32: write32(img.getRaster(), img.getAlphaRaster(), out); break; } } /** * Creates an <tt>InfoHeader</tt> from the source image. * @param img the source image * @return the resultant <tt>InfoHeader</tt> structure */ public static InfoHeader createInfoHeader(BufferedImage img) { InfoHeader ret = new InfoHeader(); ret.iColorsImportant = 0; ret.iColorsUsed = 0; ret.iCompression = 0; ret.iHeight = img.getHeight(); ret.iWidth = img.getWidth(); ret.sBitCount = (short) img.getColorModel().getPixelSize(); ret.iNumColors = 1 << (ret.sBitCount == 32 ? 24 : ret.sBitCount); ret.iImageSize = 0; return ret; } /** * Writes the file header. * @param fileSize the calculated file size for the BMP data being written * @param dataOffset the calculated offset within the BMP data where the actual bitmap begins * @param out the output to which the file header will be written * @throws java.io.IOException if an error occurs */ public static void writeFileHeader(int fileSize, int dataOffset, thridparty.image4j.LittleEndianOutputStream out) throws IOException { //signature byte[] signature = BMPConstants.FILE_HEADER.getBytes("UTF-8"); out.write(signature); //file size out.writeIntLE(fileSize); //reserved out.writeIntLE(0); //data offset out.writeIntLE(dataOffset); } /** * Writes the colour map resulting from the source <tt>IndexColorModel</tt>. * @param icm the source <tt>IndexColorModel</tt> * @param out the output to which the colour map will be written * @throws java.io.IOException if an error occurs */ public static void writeColorMap(IndexColorModel icm, thridparty.image4j.LittleEndianOutputStream out) throws IOException { int mapSize = icm.getMapSize(); for (int i = 0; i < mapSize; i++) { int rgb = icm.getRGB(i); int r = (rgb >> 16) & 0xFF; int g = (rgb >> 8) & 0xFF; int b = (rgb) &0xFF; out.writeByte(b); out.writeByte(g); out.writeByte(r); out.writeByte(0); } } /** * Calculates the number of bytes per line required for the given width in pixels, * for a 1-bit bitmap. Lines are always padded to the next 4-byte boundary. * @param width the width in pixels * @return the number of bytes per line */ public static int getBytesPerLine1(int width) { int ret = (int) width / 8; if (ret * 8 < width) { ret++; } if (ret % 4 != 0) { ret = (ret / 4 + 1) * 4; } return ret; } /** * Calculates the number of bytes per line required for the given with in pixels, * for a 4-bit bitmap. Lines are always padded to the next 4-byte boundary. * @param width the width in pixels * @return the number of bytes per line */ public static int getBytesPerLine4(int width) { int ret = (int) width / 2; if (ret % 4 != 0) { ret = (ret / 4 + 1) * 4; } return ret; } /** * Calculates the number of bytes per line required for the given with in pixels, * for a 8-bit bitmap. Lines are always padded to the next 4-byte boundary. * @param width the width in pixels * @return the number of bytes per line */ public static int getBytesPerLine8(int width) { int ret = width; if (ret % 4 != 0) { ret = (ret / 4 + 1) * 4; } return ret; } /** * Calculates the number of bytes per line required for the given with in pixels, * for a 24-bit bitmap. Lines are always padded to the next 4-byte boundary. * @param width the width in pixels * @return the number of bytes per line */ public static int getBytesPerLine24(int width) { int ret = width * 3; if (ret % 4 != 0) { ret = (ret / 4 + 1) * 4; } return ret; } /** * Calculates the size in bytes of a bitmap with the specified size and colour depth. * @param w the width in pixels * @param h the height in pixels * @param bpp the colour depth (bits per pixel) * @return the size of the bitmap in bytes */ public static int getBitmapSize(int w, int h, int bpp) { int bytesPerLine = 0; switch (bpp) { case 1: bytesPerLine = getBytesPerLine1(w); break; case 4: bytesPerLine = getBytesPerLine4(w); break; case 8: bytesPerLine = getBytesPerLine8(w); break; case 24: bytesPerLine = getBytesPerLine24(w); break; case 32: bytesPerLine = w * 4; break; } int ret = bytesPerLine * h; return ret; } /** * Encodes and writes raster data as a 1-bit bitmap. * @param raster the source raster data * @param out the output to which the bitmap will be written * @throws java.io.IOException if an error occurs */ public static void write1(Raster raster, thridparty.image4j.LittleEndianOutputStream out) throws IOException { int bytesPerLine = getBytesPerLine1(raster.getWidth()); byte[] line = new byte[bytesPerLine]; for (int y = raster.getHeight() - 1; y >= 0; y--) { for (int i = 0; i < bytesPerLine; i++) { line[i] = 0; } for (int x = 0; x < raster.getWidth(); x++) { int bi = x / 8; int i = x % 8; int index = raster.getSample(x, y, 0); line[bi] = setBit(line[bi], i, index); } out.write(line); } } /** * Encodes and writes raster data as a 4-bit bitmap. * @param raster the source raster data * @param out the output to which the bitmap will be written * @throws java.io.IOException if an error occurs */ public static void write4(Raster raster, thridparty.image4j.LittleEndianOutputStream out) throws IOException { // The approach taken here is to use a buffer to hold encoded raster data // one line at a time. // Perhaps we could just write directly to output instead // and avoid using a buffer altogether. Hypothetically speaking, // a very wide image would require a large line buffer here, but then again, // large 4 bit bitmaps are pretty uncommon, so using the line buffer approach // should be okay. int width = raster.getWidth(); int height = raster.getHeight(); // calculate bytes per line int bytesPerLine = getBytesPerLine4(width); // line buffer byte[] line = new byte[bytesPerLine]; // encode and write lines for (int y = height - 1; y >= 0; y--) { // clear line buffer for (int i = 0; i < bytesPerLine; i++) { line[i] = 0; } // encode raster data for line for (int x = 0; x < width; x++) { // calculate buffer index int bi = x / 2; // calculate nibble index (high order or low order) int i = x % 2; // get color index int index = raster.getSample(x, y, 0); // set color index in buffer line[bi] = setNibble(line[bi], i, index); } // write line data (padding bytes included) out.write(line); } } /** * Encodes and writes raster data as an 8-bit bitmap. * @param raster the source raster data * @param out the output to which the bitmap will be written * @throws java.io.IOException if an error occurs */ public static void write8(Raster raster, thridparty.image4j.LittleEndianOutputStream out) throws IOException { int width = raster.getWidth(); int height = raster.getHeight(); // calculate bytes per line int bytesPerLine = getBytesPerLine8(width); // write lines for (int y = height - 1; y >= 0; y--) { // write raster data for each line for (int x = 0; x < width; x++) { // get color index for pixel int index = raster.getSample(x, y, 0); // write color index out.writeByte(index); } // write padding bytes at end of line for (int i = width; i < bytesPerLine; i++) { out.writeByte(0); } } } /** * Encodes and writes raster data as a 24-bit bitmap. * @param raster the source raster data * @param out the output to which the bitmap will be written * @throws java.io.IOException if an error occurs */ public static void write24(Raster raster, thridparty.image4j.LittleEndianOutputStream out) throws IOException { int width = raster.getWidth(); int height = raster.getHeight(); // calculate bytes per line int bytesPerLine = getBytesPerLine24(width); // write lines for (int y = height - 1; y >= 0; y--) { // write pixel data for each line for (int x = 0; x < width; x++) { // get RGB values for pixel int r = raster.getSample(x, y, 0); int g = raster.getSample(x, y, 1); int b = raster.getSample(x, y, 2); // write RGB values out.writeByte(b); out.writeByte(g); out.writeByte(r); } // write padding bytes at end of line for (int i = width * 3; i < bytesPerLine; i++) { out.writeByte(0); } } } /** * Encodes and writes raster data, together with alpha (transparency) data, as a 32-bit bitmap. * @param raster the source raster data * @param alpha the source alpha data * @param out the output to which the bitmap will be written * @throws java.io.IOException if an error occurs */ public static void write32(Raster raster, Raster alpha, thridparty.image4j.LittleEndianOutputStream out) throws IOException { int width = raster.getWidth(); int height = raster.getHeight(); // write lines for (int y = height - 1; y >= 0; y--) { // write pixel data for each line for (int x = 0; x < width; x++) { // get RGBA values int r = raster.getSample(x, y, 0); int g = raster.getSample(x, y, 1); int b = raster.getSample(x, y, 2); int a = alpha.getSample(x, y, 0); // write RGBA values out.writeByte(b); out.writeByte(g); out.writeByte(r); out.writeByte(a); } } } /** * Sets a particular bit in a byte. * @param bits the source byte * @param index the index of the bit to set * @param bit the value for the bit, which should be either <tt>0</tt> or <tt>1</tt>. * @param the resultant byte */ private static byte setBit(byte bits, int index, int bit) { if (bit == 0) { bits &= ~(1 << (7 - index)); } else { bits |= 1 << (7 - index); } return bits; } /** * Sets a particular nibble (4 bits) in a byte. * @param nibbles the source byte * @param index the index of the nibble to set * @param the value for the nibble, which should be in the range <tt>0x0..0xF</tt>. */ private static byte setNibble(byte nibbles, int index, int nibble) { nibbles |= (nibble << ((1 - index) * 4)); return nibbles; } /** * Calculates the size in bytes for a colour map with the specified bit count. * @param sBitCount the bit count, which represents the colour depth * @return the size of the colour map, in bytes if <tt>sBitCount</tt> is less than or equal to 8, * otherwise <tt>0</tt> as colour maps are only used for bitmaps with a colour depth of 8 bits or less. */ public static int getColorMapSize(short sBitCount) { int ret = 0; if (sBitCount <= 8) { ret = (1 << sBitCount) * 4; } return ret; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/image4j/IconEntry.java
alpha/MyBox/src/main/java/thridparty/image4j/IconEntry.java
package thridparty.image4j; import java.io.IOException; /** * Represents an <tt>IconEntry</tt> structure, which contains information about an ICO image. * @author Ian McDonagh */ public class IconEntry { /** * The width of the icon image in pixels. * <tt>0</tt> specifies a width of 256 pixels. */ public int bWidth; /** * The height of the icon image in pixels. * <tt>0</tt> specifies a height of 256 pixels. */ public int bHeight; /** * The number of colours, calculated from {@link #sBitCount sBitCount}. * <tt>0</tt> specifies a colour count of &gt;= 256. */ public int bColorCount; /** * Unused. Should always be <tt>0</tt>. */ public byte bReserved; /** * Number of planes, which should always be <tt>1</tt>. */ public short sPlanes; /** * Colour depth in bits per pixel. */ public short sBitCount; /** * Size of ICO data, which should be the size of (InfoHeader + AND bitmap + XOR bitmap). */ public int iSizeInBytes; /** * Position in file where the InfoHeader starts. */ public int iFileOffset; /** * Creates an <tt>IconEntry</tt> structure from the source input * @param in the source input * @throws java.io.IOException if an error occurs */ public IconEntry(LittleEndianInputStream in) throws IOException { //Width 1 byte Cursor Width (16, 32, 64, 0 = 256) bWidth = in.readUnsignedByte(); //Height 1 byte Cursor Height (16, 32, 64, 0 = 256 , most commonly = Width) bHeight = in.readUnsignedByte(); //ColorCount 1 byte Number of Colors (2,16, 0=256) bColorCount = in.readUnsignedByte(); //Reserved 1 byte =0 bReserved = in.readByte(); //Planes 2 byte =1 sPlanes = in.readShortLE(); //BitCount 2 byte bits per pixel (1, 4, 8) sBitCount = in.readShortLE(); //SizeInBytes 4 byte Size of (InfoHeader + ANDbitmap + XORbitmap) iSizeInBytes = in.readIntLE(); //FileOffset 4 byte FilePos, where InfoHeader starts iFileOffset = in.readIntLE(); } /** * Creates and <tt>IconEntry</tt> structure with default values. */ public IconEntry() { bWidth = 0; bHeight = 0; bColorCount = 0; sPlanes = 1; bReserved = 0; sBitCount = 0; iSizeInBytes = 0; iFileOffset = 0; } /** * A string representation of this <tt>IconEntry</tt> structure. */ public String toString() { StringBuffer sb = new StringBuffer(); sb.append("width="); sb.append(bWidth); sb.append(",height="); sb.append(bHeight); sb.append(",bitCount="); sb.append(sBitCount); sb.append(",colorCount="+bColorCount); return sb.toString(); } /** * Writes the <tt>IconEntry</tt> structure to output * @param out the output * @throws java.io.IOException if an error occurs */ public void write(thridparty.image4j.LittleEndianOutputStream out) throws IOException { //Width 1 byte Cursor Width (16, 32 or 64) out.writeByte(bWidth); //Height 1 byte Cursor Height (16, 32 or 64 , most commonly = Width) out.writeByte(bHeight); //ColorCount 1 byte Number of Colors (2,16, 0=256) out.writeByte(bColorCount); //Reserved 1 byte =0 out.writeByte(bReserved); //Planes 2 byte =1 out.writeShortLE(sPlanes); //BitCount 2 byte bits per pixel (1, 4, 8) out.writeShortLE(sBitCount); //SizeInBytes 4 byte Size of (InfoHeader + ANDbitmap + XORbitmap) out.writeIntLE(iSizeInBytes); //FileOffset 4 byte FilePos, where InfoHeader starts out.writeIntLE(iFileOffset); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/image4j/CountingDataInputStream.java
alpha/MyBox/src/main/java/thridparty/image4j/CountingDataInputStream.java
package thridparty.image4j; import java.io.*; public class CountingDataInputStream extends DataInputStream implements CountingDataInput { public CountingDataInputStream(InputStream in) { super(new CountingInputStream(in)); } @Override public int getCount() { return ((CountingInputStream) in).getCount(); } public int skip(int count, boolean strict) throws IOException { return IOUtils.skip(this, count, strict); } @Override public String toString() { return getClass().getSimpleName() + "(" +in + ") ["+getCount()+"]"; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/image4j/BMPImage.java
alpha/MyBox/src/main/java/thridparty/image4j/BMPImage.java
/* * BMPImage.java * * Created on February 19, 2007, 8:08 AM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package thridparty.image4j; /** * Contains a decoded BMP image, as well as information about the source encoded image. * @since 0.7 * @author Ian McDonagh */ public class BMPImage { protected InfoHeader infoHeader; protected java.awt.image.BufferedImage image; /** * Creates a new instance of BMPImage * @param image the decoded image * @param infoHeader the InfoHeader structure providing information about the source encoded image */ public BMPImage(java.awt.image.BufferedImage image, InfoHeader infoHeader) { this.image = image; this.infoHeader = infoHeader; } /** * The InfoHeader structure representing the encoded BMP image. */ public InfoHeader getInfoHeader() { return infoHeader; } /** * Sets the InfoHeader structure used for encoding the BMP image. */ public void setInfoHeader(InfoHeader infoHeader) { this.infoHeader = infoHeader; } /** * The decoded BMP image. */ public java.awt.image.BufferedImage getImage() { return image; } /** * Sets the image to be encoded. */ public void setImage(java.awt.image.BufferedImage image) { this.image = image; } /** * The width of the BMP image in pixels. * @return the width of the BMP image, or <tt>-1</tt> if unknown * @since 0.7alpha2 */ public int getWidth() { return infoHeader == null ? -1 : infoHeader.iWidth; } /** * The height of the BMP image in pixels. * @return the height of the BMP image, or <tt>-1</tt> if unknown. * @since 0.7alpha2 */ public int getHeight() { return infoHeader == null ? -1 : infoHeader.iHeight; } /** * The colour depth of the BMP image (bits per pixel). * @return the colour depth, or <tt>-1</tt> if unknown. * @since 0.7alpha2 */ public int getColourDepth() { return infoHeader == null ? -1 : infoHeader.sBitCount; } /** * The number of possible colours for the BMP image. * @return the number of colours, or <tt>-1</tt> if unknown. * @since 0.7alpha2 */ public int getColourCount() { int bpp = infoHeader.sBitCount == 32 ? 24 : infoHeader.sBitCount; return bpp == -1 ? -1 : (int) (1 << bpp); } /** * Specifies whether this BMP image is indexed, that is, the encoded bitmap uses a colour table. * If <tt>getColourDepth()</tt> returns <tt>-1</tt>, the return value has no meaning. * @return <tt>true</tt> if indexed, <tt>false</tt> if not. * @since 0.7alpha2 */ public boolean isIndexed() { return infoHeader == null ? false : infoHeader.sBitCount <= 8; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/image4j/IOUtils.java
alpha/MyBox/src/main/java/thridparty/image4j/IOUtils.java
package thridparty.image4j; import java.io.*; public class IOUtils { public static int skip(InputStream in, int count, boolean strict) throws IOException { int skipped = 0; while (skipped < count) { int b = in.read(); if (b == -1) { break; } skipped++; } if (skipped < count && strict) { throw new EOFException("Failed to skip " + count + " bytes in input"); } return skipped; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/image4j/InfoHeader.java
alpha/MyBox/src/main/java/thridparty/image4j/InfoHeader.java
/* * InfoHeader.java * * Created on 10 May 2006, 08:10 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package thridparty.image4j; import java.io.IOException; /** * Represents a bitmap <tt>InfoHeader</tt> structure, which provides header information. * @author Ian McDonagh */ public class InfoHeader { /** * The size of this <tt>InfoHeader</tt> structure in bytes. */ public int iSize; /** * The width in pixels of the bitmap represented by this <tt>InfoHeader</tt>. */ public int iWidth; /** * The height in pixels of the bitmap represented by this <tt>InfoHeader</tt>. */ public int iHeight; /** * The number of planes, which should always be <tt>1</tt>. */ public short sPlanes; /** * The bit count, which represents the colour depth (bits per pixel). * This should be either <tt>1</tt>, <tt>4</tt>, <tt>8</tt>, <tt>24</tt> or <tt>32</tt>. */ public short sBitCount; /** * The compression type, which should be one of the following: * <ul> * <li>{@link BMPConstants#BI_RGB BI_RGB} - no compression</li> * <li>{@link BMPConstants#BI_RLE8 BI_RLE8} - 8-bit RLE compression</li> * <li>{@link BMPConstants#BI_RLE4 BI_RLE4} - 4-bit RLE compression</li> * </ul> */ public int iCompression; /** * The compressed size of the image in bytes, or <tt>0</tt> if <tt>iCompression</tt> is <tt>0</tt>. */ public int iImageSize; /** * Horizontal resolution in pixels/m. */ public int iXpixelsPerM; /** * Vertical resolution in pixels/m. */ public int iYpixelsPerM; /** * Number of colours actually used in the bitmap. */ public int iColorsUsed; /** * Number of important colours (<tt>0</tt> = all). */ public int iColorsImportant; /** * Calculated number of colours, based on the colour depth specified by {@link #sBitCount sBitCount}. */ public int iNumColors; /** * Creates an <tt>InfoHeader</tt> structure from the source input. * @param in the source input * @throws java.io.IOException if an error occurs */ public InfoHeader(thridparty.image4j.LittleEndianInputStream in) throws IOException { //Size of InfoHeader structure = 40 iSize = in.readIntLE(); init(in, iSize); } /** * @since 0.6 */ public InfoHeader(thridparty.image4j.LittleEndianInputStream in, int infoSize) throws IOException { init(in, infoSize); } /** * @since 0.6 */ protected void init(thridparty.image4j.LittleEndianInputStream in, int infoSize) throws IOException { this.iSize = infoSize; //Width iWidth = in.readIntLE(); //Height iHeight = in.readIntLE(); //Planes (=1) sPlanes = in.readShortLE(); //Bit count sBitCount = in.readShortLE(); //calculate NumColors iNumColors = (int) Math.pow(2, sBitCount); //Compression iCompression = in.readIntLE(); //Image size - compressed size of image or 0 if Compression = 0 iImageSize = in.readIntLE(); //horizontal resolution pixels/meter iXpixelsPerM = in.readIntLE(); //vertical resolution pixels/meter iYpixelsPerM = in.readIntLE(); //Colors used - number of colors actually used iColorsUsed = in.readIntLE(); //Colors important - number of important colors 0 = all iColorsImportant = in.readIntLE(); } /** * Creates an <tt>InfoHeader</tt> with default values. */ public InfoHeader() { //Size of InfoHeader structure = 40 iSize = 40; //Width iWidth = 0; //Height iHeight = 0; //Planes (=1) sPlanes = 1; //Bit count sBitCount = 0; //caculate NumColors iNumColors = 0; //Compression iCompression = BMPConstants.BI_RGB; //Image size - compressed size of image or 0 if Compression = 0 iImageSize = 0; //horizontal resolution pixels/meter iXpixelsPerM = 0; //vertical resolution pixels/meter iYpixelsPerM = 0; //Colors used - number of colors actually used iColorsUsed = 0; //Colors important - number of important colors 0 = all iColorsImportant = 0; } /** * Creates a copy of the source <tt>InfoHeader</tt>. * @param source the source to copy */ public InfoHeader(InfoHeader source) { iColorsImportant = source.iColorsImportant; iColorsUsed = source.iColorsUsed; iCompression = source.iCompression; iHeight = source.iHeight; iWidth = source.iWidth; iImageSize = source.iImageSize; iNumColors = source.iNumColors; iSize = source.iSize; iXpixelsPerM = source.iXpixelsPerM; iYpixelsPerM = source.iYpixelsPerM; sBitCount = source.sBitCount; sPlanes = source.sPlanes; } /** * Writes the <tt>InfoHeader</tt> structure to output * @param out the output to which the structure will be written * @throws java.io.IOException if an error occurs */ public void write(thridparty.image4j.LittleEndianOutputStream out) throws IOException { //Size of InfoHeader structure = 40 out.writeIntLE(iSize); //Width out.writeIntLE(iWidth); //Height out.writeIntLE(iHeight); //Planes (=1) out.writeShortLE(sPlanes); //Bit count out.writeShortLE(sBitCount); //caculate NumColors //iNumColors = (int) Math.pow(2, sBitCount); //Compression out.writeIntLE(iCompression); //Image size - compressed size of image or 0 if Compression = 0 out.writeIntLE(iImageSize); //horizontal resolution pixels/meter out.writeIntLE(iXpixelsPerM); //vertical resolution pixels/meter out.writeIntLE(iYpixelsPerM); //Colors used - number of colors actually used out.writeIntLE(iColorsUsed); //Colors important - number of important colors 0 = all out.writeIntLE(iColorsImportant); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/image4j/ICODecoder.java
alpha/MyBox/src/main/java/thridparty/image4j/ICODecoder.java
/* * ICODecoder.java * * Created on May 9, 2006, 9:31 PM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package thridparty.image4j; import java.awt.image.*; import java.io.*; import java.util.*; import mara.mybox.dev.MyBoxLog; /** * Decodes images in ICO format. * * @author Ian McDonagh */ // ##### Updated by mara. To avoid crash when the file is invalid public class ICODecoder { private static final int PNG_MAGIC = 0x89504E47; private static final int PNG_MAGIC_LE = 0x474E5089; private static final int PNG_MAGIC2 = 0x0D0A1A0A; private static final int PNG_MAGIC2_LE = 0x0A1A0A0D; // private List<BufferedImage> img; private ICODecoder() { } /** * Reads and decodes the given ICO file. Convenience method equivalent to * null null null null null {@link #read(java.io.InputStream) read(new * java.io.FileInputStream(file))}. * * @param file the source file to read * @return the list of images decoded from the ICO data * */ public static List<BufferedImage> read(File file) { try { List<ICOImage> icoList = readExt(file); if (icoList == null) { return null; } List<BufferedImage> bgList = new ArrayList<>(icoList.size()); for (int i = 0; i < icoList.size(); i++) { ICOImage icoImage = icoList.get(i); BufferedImage image = icoImage.getImage(); bgList.add(image); } return bgList; } catch (Exception e) { MyBoxLog.console(e); return null; } } /** * Reads and decodes the given ICO file, together with all metadata. * Convenience method equivalent to {@link #readExt(java.io.InputStream) * readExt(new java.io.FileInputStream(file))}. * * @param file the source file to read * @return the list of images decoded from the ICO data * @since 0.7 */ public static List<ICOImage> readExt(File file) { if (file == null || !file.exists()) { return null; } try (FileInputStream fin = new FileInputStream(file)) { return readExt(new BufferedInputStream(fin)); } catch (Exception e) { MyBoxLog.console(e); return null; } } public static List<ICOImage> readExt(java.io.InputStream is) { if (is == null) { return null; } try (LittleEndianInputStream in = new LittleEndianInputStream(new CountingInputStream(is))) { // Count 2 byte Number of Icons in this file // Reserved 2 byte =0 short sReserved = in.readShortLE(); // Type 2 byte =1 short sType = in.readShortLE(); // Count 2 byte Number of Icons in this file short sCount = in.readShortLE(); // Entries Count * 16 list of icons IconEntry[] entries = new IconEntry[sCount]; for (short s = 0; s < sCount; s++) { entries[s] = new IconEntry(in); } // Seems like we don't need this, but you never know! // entries = sortByFileOffset(entries); // images list of bitmap structures in BMP/PNG format List<ICOImage> ret = new ArrayList<>(sCount); for (int i = 0; i < sCount; i++) { // Make sure we're at the right file offset! int fileOffset = in.getCount(); if (fileOffset != entries[i].iFileOffset) { MyBoxLog.error("Cannot read image #" + i + " starting at unexpected file offset."); return null; } int info = in.readIntLE(); // MyBoxLog.console("Image #" + i + " @ " + in.getCount() // + " info = " + EndianUtils.toInfoString(info)); if (info == 40) { // read XOR bitmap // BMPDecoder bmp = new BMPDecoder(is); InfoHeader infoHeader = BMPDecoder.readInfoHeader(in, info); InfoHeader andHeader = new InfoHeader(infoHeader); andHeader.iHeight = (int) (infoHeader.iHeight / 2); InfoHeader xorHeader = new InfoHeader(infoHeader); xorHeader.iHeight = andHeader.iHeight; andHeader.sBitCount = 1; andHeader.iNumColors = 2; // for now, just read all the raster data (xor + and) // and store as separate images BufferedImage xor = BMPDecoder.read(xorHeader, in); // If we want to be sure we've decoded the XOR mask // correctly, // we can write it out as a PNG to a temp file here. // try { // File temp = File.createTempFile("image4j", ".png"); // ImageIO.write(xor, "png", temp); // log.info("Wrote xor mask for image #" + i + " to " // + temp.getAbsolutePath()); // } catch (Throwable ex) { // } // Or just add it to the output list: // img.add(xor); BufferedImage img = new BufferedImage(xorHeader.iWidth, xorHeader.iHeight, BufferedImage.TYPE_INT_ARGB); ColorEntry[] andColorTable = new ColorEntry[]{ new ColorEntry(255, 255, 255, 255), new ColorEntry(0, 0, 0, 0)}; if (infoHeader.sBitCount == 32) { // transparency from alpha // ignore bytes after XOR bitmap int size = entries[i].iSizeInBytes; int infoHeaderSize = infoHeader.iSize; // data size = w * h * 4 int dataSize = xorHeader.iWidth * xorHeader.iHeight * 4; int skip = size - infoHeaderSize - dataSize; int skip2 = entries[i].iFileOffset + size - in.getCount(); // ignore AND bitmap since alpha channel stores // transparency if (in.skip(skip, false) < skip && i < sCount - 1) { throw new EOFException("Unexpected end of input"); } // If we skipped less bytes than expected, the AND mask // is probably badly formatted. // If we're at the last/only entry in the file, silently // ignore and continue processing... // //read AND bitmap // BufferedImage and = BMPDecoder.read(andHeader, in, // andColorTable); // this.img.add(and); WritableRaster srgb = xor.getRaster(); WritableRaster salpha = xor.getAlphaRaster(); WritableRaster rgb = img.getRaster(); WritableRaster alpha = img.getAlphaRaster(); for (int y = xorHeader.iHeight - 1; y >= 0; y--) { for (int x = 0; x < xorHeader.iWidth; x++) { int r = srgb.getSample(x, y, 0); int g = srgb.getSample(x, y, 1); int b = srgb.getSample(x, y, 2); int a = salpha.getSample(x, y, 0); rgb.setSample(x, y, 0, r); rgb.setSample(x, y, 1, g); rgb.setSample(x, y, 2, b); alpha.setSample(x, y, 0, a); } } } else { BufferedImage and = BMPDecoder.read(andHeader, in, andColorTable); // img.add(and); // copy rgb WritableRaster srgb = xor.getRaster(); WritableRaster rgb = img.getRaster(); // copy alpha WritableRaster alpha = img.getAlphaRaster(); WritableRaster salpha = and.getRaster(); for (int y = 0; y < xorHeader.iHeight; y++) { for (int x = 0; x < xorHeader.iWidth; x++) { int r, g, b; int c = xor.getRGB(x, y); r = (c >> 16) & 0xFF; g = (c >> 8) & 0xFF; b = (c) & 0xFF; // red rgb.setSample(x, y, 0, r); // green rgb.setSample(x, y, 1, g); // blue rgb.setSample(x, y, 2, b); // System.out.println(x+","+y+"="+Integer.toHexString(c)); // img.setRGB(x, y, c); // alpha int a = and.getRGB(x, y); alpha.setSample(x, y, 0, a); } } } // create ICOImage IconEntry iconEntry = entries[i]; ICOImage icoImage = new ICOImage(img, infoHeader, iconEntry); icoImage.setPngCompressed(false); icoImage.setIconIndex(i); ret.add(icoImage); } // check for PNG magic header and that image height and width = // 0 = 256 -> Vista format else if (info == PNG_MAGIC_LE) { int info2 = in.readIntLE(); if (info2 != PNG_MAGIC2_LE) { MyBoxLog.error("Unrecognized icon format for image #" + i); return null; } IconEntry e = entries[i]; int size = e.iSizeInBytes - 8; byte[] pngData = new byte[size]; /* int count = */ in.readFully(pngData); // if (count != pngData.length) { // throw new // IOException("Unable to read image #"+i+" - incomplete PNG compressed data"); // } java.io.ByteArrayOutputStream bout = new java.io.ByteArrayOutputStream(); java.io.DataOutputStream dout = new java.io.DataOutputStream( bout); dout.writeInt(PNG_MAGIC); dout.writeInt(PNG_MAGIC2); dout.write(pngData); byte[] pngData2 = bout.toByteArray(); java.io.ByteArrayInputStream bin = new java.io.ByteArrayInputStream( pngData2); javax.imageio.stream.ImageInputStream input = javax.imageio.ImageIO .createImageInputStream(bin); javax.imageio.ImageReader reader = getPNGImageReader(); reader.setInput(input); java.awt.image.BufferedImage img = reader.read(0); // create ICOImage IconEntry iconEntry = entries[i]; ICOImage icoImage = new ICOImage(img, null, iconEntry); icoImage.setPngCompressed(true); icoImage.setIconIndex(i); ret.add(icoImage); } else { MyBoxLog.error("Unrecognized icon format for image #" + i); return null; } /* * InfoHeader andInfoHeader = new InfoHeader(); * andInfoHeader.iColorsImportant = 0; andInfoHeader.iColorsUsed * = 0; andInfoHeader.iCompression = BMPConstants.BI_RGB; * andInfoHeader.iHeight = xorInfoHeader.iHeight / 2; * andInfoHeader.iWidth = xorInfoHeader. */ } // long t2 = System.currentTimeMillis(); // System.out.println("Loaded ICO file in "+(t2 - t)+"ms"); return ret; } catch (Exception e) { MyBoxLog.console(e); return null; } } private static IconEntry[] sortByFileOffset(IconEntry[] entries) { List<IconEntry> list = Arrays.asList(entries); Collections.sort(list, new Comparator<IconEntry>() { @Override public int compare(IconEntry o1, IconEntry o2) { return o1.iFileOffset - o2.iFileOffset; } }); return list.toArray(new IconEntry[list.size()]); } /** * Reads and decodes ICO data from the given source, together with all * metadata. The returned list of images is in the order in which they * appear in the source ICO data. * * @param is the source <tt>InputStream</tt> to read * @return the list of images decoded from the ICO data * @throws java.io.IOException if an error occurs * @since 0.7 */ private static javax.imageio.ImageReader getPNGImageReader() { javax.imageio.ImageReader ret = null; java.util.Iterator<javax.imageio.ImageReader> itr = javax.imageio.ImageIO .getImageReadersByFormatName("png"); if (itr.hasNext()) { ret = itr.next(); } return ret; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/image4j/ICOImage.java
alpha/MyBox/src/main/java/thridparty/image4j/ICOImage.java
/* * ICOImage.java * * Created on February 19, 2007, 8:11 AM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package thridparty.image4j; import thridparty.image4j.InfoHeader; /** * Contains a decoded ICO image, as well as information about the source encoded ICO image. * @since 0.7 * @author Ian McDonagh */ public class ICOImage extends thridparty.image4j.BMPImage { protected IconEntry iconEntry; protected boolean pngCompressed = false; protected int iconIndex = -1; /** * Creates a new instance of ICOImage * @param image the BufferedImage decoded from the source ICO image * @param infoHeader the BMP InfoHeader structure for the BMP encoded ICO image * @param iconEntry the IconEntry structure describing the ICO image */ public ICOImage(java.awt.image.BufferedImage image, thridparty.image4j.InfoHeader infoHeader, IconEntry iconEntry) { super(image, infoHeader); this.iconEntry = iconEntry; } /** * The IconEntry associated with this <tt>ICOImage</tt>, which provides information * about the image format and encoding. * @return the IconEntry structure */ public IconEntry getIconEntry() { return iconEntry; } /** * Sets the IconEntry associated with this <tt>ICOImage</tt>. * @param iconEntry the new IconEntry structure to set */ public void setIconEntry(IconEntry iconEntry) { this.iconEntry = iconEntry; } /** * Specifies whether the encoded image is PNG compressed. * @return <tt>true</tt> if the encoded image is PNG compressed, <tt>false</tt> if it is plain BMP encoded */ public boolean isPngCompressed() { return pngCompressed; } /** * Sets whether the encoded image is PNG compressed. * @param pngCompressed <tt>true</tt> if the encoded image is PNG compressed, <tt>false</tt> if it is plain BMP encoded */ public void setPngCompressed(boolean pngCompressed) { this.pngCompressed = pngCompressed; } /** * The InfoHeader structure representing the encoded ICO image. * @return the InfoHeader structure, or <tt>null</tt> if there is no InfoHeader structure, which is possible for PNG compressed icons. */ public InfoHeader getInfoHeader() { return super.getInfoHeader(); } /** * The zero-based index for this <tt>ICOImage</tt> in the source ICO file or resource. * @return the index in the source, or <tt>-1</tt> if it is unknown. */ public int getIconIndex() { return iconIndex; } /** * Sets the icon index, which is zero-based. * @param iconIndex the zero-based icon index, or <tt>-1</tt> if unknown. */ public void setIconIndex(int iconIndex) { this.iconIndex = iconIndex; } /** * The width of the ICO image in pixels. * @return the width of the ICO image, or <tt>-1</tt> if unknown * @since 0.7alpha2 */ public int getWidth() { return iconEntry == null ? -1 : (iconEntry.bWidth == 0 ? 256 : iconEntry.bWidth); } /** * The height of the ICO image in pixels. * @return the height of the ICO image, or <tt>-1</tt> if unknown. * @since 0.7alpha2 */ public int getHeight() { return iconEntry == null ? -1 : (iconEntry.bHeight == 0 ? 256 : iconEntry.bHeight); } /** * The colour depth of the ICO image (bits per pixel). * @return the colour depth, or <tt>-1</tt> if unknown. * @since 0.7alpha2 */ public int getColourDepth() { return iconEntry == null ? -1 : iconEntry.sBitCount; } /** * The number of possible colours for the ICO image. * @return the number of colours, or <tt>-1</tt> if unknown. * @since 0.7alpha2 */ public int getColourCount() { int bpp = iconEntry.sBitCount == 32 ? 24 : iconEntry.sBitCount; return bpp == -1 ? -1 : (int) (1 << bpp); } /** * Specifies whether this ICO image is indexed, that is, the encoded bitmap uses a colour table. * If <tt>getColourDepth()</tt> returns <tt>-1</tt>, the return value has no meaning. * @return <tt>true</tt> if indexed, <tt>false</tt> if not. * @since 0.7alpha2 */ public boolean isIndexed() { return iconEntry == null ? false : iconEntry.sBitCount <= 8; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/image4j/ColorEntry.java
alpha/MyBox/src/main/java/thridparty/image4j/ColorEntry.java
/* * ColorEntry.java * * Created on 10 May 2006, 08:29 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package thridparty.image4j; import java.io.IOException; /** * Represents an RGB colour entry used in the palette of an indexed image (colour depth &lt;= 8). * @author Ian McDonagh */ public class ColorEntry { /** * The red component, which should be in the range <tt>0..255</tt>. */ public int bRed; /** * The green component, which should be in the range <tt>0..255</tt>. */ public int bGreen; /** * The blue component, which should be in the range <tt>0..255</tt>. */ public int bBlue; /** * Unused. */ public int bReserved; /** * Reads and creates a colour entry from the source input. * @param in the source input * @throws java.io.IOException if an error occurs */ public ColorEntry(thridparty.image4j.LittleEndianInputStream in) throws IOException { bBlue = in.readUnsignedByte(); bGreen = in.readUnsignedByte(); bRed = in.readUnsignedByte(); bReserved = in.readUnsignedByte(); } /** * Creates a colour entry with colour components initialized to <tt>0</tt>. */ public ColorEntry() { bBlue = 0; bGreen = 0; bRed = 0; bReserved = 0; } /** * Creates a colour entry with the specified colour components. * @param r red component * @param g green component * @param b blue component * @param a unused */ public ColorEntry(int r, int g, int b, int a) { bBlue = b; bGreen = g; bRed = r; bReserved = a; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/image4j/LittleEndianOutputStream.java
alpha/MyBox/src/main/java/thridparty/image4j/LittleEndianOutputStream.java
/* * LittleEndianOutputStream.java * * Created on 07 November 2006, 08:26 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package thridparty.image4j; import java.io.DataOutputStream; import java.io.IOException; /** * Writes little-endian data to a target <tt>OutputStream</tt> by reversing byte ordering. * @author Ian McDonagh */ public class LittleEndianOutputStream extends DataOutputStream { /** * Creates a new instance of <tt>LittleEndianOutputStream</tt>, which will write to the specified target. * @param out the target <tt>OutputStream</tt> */ public LittleEndianOutputStream(java.io.OutputStream out) { super(out); } /** * Writes a little-endian <tt>short</tt> value * @param value the source value to convert * @throws java.io.IOException if an error occurs */ public void writeShortLE(short value) throws IOException { value = EndianUtils.swapShort(value); super.writeShort(value); } /** * Writes a little-endian <tt>int</tt> value * @param value the source value to convert * @throws java.io.IOException if an error occurs */ public void writeIntLE(int value) throws IOException { value = EndianUtils.swapInteger(value); super.writeInt(value); } /** * Writes a little-endian <tt>float</tt> value * @param value the source value to convert * @throws java.io.IOException if an error occurs */ public void writeFloatLE(float value) throws IOException { value = EndianUtils.swapFloat(value); super.writeFloat(value); } /** * Writes a little-endian <tt>long</tt> value * @param value the source value to convert * @throws java.io.IOException if an error occurs */ public void writeLongLE(long value) throws IOException { value = EndianUtils.swapLong(value); super.writeLong(value); } /** * Writes a little-endian <tt>double</tt> value * @param value the source value to convert * @throws java.io.IOException if an error occurs */ public void writeDoubleLE(double value) throws IOException { value = EndianUtils.swapDouble(value); super.writeDouble(value); } /** * @since 0.6 */ public void writeUnsignedInt(long value) throws IOException { int i1 = (int)(value >> 24); int i2 = (int)((value >> 16) & 0xFF); int i3 = (int)((value >> 8) & 0xFF); int i4 = (int)(value & 0xFF); write(i1); write(i2); write(i3); write(i4); } /** * @since 0.6 */ public void writeUnsignedIntLE(long value) throws IOException { int i1 = (int)(value >> 24); int i2 = (int)((value >> 16) & 0xFF); int i3 = (int)((value >> 8) & 0xFF); int i4 = (int)(value & 0xFF); write(i4); write(i3); write(i2); write(i1); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/image4j/ImageUtil.java
alpha/MyBox/src/main/java/thridparty/image4j/ImageUtil.java
/* * ImageUtil.java * * Created on 15 May 2006, 01:12 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package thridparty.image4j; import java.awt.AlphaComposite; import java.awt.Composite; import java.awt.Graphics2D; import java.awt.Image; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.IndexColorModel; /** * Provides utility methods for handling images (<tt>java.awt.BufferedImage</tt>) * @author Ian McDonagh */ public class ImageUtil { /** * Creates a scaled copy of the source image. * @param src source image to be scaled * @param width the width for the new scaled image in pixels * @param height the height for the new scaled image in pixels * @return a copy of the source image scaled to <tt>width</tt> x <tt>height</tt> pixels. */ public static BufferedImage scaleImage(BufferedImage src, int width, int height) { Image scaled = src.getScaledInstance(width, height, 0); BufferedImage ret = null; /* ColorModel cm = src.getColorModel(); if (cm instanceof IndexColorModel) { ret = new BufferedImage( width, height, src.getType(), (IndexColorModel) cm ); } else { ret = new BufferedImage( src.getWidth(), src.getHeight(), src.getType() ); } Graphics2D g = ret.createGraphics(); //clear alpha channel Composite comp = g.getComposite(); g.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f)); Rectangle2D.Double d = new Rectangle2D.Double(0,0,ret.getWidth(),ret.getHeight()); g.fill(d); g.setComposite(comp); */ ret = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g = ret.createGraphics(); //copy image g.drawImage(scaled, 0, 0, null); return ret; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/image4j/CountingInputStream.java
alpha/MyBox/src/main/java/thridparty/image4j/CountingInputStream.java
package thridparty.image4j; import java.io.*; public class CountingInputStream extends FilterInputStream { private int count; public CountingInputStream(InputStream src) { super(src); } public int getCount() { return count; } @Override public int read() throws IOException { int b = super.read(); if (b != -1) { count++; } return b; } @Override public int read(byte[] b, int off, int len) throws IOException { int r = super.read(b, off, len); if (r > 0) { count += r; } return r; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/image4j/CountingDataInput.java
alpha/MyBox/src/main/java/thridparty/image4j/CountingDataInput.java
package thridparty.image4j; import java.io.DataInput; public interface CountingDataInput extends DataInput, CountingInput { }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/image4j/EndianUtils.java
alpha/MyBox/src/main/java/thridparty/image4j/EndianUtils.java
package thridparty.image4j; /** * Provides utility methods for endian conversions [big-endian to little-endian; * little-endian to big-endian]. * * @author Ian McDonagh */ public class EndianUtils { /** * Reverses the byte order of the source <tt>short</tt> value * * @param value * the source value * @return the converted value */ public static short swapShort(short value) { return (short) (((value & 0xFF00) >> 8) | ((value & 0x00FF) << 8)); } /** * Reverses the byte order of the source <tt>int</tt> value * * @param value * the source value * @return the converted value */ public static int swapInteger(int value) { return ((value & 0xFF000000) >> 24) | ((value & 0x00FF0000) >> 8) | ((value & 0x0000FF00) << 8) | ((value & 0x000000FF) << 24); } /** * Reverses the byte order of the source <tt>long</tt> value * * @param value * the source value * @return the converted value */ public static long swapLong(long value) { return ((value & 0xFF00000000000000L) >> 56) | ((value & 0x00FF000000000000L) >> 40) | ((value & 0x0000FF0000000000L) >> 24) | ((value & 0x000000FF00000000L) >> 8) | ((value & 0x00000000FF000000L) << 8) | ((value & 0x0000000000FF0000L) << 24) | ((value & 0x000000000000FF00L) << 40) | ((value & 0x00000000000000FFL) << 56); } /** * Reverses the byte order of the source <tt>float</tt> value * * @param value * the source value * @return the converted value */ public static float swapFloat(float value) { int i = Float.floatToIntBits(value); i = swapInteger(i); return Float.intBitsToFloat(i); } /** * Reverses the byte order of the source <tt>double</tt> value * * @param value * the source value * @return the converted value */ public static double swapDouble(double value) { long l = Double.doubleToLongBits(value); l = swapLong(l); return Double.longBitsToDouble(l); } public static String toHexString(int i, boolean littleEndian, int bytes) { if (littleEndian) { i = swapInteger(i); } StringBuilder sb = new StringBuilder(); sb.append(Integer.toHexString(i)); if (sb.length() % 2 != 0) { sb.insert(0, '0'); } while (sb.length() < bytes * 2) { sb.insert(0, "00"); } return sb.toString(); } public static StringBuilder toCharString(StringBuilder sb, int i, int bytes, char def) { int shift = 24; for (int j = 0; j < bytes; j++) { int b = (i >> shift) & 0xFF; char c = b < 32 ? def : (char) b; sb.append(c); shift -= 8; } return sb; } public static String toInfoString(int info) { StringBuilder sb = new StringBuilder(); sb.append("Decimal: ").append(info); sb.append(", Hex BE: ").append(toHexString(info, false, 4)); sb.append(", Hex LE: ").append(toHexString(info, true, 4)); sb.append(", String BE: ["); sb = toCharString(sb, info, 4, '.'); sb.append(']'); sb.append(", String LE: ["); sb = toCharString(sb, swapInteger(info), 4, '.'); sb.append(']'); return sb.toString(); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/image4j/BMPConstants.java
alpha/MyBox/src/main/java/thridparty/image4j/BMPConstants.java
/* * BMPConstants.java * * Created on 10 May 2006, 08:17 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package thridparty.image4j; /** * Provides constants used with BMP format. * * @author Ian McDonagh */ public class BMPConstants { private BMPConstants() { } /** * The signature for the BMP format header "BM". */ public static final String FILE_HEADER = "BM"; /** * Specifies no compression. * * @see InfoHeader#iCompression InfoHeader */ public static final int BI_RGB = 0; // no compression /** * Specifies 8-bit RLE compression. * * @see InfoHeader#iCompression InfoHeader */ public static final int BI_RLE8 = 1; // 8bit RLE compression /** * Specifies 4-bit RLE compression. * * @see InfoHeader#iCompression InfoHeader */ public static final int BI_RLE4 = 2; // 4bit RLE compression /** * Specifies 16-bit or 32-bit "bit field" compression. * * @see InfoHeader#iCompression InfoHeader */ public static final int BI_BITFIELDS = 3; // 16bit or 32bit "bit field" // compression. /** * Specifies JPEG compression. * * @see InfoHeader#iCompression InfoHeader */ public static final int BI_JPEG = 4; // _JPEG compression /** * Specifies PNG compression. * * @see InfoHeader#iCompression InfoHeader */ public static final int BI_PNG = 5; // PNG compression }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/image4j/ICOConstants.java
alpha/MyBox/src/main/java/thridparty/image4j/ICOConstants.java
/* * ICOConstants.java * * Created on May 13, 2006, 8:07 PM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package thridparty.image4j; /** * Provides constants used with ICO format. * @author Ian McDonagh */ public class ICOConstants { /** * Indicates that ICO data represents an icon (.ICO). */ public static final int TYPE_ICON = 1; /** * Indicates that ICO data represents a cursor (.CUR). */ public static final int TYPE_CURSOR = 2; }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/image4j/BMPDecoder.java
alpha/MyBox/src/main/java/thridparty/image4j/BMPDecoder.java
/* * Decodes a BMP image from an <tt>InputStream</tt> to a <tt>BufferedImage</tt> * * @author Ian McDonagh */ package thridparty.image4j; import java.awt.image.*; import java.io.*; /** * Decodes images in BMP format. * @author Ian McDonagh */ public class BMPDecoder { private BufferedImage img; private InfoHeader infoHeader; /** Creates a new instance of BMPDecoder and reads the BMP data from the source. * @param in the source <tt>InputStream</tt> from which to read the BMP data * @throws java.io.IOException if an error occurs */ public BMPDecoder(java.io.InputStream in) throws IOException { LittleEndianInputStream lis = new LittleEndianInputStream(new CountingInputStream(in)); /* header [14] */ //signature "BM" [2] byte[] bsignature = new byte[2]; lis.read(bsignature); String signature = new String(bsignature, "UTF-8"); if (!signature.equals("BM")) { throw new IOException("Invalid signature '"+signature+"' for BMP format"); } //file size [4] int fileSize = lis.readIntLE(); //reserved = 0 [4] int reserved = lis.readIntLE(); //DataOffset [4] file offset to raster data int dataOffset = lis.readIntLE(); /* info header [40] */ infoHeader = readInfoHeader(lis); /* Color table and Raster data */ img = read(infoHeader, lis); } /** * Retrieves a bit from the lowest order byte of the given integer. * @param bits the source integer, treated as an unsigned byte * @param index the index of the bit to retrieve, which must be in the range <tt>0..7</tt>. * @return the bit at the specified index, which will be either <tt>0</tt> or <tt>1</tt>. */ private static int getBit(int bits, int index) { return (bits >> (7 - index)) & 1; } /** * Retrieves a nibble (4 bits) from the lowest order byte of the given integer. * @param nibbles the source integer, treated as an unsigned byte * @param index the index of the nibble to retrieve, which must be in the range <tt>0..1</tt>. * @return the nibble at the specified index, as an unsigned byte. */ private static int getNibble(int nibbles, int index) { return (nibbles >> (4 * (1 - index))) & 0xF; } /** * The <tt>InfoHeader</tt> structure, which provides information about the BMP data. * @return the <tt>InfoHeader</tt> structure that was read from the source data when this <tt>BMPDecoder</tt> * was created. */ public InfoHeader getInfoHeader() { return infoHeader; } /** * The decoded image read from the source input. * @return the <tt>BufferedImage</tt> representing the BMP image. */ public BufferedImage getBufferedImage() { return img; } private static void getColorTable(ColorEntry[] colorTable, byte[] ar, byte[] ag, byte[] ab) { for (int i = 0; i < colorTable.length; i++) { ar[i] = (byte) colorTable[i].bRed; ag[i] = (byte) colorTable[i].bGreen; ab[i] = (byte) colorTable[i].bBlue; } } /** * Reads the BMP info header structure from the given <tt>InputStream</tt>. * @param lis the <tt>InputStream</tt> to read * @return the <tt>InfoHeader</tt> structure * @throws java.io.IOException if an error occurred */ public static InfoHeader readInfoHeader(thridparty.image4j.LittleEndianInputStream lis) throws IOException { InfoHeader infoHeader = new InfoHeader(lis); return infoHeader; } /** * @since 0.6 */ public static InfoHeader readInfoHeader(thridparty.image4j.LittleEndianInputStream lis, int infoSize) throws IOException { InfoHeader infoHeader = new InfoHeader(lis, infoSize); return infoHeader; } /** * Reads the BMP data from the given <tt>InputStream</tt> using the information * contained in the <tt>InfoHeader</tt>. * @param lis the source input * @param infoHeader an <tt>InfoHeader</tt> that was read by a call to * {@link #readInfoHeader(net.sf.image4j.io.LittleEndianInputStream) readInfoHeader()}. * @return the decoded image read from the source input * @throws java.io.IOException if an error occurs */ public static BufferedImage read(InfoHeader infoHeader, thridparty.image4j.LittleEndianInputStream lis) throws IOException { BufferedImage img = null; /* Color table (palette) */ ColorEntry[] colorTable = null; //color table is only present for 1, 4 or 8 bit (indexed) images if (infoHeader.sBitCount <= 8) { colorTable = readColorTable(infoHeader, lis); } img = read(infoHeader, lis, colorTable); return img; } /** * Reads the BMP data from the given <tt>InputStream</tt> using the information * contained in the <tt>InfoHeader</tt>. * @param colorTable <tt>ColorEntry</tt> array containing palette * @param infoHeader an <tt>InfoHeader</tt> that was read by a call to * {@link #readInfoHeader(net.sf.image4j.io.LittleEndianInputStream) readInfoHeader()}. * @param lis the source input * @return the decoded image read from the source input * @throws java.io.IOException if any error occurs */ public static BufferedImage read(InfoHeader infoHeader, thridparty.image4j.LittleEndianInputStream lis, ColorEntry[] colorTable) throws IOException { BufferedImage img = null; //1-bit (monochrome) uncompressed if (infoHeader.sBitCount == 1 && infoHeader.iCompression == BMPConstants.BI_RGB) { img = read1(infoHeader, lis, colorTable); } //4-bit uncompressed else if (infoHeader.sBitCount == 4 && infoHeader.iCompression == BMPConstants.BI_RGB) { img = read4(infoHeader, lis, colorTable); } //8-bit uncompressed else if (infoHeader.sBitCount == 8 && infoHeader.iCompression == BMPConstants.BI_RGB) { img = read8(infoHeader, lis, colorTable); } //24-bit uncompressed else if (infoHeader.sBitCount == 24 && infoHeader.iCompression == BMPConstants.BI_RGB) { img = read24(infoHeader, lis); } //32bit uncompressed else if (infoHeader.sBitCount == 32 && infoHeader.iCompression == BMPConstants.BI_RGB) { img = read32(infoHeader, lis); } else { throw new IOException("Unrecognized bitmap format: bit count="+infoHeader.sBitCount+", compression="+ infoHeader.iCompression); } return img; } /** * Reads the <tt>ColorEntry</tt> table from the given <tt>InputStream</tt> using * the information contained in the given <tt>infoHeader</tt>. * @param infoHeader the <tt>InfoHeader</tt> structure, which was read using * {@link #readInfoHeader(net.sf.image4j.io.LittleEndianInputStream) readInfoHeader()} * @param lis the <tt>InputStream</tt> to read * @throws java.io.IOException if an error occurs * @return the decoded image read from the source input */ public static ColorEntry[] readColorTable(InfoHeader infoHeader, thridparty.image4j.LittleEndianInputStream lis) throws IOException { ColorEntry[] colorTable = new ColorEntry[infoHeader.iNumColors]; for (int i = 0; i < infoHeader.iNumColors; i++) { ColorEntry ce = new ColorEntry(lis); colorTable[i] = ce; } return colorTable; } /** * Reads 1-bit uncompressed bitmap raster data, which may be monochrome depending on the * palette entries in <tt>colorTable</tt>. * @param infoHeader the <tt>InfoHeader</tt> structure, which was read using * {@link #readInfoHeader(net.sf.image4j.io.LittleEndianInputStream) readInfoHeader()} * @param lis the source input * @param colorTable <tt>ColorEntry</tt> array specifying the palette, which * must not be <tt>null</tt>. * @throws java.io.IOException if an error occurs * @return the decoded image read from the source input */ public static BufferedImage read1(InfoHeader infoHeader, thridparty.image4j.LittleEndianInputStream lis, ColorEntry[] colorTable) throws IOException { //1 bit per pixel or 8 pixels per byte //each pixel specifies the palette index byte[] ar = new byte[colorTable.length]; byte[] ag = new byte[colorTable.length]; byte[] ab = new byte[colorTable.length]; getColorTable(colorTable, ar, ag, ab); IndexColorModel icm = new IndexColorModel( 1, 2, ar, ag, ab ); // Create indexed image BufferedImage img = new BufferedImage( infoHeader.iWidth, infoHeader.iHeight, BufferedImage.TYPE_BYTE_BINARY, icm ); // We'll use the raster to set samples instead of RGB values. // The SampleModel of an indexed image interprets samples as // the index of the colour for a pixel, which is perfect for use here. WritableRaster raster = img.getRaster(); //padding int dataBitsPerLine = infoHeader.iWidth; int bitsPerLine = dataBitsPerLine; if (bitsPerLine % 32 != 0) { bitsPerLine = (bitsPerLine / 32 + 1) * 32; } int padBits = bitsPerLine - dataBitsPerLine; int padBytes = padBits / 8; int bytesPerLine = (int) (bitsPerLine / 8); int[] line = new int[bytesPerLine]; for (int y = infoHeader.iHeight - 1; y >= 0; y--) { for (int i = 0; i < bytesPerLine; i++) { line[i] = lis.readUnsignedByte(); } for (int x = 0; x < infoHeader.iWidth; x++) { int i = x / 8; int v = line[i]; int b = x % 8; int index = getBit(v, b); //int rgb = c[index]; //img.setRGB(x, y, rgb); //set the sample (colour index) for the pixel raster.setSample(x, y, 0, index); } } return img; } /** * Reads 4-bit uncompressed bitmap raster data, which is interpreted based on the colours * specified in the palette. * @param infoHeader the <tt>InfoHeader</tt> structure, which was read using * {@link #readInfoHeader(net.sf.image4j.io.LittleEndianInputStream) readInfoHeader()} * @param lis the source input * @param colorTable <tt>ColorEntry</tt> array specifying the palette, which * must not be <tt>null</tt>. * @throws java.io.IOException if an error occurs * @return the decoded image read from the source input */ public static BufferedImage read4(InfoHeader infoHeader, thridparty.image4j.LittleEndianInputStream lis, ColorEntry[] colorTable) throws IOException { // 2 pixels per byte or 4 bits per pixel. // Colour for each pixel specified by the color index in the pallette. byte[] ar = new byte[colorTable.length]; byte[] ag = new byte[colorTable.length]; byte[] ab = new byte[colorTable.length]; getColorTable(colorTable, ar, ag, ab); IndexColorModel icm = new IndexColorModel( 4, infoHeader.iNumColors, ar, ag, ab ); BufferedImage img = new BufferedImage( infoHeader.iWidth, infoHeader.iHeight, BufferedImage.TYPE_BYTE_BINARY, icm ); WritableRaster raster = img.getRaster(); //padding int bitsPerLine = infoHeader.iWidth * 4; if (bitsPerLine % 32 != 0) { bitsPerLine = (bitsPerLine / 32 + 1) * 32; } int bytesPerLine = (int) (bitsPerLine / 8); int[] line = new int[bytesPerLine]; for (int y = infoHeader.iHeight - 1; y >= 0; y--) { //scan line for (int i = 0; i < bytesPerLine; i++) { int b = lis.readUnsignedByte(); line[i] = b; } //get pixels for (int x = 0; x < infoHeader.iWidth; x++) { //get byte index for line int b = x / 2; // 2 pixels per byte int i = x % 2; int n = line[b]; int index = getNibble(n, i); raster.setSample(x, y, 0, index); } } return img; } /** * Reads 8-bit uncompressed bitmap raster data, which is interpreted based on the colours * specified in the palette. * @param infoHeader the <tt>InfoHeader</tt> structure, which was read using * {@link #readInfoHeader(net.sf.image4j.io.LittleEndianInputStream) readInfoHeader()} * @param lis the source input * @param colorTable <tt>ColorEntry</tt> array specifying the palette, which * must not be <tt>null</tt>. * @throws java.io.IOException if an error occurs * @return the decoded image read from the source input */ public static BufferedImage read8(InfoHeader infoHeader, thridparty.image4j.LittleEndianInputStream lis, ColorEntry[] colorTable) throws IOException { //1 byte per pixel // color index 1 (index of color in palette) //lines padded to nearest 32bits //no alpha byte[] ar = new byte[colorTable.length]; byte[] ag = new byte[colorTable.length]; byte[] ab = new byte[colorTable.length]; getColorTable(colorTable, ar, ag, ab); IndexColorModel icm = new IndexColorModel( 8, infoHeader.iNumColors, ar, ag, ab ); BufferedImage img = new BufferedImage( infoHeader.iWidth, infoHeader.iHeight, BufferedImage.TYPE_BYTE_INDEXED, icm ); WritableRaster raster = img.getRaster(); /* //create color pallette int[] c = new int[infoHeader.iNumColors]; for (int i = 0; i < c.length; i++) { int r = colorTable[i].bRed; int g = colorTable[i].bGreen; int b = colorTable[i].bBlue; c[i] = (r << 16) | (g << 8) | (b); } */ //padding int dataPerLine = infoHeader.iWidth; int bytesPerLine = dataPerLine; if (bytesPerLine % 4 != 0) { bytesPerLine = (bytesPerLine / 4 + 1) * 4; } int padBytesPerLine = bytesPerLine - dataPerLine; for (int y = infoHeader.iHeight - 1; y >= 0; y--) { for (int x = 0; x < infoHeader.iWidth; x++) { int b = lis.readUnsignedByte(); //int clr = c[b]; //img.setRGB(x, y, clr); //set sample (colour index) for pixel raster.setSample(x, y , 0, b); } lis.skip(padBytesPerLine); } return img; } /** * Reads 24-bit uncompressed bitmap raster data. * @param lis the source input * @param infoHeader the <tt>InfoHeader</tt> structure, which was read using * {@link #readInfoHeader(net.sf.image4j.io.LittleEndianInputStream) readInfoHeader()} * @throws java.io.IOException if an error occurs * @return the decoded image read from the source input */ public static BufferedImage read24(InfoHeader infoHeader, thridparty.image4j.LittleEndianInputStream lis) throws IOException { //3 bytes per pixel // blue 1 // green 1 // red 1 // lines padded to nearest 32 bits // no alpha BufferedImage img = new BufferedImage( infoHeader.iWidth, infoHeader.iHeight, BufferedImage.TYPE_INT_RGB ); WritableRaster raster = img.getRaster(); //padding to nearest 32 bits int dataPerLine = infoHeader.iWidth * 3; int bytesPerLine = dataPerLine; if (bytesPerLine % 4 != 0) { bytesPerLine = (bytesPerLine / 4 + 1) * 4; } int padBytesPerLine = bytesPerLine - dataPerLine; for (int y = infoHeader.iHeight - 1; y >= 0; y--) { for (int x = 0; x < infoHeader.iWidth; x++) { int b = lis.readUnsignedByte(); int g = lis.readUnsignedByte(); int r = lis.readUnsignedByte(); //int c = 0x00000000 | (r << 16) | (g << 8) | (b); //System.out.println(x + ","+y+"="+Integer.toHexString(c)); //img.setRGB(x, y, c); raster.setSample(x, y, 0, r); raster.setSample(x, y, 1, g); raster.setSample(x, y, 2, b); } lis.skip(padBytesPerLine); } return img; } /** * Reads 32-bit uncompressed bitmap raster data, with transparency. * @param lis the source input * @param infoHeader the <tt>InfoHeader</tt> structure, which was read using * {@link #readInfoHeader(net.sf.image4j.io.LittleEndianInputStream) readInfoHeader()} * @throws java.io.IOException if an error occurs * @return the decoded image read from the source input */ public static BufferedImage read32(InfoHeader infoHeader, thridparty.image4j.LittleEndianInputStream lis) throws IOException { //4 bytes per pixel // blue 1 // green 1 // red 1 // alpha 1 //No padding since each pixel = 32 bits BufferedImage img = new BufferedImage( infoHeader.iWidth, infoHeader.iHeight, BufferedImage.TYPE_INT_ARGB ); WritableRaster rgb = img.getRaster(); WritableRaster alpha = img.getAlphaRaster(); for (int y = infoHeader.iHeight - 1; y >= 0; y--) { for (int x = 0; x < infoHeader.iWidth; x++) { int b = lis.readUnsignedByte(); int g = lis.readUnsignedByte(); int r = lis.readUnsignedByte(); int a = lis.readUnsignedByte(); rgb.setSample(x, y, 0, r); rgb.setSample(x, y, 1, g); rgb.setSample(x, y, 2, b); alpha.setSample(x, y, 0, a); } } return img; } /** * Reads and decodes BMP data from the source file. * @param file the source file * @throws java.io.IOException if an error occurs * @return the decoded image read from the source file */ public static BufferedImage read(java.io.File file) throws IOException { java.io.FileInputStream fin = new java.io.FileInputStream(file); try { return read(new BufferedInputStream(fin)); } finally { try { fin.close(); } catch (IOException ex) { } } } /** * Reads and decodes BMP data from the source input. * @param in the source input * @throws java.io.IOException if an error occurs * @return the decoded image read from the source file */ public static BufferedImage read(java.io.InputStream in) throws IOException { BMPDecoder d = new BMPDecoder(in); return d.getBufferedImage(); } /** * Reads and decodes BMP data from the source file, together with metadata. * @param file the source file * @throws java.io.IOException if an error occurs * @return the decoded image read from the source file * @since 0.7 */ public static BMPImage readExt(java.io.File file) throws IOException { java.io.FileInputStream fin = new java.io.FileInputStream(file); try { return readExt(new BufferedInputStream(fin)); } finally { try { fin.close(); } catch (IOException ex) { } } } /** * Reads and decodes BMP data from the source input, together with metadata. * @param in the source input * @throws java.io.IOException if an error occurs * @return the decoded image read from the source file * @since 0.7 */ public static BMPImage readExt(java.io.InputStream in) throws IOException { BMPDecoder d = new BMPDecoder(in); BMPImage ret = new BMPImage(d.getBufferedImage(), d.getInfoHeader()); return ret; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/image4j/LittleEndianInputStream.java
alpha/MyBox/src/main/java/thridparty/image4j/LittleEndianInputStream.java
/* * LittleEndianInputStream.java * * Created on 07 November 2006, 08:26 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package thridparty.image4j; import java.io.EOFException; import java.io.IOException; /** * Reads little-endian data from a source <tt>InputStream</tt> by reversing byte ordering. * @author Ian McDonagh */ public class LittleEndianInputStream extends java.io.DataInputStream implements CountingDataInput { /** * Creates a new instance of <tt>LittleEndianInputStream</tt>, which will read from the specified source. * @param in the source <tt>InputStream</tt> */ public LittleEndianInputStream(CountingInputStream in) { super(in); } @Override public int getCount() { return ((CountingInputStream) in).getCount(); } public int skip(int count, boolean strict) throws IOException { return IOUtils.skip(this, count, strict); } /** * Reads a little-endian <tt>short</tt> value * @throws java.io.IOException if an error occurs * @return <tt>short</tt> value with reversed byte order */ public short readShortLE() throws IOException { int b1 = read(); int b2 = read(); if (b1 < 0 || b2 < 0) { throw new EOFException(); } short ret = (short) ((b2 << 8) + (b1 << 0)); return ret; } /** * Reads a little-endian <tt>int</tt> value. * @throws java.io.IOException if an error occurs * @return <tt>int</tt> value with reversed byte order */ public int readIntLE() throws IOException { int b1 = read(); int b2 = read(); int b3 = read(); int b4 = read(); if (b1 < -1 || b2 < -1 || b3 < -1 || b4 < -1) { throw new EOFException(); } int ret = (b4 << 24) + (b3 << 16) + (b2 << 8) + (b1 << 0); return ret; } /** * Reads a little-endian <tt>float</tt> value. * @throws java.io.IOException if an error occurs * @return <tt>float</tt> value with reversed byte order */ public float readFloatLE() throws IOException { int i = readIntLE(); float ret = Float.intBitsToFloat(i); return ret; } /** * Reads a little-endian <tt>long</tt> value. * @throws java.io.IOException if an error occurs * @return <tt>long</tt> value with reversed byte order */ public long readLongLE() throws IOException { int i1 = readIntLE(); int i2 = readIntLE(); long ret = ((long)(i1) << 32) + (i2 & 0xFFFFFFFFL); return ret; } /** * Reads a little-endian <tt>double</tt> value. * @throws java.io.IOException if an error occurs * @return <tt>double</tt> value with reversed byte order */ public double readDoubleLE() throws IOException { long l = readLongLE(); double ret = Double.longBitsToDouble(l); return ret; } /** * @since 0.6 */ public long readUnsignedInt() throws IOException { long i1 = readUnsignedByte(); long i2 = readUnsignedByte(); long i3 = readUnsignedByte(); long i4 = readUnsignedByte(); long ret = ((i1 << 24) | (i2 << 16) | (i3 << 8) | i4); return ret; } /** * @since 0.6 */ public long readUnsignedIntLE() throws IOException { long i1 = readUnsignedByte(); long i2 = readUnsignedByte(); long i3 = readUnsignedByte(); long i4 = readUnsignedByte(); long ret = (i4 << 24) | (i3 << 16) | (i2 << 8) | i1; return ret; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/image4j/ConvertUtil.java
alpha/MyBox/src/main/java/thridparty/image4j/ConvertUtil.java
/* * ConvertUtil.java * * Created on 12 May 2006, 09:22 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package thridparty.image4j; import java.awt.Transparency; import java.awt.image.BufferedImage; import java.awt.image.ColorConvertOp; import java.awt.image.DataBuffer; import java.awt.image.IndexColorModel; /** * Provides useful methods for converting images from one colour depth to another. * @author Ian McDonagh */ public class ConvertUtil { /** * Converts the source to 1-bit colour depth (monochrome). * No transparency. * @param src the source image to convert * @return a copy of the source image with a 1-bit colour depth. */ public static BufferedImage convert1(BufferedImage src) { IndexColorModel icm = new IndexColorModel( 1, 2, new byte[] { (byte) 0, (byte) 0xFF }, new byte[] { (byte) 0, (byte) 0xFF }, new byte[] { (byte) 0, (byte) 0xFF } ); BufferedImage dest = new BufferedImage( src.getWidth(), src.getHeight(), BufferedImage.TYPE_BYTE_BINARY, icm ); ColorConvertOp cco = new ColorConvertOp( src.getColorModel().getColorSpace(), dest.getColorModel().getColorSpace(), null ); cco.filter(src, dest); return dest; } /** * Converts the source image to 4-bit colour * using the default 16-colour palette: * <ul> * <li>black</li><li>dark red</li><li>dark green</li> * <li>dark yellow</li><li>dark blue</li><li>dark magenta</li> * <li>dark cyan</li><li>dark grey</li><li>light grey</li> * <li>red</li><li>green</li><li>yellow</li><li>blue</li> * <li>magenta</li><li>cyan</li><li>white</li> * </ul> * No transparency. * @param src the source image to convert * @return a copy of the source image with a 4-bit colour depth, with the default colour pallette */ public static BufferedImage convert4(BufferedImage src) { int[] cmap = new int[] { 0x000000, 0x800000, 0x008000, 0x808000, 0x000080, 0x800080, 0x008080, 0x808080, 0xC0C0C0, 0xFF0000, 0x00FF00, 0xFFFF00, 0x0000FF, 0xFF00FF, 0x00FFFF, 0xFFFFFF }; return convert4(src, cmap); } /** * Converts the source image to 4-bit colour * using the given colour map. No transparency. * @param src the source image to convert * @param cmap the colour map, which should contain no more than 16 entries * The entries are in the form RRGGBB (hex). * @return a copy of the source image with a 4-bit colour depth, with the custom colour pallette */ public static BufferedImage convert4(BufferedImage src, int[] cmap) { IndexColorModel icm = new IndexColorModel( 4, cmap.length, cmap, 0, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE ); BufferedImage dest = new BufferedImage( src.getWidth(), src.getHeight(), BufferedImage.TYPE_BYTE_BINARY, icm ); ColorConvertOp cco = new ColorConvertOp( src.getColorModel().getColorSpace(), dest.getColorModel().getColorSpace(), null ); cco.filter(src, dest); return dest; } /** * Converts the source image to 8-bit colour * using the default 256-colour palette. No transparency. * @param src the source image to convert * @return a copy of the source image with an 8-bit colour depth */ public static BufferedImage convert8(BufferedImage src) { BufferedImage dest = new BufferedImage( src.getWidth(), src.getHeight(), BufferedImage.TYPE_BYTE_INDEXED ); ColorConvertOp cco = new ColorConvertOp( src.getColorModel().getColorSpace(), dest.getColorModel().getColorSpace(), null ); cco.filter(src, dest); return dest; } /** * Converts the source image to 24-bit colour (RGB). No transparency. * @param src the source image to convert * @return a copy of the source image with a 24-bit colour depth */ public static BufferedImage convert24(BufferedImage src) { BufferedImage dest = new BufferedImage( src.getWidth(), src.getHeight(), BufferedImage.TYPE_INT_RGB ); ColorConvertOp cco = new ColorConvertOp( src.getColorModel().getColorSpace(), dest.getColorModel().getColorSpace(), null ); cco.filter(src, dest); return dest; } /** * Converts the source image to 32-bit colour with transparency (ARGB). * @param src the source image to convert * @return a copy of the source image with a 32-bit colour depth. */ public static BufferedImage convert32(BufferedImage src) { BufferedImage dest = new BufferedImage( src.getWidth(), src.getHeight(), BufferedImage.TYPE_INT_ARGB ); ColorConvertOp cco = new ColorConvertOp( src.getColorModel().getColorSpace(), dest.getColorModel().getColorSpace(), null ); cco.filter(src, dest); return dest; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/jankovicsandras/ImageTracer.java
alpha/MyBox/src/main/java/thridparty/jankovicsandras/ImageTracer.java
// https://github.com/jankovicsandras/imagetracerjava /* ImageTracer.java (Desktop version with javax.imageio. See ImageTracerAndroid.java for the Android version.) Simple raster image tracer and vectorizer written in Java. This is a port of imagetracer.js. by András Jankovics 2015, 2016 andras@jankovics.net */ /* The Unlicense / PUBLIC DOMAIN This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to http://unlicense.org/ */ package thridparty.jankovicsandras; import java.awt.image.BufferedImage; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.Map.Entry; import java.util.TreeMap; import javax.imageio.ImageIO; import mara.mybox.dev.MyBoxLog; public class ImageTracer { public static String versionnumber = "1.1.2"; public ImageTracer() { } public static void main(String[] args) { try { if (args.length < 1) { System.out.println("ERROR: there's no input filename. Basic usage: \r\n\r\njava -jar ImageTracer.jar <filename>" + "\r\n\r\nor\r\n\r\njava -jar ImageTracer.jar help"); } else if (arraycontains(args, "help") > -1) { System.out.println("Example usage:\r\n\r\njava -jar ImageTracer.jar <filename> outfilename test.svg " + "ltres 1 qtres 1 pathomit 8 colorsampling 1 numberofcolors 16 mincolorratio 0.02 colorquantcycles 3 " + "scale 1 simplifytolerance 0 roundcoords 1 lcpr 0 qcpr 0 desc 1 viewbox 0 blurradius 0 blurdelta 20 \r\n" + "\r\nOnly <filename> is mandatory, if some of the other optional parameters are missing, they will be set to these defaults. " + "\r\nWarning: if outfilename is not specified, then <filename>.svg will be overwritten." + "\r\nSee https://github.com/jankovicsandras/imagetracerjava for details. \r\nThis is version " + versionnumber); } else { // Parameter parsing String outfilename = args[0] + ".svg"; HashMap<String, Float> options = new HashMap<String, Float>(); String[] parameternames = {"ltres", "qtres", "pathomit", "colorsampling", "numberofcolors", "mincolorratio", "colorquantcycles", "scale", "simplifytolerance", "roundcoords", "lcpr", "qcpr", "desc", "viewbox", "blurradius", "blurdelta", "outfilename"}; int j = -1; float f = -1; for (String parametername : parameternames) { j = arraycontains(args, parametername); if (j > -1) { if (parametername == "outfilename") { if (j < (args.length - 1)) { outfilename = args[j + 1]; } } else { f = parsenext(args, j); if (f > -1) { options.put(parametername, new Float(f)); } } } }// End of parameternames loop // Loading image, tracing, rendering SVG, saving SVG file saveString(outfilename, imageToSVG(args[0], options, null)); }// End of parameter parsing and processing } catch (Exception e) { e.printStackTrace(); } }// End of main() public static int arraycontains(String[] arr, String str) { for (int j = 0; j < arr.length; j++) { if (arr[j].toLowerCase().equals(str)) { return j; } } return -1; } public static float parsenext(String[] arr, int i) { if (i < (arr.length - 1)) { try { return Float.parseFloat(arr[i + 1]); } catch (Exception e) { } } return -1; } // Container for the color-indexed image before and tracedata after vectorizing public static class IndexedImage { public int width, height; public int[][] array; // array[x][y] of palette colors public byte[][] palette;// array[palettelength][4] RGBA color palette public ArrayList<ArrayList<ArrayList<Double[]>>> layers;// tracedata public IndexedImage(int[][] marray, byte[][] mpalette) { array = marray; palette = mpalette; width = marray[0].length - 2; height = marray.length - 2;// Color quantization adds +2 to the original width and height } } // https://developer.mozilla.org/en-US/docs/Web/API/ImageData public static class ImageData { public int width, height; public byte[] data; // raw byte data: R G B A R G B A ... public ImageData(int mwidth, int mheight, byte[] mdata) { width = mwidth; height = mheight; data = mdata; } } // Saving a String as a file public static void saveString(String filename, String str) throws Exception { File file = new File(filename); // if file doesnt exists, then create it if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(str); bw.close(); } // Loading a file to ImageData, ARGB byte order public static ImageData loadImageData(String filename) throws Exception { BufferedImage image = ImageIO.read(new File(filename)); return loadImageData(image); } public static ImageData loadImageData(BufferedImage image) throws Exception { int width = image.getWidth(); int height = image.getHeight(); int[] rawdata = image.getRGB(0, 0, width, height, null, 0, width); byte[] data = new byte[rawdata.length * 4]; for (int i = 0; i < rawdata.length; i++) { data[(i * 4) + 3] = bytetrans((byte) (rawdata[i] >>> 24)); data[i * 4] = bytetrans((byte) (rawdata[i] >>> 16)); data[(i * 4) + 1] = bytetrans((byte) (rawdata[i] >>> 8)); data[(i * 4) + 2] = bytetrans((byte) (rawdata[i])); } return new ImageData(width, height, data); } // The bitshift method in loadImageData creates signed bytes where -1 -> 255 unsigned ; -128 -> 128 unsigned ; // 127 -> 127 unsigned ; 0 -> 0 unsigned ; These will be converted to -128 (representing 0 unsigned) ... // 127 (representing 255 unsigned) and tosvgcolorstr will add +128 to create RGB values 0..255 public static byte bytetrans(byte b) { if (b < 0) { return (byte) (b + 128); } else { return (byte) (b - 128); } } //////////////////////////////////////////////////////////// // // User friendly functions // //////////////////////////////////////////////////////////// // Loading an image from a file, tracing when loaded, then returning the SVG String public static String imageToSVG(String filename, HashMap<String, Float> options, byte[][] palette) throws Exception { options = checkoptions(options); ImageData imgd = loadImageData(filename); return imagedataToSVG(imgd, options, palette); }// End of imageToSVG() public static String imageToSVG(BufferedImage image, HashMap<String, Float> options, byte[][] palette) throws Exception { options = checkoptions(options); ImageData imgd = loadImageData(image); return imagedataToSVG(imgd, options, palette); }// End of imageToSVG() // Tracing ImageData, then returning the SVG String public static String imagedataToSVG(ImageData imgd, HashMap<String, Float> options, byte[][] palette) { options = checkoptions(options); IndexedImage ii = imagedataToTracedata(imgd, options, palette); return getsvgstring(ii, options); }// End of imagedataToSVG() // Loading an image from a file, tracing when loaded, then returning IndexedImage with tracedata in layers public IndexedImage imageToTracedata(String filename, HashMap<String, Float> options, byte[][] palette) throws Exception { options = checkoptions(options); ImageData imgd = loadImageData(filename); return imagedataToTracedata(imgd, options, palette); }// End of imageToTracedata() public IndexedImage imageToTracedata(BufferedImage image, HashMap<String, Float> options, byte[][] palette) throws Exception { options = checkoptions(options); ImageData imgd = loadImageData(image); return imagedataToTracedata(imgd, options, palette); }// End of imageToTracedata() // Tracing ImageData, then returning IndexedImage with tracedata in layers public static IndexedImage imagedataToTracedata(ImageData imgd, HashMap<String, Float> options, byte[][] palette) { // 1. Color quantization IndexedImage ii = colorquantization(imgd, palette, options); // 2. Layer separation and edge detection int[][][] rawlayers = layering(ii); // 3. Batch pathscan ArrayList<ArrayList<ArrayList<Integer[]>>> bps = batchpathscan(rawlayers, (int) (Math.floor(options.get("pathomit")))); // 4. Batch interpollation ArrayList<ArrayList<ArrayList<Double[]>>> bis = batchinternodes(bps); // 5. Batch tracing ii.layers = batchtracelayers(bis, options.get("ltres"), options.get("qtres")); return ii; }// End of imagedataToTracedata() // creating options object, setting defaults for missing values public static HashMap<String, Float> checkoptions(HashMap<String, Float> options) { if (options == null) { options = new HashMap<String, Float>(); } // Tracing if (!options.containsKey("ltres")) { options.put("ltres", 1f); } if (!options.containsKey("qtres")) { options.put("qtres", 1f); } if (!options.containsKey("pathomit")) { options.put("pathomit", 8f); } // Color quantization if (!options.containsKey("colorsampling")) { options.put("colorsampling", 1f); } if (!options.containsKey("numberofcolors")) { options.put("numberofcolors", 16f); } if (!options.containsKey("mincolorratio")) { options.put("mincolorratio", 0.02f); } if (!options.containsKey("colorquantcycles")) { options.put("colorquantcycles", 3f); } // SVG rendering if (!options.containsKey("scale")) { options.put("scale", 1f); } if (!options.containsKey("simplifytolerance")) { options.put("simplifytolerance", 0f); } if (!options.containsKey("roundcoords")) { options.put("roundcoords", 1f); } if (!options.containsKey("lcpr")) { options.put("lcpr", 0f); } if (!options.containsKey("qcpr")) { options.put("qcpr", 0f); } if (!options.containsKey("desc")) { options.put("desc", 1f); } if (!options.containsKey("viewbox")) { options.put("viewbox", 0f); } // Blur if (!options.containsKey("blurradius")) { options.put("blurradius", 0f); } if (!options.containsKey("blurdelta")) { options.put("blurdelta", 20f); } return options; }// End of checkoptions() //////////////////////////////////////////////////////////// // // Vectorizing functions // //////////////////////////////////////////////////////////// // 1. Color quantization repeated "cycles" times, based on K-means clustering // https://en.wikipedia.org/wiki/Color_quantization https://en.wikipedia.org/wiki/K-means_clustering public static IndexedImage colorquantization(ImageData imgd, byte[][] palette, HashMap<String, Float> options) { int numberofcolors = (int) Math.floor(options.get("numberofcolors")); float minratio = options.get("mincolorratio"); int cycles = (int) Math.floor(options.get("colorquantcycles")); // Creating indexed color array arr which has a boundary filled with -1 in every direction int[][] arr = new int[imgd.height + 2][imgd.width + 2]; for (int j = 0; j < (imgd.height + 2); j++) { arr[j][0] = -1; arr[j][imgd.width + 1] = -1; } for (int i = 0; i < (imgd.width + 2); i++) { arr[0][i] = -1; arr[imgd.height + 1][i] = -1; } int idx = 0, cd, cdl, ci, c1, c2, c3, c4; // Use custom palette if pal is defined or sample or generate custom length palette if (palette == null) { if (options.get("colorsampling") != 0) { palette = samplepalette(numberofcolors, imgd); } else { palette = generatepalette(numberofcolors); } } // Selective Gaussian blur preprocessing if (options.get("blurradius") > 0) { imgd = blur(imgd, options.get("blurradius"), options.get("blurdelta")); } long[][] paletteacc = new long[palette.length][5]; // Repeat clustering step "cycles" times for (int cnt = 0; cnt < cycles; cnt++) { // Average colors from the second iteration if (cnt > 0) { // averaging paletteacc for palette float ratio; for (int k = 0; k < palette.length; k++) { // averaging if (paletteacc[k][3] > 0) { palette[k][0] = (byte) (-128 + (paletteacc[k][0] / paletteacc[k][4])); palette[k][1] = (byte) (-128 + (paletteacc[k][1] / paletteacc[k][4])); palette[k][2] = (byte) (-128 + (paletteacc[k][2] / paletteacc[k][4])); palette[k][3] = (byte) (-128 + (paletteacc[k][3] / paletteacc[k][4])); } ratio = (float) ((double) (paletteacc[k][4]) / (double) (imgd.width * imgd.height)); // Randomizing a color, if there are too few pixels and there will be a new cycle if ((ratio < minratio) && (cnt < (cycles - 1))) { palette[k][0] = (byte) (-128 + Math.floor(Math.random() * 255)); palette[k][1] = (byte) (-128 + Math.floor(Math.random() * 255)); palette[k][2] = (byte) (-128 + Math.floor(Math.random() * 255)); palette[k][3] = (byte) (-128 + Math.floor(Math.random() * 255)); } }// End of palette loop }// End of Average colors from the second iteration // Reseting palette accumulator for averaging for (int i = 0; i < palette.length; i++) { paletteacc[i][0] = 0; paletteacc[i][1] = 0; paletteacc[i][2] = 0; paletteacc[i][3] = 0; paletteacc[i][4] = 0; } // loop through all pixels for (int j = 0; j < imgd.height; j++) { for (int i = 0; i < imgd.width; i++) { idx = ((j * imgd.width) + i) * 4; // find closest color from palette by measuring (rectilinear) color distance between this pixel and all palette colors cdl = 256 + 256 + 256 + 256; ci = 0; for (int k = 0; k < palette.length; k++) { // In my experience, https://en.wikipedia.org/wiki/Rectilinear_distance works better than https://en.wikipedia.org/wiki/Euclidean_distance c1 = Math.abs(palette[k][0] - imgd.data[idx]); c2 = Math.abs(palette[k][1] - imgd.data[idx + 1]); c3 = Math.abs(palette[k][2] - imgd.data[idx + 2]); c4 = Math.abs(palette[k][3] - imgd.data[idx + 3]); cd = c1 + c2 + c3 + (c4 * 4); // weighted alpha seems to help images with transparency // Remember this color if this is the closest yet if (cd < cdl) { cdl = cd; ci = k; } }// End of palette loop // add to palettacc paletteacc[ci][0] += 128 + imgd.data[idx]; paletteacc[ci][1] += 128 + imgd.data[idx + 1]; paletteacc[ci][2] += 128 + imgd.data[idx + 2]; paletteacc[ci][3] += 128 + imgd.data[idx + 3]; paletteacc[ci][4]++; arr[j + 1][i + 1] = ci; }// End of i loop }// End of j loop }// End of Repeat clustering step "cycles" times return new IndexedImage(arr, palette); }// End of colorquantization // Generating a palette with numberofcolors, array[numberofcolors][4] where [i][0] = R ; [i][1] = G ; [i][2] = B ; [i][3] = A public static byte[][] generatepalette(int numberofcolors) { byte[][] palette = new byte[numberofcolors][4]; if (numberofcolors < 8) { // Grayscale double graystep = 255.0 / (double) (numberofcolors - 1); for (byte ccnt = 0; ccnt < numberofcolors; ccnt++) { palette[ccnt][0] = (byte) (-128 + Math.round(ccnt * graystep)); palette[ccnt][1] = (byte) (-128 + Math.round(ccnt * graystep)); palette[ccnt][2] = (byte) (-128 + Math.round(ccnt * graystep)); palette[ccnt][3] = (byte) 127; } } else { // RGB color cube int colorqnum = (int) Math.floor(Math.pow(numberofcolors, 1.0 / 3.0)); // Number of points on each edge on the RGB color cube int colorstep = (int) Math.floor(255 / (colorqnum - 1)); // distance between points int ccnt = 0; for (int rcnt = 0; rcnt < colorqnum; rcnt++) { for (int gcnt = 0; gcnt < colorqnum; gcnt++) { for (int bcnt = 0; bcnt < colorqnum; bcnt++) { palette[ccnt][0] = (byte) (-128 + (rcnt * colorstep)); palette[ccnt][1] = (byte) (-128 + (gcnt * colorstep)); palette[ccnt][2] = (byte) (-128 + (bcnt * colorstep)); palette[ccnt][3] = (byte) 127; ccnt++; }// End of blue loop }// End of green loop }// End of red loop // Rest is random for (int rcnt = ccnt; rcnt < numberofcolors; rcnt++) { palette[ccnt][0] = (byte) (-128 + Math.floor(Math.random() * 255)); palette[ccnt][1] = (byte) (-128 + Math.floor(Math.random() * 255)); palette[ccnt][2] = (byte) (-128 + Math.floor(Math.random() * 255)); palette[ccnt][3] = (byte) (-128 + Math.floor(Math.random() * 255)); } }// End of numberofcolors check return palette; } ;// End of generatepalette() public static byte[][] samplepalette(int numberofcolors, ImageData imgd) { int idx = 0; byte[][] palette = new byte[numberofcolors][4]; for (int i = 0; i < numberofcolors; i++) { idx = (int) (Math.floor((Math.random() * imgd.data.length) / 4) * 4); palette[i][0] = imgd.data[idx]; palette[i][1] = imgd.data[idx + 1]; palette[i][2] = imgd.data[idx + 2]; palette[i][3] = imgd.data[idx + 3]; } return palette; }// End of samplepalette() // 2. Layer separation and edge detection // Edge node types ( ▓:light or 1; ░:dark or 0 ) // 12 ░░ ▓░ ░▓ ▓▓ ░░ ▓░ ░▓ ▓▓ ░░ ▓░ ░▓ ▓▓ ░░ ▓░ ░▓ ▓▓ // 48 ░░ ░░ ░░ ░░ ░▓ ░▓ ░▓ ░▓ ▓░ ▓░ ▓░ ▓░ ▓▓ ▓▓ ▓▓ ▓▓ // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // public static int[][][] layering(IndexedImage ii) { try { // Creating layers for each indexed color in arr int val = 0, aw = ii.array[0].length, ah = ii.array.length, n1, n2, n3, n4, n5, n6, n7, n8; int[][][] layers = new int[ii.palette.length][ah][aw]; // Looping through all pixels and calculating edge node type for (int j = 1; j < (ah - 1); j++) { for (int i = 1; i < (aw - 1); i++) { // This pixel's indexed color val = ii.array[j][i]; // Are neighbor pixel colors the same? n1 = ii.array[j - 1][i - 1] == val ? 1 : 0; n2 = ii.array[j - 1][i] == val ? 1 : 0; n3 = ii.array[j - 1][i + 1] == val ? 1 : 0; n4 = ii.array[j][i - 1] == val ? 1 : 0; n5 = ii.array[j][i + 1] == val ? 1 : 0; n6 = ii.array[j + 1][i - 1] == val ? 1 : 0; n7 = ii.array[j + 1][i] == val ? 1 : 0; n8 = ii.array[j + 1][i + 1] == val ? 1 : 0; // this pixel"s type and looking back on previous pixels layers[val][j + 1][i + 1] = 1 + (n5 * 2) + (n8 * 4) + (n7 * 8); if (n4 == 0) { layers[val][j + 1][i] = 0 + 2 + (n7 * 4) + (n6 * 8); } if (n2 == 0) { layers[val][j][i + 1] = 0 + (n3 * 2) + (n5 * 4) + 8; } if (n1 == 0) { layers[val][j][i] = 0 + (n2 * 2) + 4 + (n4 * 8); } }// End of i loop }// End of j loop return layers; } catch (Exception e) { MyBoxLog.error(e); return null; } }// End of layering() // Lookup tables for pathscan static byte[] pathscan_dir_lookup = {0, 0, 3, 0, 1, 0, 3, 0, 0, 3, 3, 1, 0, 3, 0, 0}; static boolean[] pathscan_holepath_lookup = {false, false, false, false, false, false, false, true, false, false, false, true, false, true, true, false}; // pathscan_combined_lookup[ arr[py][px] ][ dir ] = [nextarrpypx, nextdir, deltapx, deltapy]; static byte[][][] pathscan_combined_lookup = { {{-1, -1, -1, -1}, {-1, -1, -1, -1}, {-1, -1, -1, -1}, {-1, -1, -1, -1}},// arr[py][px]==0 is invalid {{0, 1, 0, -1}, {-1, -1, -1, -1}, {-1, -1, -1, -1}, {0, 2, -1, 0}}, {{-1, -1, -1, -1}, {-1, -1, -1, -1}, {0, 1, 0, -1}, {0, 0, 1, 0}}, {{0, 0, 1, 0}, {-1, -1, -1, -1}, {0, 2, -1, 0}, {-1, -1, -1, -1}}, {{-1, -1, -1, -1}, {0, 0, 1, 0}, {0, 3, 0, 1}, {-1, -1, -1, -1}}, {{13, 3, 0, 1}, {13, 2, -1, 0}, {7, 1, 0, -1}, {7, 0, 1, 0}}, {{-1, -1, -1, -1}, {0, 1, 0, -1}, {-1, -1, -1, -1}, {0, 3, 0, 1}}, {{0, 3, 0, 1}, {0, 2, -1, 0}, {-1, -1, -1, -1}, {-1, -1, -1, -1}}, {{0, 3, 0, 1}, {0, 2, -1, 0}, {-1, -1, -1, -1}, {-1, -1, -1, -1}}, {{-1, -1, -1, -1}, {0, 1, 0, -1}, {-1, -1, -1, -1}, {0, 3, 0, 1}}, {{11, 1, 0, -1}, {14, 0, 1, 0}, {14, 3, 0, 1}, {11, 2, -1, 0}}, {{-1, -1, -1, -1}, {0, 0, 1, 0}, {0, 3, 0, 1}, {-1, -1, -1, -1}}, {{0, 0, 1, 0}, {-1, -1, -1, -1}, {0, 2, -1, 0}, {-1, -1, -1, -1}}, {{-1, -1, -1, -1}, {-1, -1, -1, -1}, {0, 1, 0, -1}, {0, 0, 1, 0}}, {{0, 1, 0, -1}, {-1, -1, -1, -1}, {-1, -1, -1, -1}, {0, 2, -1, 0}}, {{-1, -1, -1, -1}, {-1, -1, -1, -1}, {-1, -1, -1, -1}, {-1, -1, -1, -1}}// arr[py][px]==15 is invalid }; // 3. Walking through an edge node array, discarding edge node types 0 and 15 and creating paths from the rest. // Walk directions (dir): 0 > ; 1 ^ ; 2 < ; 3 v // Edge node types ( ▓:light or 1; ░:dark or 0 ) // ░░ ▓░ ░▓ ▓▓ ░░ ▓░ ░▓ ▓▓ ░░ ▓░ ░▓ ▓▓ ░░ ▓░ ░▓ ▓▓ // ░░ ░░ ░░ ░░ ░▓ ░▓ ░▓ ░▓ ▓░ ▓░ ▓░ ▓░ ▓▓ ▓▓ ▓▓ ▓▓ // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // public static ArrayList<ArrayList<Integer[]>> pathscan(int[][] arr, float pathomit) { try { ArrayList<ArrayList<Integer[]>> paths = new ArrayList<ArrayList<Integer[]>>(); ArrayList<Integer[]> thispath; int px = 0, py = 0, w = arr[0].length, h = arr.length, dir = 0; boolean pathfinished = true, holepath = false; byte[] lookuprow; for (int j = 0; j < h; j++) { for (int i = 0; i < w; i++) { if ((arr[j][i] != 0) && (arr[j][i] != 15)) { // Init px = i; py = j; paths.add(new ArrayList<Integer[]>()); thispath = paths.get(paths.size() - 1); pathfinished = false; // fill paths will be drawn, but hole paths are also required to remove unnecessary edge nodes dir = pathscan_dir_lookup[arr[py][px]]; holepath = pathscan_holepath_lookup[arr[py][px]]; // Path points loop while (!pathfinished) { // New path point thispath.add(new Integer[3]); thispath.get(thispath.size() - 1)[0] = px - 1; thispath.get(thispath.size() - 1)[1] = py - 1; thispath.get(thispath.size() - 1)[2] = arr[py][px]; // Next: look up the replacement, direction and coordinate changes = clear this cell, turn if required, walk forward lookuprow = pathscan_combined_lookup[arr[py][px]][dir]; arr[py][px] = lookuprow[0]; dir = lookuprow[1]; px += lookuprow[2]; py += lookuprow[3]; // Close path if (((px - 1) == thispath.get(0)[0]) && ((py - 1) == thispath.get(0)[1])) { pathfinished = true; // Discarding 'hole' type paths and paths shorter than pathomit if ((holepath) || (thispath.size() < pathomit)) { paths.remove(thispath); } } }// End of Path points loop }// End of Follow path }// End of i loop }// End of j loop return paths; } catch (Exception e) { MyBoxLog.error(e); return null; } }// End of pathscan() // 3. Batch pathscan public static ArrayList<ArrayList<ArrayList<Integer[]>>> batchpathscan(int[][][] layers, float pathomit) { ArrayList<ArrayList<ArrayList<Integer[]>>> bpaths = new ArrayList<ArrayList<ArrayList<Integer[]>>>(); for (int[][] layer : layers) { bpaths.add(pathscan(layer, pathomit)); } return bpaths; } // 4. interpolating between path points for nodes with 8 directions ( East, SouthEast, S, SW, W, NW, N, NE ) public static ArrayList<ArrayList<Double[]>> internodes(ArrayList<ArrayList<Integer[]>> paths) { ArrayList<ArrayList<Double[]>> ins = new ArrayList<ArrayList<Double[]>>(); ArrayList<Double[]> thisinp; Double[] thispoint, nextpoint = new Double[2]; Integer[] pp1, pp2, pp3; int palen = 0, nextidx = 0, nextidx2 = 0; // paths loop for (int pacnt = 0; pacnt < paths.size(); pacnt++) { ins.add(new ArrayList<Double[]>()); thisinp = ins.get(ins.size() - 1); palen = paths.get(pacnt).size(); // pathpoints loop for (int pcnt = 0; pcnt < palen; pcnt++) { // interpolate between two path points nextidx = (pcnt + 1) % palen; nextidx2 = (pcnt + 2) % palen; thisinp.add(new Double[3]); thispoint = thisinp.get(thisinp.size() - 1); pp1 = paths.get(pacnt).get(pcnt); pp2 = paths.get(pacnt).get(nextidx); pp3 = paths.get(pacnt).get(nextidx2); thispoint[0] = (pp1[0] + pp2[0]) / 2.0; thispoint[1] = (pp1[1] + pp2[1]) / 2.0; nextpoint[0] = (pp2[0] + pp3[0]) / 2.0; nextpoint[1] = (pp2[1] + pp3[1]) / 2.0; // line segment direction to the next point if (thispoint[0] < nextpoint[0]) { if (thispoint[1] < nextpoint[1]) { thispoint[2] = 1.0; }// SouthEast else if (thispoint[1] > nextpoint[1]) { thispoint[2] = 7.0; }// NE else { thispoint[2] = 0.0; } // E } else if (thispoint[0] > nextpoint[0]) { if (thispoint[1] < nextpoint[1]) { thispoint[2] = 3.0; }// SW else if (thispoint[1] > nextpoint[1]) { thispoint[2] = 5.0; }// NW else { thispoint[2] = 4.0; }// W } else { if (thispoint[1] < nextpoint[1]) { thispoint[2] = 2.0; }// S else if (thispoint[1] > nextpoint[1]) { thispoint[2] = 6.0; }// N else { thispoint[2] = 8.0; }// center, this should not happen } }// End of pathpoints loop }// End of paths loop return ins; }// End of internodes() // 4. Batch interpollation public static ArrayList<ArrayList<ArrayList<Double[]>>> batchinternodes(ArrayList<ArrayList<ArrayList<Integer[]>>> bpaths) { ArrayList<ArrayList<ArrayList<Double[]>>> binternodes = new ArrayList<ArrayList<ArrayList<Double[]>>>(); for (int k = 0; k < bpaths.size(); k++) { binternodes.add(internodes(bpaths.get(k))); } return binternodes; } // 5. tracepath() : recursively trying to fit straight and quadratic spline segments on the 8 direction internode path // 5.1. Find sequences of points with only 2 segment types // 5.2. Fit a straight line on the sequence // 5.3. If the straight line fails (an error>ltreshold), find the point with the biggest error // 5.4. Fit a quadratic spline through errorpoint (project this to get controlpoint), then measure errors on every point in the sequence
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
true
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/pdfdom/IgnoreResourceHandler.java
alpha/MyBox/src/main/java/thridparty/pdfdom/IgnoreResourceHandler.java
/* * Copyright (c) Matthew Abboud 2016 * * Pdf2Dom is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pdf2Dom 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CSSBox. If not, see <http://www.gnu.org/licenses/>. */ package thridparty.pdfdom; import java.io.IOException; public class IgnoreResourceHandler implements HtmlResourceHandler { public String handleResource(HtmlResource resource) throws IOException { return ""; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/pdfdom/HtmlDivLine.java
alpha/MyBox/src/main/java/thridparty/pdfdom/HtmlDivLine.java
/** * HtmlDivLine.java * * Created on 13. 10. 2022, 11:33:54 by burgetr */ package thridparty.pdfdom; /** * Maps input line to an HTML div rectangle, since HTML does not support standard lines. */ public class HtmlDivLine { private final float x1; private final float y1; private final float x2; private final float y2; private final float width; private final float height; private final float lineWidth; //horizontal or vertical lines are treated separately (no rotations used) private final boolean horizontal; private final boolean vertical; public HtmlDivLine(float x1, float y1, float x2, float y2, float lineWidth) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; this.lineWidth = lineWidth; this.width = Math.abs(x2 - x1); this.height = Math.abs(y2 - y1); this.horizontal = (height < 0.5f); this.vertical = (width < 0.5f); } public float getHeight() { return vertical ? height : 0; } public float getWidth() { if (vertical) return 0; else if (horizontal) return width; else return distanceFormula(x1, y1, x2, y2); } public float getLeft() { if (horizontal || vertical) return Math.min(x1, x2); else return Math.abs((x2 + x1) / 2) - getWidth() / 2; } public float getTop() { if (horizontal || vertical) return Math.min(y1, y2); else // after rotation top left will be center of line so find the midpoint and correct for the line to border transform return Math.abs((y2 + y1) / 2) - (getLineStrokeWidth() + getHeight()) / 2; } public double getAngleDegrees() { if (horizontal || vertical) return 0; else return Math.toDegrees(Math.atan((y2 - y1) / (x2 - x1))); } public float getLineStrokeWidth() { float lw = lineWidth; if (lw < 0.5f) lw = 0.5f; return lw; } public boolean isVertical() { return vertical; } public String getBorderSide() { return vertical ? "border-right" : "border-bottom"; } private float distanceFormula(float x1, float y1, float x2, float y2) { return (float) Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/pdfdom/FontTable.java
alpha/MyBox/src/main/java/thridparty/pdfdom/FontTable.java
/** * */ package thridparty.pdfdom; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import mara.mybox.dev.MyBoxLog; import org.apache.pdfbox.pdmodel.common.PDStream; import org.apache.pdfbox.pdmodel.font.PDFont; import org.apache.pdfbox.pdmodel.font.PDFontDescriptor; import org.apache.pdfbox.pdmodel.font.PDType0Font; import org.apache.pdfbox.pdmodel.font.PDType1CFont; import org.apache.pdfbox.pdmodel.font.PDType1Font; import org.mabb.fontverter.FVFont; import org.mabb.fontverter.FontVerter; import org.mabb.fontverter.pdf.PdfFontExtractor; /** * A table for storing entries about the embedded fonts and their usage. * * @author burgetr * * Updated by Mara */ public class FontTable { private static final Pattern fontFamilyRegex = Pattern.compile("([^+^-]*)[+-]([^+]*)"); private final List<Entry> entries = new ArrayList<>(); public void addEntry(PDFont font) { try { FontTable.Entry entry = get(font); if (entry == null) { String fontName = font.getName(); String family = findFontFamily(fontName); String usedName = nextUsedName(family); FontTable.Entry newEntry = new FontTable.Entry(font.getName(), usedName, font); if (newEntry.isEntryValid()) { add(newEntry); } } } catch (Exception e) { MyBoxLog.console(e.toString()); } } public Entry get(PDFont find) { try { for (Entry entryOn : entries) { if (entryOn.equalToPDFont(find)) { return entryOn; } } } catch (Exception e) { MyBoxLog.console(e.toString()); } return null; } public List<Entry> getEntries() { return new ArrayList<>(entries); } public String getUsedName(PDFont font) { FontTable.Entry entry = get(font); if (entry == null) { return null; } else { return entry.usedName; } } protected String nextUsedName(String fontName) { int i = 1; String usedName = fontName; while (isNameUsed(usedName)) { usedName = fontName + i; i++; } return usedName; } protected boolean isNameUsed(String name) { for (Entry entryOn : entries) { if (entryOn.usedName.equals(name)) { return true; } } return false; } protected void add(Entry entry) { entries.add(entry); } private String findFontFamily(String fontName) { // pdf font family name isn't always populated so have to find ourselves from full name String familyName = fontName; Matcher familyMatcher = fontFamilyRegex.matcher(fontName); if (familyMatcher.find()) // currently tacking on weight/style too since we don't generate html for it yet // and it's helpful for debugugging { familyName = familyMatcher.group(1) + " " + familyMatcher.group(2); } // browsers will barf if + in family name return familyName.replaceAll("[+]", " "); } public class Entry extends HtmlResource { public String fontName; public String usedName; public PDFontDescriptor descriptor; private final PDFont baseFont; private byte[] cachedFontData; private String mimeType = "x-font-truetype"; private String fileEnding; public Entry(String fontName, String usedName, PDFont font) { super(fontName); this.fontName = fontName; this.usedName = usedName; this.descriptor = font.getFontDescriptor(); this.baseFont = font; } @Override public byte[] getData() { try { if (cachedFontData != null) { return cachedFontData; } if (baseFont instanceof PDType1CFont || baseFont instanceof PDType1Font) { cachedFontData = loadType1Font(descriptor.getFontFile3()); } else if (descriptor.getFontFile2() != null && baseFont instanceof PDType0Font) { cachedFontData = loadType0TtfDescendantFont(); } else if (descriptor.getFontFile2() != null) { cachedFontData = loadTrueTypeFont(descriptor.getFontFile2()); } else if (descriptor.getFontFile() != null) { cachedFontData = loadType1Font(descriptor.getFontFile()); } else if (descriptor.getFontFile3() != null) { // FontFile3 docs say any font type besides TTF/OTF or Type 1.. cachedFontData = loadOtherTypeFont(descriptor.getFontFile3()); } return cachedFontData; } catch (Exception e) { MyBoxLog.console(e.toString()); return null; } } public boolean isEntryValid() { try { byte[] fontData = new byte[0]; fontData = getData(); return fontData != null && fontData.length != 0; } catch (Exception e) { MyBoxLog.console(e.toString()); return false; } } private byte[] loadTrueTypeFont(PDStream fontFile) { // MyBoxLog.console("Fail to convert True Type fonts."); // try { // // could convert to WOFF though for optimal html output instead. // FVFont font = FontVerter.readFont(fontFile.toByteArray()); // if (font != null) { // byte[] fvFontData = tryNormalizeFVFont(font); // if (fvFontData != null && fvFontData.length != 0) { // mimeType = "application/x-font-truetype"; // fileEnding = "otf"; // return fvFontData; // } // } // } catch (Exception e) { // MyBoxLog.console("Unsupported FontFile found. Normalisation will be skipped."); // MyBoxLog.console(e.toString()); // } return new byte[0]; } private byte[] loadType0TtfDescendantFont() { mimeType = "application/x-font-truetype"; fileEnding = "ttf"; try { FVFont font = PdfFontExtractor.convertType0FontToOpenType((PDType0Font) baseFont); byte[] fontData = tryNormalizeFVFont(font); if (fontData.length != 0) { return fontData; } } catch (Exception ex) { // MyBoxLog.console("Error loading type 0 with ttf descendant font '{}' Message: {} {}", // fontName + " " + ex.getMessage() + " " + ex.getClass()); } try { return descriptor.getFontFile2().toByteArray(); } catch (Exception ex) { return new byte[0]; } } private byte[] loadType1Font(PDStream fontFile) { // MyBoxLog.console("Type 1 fonts are not supported by Pdf2Dom."); return new byte[0]; } private byte[] loadOtherTypeFont(PDStream fontFile) { // Likley Bare CFF which needs to be converted to a font supported by browsers, can be // other font types which are not yet supported. try { FVFont font = FontVerter.convertFont(fontFile.toByteArray(), FontVerter.FontFormat.WOFF1); mimeType = "application/x-font-woff"; fileEnding = font.getProperties().getFileEnding(); return font.getData(); } catch (Exception ex) { // MyBoxLog.console("Issue converting Bare CFF font or the font type is not supportedby Pdf2Dom, " // + "Font: {} Exception: {} {}" + " " + fontName, ex.getMessage() + " " + ex.getClass()); // don't barf completley for font conversion issue, html will still be useable without. return new byte[0]; } } private byte[] tryNormalizeFVFont(FVFont font) { try { // browser validation can fail for many TTF fonts from pdfs if (!font.isValid()) { font.normalize(); } return font.getData(); } catch (Exception ex) { // MyBoxLog.console("Error normalizing font '{}' Message: {} {}", // fontName + " " + ex.getMessage() + " " + ex.getClass()); } return new byte[0]; } public boolean equalToPDFont(PDFont compare) { // Appears you can have two different fonts with the same actual font name since text position font // references go off a seperate dict lookup name. PDFBox doesn't include the lookup name with the // PDFont, so might have to submit a change there to be really sure fonts are indeed the same. return compare.getName().equals(baseFont.getName()) && compare.getType().equals(baseFont.getType()) && compare.getSubType().equals(baseFont.getSubType()); } @Override public int hashCode() { return fontName.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Entry other = (Entry) obj; if (!getOuterType().equals(other.getOuterType())) { return false; } if (fontName == null) { if (other.fontName != null) { return false; } } else if (!fontName.equals(other.fontName)) { return false; } return true; } @Override public String getFileEnding() { return fileEnding; } private FontTable getOuterType() { return FontTable.this; } @Override public String getMimeType() { return mimeType; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/pdfdom/PDFDomTreeConfig.java
alpha/MyBox/src/main/java/thridparty/pdfdom/PDFDomTreeConfig.java
/* * Copyright (c) Matthew Abboud 2016 * * Pdf2Dom is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pdf2Dom 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CSSBox. If not, see <http://www.gnu.org/licenses/>. */ package thridparty.pdfdom; import java.io.File; public class PDFDomTreeConfig { private HtmlResourceHandler imageHandler; private HtmlResourceHandler fontHandler; public static PDFDomTreeConfig createDefaultConfig() { PDFDomTreeConfig config = new PDFDomTreeConfig(); config.setFontHandler(embedAsBase64()); config.setImageHandler(embedAsBase64()); return config; } public static HtmlResourceHandler embedAsBase64() { return new EmbedAsBase64Handler(); } public static HtmlResourceHandler saveToDirectory(File directory) { return new SaveResourceToDirHandler(directory); } public static HtmlResourceHandler ignoreResource() { return new IgnoreResourceHandler(); } private PDFDomTreeConfig() { } public HtmlResourceHandler getImageHandler() { return imageHandler; } public void setImageHandler(HtmlResourceHandler imageHandler) { this.imageHandler = imageHandler; } public HtmlResourceHandler getFontHandler() { return fontHandler; } public void setFontHandler(HtmlResourceHandler fontHandler) { this.fontHandler = fontHandler; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/pdfdom/SaveResourceToDirHandler.java
alpha/MyBox/src/main/java/thridparty/pdfdom/SaveResourceToDirHandler.java
/* * Copyright (c) Matthew Abboud 2016 * * Pdf2Dom is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pdf2Dom 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CSSBox. If not, see <http://www.gnu.org/licenses/>. */ package thridparty.pdfdom; import java.io.File; import java.io.IOException; import java.util.LinkedList; import java.util.List; import org.apache.commons.io.FileUtils; public class SaveResourceToDirHandler implements HtmlResourceHandler { public static final String DEFAULT_RESOURCE_DIR = "resources/"; private final File directory; private List<String> writtenFileNames = new LinkedList<>(); public SaveResourceToDirHandler() { directory = null; } public SaveResourceToDirHandler(File directory) { this.directory = directory; } @Override public String handleResource(HtmlResource resource) throws IOException { String dir = DEFAULT_RESOURCE_DIR; if (directory != null) { dir = directory.getPath() + "/"; } String fileName = findNextUnusedFileName(resource.getName()); String resourcePath = dir + fileName + "." + resource.getFileEnding(); File file = new File(resourcePath); FileUtils.writeByteArrayToFile(file, resource.getData()); writtenFileNames.add(fileName); // #### write relative path in html. Changed by Mara return new File(dir).getName() + File.separator + fileName + "." + resource.getFileEnding(); // return "file:///" + resourcePath; // For FireFox and WebView // return resourcePath; } private String findNextUnusedFileName(String fileName) { int i = 1; String usedName = fileName; while (writtenFileNames.contains(usedName)) { usedName = fileName + i; i++; } return usedName; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/pdfdom/BoxStyle.java
alpha/MyBox/src/main/java/thridparty/pdfdom/BoxStyle.java
/** * BoxStyle.java * (c) Radek Burget, 2011 * * Pdf2Dom is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pdf2Dom 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CSSBox. If not, see <http://www.gnu.org/licenses/>. * * Created on 16.9.2011, 22:29:26 by radek */ package thridparty.pdfdom; /** * This class represents a style of a text box. * @author radek */ public class BoxStyle { public static final String defaultColor = "#000000"; public static final String defaultFontWeight = "normal"; public static final String defaultFontStyle = "normal"; public static final String defaultPosition = "absolute"; public static final String transparentColor = "rgba(0,0,0,0)"; private String units; //font private String fontFamily; private float fontSize; private String fontWeight; private String fontStyle; private float lineHeight; private float wordSpacing; private float letterSpacing; private String color; private String strokeColor; //position private String position; private float left; private float top; /** * Creates a new style using the specified units for lengths. * @param units Units used for lengths (e.g. 'pt') */ public BoxStyle(String units) { this.units = new String(units); fontFamily = null; fontSize = 0; fontWeight = null; fontStyle = null; lineHeight = 0; wordSpacing = 0; letterSpacing = 0; color = null; position = null; left = 0; top = 0; } public BoxStyle(BoxStyle src) { this.units = new String(src.units); fontFamily = src.fontFamily == null ? null : new String(src.fontFamily); fontSize = src.fontSize; fontWeight = src.fontWeight == null ? null : new String(src.fontWeight); fontStyle = src.fontStyle == null ? null : new String(src.fontStyle); lineHeight = src.lineHeight; wordSpacing = src.wordSpacing; letterSpacing = src.letterSpacing; color = src.color == null ? null : new String(src.color); position = src.position == null ? null : new String(src.position); left = src.left; top = src.top; strokeColor = src.strokeColor; } public String toString() { StringBuilder ret = new StringBuilder(); if (position != null && !position.equals(defaultPosition)) appendString(ret, "position", position); appendLength(ret, "top", top); appendLength(ret, "left", left); appendLength(ret, "line-height", lineHeight); if (fontFamily != null) appendString(ret, "font-family", fontFamily); if (fontSize != 0) appendLength(ret, "font-size", fontSize); if (fontWeight != null && !defaultFontWeight.equals(fontWeight)) appendString(ret, "font-weight", fontWeight); if (fontStyle != null && !defaultFontStyle.equals(fontStyle)) appendString(ret, "font-style", fontStyle); if (wordSpacing != 0) appendLength(ret, "word-spacing", wordSpacing); if (letterSpacing != 0) appendLength(ret, "letter-spacing", letterSpacing); if (color != null && !defaultColor.equals(color)) appendString(ret, "color", color); if (strokeColor != null && !strokeColor.equals(transparentColor)) ret.append(createTextStrokeCss(strokeColor)); return ret.toString(); } private void appendString(StringBuilder s, String propertyName, String value) { s.append(propertyName); s.append(':'); s.append(value); s.append(';'); } private void appendLength(StringBuilder s, String propertyName, float value) { s.append(propertyName); s.append(':'); s.append(formatLength(value)); s.append(';'); } public String formatLength(float length) { //return String.format(Locale.US, "%1.1f%s", length, units); //nice but slow return (float) length + units; } private String createTextStrokeCss(String color) { // text shadow fall back for non webkit, gets disabled in default style sheet // since can't use @media in inline styles String strokeCss = "-webkit-text-stroke: %color% 1px ;" + "text-shadow:" + "-1px -1px 0 %color%, " + "1px -1px 0 %color%," + "-1px 1px 0 %color%, " + "1px 1px 0 %color%;"; return strokeCss.replaceAll("%color%", color); } //================================================================ /** * @return the units */ public String getUnits() { return units; } /** * @param units the units to set */ public void setUnits(String units) { this.units = units; } /** * @return the fontFamily */ public String getFontFamily() { return fontFamily; } /** * @param fontFamily the fontFamily to set */ public void setFontFamily(String fontFamily) { this.fontFamily = fontFamily; } /** * @return the fontSize */ public float getFontSize() { return fontSize; } /** * @param fontSize the fontSize to set */ public void setFontSize(float fontSize) { this.fontSize = fontSize; } /** * @return the fontWeight */ public String getFontWeight() { return fontWeight; } /** * @param fontWeight the fontWeight to set */ public void setFontWeight(String fontWeight) { this.fontWeight = fontWeight; } /** * @return the fontStyle */ public String getFontStyle() { return fontStyle; } /** * @param fontStyle the fontStyle to set */ public void setFontStyle(String fontStyle) { this.fontStyle = fontStyle; } /** * @return the lineHeight */ public float getLineHeight() { return lineHeight; } /** * @param lineHeight the lineHeight to set */ public void setLineHeight(float lineHeight) { this.lineHeight = lineHeight; } /** * @return the wordSpacing */ public float getWordSpacing() { return wordSpacing; } /** * @param wordSpacing the wordSpacing to set */ public void setWordSpacing(float wordSpacing) { this.wordSpacing = wordSpacing; } /** * @return the letterSpacing */ public float getLetterSpacing() { return letterSpacing; } /** * @param letterSpacing the letterSpacing to set */ public void setLetterSpacing(float letterSpacing) { this.letterSpacing = letterSpacing; } /** * @return the color */ public String getColor() { return color; } /** * @param color the color to set */ public void setColor(String color) { this.color = color; } /** * @return the strokeColor */ public String getStrokeColor() { return strokeColor; } /** * @param strokeColor the strokeColor to set */ public void setStrokeColor(String strokeColor) { this.strokeColor = strokeColor; } /** * @return the left */ public float getLeft() { return left; } /** * @param left the left to set */ public void setLeft(float left) { this.left = left; } /** * @return the top */ public float getTop() { return top; } /** * @param top the top to set */ public void setTop(float top) { this.top = top; } //================================================================ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((color == null) ? 0 : color.hashCode()); result = prime * result + ((strokeColor == null) ? 0 : strokeColor.hashCode()); result = prime * result + ((fontFamily == null) ? 0 : fontFamily.hashCode()); result = prime * result + Float.floatToIntBits(fontSize); result = prime * result + ((fontStyle == null) ? 0 : fontStyle.hashCode()); result = prime * result + ((fontWeight == null) ? 0 : fontWeight.hashCode()); result = prime * result + Float.floatToIntBits(letterSpacing); result = prime * result + Float.floatToIntBits(wordSpacing); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BoxStyle other = (BoxStyle) obj; if (color == null) { if (other.color != null) return false; } else if (!color.equals(other.color)) return false; if (strokeColor == null) { if (other.strokeColor != null) return false; } else if (!strokeColor.equals(other.strokeColor)) return false; if (fontFamily == null) { if (other.fontFamily != null) return false; } else if (!fontFamily.equals(other.fontFamily)) return false; if (Float.floatToIntBits(fontSize) != Float .floatToIntBits(other.fontSize)) return false; if (fontStyle == null) { if (other.fontStyle != null) return false; } else if (!fontStyle.equals(other.fontStyle)) return false; if (fontWeight == null) { if (other.fontWeight != null) return false; } else if (!fontWeight.equals(other.fontWeight)) return false; if (Float.floatToIntBits(letterSpacing) != Float .floatToIntBits(other.letterSpacing)) return false; if (Float.floatToIntBits(wordSpacing) != Float .floatToIntBits(other.wordSpacing)) return false; return true; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/pdfdom/PathDrawer.java
alpha/MyBox/src/main/java/thridparty/pdfdom/PathDrawer.java
/* * Copyright (c) Matthew Abboud 2016 * * Pdf2Dom is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pdf2Dom 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CSSBox. If not, see <http://www.gnu.org/licenses/>. */ package thridparty.pdfdom; import java.awt.*; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.List; import org.apache.pdfbox.pdmodel.graphics.color.PDColor; import org.apache.pdfbox.pdmodel.graphics.state.PDGraphicsState; import org.slf4j.Logger; import static org.slf4j.LoggerFactory.getLogger; public class PathDrawer { private static final Logger log = getLogger(PathDrawer.class); private final PDGraphicsState state; public PathDrawer(PDGraphicsState state) { this.state = state; } public ImageResource drawPath(List<PathSegment> path) throws IOException { if (path.size() == 0) { return new ImageResource("PathImage", new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)); } Rectangle2D.Double bounds = getPathBounds(path); if (bounds.getHeight() <= 0 || bounds.getWidth() <= 0) { bounds.width = bounds.height = 1; log.info("Filled curved paths are not yet supported by Pdf2Dom."); } BufferedImage image = new BufferedImage((int) bounds.getWidth(), (int) bounds.getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D gfx = image.createGraphics(); try { clearPathGraphics(bounds, gfx); drawPathSegments(path, gfx); } catch (UnsupportedOperationException e) { log.info("Discarding unsupported path"); image = null; } gfx.dispose(); if (image != null) { // keep track of whitespace cropped off for html element positioning ImageResource drawnPath = new ImageResource("PathImage", image); drawnPath.setX(bounds.getX()); drawnPath.setY(bounds.getY()); return drawnPath; } else { return null; } } private void clearPathGraphics(Rectangle2D.Double bounds, Graphics2D gfx) throws IOException { Color transparent = new Color(255, 255, 255, 0); gfx.setColor(transparent); gfx.fillRect(0, 0, (int) bounds.getWidth() * 2, (int) bounds.getHeight() * 2); Color fill = pdfColorToColor(state.getNonStrokingColor()); Color stroke = pdfColorToColor(state.getStrokingColor()); // crop off rendered path whitespace gfx.translate(-bounds.getX(), -bounds.getY()); gfx.setPaint(stroke); gfx.setColor(fill); } private void drawPathSegments(List<PathSegment> path, Graphics2D gfx) { int[] xPts = new int[path.size()]; int[] yPts = new int[path.size()]; for (int i = 0; i < path.size(); i++) { PathSegment segmentOn = path.get(i); xPts[i] = (int) segmentOn.getX1(); yPts[i] = (int) segmentOn.getY1(); } gfx.fillPolygon(xPts, yPts, path.size()); } private Rectangle2D.Double getPathBounds(List<PathSegment> path) { PathSegment first = path.get(0); int minX = (int) first.getX1(), maxX = (int) first.getX1(); int minY = (int) first.getY2(), maxY = (int) first.getY1(); for (PathSegment segmentOn : path) { maxX = Math.max((int) segmentOn.getX1(), maxX); maxX = Math.max((int) segmentOn.getX2(), maxX); maxY = Math.max((int) segmentOn.getY1(), maxY); maxY = Math.max((int) segmentOn.getY2(), maxY); minX = Math.min((int) segmentOn.getX1(), minX); minX = Math.min((int) segmentOn.getX2(), minX); minY = Math.min((int) segmentOn.getY1(), minY); minY = Math.min((int) segmentOn.getY2(), minY); } int width = maxX - minX; int height = maxY - minY; int x = minX; int y = minY; return new Rectangle2D.Double(x, y, width, height); } private Color pdfColorToColor(PDColor color) throws IOException { float[] rgb = color.getColorSpace().toRGB(color.getComponents()); return new Color(rgb[0], rgb[1], rgb[2]); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/pdfdom/PDFBoxTree.java
alpha/MyBox/src/main/java/thridparty/pdfdom/PDFBoxTree.java
/** * PDFBoxTree.java * (c) Radek Burget, 2011 * * Pdf2Dom is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pdf2Dom 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CSSBox. If not, see <http://www.gnu.org/licenses/>. * * Created on 27.9.2011, 16:56:55 by burgetr */ package thridparty.pdfdom; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.Vector; import mara.mybox.dev.MyBoxLog; import org.apache.pdfbox.contentstream.operator.Operator; import org.apache.pdfbox.contentstream.operator.color.SetNonStrokingColor; import org.apache.pdfbox.contentstream.operator.color.SetNonStrokingColorN; import org.apache.pdfbox.contentstream.operator.color.SetNonStrokingColorSpace; import org.apache.pdfbox.contentstream.operator.color.SetNonStrokingDeviceCMYKColor; import org.apache.pdfbox.contentstream.operator.color.SetNonStrokingDeviceGrayColor; import org.apache.pdfbox.contentstream.operator.color.SetNonStrokingDeviceRGBColor; import org.apache.pdfbox.contentstream.operator.color.SetStrokingColor; import org.apache.pdfbox.contentstream.operator.color.SetStrokingColorN; import org.apache.pdfbox.contentstream.operator.color.SetStrokingColorSpace; import org.apache.pdfbox.contentstream.operator.color.SetStrokingDeviceCMYKColor; import org.apache.pdfbox.contentstream.operator.color.SetStrokingDeviceGrayColor; import org.apache.pdfbox.contentstream.operator.color.SetStrokingDeviceRGBColor; import org.apache.pdfbox.contentstream.operator.state.SetFlatness; import org.apache.pdfbox.contentstream.operator.state.SetLineCapStyle; import org.apache.pdfbox.contentstream.operator.state.SetLineDashPattern; import org.apache.pdfbox.contentstream.operator.state.SetLineJoinStyle; import org.apache.pdfbox.contentstream.operator.state.SetLineMiterLimit; import org.apache.pdfbox.contentstream.operator.state.SetLineWidth; import org.apache.pdfbox.contentstream.operator.state.SetRenderingIntent; import org.apache.pdfbox.contentstream.operator.text.SetFontAndSize; import org.apache.pdfbox.cos.COSBase; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.cos.COSNumber; import org.apache.pdfbox.cos.COSString; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDResources; import org.apache.pdfbox.pdmodel.common.PDRectangle; import org.apache.pdfbox.pdmodel.font.*; import org.apache.pdfbox.pdmodel.graphics.PDXObject; import org.apache.pdfbox.pdmodel.graphics.color.PDColor; import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject; import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; import org.apache.pdfbox.pdmodel.graphics.state.RenderingMode; import static org.apache.pdfbox.pdmodel.graphics.state.RenderingMode.*; import org.apache.pdfbox.text.PDFTextStripper; import org.apache.pdfbox.text.TextPosition; import org.apache.pdfbox.util.Matrix; /** * A generic tree of boxes created from a PDF file. It processes the PDF * document and calls the appropriate abstract methods in order to render a * page, text box, etc. The particular implementations are expected to implement * these actions in order to build the resulting document tree. * * @author burgetr * * Updated by Mara */ public abstract class PDFBoxTree extends PDFTextStripper { /** * Length units used in the generated CSS */ public static final String UNIT = "pt"; /** * Known font names that are recognized in the PDF files */ protected static String[] cssFontFamily = {"Times New Roman", "Times", "Garamond", "Helvetica", "Arial Narrow", "Arial", "Verdana", "Courier New", "MS Sans Serif"}; /** * Known font subtypes recognized in PDF files */ protected static String[] pdFontType = {"normal", "roman", "bold", "italic", "bolditalic"}; /** * Font weights corresponding to the font subtypes in * {@link PDFDomTree#pdFontType} */ protected static String[] cssFontWeight = {"normal", "normal", "bold", "normal", "bold"}; /** * Font styles corresponding to the font subtypes in * {@link PDFDomTree#pdFontType} */ protected static String[] cssFontStyle = {"normal", "normal", "normal", "italic", "italic"}; /** * When set to <code>true</code>, the graphics in the PDF file will be * ignored. */ protected boolean disableGraphics = false; /** * When set to <code>true</code>, the embedded images will be ignored. */ protected boolean disableImages = false; /** * When set to <code>true</code>, the image data will not be transferred to * the HTML data: url. */ protected boolean disableImageData = false; /** * First page to be processed */ protected int startPage; /** * Last page to be processed */ protected int endPage; /** * Table of embedded fonts */ protected FontTable fontTable; /** * The PDF page currently being processed */ protected PDPage pdpage; /** * Current text coordinates (the coordinates of the last encountered text * box). */ protected float cur_x; /** * Current text coordinates (the coordinates of the last encountered text * box). */ protected float cur_y; /** * Current path construction position */ protected float path_x; /** * Current path construction position */ protected float path_y; /** * Starting path construction position */ protected float path_start_x; /** * Starting path construction position */ protected float path_start_y; /** * Previous positioned text. */ protected TextPosition lastText = null; /** * Last diacritic if any */ protected TextPosition lastDia = null; /** * The text box currently being created. */ protected StringBuilder textLine; /** * Current text line metrics */ protected TextMetrics textMetrics; /** * Current graphics path */ protected Vector<PathSegment> graphicsPath; /** * The style of the future box being modified by the operators */ protected BoxStyle style; /** * The style of the text line being created */ protected BoxStyle curstyle; public PDFBoxTree() throws IOException { super(); super.setSortByPosition(true); super.setSuppressDuplicateOverlappingText(true); //add operators for tracking the graphic state addOperator(new SetStrokingColorSpace(this)); addOperator(new SetNonStrokingColorSpace(this)); addOperator(new SetLineDashPattern(this)); addOperator(new SetStrokingDeviceGrayColor(this)); addOperator(new SetNonStrokingDeviceGrayColor(this)); addOperator(new SetFlatness(this)); addOperator(new SetLineJoinStyle(this)); addOperator(new SetLineCapStyle(this)); addOperator(new SetStrokingDeviceCMYKColor(this)); addOperator(new SetNonStrokingDeviceCMYKColor(this)); addOperator(new SetLineMiterLimit(this)); addOperator(new SetStrokingDeviceRGBColor(this)); addOperator(new SetNonStrokingDeviceRGBColor(this)); addOperator(new SetRenderingIntent(this)); addOperator(new SetStrokingColor(this)); addOperator(new SetNonStrokingColor(this)); addOperator(new SetStrokingColorN(this)); addOperator(new SetNonStrokingColorN(this)); addOperator(new SetFontAndSize(this)); addOperator(new SetLineWidth(this)); init(); } /** * Internal initialization. */ private void init() { style = new BoxStyle(UNIT); textLine = new StringBuilder(); textMetrics = null; graphicsPath = new Vector<>(); startPage = 0; endPage = Integer.MAX_VALUE; fontTable = new FontTable(); } @Override public void processPage(PDPage page) { try { int p = this.getCurrentPageNo(); if (p >= startPage && p <= endPage) { pdpage = page; updateFontTable(); startNewPage(); super.processPage(page); finishBox(); } } catch (Exception e) { MyBoxLog.console(e.toString()); } } /** * Checks whether the graphics processing is disabled. * * @return <code>true</code> when the graphics processing is disabled in the * parser configuration. */ public boolean getDisableGraphics() { return disableGraphics; } /** * Disables the processing of the graphic operators in the PDF files. * * @param disableGraphics when set to <code>true</code> the graphics is * ignored in the source file. */ public void setDisableGraphics(boolean disableGraphics) { this.disableGraphics = disableGraphics; } /** * Checks whether processing of embedded images is disabled. * * @return <code>true</code> when the processing of embedded images is * disabled in the parser configuration. */ public boolean getDisableImages() { return disableImages; } /** * Disables the processing of images contained in the PDF files. * * @param disableImages when set to <code>true</code> the images are ignored * in the source file. */ public void setDisableImages(boolean disableImages) { this.disableImages = disableImages; } /** * Checks whether the copying of image data is disabled. * * @return <code>true</code> when the copying of image data is disabled in * the parser configuration. */ public boolean getDisableImageData() { return disableImageData; } /** * Disables the copying the image data to the resulting DOM tree. * * @param disableImageData when set to <code>true</code> the image data is * not copied to the document tree. The eventual <code>img</code> elements * will have an empty <code>src</code> attribute. */ public void setDisableImageData(boolean disableImageData) { this.disableImageData = disableImageData; } @Override public int getStartPage() { return startPage; } @Override public void setStartPage(int startPage) { this.startPage = startPage; } @Override public int getEndPage() { return endPage; } @Override public void setEndPage(int endPage) { this.endPage = endPage; } //=========================================================================================== /** * Adds a new page to the resulting document and makes it a current (active) * page. */ protected abstract void startNewPage(); /** * Creates a new text box in the current page. The style and position of the * text are contained in the {@link PDFBoxTree#curstyle} property. * * @param data The text contents. */ protected abstract void renderText(String data, TextMetrics metrics); /** * Adds a rectangle to the current page on the specified position. * * @param rect the rectangle to be rendered * @param stroke should there be a stroke around? * @param fill should the rectangle be filled? */ protected abstract void renderPath(List<PathSegment> path, boolean stroke, boolean fill) throws IOException; /** * Adds an image to the current page. * * @param type the image type: <code>"png"</code> or <code>"jpeg"</code> * @param x the X coordinate of the image * @param y the Y coordinate of the image * @param width the width coordinate of the image * @param height the height coordinate of the image * @param data the image data depending on the specified type * @return */ protected abstract void renderImage(float x, float y, float width, float height, ImageResource data) throws IOException; protected float[] toRectangle(List<PathSegment> path) { if (path.size() == 4) { Set<Float> xc = new HashSet<Float>(); Set<Float> yc = new HashSet<Float>(); //find x/y 1/2 for (PathSegment line : path) { xc.add(line.getX1()); xc.add(line.getX2()); yc.add(line.getY1()); yc.add(line.getY2()); } if (xc.size() == 2 && yc.size() == 2) { return new float[]{Collections.min(xc), Collections.min(yc), Collections.max(xc), Collections.max(yc)}; } else { return null; //two different X and Y coordinates required } } else { return null; //four segments required } } /** * Updates the font table by adding new fonts used at the current page. */ protected void updateFontTable() { try { PDResources resources = pdpage.getResources(); if (resources != null) { processFontResources(resources, fontTable); } } catch (Exception e) { MyBoxLog.console(e.toString()); } } private void processFontResources(PDResources resources, FontTable table) { try { for (COSName key : resources.getFontNames()) { PDFont font = resources.getFont(key); if (font instanceof PDTrueTypeFont) { table.addEntry(font); } else if (font instanceof PDType0Font) { PDCIDFont descendantFont = ((PDType0Font) font).getDescendantFont(); if (descendantFont instanceof PDCIDFontType2) { table.addEntry(font); } else { // MyBoxLog.console("fontNotSupported: " + font.getName() + " " + font.getClass().getSimpleName()); } } else if (font instanceof PDType1CFont) { table.addEntry(font); } else { // MyBoxLog.console("fontNotSupported: " + font.getName() + " " + font.getClass().getSimpleName()); } } for (COSName name : resources.getXObjectNames()) { PDXObject xobject = resources.getXObject(name); if (xobject instanceof PDFormXObject) { PDFormXObject xObjectForm = (PDFormXObject) xobject; PDResources formResources = xObjectForm.getResources(); if (formResources != null && formResources != resources && formResources.getCOSObject() != resources.getCOSObject()) { processFontResources(formResources, table); } } } } catch (Exception e) { MyBoxLog.console(e.toString()); } } //=========================================================================================== @Override protected void processOperator(Operator operator, List<COSBase> arguments) { try { String operation = operator.getName(); /*System.out.println("Operator: " + operation + ":" + arguments.size()); if (operation.equals("sc") || operation.equals("cs")) { System.out.print(" "); for (int i = 0; i < arguments.size(); i++) System.out.print(arguments.get(i) + " "); System.out.println(); }*/ //word spacing if (operation.equals("Tw")) { style.setWordSpacing(getLength(arguments.get(0))); } //letter spacing else if (operation.equals("Tc")) { style.setLetterSpacing(getLength(arguments.get(0))); } //graphics else if (operation.equals("m")) //move { if (!disableGraphics) { if (arguments.size() == 2) { float[] pos = transformPosition(getLength(arguments.get(0)), getLength(arguments.get(1))); path_x = pos[0]; path_y = pos[1]; path_start_x = pos[0]; path_start_y = pos[1]; } } } else if (operation.equals("l")) //line { if (!disableGraphics) { if (arguments.size() == 2) { float[] pos = transformPosition(getLength(arguments.get(0)), getLength(arguments.get(1))); graphicsPath.add(new PathSegment(path_x, path_y, pos[0], pos[1])); path_x = pos[0]; path_y = pos[1]; } } } else if (operation.equals("h")) //end subpath { if (!disableGraphics) { graphicsPath.add(new PathSegment(path_x, path_y, path_start_x, path_start_y)); } } //rectangle else if (operation.equals("re")) { if (!disableGraphics) { if (arguments.size() == 4) { float x = getLength(arguments.get(0)); float y = getLength(arguments.get(1)); float width = getLength(arguments.get(2)); float height = getLength(arguments.get(3)); float[] p1 = transformPosition(x, y); float[] p2 = transformPosition(x + width, y + height); graphicsPath.add(new PathSegment(p1[0], p1[1], p2[0], p1[1])); graphicsPath.add(new PathSegment(p2[0], p1[1], p2[0], p2[1])); graphicsPath.add(new PathSegment(p2[0], p2[1], p1[0], p2[1])); graphicsPath.add(new PathSegment(p1[0], p2[1], p1[0], p1[1])); } } } //fill else if (operation.equals("f") || operation.equals("F") || operation.equals("f*")) { renderPath(graphicsPath, false, true); graphicsPath.removeAllElements(); } //stroke else if (operation.equals("S")) { renderPath(graphicsPath, true, false); graphicsPath.removeAllElements(); } else if (operation.equals("s")) { graphicsPath.add(new PathSegment(path_x, path_y, path_start_x, path_start_y)); renderPath(graphicsPath, true, false); graphicsPath.removeAllElements(); } //stroke and fill else if (operation.equals("B") || operation.equals("B*")) { renderPath(graphicsPath, true, true); graphicsPath.removeAllElements(); } else if (operation.equals("b") || operation.equals("b*")) { graphicsPath.add(new PathSegment(path_x, path_y, path_start_x, path_start_y)); renderPath(graphicsPath, true, true); graphicsPath.removeAllElements(); } //cancel path else if (operation.equals("n")) { graphicsPath.removeAllElements(); } //invoke named object - images else if (operation.equals("Do")) { if (!disableImages) { processImageOperation(arguments); } } super.processOperator(operator, arguments); } catch (Exception e) { MyBoxLog.console(e.toString()); } } protected void processImageOperation(List<COSBase> arguments) { try { COSName objectName = (COSName) arguments.get(0); PDXObject xobject = getResources().getXObject(objectName); if (xobject instanceof PDImageXObject) { PDImageXObject pdfImage = (PDImageXObject) xobject; BufferedImage outputImage = pdfImage.getImage(); outputImage = rotateImage(outputImage); ImageResource imageData = new ImageResource(getTitle(), outputImage); Rectangle2D bounds = calculateImagePosition(pdfImage); float x = (float) bounds.getX(); float y = (float) bounds.getY(); renderImage(x, y, (float) bounds.getWidth(), (float) bounds.getHeight(), imageData); } } catch (Exception e) { MyBoxLog.console(e.toString()); } } private BufferedImage rotateImage(BufferedImage outputImage) { try { // x, y and size are handled by css attributes but still need to rotate the image so pulling // only rotation out of the matrix so no giant whitespace offset from translations Matrix ctm = getGraphicsState().getCurrentTransformationMatrix(); AffineTransform tr = ctm.createAffineTransform(); double rotate = Math.atan2(tr.getShearY(), tr.getScaleY()) - Math.toRadians(pdpage.getRotation()); outputImage = ImageUtils.rotateImage(outputImage, rotate); return outputImage; } catch (Exception e) { MyBoxLog.console(e.toString()); return null; } } private Rectangle2D calculateImagePosition(PDImageXObject pdfImage) { try { Matrix ctm = getGraphicsState().getCurrentTransformationMatrix(); Rectangle2D imageBounds = pdfImage.getImage().getRaster().getBounds(); AffineTransform imageTransform = new AffineTransform(ctm.createAffineTransform()); imageTransform.scale(1.0 / pdfImage.getWidth(), -1.0 / pdfImage.getHeight()); imageTransform.translate(0, -pdfImage.getHeight()); AffineTransform pageTransform = createCurrentPageTransformation(); pageTransform.concatenate(imageTransform); return pageTransform.createTransformedShape(imageBounds).getBounds2D(); } catch (Exception e) { MyBoxLog.console(e.toString()); return null; } } @Override protected void processTextPosition(TextPosition text) { try { if (text.isDiacritic()) { lastDia = text; } else if (!text.getUnicode().trim().isEmpty()) { if (lastDia != null) { if (text.contains(lastDia)) { text.mergeDiacritic(lastDia); } lastDia = null; } /*float[] c = transformPosition(text.getX(), text.getY()); cur_x = c[0]; cur_y = c[1];*/ cur_x = text.getX(); cur_y = text.getY(); /*System.out.println("Text: " + text.getCharacter()); System.out.println(" Font size: " + text.getFontSize() + " " + text.getFontSizeInPt() + "pt"); System.out.println(" Width: " + text.getWidth()); System.out.println(" Width adj: " + text.getWidthDirAdj()); System.out.println(" Height: " + text.getHeight()); System.out.println(" Height dir: " + text.getHeightDir()); System.out.println(" XScale: " + text.getXScale()); System.out.println(" YScale: " + text.getYScale());*/ float distx = 0; float disty = 0; if (lastText != null) { distx = text.getX() - (lastText.getX() + lastText.getWidth()); disty = text.getY() - lastText.getY(); } //should we split the boxes? boolean split = lastText == null || distx > 1.0f || distx < -6.0f || Math.abs(disty) > 1.0f || isReversed(getTextDirectionality(text)) != isReversed(getTextDirectionality(lastText)); //if the style changed, we should split the boxes updateStyle(style, text); if (!style.equals(curstyle)) { split = true; } if (split) //start of a new box { //finish current box (if any) if (lastText != null) { finishBox(); } //start a new box curstyle = new BoxStyle(style); } textLine.append(text.getUnicode()); if (textMetrics == null) { textMetrics = new TextMetrics(text); } else { textMetrics.append(text); } lastText = text; } } catch (Exception e) { MyBoxLog.console(e.toString()); } } /** * Finishes the current box - empties the text line buffer and creates a DOM * element from it. */ protected void finishBox() { try { if (textLine.length() > 0) { String s; if (isReversed(Character.getDirectionality(textLine.charAt(0)))) { s = textLine.reverse().toString(); } else { s = textLine.toString(); } curstyle.setLeft(textMetrics.getX()); curstyle.setTop(textMetrics.getTop()); curstyle.setLineHeight(textMetrics.getHeight()); renderText(s, textMetrics); textLine = new StringBuilder(); textMetrics = null; } } catch (Exception e) { MyBoxLog.console(e.toString()); } } /** * Checks whether the text directionality corresponds to reversed text (very * rough) * * @param directionality the Character.directionality * @return */ protected boolean isReversed(byte directionality) { try { switch (directionality) { case Character.DIRECTIONALITY_RIGHT_TO_LEFT: case Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC: case Character.DIRECTIONALITY_RIGHT_TO_LEFT_EMBEDDING: case Character.DIRECTIONALITY_RIGHT_TO_LEFT_OVERRIDE: return true; } } catch (Exception e) { MyBoxLog.console(e.toString()); } return false; } /** * Updates the text style according to a new text position * * @param bstyle the style to be updated * @param text the text position */ protected void updateStyle(BoxStyle bstyle, TextPosition text) { try { String font = text.getFont().getName(); String family = null; String weight = null; String fstyle = null; bstyle.setFontSize(text.getXScale()); //this seems to give better results than getFontSizeInPt() bstyle.setLineHeight(text.getHeight()); if (font != null) { //font style and weight for (int i = 0; i < pdFontType.length; i++) { if (font.toLowerCase().lastIndexOf(pdFontType[i]) >= 0) { weight = cssFontWeight[i]; fstyle = cssFontStyle[i]; break; } } if (weight != null) { bstyle.setFontWeight(weight); } else { bstyle.setFontWeight(cssFontWeight[0]); } if (fstyle != null) { bstyle.setFontStyle(fstyle); } else { bstyle.setFontStyle(cssFontStyle[0]); } //font family //If it's a known common font don't embed in html output to save space String knownFontFamily = findKnownFontFamily(font); if (!knownFontFamily.equals("")) { family = knownFontFamily; } else { family = fontTable.getUsedName(text.getFont()); if (family == null) { family = font; } } if (family != null) { bstyle.setFontFamily(family); } } updateStyleForRenderingMode(); } catch (Exception e) { MyBoxLog.console(e.toString()); } } private String findKnownFontFamily(String font) { try { for (String fontFamilyOn : cssFontFamily) { if (font.toLowerCase().lastIndexOf(fontFamilyOn.toLowerCase().replaceAll("\\s+", "")) >= 0) { return fontFamilyOn; } } } catch (Exception e) { MyBoxLog.console(e.toString()); } return ""; } private void updateStyleForRenderingMode() { try { String fillColor = colorString(getGraphicsState().getNonStrokingColor()); String strokeColor = colorString(getGraphicsState().getStrokingColor()); if (isTextFillEnabled()) { style.setColor(fillColor); } else { style.setColor(BoxStyle.transparentColor); } if (isTextStrokeEnabled()) { style.setStrokeColor(strokeColor); } else { style.setStrokeColor(BoxStyle.transparentColor); } } catch (Exception e) { MyBoxLog.console(e.toString()); } } private boolean isTextStrokeEnabled() { RenderingMode mode = getGraphicsState().getTextState().getRenderingMode(); return mode == STROKE || mode == STROKE_CLIP || mode == FILL_STROKE || mode == FILL_STROKE_CLIP; } private boolean isTextFillEnabled() { RenderingMode mode = getGraphicsState().getTextState().getRenderingMode(); return mode == FILL || mode == FILL_CLIP || mode == FILL_STROKE || mode == FILL_STROKE_CLIP; } /** * Obtains the media box valid for the current page. * * @return the media box rectangle */ protected PDRectangle getCurrentMediaBox() { PDRectangle layout = pdpage.getCropBox(); return layout; } //=========================================================================================== /** * Transforms a length according to the current transformation matrix. */ protected float transformLength(float w) { Matrix ctm = getGraphicsState().getCurrentTransformationMatrix(); Matrix m = new Matrix(); m.setValue(2, 0, w); return m.multiply(ctm).getTranslateX(); } /** * Transforms a position according to the current transformation matrix and * current page transformation. * * @param x * @param y * @return */ protected float[] transformPosition(float x, float y) { Point2D.Float point = super.transformedPoint(x, y); AffineTransform pageTransform = createCurrentPageTransformation(); Point2D.Float transformedPoint = (Point2D.Float) pageTransform.transform(point, null); return new float[]{(float) transformedPoint.getX(), (float) transformedPoint.getY()}; } protected AffineTransform createCurrentPageTransformation() { PDRectangle cb = pdpage.getCropBox(); AffineTransform pageTransform = new AffineTransform(); switch (pdpage.getRotation()) { case 90: pageTransform.translate(cb.getHeight(), 0); break; case 180: pageTransform.translate(cb.getWidth(), cb.getHeight()); break; case 270: pageTransform.translate(0, cb.getWidth()); break; } pageTransform.rotate(Math.toRadians(pdpage.getRotation())); pageTransform.translate(0, cb.getHeight()); pageTransform.scale(1, -1);
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
true
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/pdfdom/EmbedAsBase64Handler.java
alpha/MyBox/src/main/java/thridparty/pdfdom/EmbedAsBase64Handler.java
/* * Copyright (c) Matthew Abboud 2016 * * Pdf2Dom is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pdf2Dom 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CSSBox. If not, see <http://www.gnu.org/licenses/>. */ package thridparty.pdfdom; import java.io.IOException; public class EmbedAsBase64Handler implements HtmlResourceHandler { public String handleResource(HtmlResource resource) throws IOException { char[] base64Data = new char[0]; byte[] data = resource.getData(); if (data != null) base64Data = Base64Coder.encode(data); return String.format("data:%s;base64,%s", resource.getMimeType(), new String(base64Data)); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/pdfdom/ImageResource.java
alpha/MyBox/src/main/java/thridparty/pdfdom/ImageResource.java
/* * Copyright (c) Matthew Abboud 2016 * * Pdf2Dom is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pdf2Dom 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CSSBox. If not, see <http://www.gnu.org/licenses/>. */ package thridparty.pdfdom; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; public class ImageResource extends HtmlResource { private final BufferedImage image; private double x = 0; private double y = 0; public ImageResource(String name, BufferedImage image) { super(name); this.image = image; } public byte[] getData() throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ImageIO.write(image, "PNG", buffer); return buffer.toByteArray(); } public String getFileEnding() { return "png"; } public String getMimeType() { return "image/png"; } public void setX(double x) { this.x = x; } public double getX() { return x; } public void setY(double y) { this.y = y; } public double getY() { return y; } public float getHeight() { return image.getHeight(); } public float getWidth() { return image.getWidth(); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/pdfdom/Base64Coder.java
alpha/MyBox/src/main/java/thridparty/pdfdom/Base64Coder.java
package thridparty.pdfdom; /** * A Base64 Encoder/Decoder. * * <p> * This class is used to encode and decode data in Base64 format as described in RFC 1521. * * <p> * This is "Open Source" software and released under the <a href="http://www.gnu.org/licenses/lgpl.html">GNU/LGPL</a> license.<br> * It is provided "as is" without warranty of any kind.<br> * Copyright 2003: Christian d'Heureuse, Inventec Informatik AG, Switzerland.<br> * Home page: <a href="http://www.source-code.biz">www.source-code.biz</a><br> * * <p> * Version history:<br> * 2003-07-22 Christian d'Heureuse (chdh): Module created.<br> * 2005-08-11 chdh: Lincense changed from GPL to LGPL.<br> * 2006-11-21 chdh:<br> * &nbsp; Method encode(String) renamed to encodeString(String).<br> * &nbsp; Method decode(String) renamed to decodeString(String).<br> * &nbsp; New method encode(byte[],int) added.<br> * &nbsp; New method decode(String) added.<br> */ public class Base64Coder { // Mapping table from 6-bit nibbles to Base64 characters. private static char[] map1 = new char[64]; static { int i=0; for (char c='A'; c<='Z'; c++) map1[i++] = c; for (char c='a'; c<='z'; c++) map1[i++] = c; for (char c='0'; c<='9'; c++) map1[i++] = c; map1[i++] = '+'; map1[i++] = '/'; } // Mapping table from Base64 characters to 6-bit nibbles. private static byte[] map2 = new byte[128]; static { for (int i=0; i<map2.length; i++) map2[i] = -1; for (int i=0; i<64; i++) map2[map1[i]] = (byte)i; } /** * Encodes a string into Base64 format. * No blanks or line breaks are inserted. * @param s a String to be encoded. * @return A String with the Base64 encoded data. */ public static String encodeString (String s) { return new String(encode(s.getBytes())); } /** * Encodes a byte array into Base64 format. * No blanks or line breaks are inserted. * @param in an array containing the data bytes to be encoded. * @return A character array with the Base64 encoded data. */ public static char[] encode (byte[] in) { return encode(in,in.length); } /** * Encodes a byte array into Base64 format. * No blanks or line breaks are inserted. * @param in an array containing the data bytes to be encoded. * @param iLen number of bytes to process in <code>in</code>. * @return A character array with the Base64 encoded data. */ public static char[] encode (byte[] in, int iLen) { int oDataLen = (iLen*4+2)/3; // output length without padding int oLen = ((iLen+2)/3)*4; // output length including padding char[] out = new char[oLen]; int ip = 0; int op = 0; while (ip < iLen) { int i0 = in[ip++] & 0xff; int i1 = ip < iLen ? in[ip++] & 0xff : 0; int i2 = ip < iLen ? in[ip++] & 0xff : 0; int o0 = i0 >>> 2; int o1 = ((i0 & 3) << 4) | (i1 >>> 4); int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6); int o3 = i2 & 0x3F; out[op++] = map1[o0]; out[op++] = map1[o1]; out[op] = op < oDataLen ? map1[o2] : '='; op++; out[op] = op < oDataLen ? map1[o3] : '='; op++; } return out; } /** * Decodes a string from Base64 format. * @param s a Base64 String to be decoded. * @return A String containing the decoded data. * @throws IllegalArgumentException if the input is not valid Base64 encoded data. */ public static String decodeString (String s) { return new String(decode(s)); } /** * Decodes a byte array from Base64 format. * @param s a Base64 String to be decoded. * @return An array containing the decoded data bytes. * @throws IllegalArgumentException if the input is not valid Base64 encoded data. */ public static byte[] decode (String s) { return decode(s.toCharArray()); } /** * Decodes a byte array from Base64 format. * No blanks or line breaks are allowed within the Base64 encoded data. * @param in a character array containing the Base64 encoded data. * @return An array containing the decoded data bytes. * @throws IllegalArgumentException if the input is not valid Base64 encoded data. */ public static byte[] decode (char[] in) { int iLen = in.length; if (iLen%4 != 0) throw new IllegalArgumentException ("Length of Base64 encoded input string is not a multiple of 4."); while (iLen > 0 && in[iLen-1] == '=') iLen--; int oLen = (iLen*3) / 4; byte[] out = new byte[oLen]; int ip = 0; int op = 0; while (ip < iLen) { int i0 = in[ip++]; int i1 = in[ip++]; int i2 = ip < iLen ? in[ip++] : 'A'; int i3 = ip < iLen ? in[ip++] : 'A'; if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127) throw new IllegalArgumentException ("Illegal character in Base64 encoded data."); int b0 = map2[i0]; int b1 = map2[i1]; int b2 = map2[i2]; int b3 = map2[i3]; if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0) throw new IllegalArgumentException ("Illegal character in Base64 encoded data."); int o0 = ( b0 <<2) | (b1>>>4); int o1 = ((b1 & 0xf)<<4) | (b2>>>2); int o2 = ((b2 & 3)<<6) | b3; out[op++] = (byte)o0; if (op<oLen) out[op++] = (byte)o1; if (op<oLen) out[op++] = (byte)o2; } return out; } // Dummy constructor. private Base64Coder() {} } // end class Base64Coder
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/pdfdom/HtmlResourceHandler.java
alpha/MyBox/src/main/java/thridparty/pdfdom/HtmlResourceHandler.java
/* * Copyright (c) Matthew Abboud 2016 * * Pdf2Dom is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pdf2Dom 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CSSBox. If not, see <http://www.gnu.org/licenses/>. */ package thridparty.pdfdom; import java.io.IOException; public interface HtmlResourceHandler { /** * @param data name for the resource * @param resourceName resource data * @return the URI to be used in generated HTML resource elements/ */ String handleResource(HtmlResource resource) throws IOException; }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/pdfdom/ImageUtils.java
alpha/MyBox/src/main/java/thridparty/pdfdom/ImageUtils.java
package thridparty.pdfdom; import java.awt.*; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.awt.image.AffineTransformOp; import java.awt.image.BufferedImage; class ImageUtils { public static BufferedImage rotateImage(BufferedImage image, double theta) { int degrees = (int) Math.abs(Math.toDegrees(theta)); double xCenter = image.getWidth() / 2; double yCenter = image.getHeight() / 2; AffineTransform rotateTransform = AffineTransform.getRotateInstance(-theta, xCenter, yCenter); // Translation adjustments so image still centered after rotate width/height changes if (image.getHeight() != image.getWidth() && degrees != 180 && degrees != 0) { Point2D origin = new Point2D.Double(0.0, 0.0); origin = rotateTransform.transform(origin, null); double yTranslate = origin.getY(); Point2D yMax = new Point2D.Double(0, image.getHeight()); yMax = rotateTransform.transform(yMax, null); double xTranslate = yMax.getX(); AffineTransform translationAdjustment = AffineTransform.getTranslateInstance(-xTranslate, -yTranslate); rotateTransform.preConcatenate(translationAdjustment); } AffineTransformOp op = new AffineTransformOp(rotateTransform, AffineTransformOp.TYPE_BILINEAR); // Have to recopy image because of JDK bug #4723021, AffineTransformationOp throwing exception sometimes image = copyImage(image, BufferedImage.TYPE_INT_ARGB); // Need to create filter dest image ourselves since AffineTransformOp's own dest image creation // throws exceptions in some cases. Rectangle bounds = op.getBounds2D(image).getBounds(); BufferedImage finalImage = new BufferedImage((int) bounds.getWidth(), (int) bounds.getHeight(), BufferedImage.TYPE_INT_ARGB); return op.filter(image, finalImage); } public static BufferedImage copyImage(BufferedImage source, int type) { BufferedImage copy = new BufferedImage(source.getWidth(), source.getHeight(), type); Graphics gfx = copy.getGraphics(); gfx.drawImage(source, 0, 0, null); gfx.dispose(); return copy; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/pdfdom/PDFDomTree.java
alpha/MyBox/src/main/java/thridparty/pdfdom/PDFDomTree.java
/** * PDFDomTree.java * (c) Radek Burget, 2011 * * Pdf2Dom is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pdf2Dom 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CSSBox. If not, see <http://www.gnu.org/licenses/>. * * Created on 13.9.2011, 14:17:24 by burgetr */ package thridparty.pdfdom; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import mara.mybox.dev.MyBoxLog; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.common.PDRectangle; import org.w3c.dom.Document; import org.w3c.dom.DocumentType; import org.w3c.dom.Element; import org.w3c.dom.Text; import org.w3c.dom.bootstrap.DOMImplementationRegistry; import org.w3c.dom.ls.DOMImplementationLS; import org.w3c.dom.ls.LSOutput; import org.w3c.dom.ls.LSSerializer; /** * A DOM representation of a PDF file. * * @author burgetr * * Updated by Mara */ public class PDFDomTree extends PDFBoxTree { /** * Default style placed in the begining of the resulting document */ protected String defaultStyle = ".page{position:relative; border:1px solid blue;margin:0.5em}\n" + ".p,.r{position:absolute;}\n" + ".p{white-space:nowrap;}\n" + // disable text-shadow fallback for text stroke if stroke supported by browser "@supports(-webkit-text-stroke: 1px black) {" + ".p{text-shadow:none !important;}" + "}"; /** * The resulting document representing the PDF file. */ protected Document doc; /** * The head element of the resulting document. */ protected Element head; /** * The body element of the resulting document. */ protected Element body; /** * The title element of the resulting document. */ protected Element title; /** * The global style element of the resulting document. */ protected Element globalStyle; /** * The element representing the page currently being created in the * resulting document. */ protected Element curpage; /** * Text element counter for assigning IDs to the text elements. */ protected int textcnt; /** * Page counter for assigning IDs to the pages. */ protected int pagecnt; protected PDFDomTreeConfig config; /** * Creates a new PDF DOM parser. * * @throws IOException */ public PDFDomTree() throws IOException { super(); init(); } /** * Creates a new PDF DOM parser. * * @param config * @throws IOException */ public PDFDomTree(PDFDomTreeConfig config) throws IOException { this(); if (config != null) { this.config = config; } } /** * Internal initialization. */ private void init() { pagecnt = 0; textcnt = 0; this.config = PDFDomTreeConfig.createDefaultConfig(); } /** * Creates a new empty HTML document tree. */ protected void createDocument() { try { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = builderFactory.newDocumentBuilder(); DocumentType doctype = builder.getDOMImplementation().createDocumentType("html", "-//W3C//DTD XHTML 1.1//EN", "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"); doc = builder.getDOMImplementation().createDocument("http://www.w3.org/1999/xhtml", "html", doctype); head = doc.createElement("head"); Element meta = doc.createElement("meta"); meta.setAttribute("http-equiv", "content-type"); meta.setAttribute("content", "text/html;charset=utf-8"); head.appendChild(meta); title = doc.createElement("title"); title.setTextContent("PDF Document"); head.appendChild(title); globalStyle = doc.createElement("style"); globalStyle.setAttribute("type", "text/css"); //globalStyle.setTextContent(createGlobalStyle()); head.appendChild(globalStyle); body = doc.createElement("body"); Element root = doc.getDocumentElement(); root.appendChild(head); root.appendChild(body); } catch (Exception e) { MyBoxLog.console(e.toString()); } } /** * Obtains the resulting document tree. * * @return The DOM root element. */ public Document getDocument() { return doc; } @Override public void startDocument(PDDocument document) { createDocument(); } @Override protected void endDocument(PDDocument document) { try { //use the PDF title String doctitle = document.getDocumentInformation().getTitle(); if (doctitle != null && doctitle.trim().length() > 0) { title.setTextContent(doctitle); } //set the main style globalStyle.setTextContent(createGlobalStyle()); } catch (Exception e) { MyBoxLog.console(e.toString()); } } /** * Parses a PDF document and serializes the resulting DOM tree to an output. * This requires a DOM Level 3 capable implementation to be available. */ @Override public void writeText(PDDocument doc, Writer outputStream) { try { DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS"); LSSerializer writer = impl.createLSSerializer(); writer.getDomConfig().setParameter("format-pretty-print", true); LSOutput lsOutput = impl.createLSOutput(); lsOutput.setCharacterStream(outputStream); createDOM(doc); writer.write(getDocument(), lsOutput); } catch (Exception e) { MyBoxLog.console(e.toString()); } } /** * Loads a PDF document and creates a DOM tree from it. * * @param doc the source document * @return a DOM Document representing the DOM tree */ public Document createDOM(PDDocument doc) { try { /* We call the original PDFTextStripper.writeText but nothing should be printed actually because our processing methods produce no output. They create the DOM structures instead */ super.writeText(doc, new OutputStreamWriter(System.out)); return this.doc; } catch (Exception e) { MyBoxLog.console(e.toString()); return null; } } //=========================================================================================== @Override protected void startNewPage() { try { curpage = createPageElement(); body.appendChild(curpage); } catch (Exception e) { MyBoxLog.console(e.toString()); } } @Override protected void renderText(String data, TextMetrics metrics) { try { curpage.appendChild(createTextElement(data, metrics.getWidth())); } catch (Exception e) { MyBoxLog.console(e.toString()); } } @Override protected void renderPath(List<PathSegment> path, boolean stroke, boolean fill) throws IOException { float[] rect = toRectangle(path); if (rect != null) { curpage.appendChild(createRectangleElement(rect[0], rect[1], rect[2] - rect[0], rect[3] - rect[1], stroke, fill)); } else if (stroke) { for (PathSegment segm : path) { curpage.appendChild(createLineElement(segm.getX1(), segm.getY1(), segm.getX2(), segm.getY2())); } } else { Element pathImage = createPathImage(path); if (pathImage != null) { curpage.appendChild(pathImage); } } } @Override protected void renderImage(float x, float y, float width, float height, ImageResource resource) throws IOException { curpage.appendChild(createImageElement(x, y, width, height, resource)); } //=========================================================================================== /** * Creates an element that represents a single page. * * @return the resulting DOM element */ protected Element createPageElement() { String pstyle = ""; PDRectangle layout = getCurrentMediaBox(); if (layout != null) { /*System.out.println("x1 " + layout.getLowerLeftX()); System.out.println("y1 " + layout.getLowerLeftY()); System.out.println("x2 " + layout.getUpperRightX()); System.out.println("y2 " + layout.getUpperRightY()); System.out.println("rot " + pdpage.findRotation());*/ float w = layout.getWidth(); float h = layout.getHeight(); final int rot = pdpage.getRotation(); if (rot == 90 || rot == 270) { float x = w; w = h; h = x; } pstyle = "width:" + w + UNIT + ";" + "height:" + h + UNIT + ";"; pstyle += "overflow:hidden;"; } else { MyBoxLog.console("No media box found"); } Element el = doc.createElement("div"); el.setAttribute("id", "page_" + (pagecnt++)); el.setAttribute("class", "page"); el.setAttribute("style", pstyle); return el; } /** * Creates an element that represents a single positioned box with no * content. * * @return the resulting DOM element */ protected Element createTextElement(float width) { Element el = doc.createElement("div"); el.setAttribute("id", "p" + (textcnt++)); el.setAttribute("class", "p"); String style = curstyle.toString(); style += "width:" + width + UNIT + ";"; el.setAttribute("style", style); return el; } /** * Creates an element that represents a single positioned box containing the * specified text string. * * @param data the text string to be contained in the created box. * @return the resulting DOM element */ protected Element createTextElement(String data, float width) { Element el = createTextElement(width); Text text = doc.createTextNode(data); el.appendChild(text); return el; } /** * Creates an element that represents a rectangle drawn at the specified * coordinates in the page. * * @param x the X coordinate of the rectangle * @param y the Y coordinate of the rectangle * @param width the width of the rectangle * @param height the height of the rectangle * @param stroke should there be a stroke around? * @param fill should the rectangle be filled? * @return the resulting DOM element */ protected Element createRectangleElement(float x, float y, float width, float height, boolean stroke, boolean fill) { float lineWidth = transformWidth(getGraphicsState().getLineWidth()); float wcor = stroke ? lineWidth : 0.0f; float strokeOffset = wcor == 0 ? 0 : wcor / 2; width = width - wcor < 0 ? 1 : width - wcor; height = height - wcor < 0 ? 1 : height - wcor; StringBuilder pstyle = new StringBuilder(50); pstyle.append("left:").append(style.formatLength(x - strokeOffset)).append(';'); pstyle.append("top:").append(style.formatLength(y - strokeOffset)).append(';'); pstyle.append("width:").append(style.formatLength(width)).append(';'); pstyle.append("height:").append(style.formatLength(height)).append(';'); if (stroke) { String color = colorString(getGraphicsState().getStrokingColor()); pstyle.append("border:").append(style.formatLength(lineWidth)).append(" solid ").append(color).append(';'); } if (fill) { String fcolor = colorString(getGraphicsState().getNonStrokingColor()); pstyle.append("background-color:").append(fcolor).append(';'); } Element el = doc.createElement("div"); el.setAttribute("class", "r"); el.setAttribute("style", pstyle.toString()); el.appendChild(doc.createEntityReference("nbsp")); return el; } /** * Create an element that represents a horizntal or vertical line. * * @param x1 * @param y1 * @param x2 * @param y2 * @return the created DOM element */ protected Element createLineElement(float x1, float y1, float x2, float y2) { HtmlDivLine line = new HtmlDivLine(x1, y1, x2, y2, transformWidth(getGraphicsState().getLineWidth())); String color = colorString(getGraphicsState().getStrokingColor()); StringBuilder pstyle = new StringBuilder(50); pstyle.append("left:").append(style.formatLength(line.getLeft())).append(';'); pstyle.append("top:").append(style.formatLength(line.getTop())).append(';'); pstyle.append("width:").append(style.formatLength(line.getWidth())).append(';'); pstyle.append("height:").append(style.formatLength(line.getHeight())).append(';'); pstyle.append(line.getBorderSide()).append(':').append(style.formatLength(line.getLineStrokeWidth())).append(" solid ").append(color).append(';'); if (line.getAngleDegrees() != 0) { pstyle.append("transform:").append("rotate(").append(line.getAngleDegrees()).append("deg);"); } Element el = doc.createElement("div"); el.setAttribute("class", "r"); el.setAttribute("style", pstyle.toString()); el.appendChild(doc.createEntityReference("nbsp")); return el; } protected Element createPathImage(List<PathSegment> path) throws IOException { PathDrawer drawer = new PathDrawer(getGraphicsState()); ImageResource renderedPath = drawer.drawPath(path); if (renderedPath != null) { return createImageElement((float) renderedPath.getX(), (float) renderedPath.getY(), renderedPath.getWidth(), renderedPath.getHeight(), renderedPath); } else { return null; } } /** * Creates an element that represents an image drawn at the specified * coordinates in the page. * * @param x the X coordinate of the image * @param y the Y coordinate of the image * @param width the width coordinate of the image * @param height the height coordinate of the image * @param type the image type: <code>"png"</code> or <code>"jpeg"</code> * @param resource the image data depending on the specified type * @return */ protected Element createImageElement(float x, float y, float width, float height, ImageResource resource) throws IOException { StringBuilder pstyle = new StringBuilder("position:absolute;"); pstyle.append("left:").append(x).append(UNIT).append(';'); pstyle.append("top:").append(y).append(UNIT).append(';'); pstyle.append("width:").append(width).append(UNIT).append(';'); pstyle.append("height:").append(height).append(UNIT).append(';'); //pstyle.append("border:1px solid red;"); Element el = doc.createElement("img"); el.setAttribute("style", pstyle.toString()); String imgSrc = config.getImageHandler().handleResource(resource); if (!disableImageData && !imgSrc.isEmpty()) { el.setAttribute("src", imgSrc); } else { el.setAttribute("src", ""); } return el; } /** * Generate the global CSS style for the whole document. * * @return the CSS code used in the generated document header */ protected String createGlobalStyle() { StringBuilder ret = new StringBuilder(); ret.append(createFontFaces()); ret.append("\n"); ret.append(defaultStyle); return ret.toString(); } @Override protected void updateFontTable() { // skip font processing completley if ignore fonts mode to optimize processing speed if (!(config.getFontHandler() instanceof IgnoreResourceHandler)) { super.updateFontTable(); } } protected String createFontFaces() { StringBuilder ret = new StringBuilder(); for (FontTable.Entry font : fontTable.getEntries()) { createFontFace(ret, font); } return ret.toString(); } private void createFontFace(StringBuilder ret, FontTable.Entry font) { try { final String src = config.getFontHandler().handleResource(font); if (src != null && !src.trim().isEmpty()) { ret.append("@font-face {"); ret.append("font-family:\"").append(font.usedName).append("\";"); ret.append("src:url('"); ret.append(src); ret.append("');"); ret.append("}\n"); } } catch (IOException e) { MyBoxLog.console("Error writing font face data for font: " + font.getName() + "Exception: " + e.getMessage() + "\n" + e.getClass() ); } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/pdfdom/PathSegment.java
alpha/MyBox/src/main/java/thridparty/pdfdom/PathSegment.java
/** * SubPath.java * (c) Radek Burget, 2015 * * Pdf2Dom is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pdf2Dom 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CSSBox. If not, see <http://www.gnu.org/licenses/>. * * Created on 9.9.2015, 15:27:27 by burgetr */ package thridparty.pdfdom; /** * @author burgetr * */ public class PathSegment { private float x1, y1, x2, y2; public PathSegment(float x1, float y1, float x2, float y2) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } public float getX1() { return x1; } public void setX1(float x1) { this.x1 = x1; } public float getY1() { return y1; } public void setY1(float y1) { this.y1 = y1; } public float getX2() { return x2; } public void setX2(float x2) { this.x2 = x2; } public float getY2() { return y2; } public void setY2(float y2) { this.y2 = y2; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/pdfdom/PDFToHTML.java
alpha/MyBox/src/main/java/thridparty/pdfdom/PDFToHTML.java
/** * PDFToHTML.java * (c) Radek Burget, 2011 * * Pdf2Dom is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pdf2Dom 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CSSBox. If not, see <http://www.gnu.org/licenses/>. * * Created on 19.9.2011, 13:34:54 by burgetr */ package thridparty.pdfdom; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import java.util.ArrayList; import java.util.List; import org.apache.pdfbox.Loader; import org.apache.pdfbox.pdmodel.PDDocument; /** * @author burgetr * */ public class PDFToHTML { public static void main(String[] args) { if (args.length < 1) { System.out.println("Usage: PDFToHTML <infile> [<outfile>] [<options>]"); System.out.println("Options: "); System.out.println("-fm=[mode] Font handler mode. [mode] = EMBED_BASE64, SAVE_TO_DIR, IGNORE"); System.out.println("-fdir=[path] Directory to extract fonts to. [path] = font extract directory ie dir/my-font-dir"); System.out.println(); System.out.println("-im=[mode] Image handler mode. [mode] = EMBED_BASE64, SAVE_TO_DIR, IGNORE"); System.out.println("-idir=[path] Directory to extract images to. [path] = image extract directory ie dir/my-image-dir"); System.exit(1); } String infile = args[0]; String outfile; if (args.length > 1 && !args[1].startsWith("-")) { outfile = args[1]; } else { String base = args[0]; if (base.toLowerCase().endsWith(".pdf")) { base = base.substring(0, base.length() - 4); } outfile = base + ".html"; } PDFDomTreeConfig config = parseOptions(args); PDDocument document = null; try { document = Loader.loadPDF(new File(infile)); PDFDomTree parser = new PDFDomTree(config); //parser.setDisableImageData(true); Writer output = new PrintWriter(outfile, "utf-8"); parser.writeText(document, output); output.close(); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); e.printStackTrace(); } finally { if (document != null) { try { document.close(); } catch (IOException e) { System.err.println("Error: " + e.getMessage()); //e.printStackTrace(); } } } } private static PDFDomTreeConfig parseOptions(String[] args) { PDFDomTreeConfig config = PDFDomTreeConfig.createDefaultConfig(); List<CommandLineFlag> flags = parseFlags(args); for (CommandLineFlag flagOn : flags) { if (flagOn.flagName.equals("fm")) { HtmlResourceHandler handler = createResourceHandlerFor(flagOn.value); config.setFontHandler(handler); } else if (flagOn.flagName.equals("fdir")) { config.setFontHandler(new SaveResourceToDirHandler(new File(flagOn.value))); } else if (flagOn.flagName.equals("im")) { HtmlResourceHandler handler = createResourceHandlerFor(flagOn.value); config.setImageHandler(handler); } else if (flagOn.flagName.equals("idir")) { config.setImageHandler(new SaveResourceToDirHandler(new File(flagOn.value))); } } return config; } private static HtmlResourceHandler createResourceHandlerFor(String value) { HtmlResourceHandler handler = PDFDomTreeConfig.embedAsBase64(); if (value.equalsIgnoreCase("EMBED_BASE64")) { handler = PDFDomTreeConfig.embedAsBase64(); } else if (value.equalsIgnoreCase("SAVE_TO_DIR")) { handler = new SaveResourceToDirHandler(); } else if (value.equalsIgnoreCase("IGNORE")) { handler = new IgnoreResourceHandler(); } return handler; } private static List<CommandLineFlag> parseFlags(String[] args) { List<CommandLineFlag> flags = new ArrayList<CommandLineFlag>(); for (String argOn : args) { if (argOn.startsWith("-")) { flags.add(CommandLineFlag.parse(argOn)); } } return flags; } private static class CommandLineFlag { public String flagName; public String value = ""; public static CommandLineFlag parse(String argOn) { CommandLineFlag flag = new CommandLineFlag(); String[] flagSplit = argOn.split("="); flag.flagName = flagSplit[0].replace("-", ""); if (flagSplit.length > 1) { flag.value = flagSplit[1].replace("=", ""); } return flag; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/pdfdom/HtmlResource.java
alpha/MyBox/src/main/java/thridparty/pdfdom/HtmlResource.java
/* * Copyright (c) Matthew Abboud 2016 * * Pdf2Dom is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pdf2Dom 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CSSBox. If not, see <http://www.gnu.org/licenses/>. */ package thridparty.pdfdom; import java.io.IOException; public abstract class HtmlResource { protected String name; public HtmlResource(String name) { this.name = name; } public abstract byte[] getData() throws IOException; public abstract String getFileEnding(); public abstract String getMimeType(); public String getName() { return name; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/thridparty/pdfdom/TextMetrics.java
alpha/MyBox/src/main/java/thridparty/pdfdom/TextMetrics.java
package thridparty.pdfdom; import java.io.IOException; import org.apache.fontbox.util.BoundingBox; import org.apache.pdfbox.pdmodel.font.PDFont; import org.apache.pdfbox.text.TextPosition; public class TextMetrics { private float x, baseline, width, height, pointSize, descent, ascent, fontSize; private PDFont font; public TextMetrics(TextPosition tp) { x = tp.getX(); baseline = tp.getY(); font = tp.getFont(); width = tp.getWidth(); height = tp.getHeight(); pointSize = tp.getFontSizeInPt(); fontSize = tp.getYScale(); ascent = getAscent(); descent = getDescent(); } public void append(TextPosition tp) { width += tp.getX() - (x + width) + tp.getWidth(); height = Math.max(height, tp.getHeight()); ascent = Math.max(ascent, getAscent(tp.getFont(), tp.getYScale())); descent = Math.min(descent, getDescent(tp.getFont(), tp.getYScale())); } public float getX() { return x; } public float getTop() { if (ascent != 0) return baseline - ascent; else return baseline - getBoundingBoxAscent(); } public float getBottom() { if (descent != 0) return baseline - descent; else return baseline - getBoundingBoxDescent(); } public float getBaseline() { return baseline; } public float getAscent() { return getAscent(font, fontSize); } public float getDescent() { final float descent = getDescent(font, fontSize); return descent > 0 ? -descent : descent; //positive descent is not allowed } public float getBoundingBoxDescent() { return getBoundingBoxDescent(font, fontSize); } public float getBoundingBoxAscent() { return getBoundingBoxAscent(font, fontSize); } public static float getBoundingBoxDescent(PDFont font, float fontSize) { try { BoundingBox bBox = font.getBoundingBox(); float boxDescent = bBox.getLowerLeftY(); return (boxDescent / 1000) * fontSize; } catch (IOException e) { } return 0.0f; } public static float getBoundingBoxAscent(PDFont font, float fontSize) { try { BoundingBox bBox = font.getBoundingBox(); float boxAscent = bBox.getUpperRightY(); return (boxAscent / 1000) * fontSize; } catch (IOException e) { } return 0.0f; } private static float getAscent(PDFont font, float fontSize) { try { return (font.getFontDescriptor().getAscent() / 1000) * fontSize; } catch (Exception e) { } return 0.0f; } private static float getDescent(PDFont font, float fontSize) { try { return (font.getFontDescriptor().getDescent() / 1000) * fontSize; } catch (Exception e) { } return 0.0f; } public float getWidth() { return width; } public float getHeight() { return getBottom() - getTop(); } public float getPointSize() { return pointSize; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/MainApp.java
alpha/MyBox/src/main/java/mara/mybox/MainApp.java
package mara.mybox; import java.util.ResourceBundle; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.layout.Pane; import javafx.stage.Stage; import mara.mybox.controller.MyBoxLoadingController; import mara.mybox.dev.MyBoxLog; import mara.mybox.value.AppValues; import mara.mybox.value.AppVariables; import mara.mybox.value.Fxmls; import mara.mybox.value.Languages; import static mara.mybox.value.Languages.sysDefaultLanguage; /** * @Author Mara * @CreateDate 2020-11-7 * @License Apache License Version 2.0 */ public class MainApp extends Application { @Override public void init() throws Exception { } @Override public void start(Stage stage) throws Exception { try { if (AppVariables.MyboxConfigFile == null || !AppVariables.MyboxConfigFile.exists() || !AppVariables.MyboxConfigFile.isFile()) { openStage(stage, Fxmls.MyBoxSetupFxml); } else { MyBoxLoading(stage); } } catch (Exception e) { MyBoxLog.error(e); stage.close(); } } public static void MyBoxLoading(Stage stage) throws Exception { try { FXMLLoader fxmlLoader = openStage(stage, Fxmls.MyBoxLoadingFxml); if (fxmlLoader != null) { MyBoxLoadingController loadController = (MyBoxLoadingController) fxmlLoader.getController(); loadController.run(); } } catch (Exception e) { MyBoxLog.error(e); stage.close(); } } public static FXMLLoader openStage(Stage stage, String fxml) throws Exception { try { String lang = sysDefaultLanguage(); ResourceBundle bundle; if (lang.startsWith("zh")) { bundle = Languages.BundleZhCN; } else { bundle = Languages.BundleEn; } FXMLLoader fxmlLoader = new FXMLLoader(MainApp.class.getResource(fxml), bundle); Pane pane = fxmlLoader.load(); Scene scene = new Scene(pane); stage.setTitle("MyBox v" + AppValues.AppVersion); stage.getIcons().add(AppValues.AppIcon); stage.setScene(scene); stage.show(); return fxmlLoader; } catch (Exception e) { MyBoxLog.error(e); stage.close(); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/MyBox.java
alpha/MyBox/src/main/java/mara/mybox/MyBox.java
package mara.mybox; import java.io.File; import java.lang.management.ManagementFactory; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import javafx.application.Application; import javafx.application.Platform; import javax.imageio.ImageIO; import mara.mybox.controller.MyBoxLoadingController; import mara.mybox.db.DerbyBase; import mara.mybox.db.migration.DataMigration; import mara.mybox.dev.BaseMacro; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.PopTools; import mara.mybox.fxml.WindowTools; import mara.mybox.image.data.ImageColorSpace; import mara.mybox.tools.CertificateTools; import mara.mybox.tools.ConfigTools; import mara.mybox.tools.FileDeleteTools; import mara.mybox.tools.MicrosoftDocumentTools; import mara.mybox.tools.SystemTools; import mara.mybox.value.AppPaths; import mara.mybox.value.AppValues; import mara.mybox.value.AppVariables; import mara.mybox.value.Languages; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2019-1-22 14:35:50 * @License Apache License Version 2.0 */ public class MyBox { public static String InternalRestartFlag = "MyBoxInternalRestarting"; // To pass arguments to JavaFx GUI // https://stackoverflow.com/questions/33549820/javafx-not-calling-mainstring-args-method/33549932#33549932 public static void main(String[] args) { if (args == null) { AppVariables.AppArgs = null; } else { AppVariables.AppArgs = new String[args.length]; System.arraycopy(args, 0, AppVariables.AppArgs, 0, args.length); } initConfigValues(); BaseMacro macro = BaseMacro.create(AppVariables.AppArgs); if (macro != null) { runMacro(macro); } else { launchApp(); } } public static boolean initConfigValues() { MyBoxLog.console("Checking configuration parameters..."); if (AppVariables.AppArgs != null) { for (String arg : AppVariables.AppArgs) { if (arg.startsWith("config=")) { String config = arg.substring("config=".length()); File configFile = new File(config); String dataPath = ConfigTools.readValue(configFile, "MyBoxDataPath"); if (dataPath != null) { try { File dataPathFile = new File(dataPath); if (!dataPathFile.exists()) { dataPathFile.mkdirs(); } else if (!dataPathFile.isDirectory()) { FileDeleteTools.delete(null, dataPathFile); dataPathFile.mkdirs(); } if (dataPathFile.exists() && dataPathFile.isDirectory()) { AppVariables.MyboxConfigFile = configFile; AppVariables.MyboxDataPath = dataPathFile.getAbsolutePath(); return true; } } catch (Exception e) { } } } } } AppVariables.MyboxConfigFile = ConfigTools.defaultConfigFile(); MyBoxLog.console("MyBox Config file:" + AppVariables.MyboxConfigFile); String dataPath = ConfigTools.readValue("MyBoxDataPath"); if (dataPath != null) { try { File dataPathFile = new File(dataPath); if (!dataPathFile.exists()) { dataPathFile.mkdirs(); } else if (!dataPathFile.isDirectory()) { FileDeleteTools.delete(null, dataPathFile); dataPathFile.mkdirs(); } if (dataPathFile.exists() && dataPathFile.isDirectory()) { AppVariables.MyboxDataPath = dataPathFile.getAbsolutePath(); MyBoxLog.console("MyBox Data Path:" + AppVariables.MyboxDataPath); return true; } } catch (Exception e) { } } return true; } public static void runMacro(BaseMacro macro) { if (macro == null) { return; } MyBoxLog.console("Running Mybox Macro..."); MyBoxLog.console("JVM path: " + System.getProperty("java.home")); setSystemProperty(); initEnv(null, Languages.embedLangName()); macro.info(); if (macro.checkParameters()) { macro.run(); macro.displayEnd(); if (macro.isOpenResult()) { File file = macro.getOutputFile(); if (file != null && file.exists()) { AppVariables.AppArgs = new String[1]; AppVariables.AppArgs[0] = file.getAbsolutePath(); launchApp(); return; } } } WindowTools.doExit(); } public static void launchApp() { MyBoxLog.console("Starting Mybox..."); MyBoxLog.console("JVM path: " + System.getProperty("java.home")); if (AppVariables.MyboxDataPath != null && setJVMmemory() && !internalRestart()) { restart(); } else { setSystemProperty(); Application.launch(MainApp.class, AppVariables.AppArgs); } } public static boolean internalRestart() { return AppVariables.AppArgs != null && AppVariables.AppArgs.length > 0 && InternalRestartFlag.equals(AppVariables.AppArgs[0]); } public static boolean setJVMmemory() { String JVMmemory = ConfigTools.readValue("JVMmemory"); if (JVMmemory == null) { return false; } long jvmM = Runtime.getRuntime().maxMemory() / (1024 * 1024); if (JVMmemory.equals("-Xms" + jvmM + "m")) { return false; } if (AppVariables.AppArgs == null || AppVariables.AppArgs.length == 0) { return true; } for (String s : AppVariables.AppArgs) { if (s.startsWith("-Xms")) { return false; } } return true; } // Set properties before JavaFx starting to make sure they take effect against JavaFX public static void setSystemProperty() { try { // https://pdfbox.apache.org/2.0/getting-started.html // System.setProperty("sun.java2d.cmm", "sun.java2d.cmm.kcms.KcmsServiceProvider"); System.setProperty("org.apache.pdfbox.rendering.UsePureJavaCMYKConversion", "true"); // https://blog.csdn.net/iteye_3493/article/details/82060349 // https://stackoverflow.com/questions/1004327/getting-rid-of-derby-log/1933310#1933310 if (AppVariables.MyboxDataPath != null) { System.setProperty("javax.net.ssl.keyStore", CertificateTools.keystore()); System.setProperty("javax.net.ssl.keyStorePassword", CertificateTools.keystorePassword()); System.setProperty("javax.net.ssl.trustStore", CertificateTools.keystore()); System.setProperty("javax.net.ssl.trustStorePassword", CertificateTools.keystorePassword()); MyBoxLog.console(System.getProperty("javax.net.ssl.keyStore")); } // System.setProperty("derby.language.logQueryPlan", "true"); // System.setProperty("jdk.tls.client.protocols", "TLSv1.1,TLSv1.2"); // System.setProperty("jdk.tls.server.protocols", "TLSv1,TLSv1.1,TLSv1.2,TLSv1.3"); // System.setProperty("https.protocol", "TLSv1"); // System.setProperty("com.sun.security.enableAIAcaIssuers", "true"); // System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); // System.setProperty("javax.net.debug", "ssl,record, plaintext, handshake,session,trustmanager,sslctx"); // System.setProperty("javax.net.debug", "ssl,handshake,session,trustmanager,sslctx"); } catch (Exception e) { MyBoxLog.error(e); } } public static boolean initEnv(MyBoxLoadingController controller, String lang) { try { if (controller != null) { controller.info(MessageFormat.format(message(lang, "InitializeDataUnder"), AppVariables.MyboxDataPath)); } if (!initFiles(controller, lang)) { return false; } if (controller != null) { controller.info(MessageFormat.format(message(lang, "LoadingDatabase"), AppVariables.MyBoxDerbyPath)); } DerbyBase.status = DerbyBase.DerbyStatus.NotConnected; String initDB = DerbyBase.startDerby(); if (!DerbyBase.isStarted()) { if (controller != null) { Platform.runLater(() -> { PopTools.alertWarning(null, initDB); MyBoxLog.console(initDB); }); } AppVariables.initAppVaribles(); } else { // The following statements should be executed in this order if (controller != null) { controller.info(message(lang, "InitializingTables")); } DerbyBase.initTables(null); if (controller != null) { controller.info(message(lang, "InitializingVariables")); } AppVariables.initAppVaribles(); if (controller != null) { controller.info(message(lang, "CheckingMigration")); } MyBoxLog.console(message(lang, "CheckingMigration")); if (!DataMigration.checkUpdates(controller, lang)) { return false; } if (controller != null) { controller.info(message(lang, "InitializingTableValues")); } } try { if (controller != null) { controller.info(message(lang, "InitializingEnv")); } ImageColorSpace.registrySupportedImageFormats(); ImageIO.setUseCache(true); ImageIO.setCacheDirectory(AppVariables.MyBoxTempPath); MicrosoftDocumentTools.registryFactories(); // AlarmClock.scheduleAll(); } catch (Exception e) { if (controller != null) { controller.info(e.toString()); } MyBoxLog.console(e.toString()); } MyBoxLog.info(message(lang, "Load") + " " + AppValues.AppVersion); return true; } catch (Exception e) { if (controller != null) { controller.info(e.toString()); } MyBoxLog.console(e.toString()); return false; } } public static boolean initRootPath(MyBoxLoadingController controller, String lang) { try { File currentDataPath = new File(AppVariables.MyboxDataPath); if (!currentDataPath.exists()) { if (!currentDataPath.mkdirs()) { if (controller != null) { Platform.runLater(() -> { PopTools.alertError(null, MessageFormat.format(message(lang, "UserPathFail"), AppVariables.MyboxDataPath)); }); } return false; } } MyBoxLog.console("MyBox Data Path:" + AppVariables.MyboxDataPath); String oldPath = ConfigTools.readValue("MyBoxOldDataPath"); if (oldPath != null) { if (oldPath.equals(ConfigTools.defaultDataPath())) { FileDeleteTools.deleteDirExcept(null, new File(oldPath), ConfigTools.defaultConfigFile()); } else { FileDeleteTools.deleteDir(new File(oldPath)); } ConfigTools.writeConfigValue("MyBoxOldDataPath", null); } return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean initFiles(MyBoxLoadingController controller, String lang) { try { if (!initRootPath(controller, lang)) { return false; } AppVariables.MyBoxLogsPath = new File(AppVariables.MyboxDataPath + File.separator + "logs"); if (!AppVariables.MyBoxLogsPath.exists()) { if (!AppVariables.MyBoxLogsPath.mkdirs()) { if (controller != null) { Platform.runLater(() -> { PopTools.alertError(null, MessageFormat.format(message(lang, "UserPathFail"), AppVariables.MyBoxLogsPath)); }); } return false; } } AppVariables.MyBoxDerbyPath = new File(AppVariables.MyboxDataPath + File.separator + "mybox_derby"); System.setProperty("derby.stream.error.file", AppVariables.MyBoxLogsPath + File.separator + "derby.log"); AppVariables.MyBoxLanguagesPath = new File(AppVariables.MyboxDataPath + File.separator + "mybox_languages"); if (!AppVariables.MyBoxLanguagesPath.exists()) { if (!AppVariables.MyBoxLanguagesPath.mkdirs()) { if (controller != null) { Platform.runLater(() -> { PopTools.alertError(null, MessageFormat.format(message(lang, "UserPathFail"), AppVariables.MyBoxLanguagesPath)); }); } return false; } } AppVariables.MyBoxTempPath = new File(AppVariables.MyboxDataPath + File.separator + "AppTemp"); if (!AppVariables.MyBoxTempPath.exists()) { if (!AppVariables.MyBoxTempPath.mkdirs()) { if (controller != null) { Platform.runLater(() -> { PopTools.alertError(null, MessageFormat.format(message(lang, "UserPathFail"), AppVariables.MyBoxTempPath)); }); } return false; } } AppVariables.AlarmClocksFile = AppVariables.MyboxDataPath + File.separator + ".alarmClocks"; AppVariables.MyBoxReservePaths = new ArrayList<File>() { { add(AppVariables.MyBoxTempPath); add(AppVariables.MyBoxDerbyPath); add(AppVariables.MyBoxLanguagesPath); add(new File(AppPaths.getDownloadsPath())); add(AppVariables.MyBoxLogsPath); } }; String prefix = AppPaths.getGeneratedPath() + File.separator; new File(prefix + "png").mkdirs(); new File(prefix + "jpg").mkdirs(); new File(prefix + "pdf").mkdirs(); new File(prefix + "htm").mkdirs(); new File(prefix + "xml").mkdirs(); new File(prefix + "json").mkdirs(); new File(prefix + "txt").mkdirs(); new File(prefix + "csv").mkdirs(); new File(prefix + "md").mkdirs(); new File(prefix + "xlsx").mkdirs(); new File(prefix + "docx").mkdirs(); new File(prefix + "pptx").mkdirs(); new File(prefix + "svg").mkdirs(); new File(prefix + "js").mkdirs(); new File(prefix + "mp4").mkdirs(); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } /* restart */ // Restart with parameters. Use "ProcessBuilder", instead of "Runtime.getRuntime().exec" which is not safe // https://stackoverflow.com/questions/4159802/how-can-i-restart-a-java-application?r=SearchResults public static void restart() { try { String javaHome = System.getProperty("java.home"); File boundlesJar; if (SystemTools.isMac()) { boundlesJar = new File(javaHome.substring(0, javaHome.length() - "runtime/Contents/Home".length()) + "Java" + File.separator + "MyBox-" + AppValues.AppVersion + ".jar"); } else { boundlesJar = new File(javaHome.substring(0, javaHome.length() - "runtime".length()) + "app" + File.separator + "MyBox-" + AppValues.AppVersion + ".jar"); } if (boundlesJar.exists()) { restartBundles(boundlesJar); } else { restartJar(); } } catch (Exception e) { MyBoxLog.error(e); } } public static void restartBundles(File jar) { try { MyBoxLog.console("Restarting Mybox bundles..."); List<String> commands = new ArrayList<>(); commands.add(System.getProperty("java.home") + File.separator + "bin" + File.separator + "java"); String JVMmemory = ConfigTools.readValue("JVMmemory"); if (JVMmemory != null) { commands.add(JVMmemory); } commands.add("-jar"); commands.add(jar.getAbsolutePath()); commands.add(InternalRestartFlag); if (AppVariables.AppArgs != null) { for (String arg : AppVariables.AppArgs) { if (arg != null) { commands.add(arg); } } } ProcessBuilder pb = new ProcessBuilder(commands); pb.start(); System.exit(0); } catch (Exception e) { MyBoxLog.error(e); } } public static void restartJar() { try { MyBoxLog.console("Restarting Mybox Jar package..."); List<String> commands = new ArrayList<>(); commands.add(System.getProperty("java.home") + File.separator + "bin" + File.separator + "java"); List<String> jvmArgs = ManagementFactory.getRuntimeMXBean().getInputArguments(); for (String jvmArg : jvmArgs) { if (jvmArg != null) { commands.add(jvmArg); } } commands.add("-cp"); commands.add(ManagementFactory.getRuntimeMXBean().getClassPath()); String JVMmemory = ConfigTools.readValue("JVMmemory"); if (JVMmemory != null) { commands.add(JVMmemory); } commands.add(MyBox.class.getName()); commands.add(InternalRestartFlag); if (AppVariables.AppArgs != null) { for (String arg : AppVariables.AppArgs) { if (arg != null) { commands.add(arg); } } } ProcessBuilder pb = new ProcessBuilder(commands); pb.start(); System.exit(0); } catch (Exception e) { MyBoxLog.error(e); } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/Data2DChartGroupSelfComparisonBarsController.java
alpha/MyBox/src/main/java/mara/mybox/controller/Data2DChartGroupSelfComparisonBarsController.java
package mara.mybox.controller; import javafx.scene.Node; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.WindowTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2022-10-30 * @License Apache License Version 2.0 */ public class Data2DChartGroupSelfComparisonBarsController extends Data2DChartSelfComparisonBarsController { public Data2DChartGroupSelfComparisonBarsController() { baseTitle = message("GroupData") + " - " + message("SelfComparisonBarsChart"); } @Override public void drawFrame() { if (outputData == null) { return; } outputHtml(makeHtml()); } @Override public Node snapNode() { return webViewController.webView; } /* static */ public static Data2DChartGroupSelfComparisonBarsController open(BaseData2DLoadController tableController) { try { Data2DChartGroupSelfComparisonBarsController controller = (Data2DChartGroupSelfComparisonBarsController) WindowTools.referredStage( tableController, Fxmls.Data2DChartGroupSelfComparisonBarsFxml); controller.setParameters(tableController); controller.requestMouse(); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/DataTreeQueryResultsController.java
alpha/MyBox/src/main/java/mara/mybox/controller/DataTreeQueryResultsController.java
package mara.mybox.controller; import java.util.List; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.input.KeyEvent; import mara.mybox.data2d.DataTable; import mara.mybox.data2d.TmpTable; import mara.mybox.db.table.BaseNodeTable; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.WindowTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2025-5-14 * @License Apache License Version 2.0 */ public class DataTreeQueryResultsController extends BaseData2DLoadController { protected BaseDataTreeController dataController; protected BaseNodeTable nodeTable; protected String info; protected DataTable treeTable; protected TmpTable results; @FXML protected ControlDataTreeNodeView viewController; @Override public void initValues() { try { super.initValues(); leftPaneControl = viewController.leftPaneControl; } catch (Exception e) { MyBoxLog.error(e); } } public void setParameters(BaseController parent, BaseDataTreeController controller, String conditions, TmpTable data) { try { if (parent == null || controller == null || data == null) { close(); return; } parentController = parent; dataController = controller; results = data; nodeTable = dataController.nodeTable; baseName = baseName + "_" + nodeTable.getDataName(); info = conditions; baseTitle = nodeTable.getTreeName() + " - " + message("QueryResults"); setTitle(baseTitle); parentController.setIconified(true); viewController.setParameters(this, nodeTable); loadDef(results); } catch (Exception e) { MyBoxLog.error(e); } } @Override public void postLoadedTableData() { super.postLoadedTableData(); tableView.getColumns().remove(1); } @Override public void clicked(Event event) { List<String> row = selectedItem(); if (row == null) { return; } viewController.loadNode(Long.parseLong(row.get(2))); } @FXML public void dataAction(Event event) { if (results != null) { Data2DManufactureController.openDef(results); } } @FXML public void infoAction(Event event) { if (info != null) { TextPopController.loadText(info); } } @Override public boolean handleKeyEvent(KeyEvent event) { if (super.handleKeyEvent(event)) { return true; } if (viewController != null) { if (viewController.handleKeyEvent(event)) { return true; } } return false; } @Override public boolean needStageVisitHistory() { return false; } @Override public void cleanPane() { try { if (WindowTools.isRunning(parentController)) { parentController.setIconified(false); parentController = null; } dataController = null; } catch (Exception e) { } super.cleanPane(); } /* static */ public static DataTreeQueryResultsController open(BaseController parent, BaseDataTreeController tree, String conditions, TmpTable data) { try { DataTreeQueryResultsController controller = (DataTreeQueryResultsController) WindowTools .forkStage(parent, Fxmls.DataTreeQueryResultsFxml); controller.setParameters(parent, tree, conditions, data); controller.requestMouse(); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/ImagesSpliceController.java
alpha/MyBox/src/main/java/mara/mybox/controller/ImagesSpliceController.java
package mara.mybox.controller; import java.sql.Connection; import java.util.Arrays; import java.util.List; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.control.ComboBox; import javafx.scene.control.RadioButton; import javafx.scene.control.TextField; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleGroup; import javafx.scene.image.Image; import javafx.scene.input.KeyEvent; import javafx.scene.layout.VBox; import mara.mybox.db.DerbyBase; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.fxml.ValidationTools; import mara.mybox.fxml.WindowTools; import mara.mybox.image.data.ImageCombine; import mara.mybox.image.data.ImageCombine.ArrayType; import mara.mybox.image.data.ImageCombine.CombineSizeType; import mara.mybox.image.data.ImageInformation; import mara.mybox.image.tools.CombineTools; import mara.mybox.value.Fxmls; import mara.mybox.value.Languages; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2018-8-11 * @License Apache License Version 2.0 */ public class ImagesSpliceController extends BaseController { protected ImageCombine imageCombine; protected int columns, interval, margins, eachWidthValue, eachHeightValue, totalWidthValue, totalHeightValue; @FXML protected ControlImagesTable tableController; @FXML protected ToggleGroup sizeGroup, arrayGroup; @FXML protected RadioButton arrayColumnRadio, arrayRowRadio, arrayColumnsRadio, keepSizeRadio, sizeBiggerRadio, sizeSmallerRadio, eachWidthRadio, eachHeightRadio, totalWidthRadio, totalHeightRadio; @FXML protected TextField totalWidthInput, totalHeightInput, eachWidthInput, eachHeightInput; @FXML protected ComboBox<String> columnsSelector, intervalSelector, marginsSelector; @FXML protected ControlColorSet colorController; @FXML protected ControlImageView viewController; @FXML protected VBox viewBox, sourceBox; public ImagesSpliceController() { baseTitle = Languages.message("ImagesSplice"); } @Override public void initControls() { try { super.initControls(); imageCombine = new ImageCombine(); tableController.parentController = this; tableController.parentFxml = myFxml; initArray(); initSize(); initOthers(); saveButton.disableProperty().bind(viewController.imageView.imageProperty().isNull()); } catch (Exception e) { MyBoxLog.error(e); } } private void initArray() { try { columns = UserConfig.getInt(baseName + "Columns", 2); if (columns <= 0) { columns = 2; } columnsSelector.getItems().addAll(Arrays.asList("2", "3", "4", "5", "6", "7", "8", "9", "10")); columnsSelector.setValue(columns + ""); columnsSelector.valueProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> ov, String oldValue, String newValue) { checkArray(); } }); String arraySelect = UserConfig.getString(baseName + "ArrayType", "SingleColumn"); switch (arraySelect) { case "SingleColumn": arrayColumnRadio.setSelected(true); break; case "SingleRow": arrayRowRadio.setSelected(true); break; case "ColumnsNumber": arrayColumnsRadio.setSelected(true); break; } arrayGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> ov, Toggle old_toggle, Toggle new_toggle) { checkArray(); } }); checkArray(); } catch (Exception e) { MyBoxLog.error(e); } } private boolean checkArray() { if (arrayColumnRadio.isSelected() || arrayRowRadio.isSelected()) { columnsSelector.setDisable(true); ValidationTools.setEditorNormal(columnsSelector); return true; } columnsSelector.setDisable(false); int v; try { v = Integer.parseInt(columnsSelector.getValue()); } catch (Exception e) { v = -1; } if (v > 0) { columns = v; ValidationTools.setEditorNormal(columnsSelector); return true; } else { ValidationTools.setEditorBadStyle(columnsSelector); popError(message("InvalidParameter") + ": " + message("ColumnsNumber")); return false; } } private void initSize() { try { eachWidthValue = UserConfig.getInt(baseName + "EachWidth", 500); if (eachWidthValue <= 0) { eachWidthValue = 500; } eachWidthInput.setText(eachWidthValue + ""); eachWidthInput.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> v, String ov, String nv) { checkEachWidthValue(); } }); eachHeightValue = UserConfig.getInt(baseName + "EachHeight", 500); if (eachHeightValue <= 0) { eachHeightValue = 500; } eachHeightInput.setText(eachHeightValue + ""); eachHeightInput.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> v, String ov, String nv) { checkEachHeightValue(); } }); totalWidthValue = UserConfig.getInt(baseName + "TotalWidth", 1000); if (totalWidthValue <= 0) { totalWidthValue = 1000; } totalWidthInput.setText(totalWidthValue + ""); totalWidthInput.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> v, String ov, String nv) { checkTotalWidthValue(); } }); totalHeightValue = UserConfig.getInt(baseName + "TotalHeight", 1000); if (totalHeightValue <= 0) { totalHeightValue = 1000; } totalHeightInput.setText(totalHeightValue + ""); totalHeightInput.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> v, String ov, String nv) { checkTotalHeightValue(); } }); String arraySelect = UserConfig.getString(baseName + "SizeType", "KeepSize"); switch (arraySelect) { case "KeepSize": keepSizeRadio.setSelected(true); break; case "AlignAsBigger": sizeBiggerRadio.setSelected(true); break; case "AlignAsSmaller": sizeSmallerRadio.setSelected(true); break; case "EachWidth": eachWidthRadio.setSelected(true); break; case "EachHeight": eachHeightRadio.setSelected(true); break; case "TotalWidth": totalWidthRadio.setSelected(true); break; case "TotalHeight": totalHeightRadio.setSelected(true); break; } sizeGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> v, Toggle ov, Toggle nv) { checkSize(); } }); checkSize(); } catch (Exception e) { MyBoxLog.error(e); } } private boolean checkSize() { totalWidthInput.setDisable(true); totalWidthInput.setStyle(null); totalHeightInput.setDisable(true); totalHeightInput.setStyle(null); eachWidthInput.setDisable(true); eachWidthInput.setStyle(null); eachHeightInput.setDisable(true); eachHeightInput.setStyle(null); if (keepSizeRadio.isSelected() || sizeBiggerRadio.isSelected() || sizeSmallerRadio.isSelected()) { return true; } else if (eachWidthRadio.isSelected()) { eachWidthInput.setDisable(false); return checkEachWidthValue(); } else if (eachHeightRadio.isSelected()) { eachHeightInput.setDisable(false); return checkEachHeightValue(); } else if (totalWidthRadio.isSelected()) { totalWidthInput.setDisable(false); return checkTotalWidthValue(); } else if (totalHeightRadio.isSelected()) { totalHeightInput.setDisable(false); return checkTotalHeightValue(); } return false; } private boolean checkEachWidthValue() { int v; try { v = Integer.parseInt(eachWidthInput.getText()); } catch (Exception e) { v = -1; } if (v > 0) { eachWidthValue = v; eachWidthInput.setStyle(null); return true; } else { eachWidthInput.setStyle(UserConfig.badStyle()); popError(message("InvalidParameter") + ": " + message("EachWidth")); return false; } } private boolean checkEachHeightValue() { int v; try { v = Integer.parseInt(eachHeightInput.getText()); } catch (Exception e) { v = -1; } if (v > 0) { eachHeightValue = v; eachHeightInput.setStyle(null); return true; } else { eachHeightInput.setStyle(UserConfig.badStyle()); popError(message("InvalidParameter") + ": " + message("EachHeight")); return false; } } private boolean checkTotalWidthValue() { int v; try { v = Integer.parseInt(totalWidthInput.getText()); } catch (Exception e) { v = -1; } if (v > 0) { totalWidthValue = v; totalWidthInput.setStyle(null); return true; } else { totalWidthInput.setStyle(UserConfig.badStyle()); popError(message("InvalidParameter") + ": " + message("TotalWidth")); return false; } } private boolean checkTotalHeightValue() { int v; try { v = Integer.parseInt(totalHeightInput.getText()); } catch (Exception e) { v = -1; } if (v > 0) { totalHeightValue = v; totalHeightInput.setStyle(null); return true; } else { totalHeightInput.setStyle(UserConfig.badStyle()); popError(message("InvalidParameter") + ": " + message("TotalHeight")); return false; } } private void initOthers() { try { interval = UserConfig.getInt(baseName + "Interval", 0); intervalSelector.getItems().addAll( Arrays.asList("0", "5", "-5", "1", "-1", "10", "-10", "15", "-15", "20", "-20", "30", "-30")); intervalSelector.setValue(interval + ""); intervalSelector.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> v, String ov, String nv) { checkInterval(); } }); margins = UserConfig.getInt(baseName + "Margins", 0); marginsSelector.getItems().addAll(Arrays.asList("0", "5", "-5", "10", "-10", "20", "-20", "30", "-30")); marginsSelector.setValue(margins + ""); marginsSelector.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> v, String ov, String nv) { checkMargins(); } }); colorController.init(this, baseName + "Color"); } catch (Exception e) { MyBoxLog.error(e); } } private boolean checkInterval() { try { interval = Integer.parseInt(intervalSelector.getValue()); ValidationTools.setEditorNormal(intervalSelector); return true; } catch (Exception e) { ValidationTools.setEditorBadStyle(intervalSelector); popError(message("InvalidParameter") + ": " + message("Interval")); return false; } } private boolean checkMargins() { try { margins = Integer.parseInt(marginsSelector.getValue()); ValidationTools.setEditorNormal(marginsSelector); return true; } catch (Exception e) { ValidationTools.setEditorBadStyle(marginsSelector); popError(message("InvalidParameter") + ": " + message("Margins")); return false; } } public boolean checkOptions() { if (tableController.tableData == null || tableController.tableData.isEmpty() || !checkArray() || !checkSize() || !checkInterval() || !checkMargins()) { return false; } try (Connection conn = DerbyBase.getConnection()) { if (arrayColumnRadio.isSelected()) { imageCombine.setArrayType(ArrayType.SingleColumn); UserConfig.setString(conn, baseName + "ArrayType", "SingleColumn"); } else if (arrayRowRadio.isSelected()) { imageCombine.setArrayType(ArrayType.SingleRow); UserConfig.setString(conn, baseName + "ArrayType", "SingleRow"); } else if (arrayColumnsRadio.isSelected()) { imageCombine.setArrayType(ArrayType.ColumnsNumber); imageCombine.setColumnsValue(columns); UserConfig.setString(conn, baseName + "ArrayType", "ColumnsNumber"); UserConfig.setInt(conn, baseName + "Columns", columns); } if (keepSizeRadio.isSelected()) { imageCombine.setSizeType(CombineSizeType.KeepSize); UserConfig.setString(conn, baseName + "SizeType", "KeepSize"); } else if (sizeBiggerRadio.isSelected()) { imageCombine.setSizeType(CombineSizeType.AlignAsBigger); UserConfig.setString(conn, baseName + "SizeType", "AlignAsBigger"); } else if (sizeSmallerRadio.isSelected()) { imageCombine.setSizeType(CombineSizeType.AlignAsSmaller); UserConfig.setString(conn, baseName + "SizeType", "AlignAsSmaller"); } else if (eachWidthRadio.isSelected()) { imageCombine.setSizeType(CombineSizeType.EachWidth); imageCombine.setEachWidthValue(eachWidthValue); UserConfig.setString(conn, baseName + "SizeType", "EachWidth"); UserConfig.setInt(conn, baseName + "EachWidth", eachWidthValue); } else if (eachHeightRadio.isSelected()) { imageCombine.setSizeType(CombineSizeType.EachHeight); imageCombine.setEachHeightValue(eachHeightValue); UserConfig.setString(conn, baseName + "SizeType", "EachHeight"); UserConfig.setInt(conn, baseName + "EachHeight", eachHeightValue); } else if (totalWidthRadio.isSelected()) { imageCombine.setSizeType(CombineSizeType.TotalWidth); imageCombine.setTotalWidthValue(totalWidthValue); UserConfig.setString(conn, baseName + "SizeType", "TotalWidth"); UserConfig.setInt(conn, baseName + "TotalWidth", totalWidthValue); } else if (totalHeightRadio.isSelected()) { imageCombine.setSizeType(CombineSizeType.TotalHeight); imageCombine.setTotalHeightValue(totalHeightValue); UserConfig.setString(conn, baseName + "SizeType", "TotalHeight"); UserConfig.setInt(conn, baseName + "TotalHeight", totalHeightValue); } imageCombine.setIntervalValue(interval); UserConfig.setInt(conn, baseName + "Interval", interval); imageCombine.setMarginsValue(margins); UserConfig.setInt(conn, baseName + "Margins", margins); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } @FXML @Override public void goAction() { if (!checkOptions()) { return; } List<ImageInformation> imageInfos = tableController.selectedItems(); if (imageInfos == null || imageInfos.isEmpty()) { imageInfos = tableController.tableData; } if (imageInfos == null || imageInfos.isEmpty()) { popError(message("SelectToHandle")); return; } List<ImageInformation> infos = imageInfos; imageCombine.setBgColor(colorController.color()); if (task != null) { task.cancel(); } task = new FxSingletonTask<Void>(this) { Image image; @Override protected boolean handle() { if (imageCombine.getArrayType() == ArrayType.SingleColumn) { image = CombineTools.combineSingleColumn(this, imageCombine, infos, false, true); } else if (imageCombine.getArrayType() == ArrayType.SingleRow) { image = CombineTools.combineSingleRow(this, imageCombine, infos, false, true); } else if (imageCombine.getArrayType() == ArrayType.ColumnsNumber) { image = CombineTools.combineImagesColumns(this, imageCombine, infos); } else { image = null; } return image != null; } @Override protected void whenSucceeded() { viewController.image = image; viewController.imageView.setImage(image); viewController.setZoomStep(image); viewController.fitSize(); viewController.imageLabel.setText(Languages.message("CombinedSize") + ": " + (int) image.getWidth() + "x" + (int) image.getHeight()); } }; start(task); } @FXML @Override public void saveAction() { viewController.saveAsAction(); } @FXML @Override public boolean menuAction(Event event) { if (viewBox.isFocused() || viewBox.isFocusWithin()) { viewController.menuAction(event); return true; } else if (sourceBox.isFocused() || sourceBox.isFocusWithin()) { tableController.menuAction(event); return true; } return super.menuAction(event); } @FXML @Override public boolean popAction() { if (viewBox.isFocused() || viewBox.isFocusWithin()) { viewController.popAction(); return true; } else if (sourceBox.isFocused() || sourceBox.isFocusWithin()) { tableController.popAction(); return true; } return super.popAction(); } @Override public boolean handleKeyEvent(KeyEvent event) { if (viewBox.isFocused() || viewBox.isFocusWithin()) { if (viewController.handleKeyEvent(event)) { return true; } } else if (sourceBox.isFocused() || sourceBox.isFocusWithin()) { if (tableController.handleKeyEvent(event)) { return true; } } if (super.handleKeyEvent(event)) { return true; } if (viewController.handleKeyEvent(event)) { return true; } return tableController.handleKeyEvent(event); } /* static methods */ public static ImagesSpliceController open(List<ImageInformation> imageInfos) { try { ImagesSpliceController controller = (ImagesSpliceController) WindowTools.openStage(Fxmls.ImagesSpliceFxml); controller.tableController.tableData.setAll(imageInfos);; return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/LoadingController.java
alpha/MyBox/src/main/java/mara/mybox/controller/LoadingController.java
package mara.mybox.controller; import java.util.Date; import java.util.Timer; import java.util.TimerTask; import javafx.application.Platform; import javafx.beans.property.SimpleBooleanProperty; import javafx.concurrent.Task; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.control.ProgressIndicator; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.tools.DateTools; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2018-6-11 8:14:06 * @License Apache License Version 2.0 */ public class LoadingController extends BaseLogsController { private Task<?> loadingTask; protected SimpleBooleanProperty canceled; @FXML protected ProgressIndicator progressIndicator; @FXML protected Label timeLabel; public LoadingController() { canceled = new SimpleBooleanProperty(); } public void init(final Task<?> task) { try { loadingTask = task; canceled.set(false); progressIndicator.setProgress(-1F); if (timeLabel != null) { showTimer(); } getMyStage().toFront(); if (task != null && (task instanceof FxTask)) { FxTask stask = (FxTask) task; setTitle(stask.getController().getTitle()); setInfo(getTitle()); } else { setInfo(message("Handling...")); } logsTextArea.requestFocus(); } catch (Exception e) { MyBoxLog.error(e); } } public void showTimer() { try { if (timer != null) { timer.cancel(); } final Date startTime = new Date(); final String prefix = message("StartTime") + ": " + DateTools.nowString() + " " + message("ElapsedTime") + ": "; timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { Platform.runLater(() -> { if (loadingTask != null && loadingTask.isCancelled()) { cancelAction(); return; } timeLabel.setText(prefix + DateTools.datetimeMsDuration(new Date(), startTime)); }); Platform.requestNextPulse(); } }, 0, 1000); } catch (Exception e) { MyBoxLog.error(e); } } @FXML @Override public void cancelAction() { clear(); closeStage(); } public void clear() { canceled.set(true); if (loadingTask != null) { if (parentController != null) { parentController.taskCanceled(loadingTask); } loadingTask.cancel(); loadingTask = null; } if (timer != null) { timer.cancel(); timer = null; } } public void setInfo(String info) { updateLogs(info, true); } public String getInfo() { return logsTextArea.getText(); } @Override public boolean isRunning() { return timer != null; } public boolean canceled() { return canceled != null && canceled.get(); } public void setProgress(float value) { if (loadingTask == null || loadingTask.isDone()) { return; } progressIndicator.setProgress(value); } public ProgressIndicator getProgressIndicator() { return progressIndicator; } public void setProgressIndicator(ProgressIndicator progressIndicator) { this.progressIndicator = progressIndicator; } public Task<?> getLoadingTask() { return loadingTask; } public void setLoadingTask(Task<?> loadingTask) { this.loadingTask = loadingTask; } public Label getTimeLabel() { return timeLabel; } public void setTimeLabel(Label timeLabel) { this.timeLabel = timeLabel; } @Override public void cleanPane() { try { clear(); } catch (Exception e) { } super.cleanPane(); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/ControlStroke.java
alpha/MyBox/src/main/java/mara/mybox/controller/ControlStroke.java
package mara.mybox.controller; import java.awt.BasicStroke; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javafx.fxml.FXML; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.RadioButton; import javafx.scene.control.TextField; import javafx.scene.control.ToggleGroup; import javafx.scene.image.ImageView; import javafx.scene.layout.FlowPane; import javafx.scene.layout.VBox; import javafx.scene.shape.StrokeLineCap; import javafx.scene.shape.StrokeLineJoin; import mara.mybox.data.ShapeStyle; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.HelpTools; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2019-8-13 * @License Apache License Version 2.0 */ public class ControlStroke extends BaseController { protected BaseShapeController shapeController; protected ShapeStyle style; @FXML protected ControlColorSet colorController, fillController; @FXML protected ComboBox<String> widthSelector, limitSelector, fillOpacitySelector; @FXML protected ToggleGroup joinGroup, capGroup; @FXML protected RadioButton joinMiterRadio, joinBevelRadio, joinRoundRadio, capButtRadio, capSquareRadio, capRoundRadio; @FXML protected TextField arrayInput, offsetInput; @FXML protected CheckBox dashCheck, fillCheck; @FXML protected VBox fillBox; @FXML protected FlowPane fillOpacityPane; protected void setParameters(BaseShapeController parent) { try { if (parent == null) { return; } shapeController = parent; baseName = parent.baseName; style = new ShapeStyle(baseName); colorController.init(this, baseName + "Color", style.getStrokeColor()); widthSelector.setValue((int) style.getStrokeWidth() + ""); switch (style.getStrokeLineJoinAwt()) { case BasicStroke.JOIN_ROUND: joinRoundRadio.setSelected(true); break; case BasicStroke.JOIN_BEVEL: joinBevelRadio.setSelected(true); break; default: joinMiterRadio.setSelected(true); break; } List<String> vl = new ArrayList<>(); vl.addAll(Arrays.asList("10", "5", "2", "1", "8", "15", "20")); int iv = (int) style.getStrokeLineLimit(); if (!vl.contains(iv + "")) { vl.add(0, iv + ""); } limitSelector.getItems().setAll(vl); limitSelector.setValue(iv + ""); switch (style.getStrokeLineCapAwt()) { case BasicStroke.CAP_ROUND: capRoundRadio.setSelected(true); break; case BasicStroke.CAP_SQUARE: capSquareRadio.setSelected(true); break; default: capButtRadio.setSelected(true); break; } dashCheck.setSelected(style.isIsStrokeDash()); if (arrayInput != null) { arrayInput.setText(style.getStrokeDashText()); } if (offsetInput != null) { offsetInput.setText(style.getDashOffset() + ""); } fillCheck.setSelected(style.isIsFillColor()); fillController.init(this, baseName + "Fill", style.getFillColor()); vl = new ArrayList<>(); vl.addAll(Arrays.asList("0.5", "0.3", "0", "1.0", "0.05", "0.02", "0.1", "0.2", "0.8", "0.6", "0.4", "0.7", "0.9")); float fv = style.getFillOpacity(); if (!vl.contains(fv + "")) { vl.add(0, fv + ""); } fillOpacitySelector.getItems().setAll(vl); fillOpacitySelector.setValue(fv + ""); if (shapeController instanceof BaseImageEditController) { fillBox.getChildren().remove(fillOpacityPane); } } catch (Exception e) { MyBoxLog.error(e); } } protected void setWidthList() { isSettingValues = true; setWidthList(widthSelector, shapeController.imageView, (int) style.getStrokeWidth()); isSettingValues = false; } protected static void setWidthList(ComboBox<String> selector, ImageView view, int initValue) { if (selector == null || view == null) { return; } List<String> ws = new ArrayList<>(); ws.addAll(Arrays.asList("2", "3", "1", "5", "8", "10", "15", "25", "30", "50", "80", "100", "150", "200", "300", "500")); int max = (int) view.getImage().getWidth(); int step = max / 10; for (int w = 10; w < max; w += step) { if (!ws.contains(w + "")) { ws.add(0, w + ""); } } if (initValue >= 0) { if (!ws.contains(initValue + "")) { ws.add(0, initValue + ""); } } else { initValue = 2; } selector.getItems().setAll(ws); selector.setValue(initValue + ""); } protected ShapeStyle pickValues() { float v = -1; try { v = Float.parseFloat(widthSelector.getValue()); } catch (Exception e) { } if (v <= 0) { popError(message("InvalidParameter") + ": " + message("Width")); return null; } style.setStrokeWidth(v); style.setStrokeColor(colorController.color()); if (joinRoundRadio.isSelected()) { style.setStrokeLineJoin(StrokeLineJoin.ROUND); } else if (joinBevelRadio.isSelected()) { style.setStrokeLineJoin(StrokeLineJoin.BEVEL); } else { style.setStrokeLineJoin(StrokeLineJoin.MITER); } v = -1; try { v = Float.parseFloat(limitSelector.getValue()); } catch (Exception e) { } if (v < 1) { popError(message("InvalidParameter") + ": " + message("StrokeMiterLimit")); return null; } style.setStrokeLineLimit(v); if (capRoundRadio.isSelected()) { style.setStrokeLineCap(StrokeLineCap.ROUND); } else if (capSquareRadio.isSelected()) { style.setStrokeLineCap(StrokeLineCap.SQUARE); } else { style.setStrokeLineCap(StrokeLineCap.BUTT); } style.setIsStrokeDash(dashCheck.isSelected()); if (dashCheck.isSelected()) { List<Double> values = ShapeStyle.text2StrokeDash(arrayInput.getText()); if (values == null || values.isEmpty()) { popError(message("InvalidParameter") + ": " + message("StrokeDashArray")); return null; } style.setStrokeDash(values); v = -1; try { v = Float.parseFloat(offsetInput.getText()); } catch (Exception e) { } if (v < 0) { popError(message("InvalidParameter") + ": " + message("StrokeDashOffset")); return null; } style.setDashOffset(v); } style.setIsFillColor(fillCheck.isSelected()); style.setFillColor(fillController.color()); if (fillCheck.isSelected()) { v = -1; try { v = Float.parseFloat(fillOpacitySelector.getValue()); } catch (Exception e) { } if (v < 0 || v > 1) { popError(message("InvalidParameter") + ": " + message("FillOpacity")); return null; } style.setFillOpacity(v); } style.save(); return style; } @FXML public void aboutStroke() { openLink(HelpTools.strokeLink()); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/HtmlDomDeleteController.java
alpha/MyBox/src/main/java/mara/mybox/controller/HtmlDomDeleteController.java
package mara.mybox.controller; import java.util.List; import javafx.fxml.FXML; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeTableView; import mara.mybox.data.HtmlNode; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.fxml.WindowTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; import org.jsoup.nodes.Element; /** * @Author Mara * @CreateDate 2023-3-6 * @License Apache License Version 2.0 */ public class HtmlDomDeleteController extends BaseChildController { protected BaseHtmlFormat editor; protected TreeTableView<HtmlNode> sourceTree; protected BaseHtmlTreeController manageController; protected int count; @FXML protected ControlHtmlDomSource sourceController; public HtmlDomDeleteController() { baseTitle = message("DeleteNodes"); } public void setParamters(BaseHtmlFormat editor, TreeItem<HtmlNode> sourceItem) { try { this.editor = editor; if (invalidTarget()) { return; } manageController = editor.domController; Element root = manageController.treeView.getRoot().getValue().getElement(); sourceController.load(root, sourceItem); sourceController.setLabel(message("Select")); sourceTree = sourceController.treeView; } catch (Exception e) { MyBoxLog.error(e); closeStage(); } } public boolean invalidTarget() { if (editor == null || editor.getMyStage() == null || !editor.getMyStage().isShowing()) { popError(message("Invalid")); closeStage(); return true; } return false; } public boolean checkParameters() { return !invalidTarget(); } @FXML @Override public void okAction() { if (!checkParameters()) { return; } if (task != null) { task.cancel(); } task = new FxSingletonTask<Void>(this) { @Override protected boolean handle() { return delete(); } @Override protected void whenSucceeded() { if (count > 0) { closeStage(); manageController.refreshAction(); editor.domChanged(true); } editor.popInformation(message("Deleted") + ": " + count); } }; start(task); } protected boolean delete() { try { count = 0; List<TreeItem<HtmlNode>> sourcesItems = sourceController.selectedItems(); for (TreeItem<HtmlNode> sourceItem : sourcesItems) { String sourceNumber = sourceController.makeHierarchyNumber(sourceItem); TreeItem<HtmlNode> manageItem = manageController.findSequenceNumber(sourceNumber); Element selectedElement = manageItem.getValue().getElement(); selectedElement.remove(); count++; } return true; } catch (Exception e) { error = e.toString(); return false; } } /* static methods */ public static HtmlDomDeleteController open(BaseHtmlFormat editor, TreeItem<HtmlNode> sourceItem) { if (editor == null) { return null; } HtmlDomDeleteController controller = (HtmlDomDeleteController) WindowTools.childStage( editor, Fxmls.HtmlDomDeleteFxml); if (controller != null) { controller.setParamters(editor, sourceItem); controller.requestMouse(); } return controller; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/Data2DGroupStatisticController.java
alpha/MyBox/src/main/java/mara/mybox/controller/Data2DGroupStatisticController.java
package mara.mybox.controller; import java.util.ArrayList; import java.util.List; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.CheckBox; import javafx.scene.control.RadioButton; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.control.TextField; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleGroup; import javafx.scene.control.Tooltip; import javafx.scene.layout.FlowPane; import mara.mybox.calculation.DescriptiveStatistic; import mara.mybox.calculation.DescriptiveStatistic.StatisticObject; import mara.mybox.calculation.DescriptiveStatistic.StatisticType; import mara.mybox.data2d.DataFileCSV; import mara.mybox.data2d.DataTableGroup; import mara.mybox.data2d.DataTableGroupStatistic; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.Data2DColumn; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxBackgroundTask; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.fxml.WindowTools; import mara.mybox.fxml.chart.PieChartMaker; import mara.mybox.fxml.style.NodeStyleTools; import mara.mybox.tools.DoubleTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2022-8-10 * @License Apache License Version 2.0 */ public class Data2DGroupStatisticController extends Data2DChartXYController { protected DescriptiveStatistic calculation; protected DataFileCSV dataFile; protected PieChartMaker pieMaker; protected List<List<String>> pieData; protected List<Data2DColumn> pieColumns; protected int pieMaxData; @FXML protected TabPane chartTabPane; @FXML protected Tab groupDataTab, statisticDataTab, chartDataTab, xyChartTab, pieChartTab; @FXML protected ControlStatisticSelection statisticController; @FXML protected ControlData2DView statisticDataController, chartDataController; @FXML protected ControlData2DChartPie pieChartController; @FXML protected FlowPane columnsDisplayPane, valuesDisplayPane; @FXML protected RadioButton xyParametersRadio, pieParametersRadio; @FXML protected ToggleGroup pieCategoryGroup; @FXML protected TextField pieMaxInput; public Data2DGroupStatisticController() { baseTitle = message("GroupStatistic"); } @Override public void initOptions() { try { super.initOptions(); pieMaker = pieChartController.pieMaker; pieChartController.redrawNotify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { drawPieChart(); } }); pieMaxData = UserConfig.getInt(baseName + "PieMaxData", 100); if (pieMaxData <= 0) { pieMaxData = 100; } if (pieMaxInput != null) { pieMaxInput.setText(pieMaxData + ""); } statisticController.mustCount(); chartDataController.loadedNotify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { xyChartTab.setDisable(false); pieChartTab.setDisable(false); refreshAction(); } }); pieCategoryGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue ov, Toggle oldValue, Toggle newValue) { makeCharts(false, true); } }); xyChartTab.setDisable(true); pieChartTab.setDisable(true); displayAllCheck.visibleProperty().unbind(); displayAllCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { refreshAction(); } }); } catch (Exception e) { MyBoxLog.error(e); } } @Override public void setControlsStyle() { try { super.setControlsStyle(); NodeStyleTools.setTooltip(displayAllCheck, new Tooltip(message("AllRowsLoadComments"))); } catch (Exception e) { MyBoxLog.debug(e); } } @Override public boolean checkOptions() { if (!groupController.pickValues()) { return false; } checkObject(); checkInvalidAs(); return true; } @Override public boolean initChart() { return initChart(false); } @Override protected void startOperation() { if (task != null) { task.cancel(); } dataFile = null; groupDataController.loadNull(); statisticDataController.loadNull(); chartDataController.loadNull(); xyChartTab.setDisable(true); pieChartTab.setDisable(true); calculation = statisticController.pickValues() .setStatisticObject(StatisticObject.Columns) .setScale(scale) .setInvalidAs(invalidAs) .setTaskController(this) .setData2D(data2D) .setColsIndices(checkedColsIndices) .setColsNames(checkedColsNames); columnsDisplayPane.getChildren().clear(); for (String c : checkedColsNames) { columnsDisplayPane.getChildren().add(new CheckBox(c)); } valuesDisplayPane.getChildren().clear(); for (StatisticType t : calculation.types) { valuesDisplayPane.getChildren().add(new CheckBox(message(t.name()))); } taskSuccessed = false; task = new FxSingletonTask<Void>(this) { private DataTableGroup group; private DataTableGroupStatistic statistic; @Override protected boolean handle() { try { data2D.setTask(this); group = groupData(DataTableGroup.TargetType.Table, checkedColsIndices, false, -1, scale); if (!group.run()) { return false; } if (task == null || isCancelled()) { return false; } task.setInfo(message("Statistic") + "..."); statistic = new DataTableGroupStatistic() .setGroups(group).setCountChart(true) .setCalculation(calculation) .setCalNames(checkedColsNames) .setTask(this); if (!statistic.run()) { return false; } if (task == null || isCancelled()) { return false; } dataFile = statistic.getChartData(); taskSuccessed = dataFile != null; return taskSuccessed; } catch (Exception e) { error = e.toString(); return false; } } @Override protected void whenSucceeded() { chartDataController.loadDef(dataFile); groupDataController.loadDef(group.getTargetData()); statisticDataController.loadDef(statistic.getStatisticData()); rightPane.setDisable(false); } @Override protected void finalAction() { super.finalAction(); closeTask(ok); } }; start(task, false); } @FXML public void makeCharts(boolean forXY, boolean forPie) { if (forXY) { outputColumns = null; outputData = null; chartMaker.clearChart(); } if (forPie) { pieColumns = null; pieData = null; pieMaker.clearChart(); } if (dataFile == null) { return; } if (backgroundTask != null) { backgroundTask.cancel(); backgroundTask = null; } backgroundTask = new FxBackgroundTask<Void>(this) { @Override protected boolean handle() { try { dataFile.startTask(this, null); List<List<String>> resultsData; if (displayAllCheck.isSelected()) { resultsData = dataFile.allRows(false); } else { resultsData = chartDataController.data2D.pageData(); } if (resultsData == null) { return false; } if (forXY && !makeXYData(resultsData)) { return false; } if (forPie && !makePieData(resultsData)) { return false; } return true; } catch (Exception e) { error = e.toString(); MyBoxLog.error(e); return false; } } @Override protected void whenSucceeded() { if (forXY) { drawXYChart(); } if (forPie) { drawPieChart(); } } @Override protected void whenFailed() { } @Override protected void finalAction() { super.finalAction(); dataFile.stopTask(); } }; start(backgroundTask, false); } protected boolean makeXYData(List<List<String>> resultsData) { try { if (resultsData == null) { return false; } outputColumns = new ArrayList<>(); Data2DColumn xyCategoryColumn = dataFile.column(xyParametersRadio.isSelected() ? 1 : 0); outputColumns.add(xyCategoryColumn); List<String> colNames = new ArrayList<>(); List<String> allName = new ArrayList<>(); for (Node n : columnsDisplayPane.getChildren()) { CheckBox cb = (CheckBox) n; String name = Data2DColumn.getCheckBoxColumnName(cb); if (cb.isSelected()) { colNames.add(name); } allName.add(name); } if (colNames.isEmpty()) { if (allName.isEmpty()) { error = message("SelectToHanlde") + ": " + message("ColumnsDisplayed"); return false; } colNames = allName; } List<String> sTypes = new ArrayList<>(); List<String> allTypes = new ArrayList<>(); for (Node n : valuesDisplayPane.getChildren()) { CheckBox cb = (CheckBox) n; String tname = Data2DColumn.getCheckBoxColumnName(cb); if (cb.isSelected()) { sTypes.add(tname); } allTypes.add(tname); } if (sTypes.isEmpty()) { if (allTypes.isEmpty()) { error = message("SelectToHanlde") + ": " + message("ValuesDisplayed"); return false; } sTypes = allTypes; } List<Integer> cols = new ArrayList<>(); for (String stype : sTypes) { if (message("Count").equals(stype)) { outputColumns.add(dataFile.column(2)); cols.add(2); } else { for (String col : colNames) { int colIndex = dataFile.colOrder(col + "_" + stype); outputColumns.add(dataFile.column(colIndex)); cols.add(colIndex); } } } outputData = new ArrayList<>(); for (List<String> data : resultsData) { List<String> xyRow = new ArrayList<>(); String category = data.get(xyParametersRadio.isSelected() ? 1 : 0); xyRow.add(category); for (int colIndex : cols) { xyRow.add(data.get(colIndex)); } outputData.add(xyRow); } selectedCategory = xyCategoryColumn.getColumnName(); selectedValue = message("Statistic"); return initChart(); } catch (Exception e) { error = e.toString(); MyBoxLog.error(e); return false; } } protected boolean makePieData(List<List<String>> resultsData) { try { if (resultsData == null) { return false; } pieColumns = new ArrayList<>(); Data2DColumn pieCategoryColumn = dataFile.columns.get(pieParametersRadio.isSelected() ? 1 : 0); pieColumns.add(pieCategoryColumn); pieColumns.add(dataFile.columns.get(2)); pieColumns.add(new Data2DColumn(message("Percentage"), ColumnDefinition.ColumnType.Double)); pieData = new ArrayList<>(); double sum = 0, count; for (List<String> data : resultsData) { try { sum += Double.parseDouble(data.get(2)); } catch (Exception e) { } } for (List<String> data : resultsData) { try { String category = data.get(pieParametersRadio.isSelected() ? 1 : 0); List<String> pieRow = new ArrayList<>(); pieRow.add(category); count = Double.parseDouble(data.get(2)); pieRow.add((long) count + ""); pieRow.add(DoubleTools.percentage(count, sum, scale)); pieData.add(pieRow); } catch (Exception e) { } } selectedCategory = pieCategoryColumn.getColumnName(); String title = chartTitle(); pieMaker.init(message("PieChart")) .setDefaultChartTitle(title + " - " + message("Count")) .setDefaultCategoryLabel(selectedCategory) .setDefaultValueLabel(message("Count")) .setValueLabel(message("Count")) .setInvalidAs(invalidAs); return true; } catch (Exception e) { error = e.toString(); MyBoxLog.error(e); return false; } } @Override public void drawChart() { drawXYChart(); drawPieChart(); } @Override public void drawXYChart() { try { chartData = chartMax(); if (chartData == null || chartData.isEmpty()) { return; } chartController.writeXYChart(outputColumns, chartData); } catch (Exception e) { MyBoxLog.error(e); } } @FXML public void drawPieChart() { try { if (pieData == null || pieData.isEmpty()) { popError(message("NoData")); return; } List<List<String>> maxPieData; if (pieMaxData > 0 && pieMaxData < pieData.size()) { maxPieData = pieData.subList(0, pieMaxData); } else { maxPieData = pieData; } pieChartController.writeChart(pieColumns, maxPieData); } catch (Exception e) { MyBoxLog.error(e); } } @FXML public void goXYchart() { makeCharts(true, false); } @FXML @Override public void refreshAction() { makeCharts(true, true); } @Override public void typeChanged() { initChart(); goXYchart(); } @FXML public void pieMaxAction() { if (pieMaxInput != null) { boolean ok; String s = pieMaxInput.getText(); if (s == null || s.isBlank()) { pieMaxData = -1; ok = true; } else { try { int v = Integer.parseInt(s); if (v > 0) { pieMaxData = v; ok = true; } else { ok = false; } } catch (Exception ex) { ok = false; } } if (ok) { UserConfig.setInt(baseName + "PieMaxData", pieMaxData); pieMaxInput.setStyle(null); } else { pieMaxInput.setStyle(UserConfig.badStyle()); popError(message("Invalid") + ": " + message("Maximum")); return; } } drawPieChart(); } @FXML @Override public boolean menuAction(Event event) { Tab tab = chartTabPane.getSelectionModel().getSelectedItem(); if (tab == groupDataTab) { return groupDataController.menuAction(event); } else if (tab == statisticDataTab) { return statisticDataController.menuAction(event); } else if (tab == chartDataTab) { return chartDataController.menuAction(event); } else if (tab == xyChartTab) { return chartController.menuAction(event); } else if (tab == pieChartTab) { return pieChartController.menuAction(event); } return false; } @FXML @Override public boolean popAction() { Tab tab = chartTabPane.getSelectionModel().getSelectedItem(); if (tab == groupDataTab) { return groupDataController.popAction(); } else if (tab == statisticDataTab) { return statisticDataController.popAction(); } else if (tab == chartDataTab) { return chartDataController.popAction(); } else if (tab == xyChartTab) { return chartController.popAction(); } else if (tab == pieChartTab) { return pieChartController.popAction(); } return false; } @Override public boolean controlAlt2() { Tab tab = chartTabPane.getSelectionModel().getSelectedItem(); if (tab == xyChartTab) { return chartController.controlAlt2(); } else if (tab == pieChartTab) { return pieChartController.controlAlt2(); } return false; } @Override public boolean controlAlt3() { Tab tab = chartTabPane.getSelectionModel().getSelectedItem(); if (tab == xyChartTab) { return chartController.controlAlt3(); } else if (tab == pieChartTab) { return pieChartController.controlAlt3(); } return false; } @Override public boolean controlAlt4() { Tab tab = chartTabPane.getSelectionModel().getSelectedItem(); if (tab == xyChartTab) { return chartController.controlAlt4(); } else if (tab == pieChartTab) { return pieChartController.controlAlt4(); } return false; } /* static */ public static Data2DGroupStatisticController open(BaseData2DLoadController tableController) { try { Data2DGroupStatisticController controller = (Data2DGroupStatisticController) WindowTools.referredStage( tableController, Fxmls.Data2DGroupStatisticFxml); controller.setParameters(tableController); controller.requestMouse(); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/SvgFromImageController.java
alpha/MyBox/src/main/java/mara/mybox/controller/SvgFromImageController.java
package mara.mybox.controller; import java.awt.image.BufferedImage; import java.io.File; import java.nio.charset.Charset; import javafx.embed.swing.SwingFXUtils; import javafx.fxml.FXML; import javafx.scene.image.Image; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.fxml.WindowTools; import mara.mybox.tools.FileTmpTools; import mara.mybox.tools.SvgTools; import mara.mybox.tools.TextFileTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2023-6-29 * @License Apache License Version 2.0 */ public class SvgFromImageController extends BaseChildController { protected BufferedImage bufferedImage; @FXML protected ControlSvgFromImage optionsController; public SvgFromImageController() { baseTitle = message("ImageToSvg"); } public void setParameters(Image image) { if (image == null) { close(); return; } bufferedImage = SwingFXUtils.fromFXImage(image, null); } @FXML @Override public void startAction() { if (!optionsController.pickValues()) { return; } if (task != null) { task.cancel(); } task = new FxSingletonTask<Void>(this) { private File svgFile; @Override protected boolean handle() { try { String svg = SvgTools.imageToSvg(this, myController, bufferedImage, optionsController); if (svg == null || svg.isBlank() || !isWorking()) { return false; } svgFile = FileTmpTools.generateFile(optionsController.getQuantization().name(), "svg"); svgFile = TextFileTools.writeFile(svgFile, svg, Charset.forName("utf-8")); return svgFile != null && svgFile.exists(); } catch (Exception e) { error = e.toString(); return false; } } @Override protected void whenSucceeded() { SvgEditorController.open(svgFile); if (closeAfterCheck.isSelected()) { close(); } } }; start(task); } /* static methods */ public static SvgFromImageController open(Image image) { SvgFromImageController controller = (SvgFromImageController) WindowTools.openStage(Fxmls.SvgFromImageFxml); if (controller != null) { controller.setParameters(image); controller.requestMouse(); } return controller; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/ColorQueryController.java
alpha/MyBox/src/main/java/mara/mybox/controller/ColorQueryController.java
package mara.mybox.controller; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.RadioButton; import javafx.scene.control.Tab; import javafx.scene.control.TextField; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleGroup; import javafx.scene.input.KeyEvent; import javafx.scene.paint.Color; import mara.mybox.db.data.ColorData; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.HelpTools; import mara.mybox.fxml.WindowTools; import mara.mybox.fxml.style.HtmlStyles; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2021-8-29 * @License Apache License Version 2.0 */ public class ColorQueryController extends BaseController { protected ColorData colorData; @FXML protected Tab colorTab, resultTab; @FXML protected ControlColorInput colorController; @FXML protected Button refreshButton, paletteButton; @FXML protected TextField separatorInput; @FXML protected ToggleGroup separatorGroup; @FXML protected RadioButton commaRadio, hyphenRadio, colonRadio, blankRadio, inputRadio; @FXML protected HtmlTableController htmlController; public ColorQueryController() { baseTitle = message("QueryColor"); } @Override public void initControls() { try { separatorGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> v, Toggle ov, Toggle nv) { if (!inputRadio.isSelected()) { goAction(); } } }); separatorInput.setText(UserConfig.getString(baseName + "Separator", null)); goButton.disableProperty().bind(colorController.colorInput.textProperty().isEmpty() .or(separatorInput.textProperty().isEmpty()) ); htmlController.initStyle(HtmlStyles.TableStyle); initMore(); } catch (Exception e) { MyBoxLog.error(e); } } public void initMore() { try { colorController.setParameter(baseName, Color.GOLD); colorController.updateNotify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { goAction(); } }); goAction(); } catch (Exception e) { MyBoxLog.error(e); } } public String pickSeparator() { try { String separator = ", "; if (commaRadio.isSelected()) { separator = ", "; } else if (hyphenRadio.isSelected()) { separator = "-"; } else if (colonRadio.isSelected()) { separator = ":"; } else if (blankRadio.isSelected()) { separator = " "; } else if (inputRadio.isSelected()) { separator = separatorInput.getText(); if (separator == null || separator.isEmpty()) { return null; } UserConfig.setString(baseName + "Separator", separator); } return separator; } catch (Exception e) { MyBoxLog.error(e); return null; } } @FXML @Override public void goAction() { try { colorData = colorController.colorData; if (colorData == null || colorData.getRgba() == null) { return; } String separator = pickSeparator(); if (separator == null || separator.isEmpty()) { popError(message("InvalidParamter") + ": " + message("ValueSeparator")); return; } colorData = new ColorData(colorData.getRgba()) .setvSeparator(separator).convert(); htmlController.displayHtml(colorData.html()); } catch (Exception e) { MyBoxLog.error(e); } } @FXML protected void popHelps(Event event) { if (UserConfig.getBoolean("ColorHelpsPopWhenMouseHovering", false)) { showHelps(event); } } @FXML protected void showHelps(Event event) { popEventMenu(event, HelpTools.colorHelps(true)); } @Override public boolean handleKeyEvent(KeyEvent event) { if (colorTab.isSelected()) { if (colorController.handleKeyEvent(event)) { return true; } } return super.handleKeyEvent(event); } /* static */ public static ColorQueryController open() { try { ColorQueryController controller = (ColorQueryController) WindowTools.openStage(Fxmls.ColorQueryFxml); controller.requestMouse(); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/ColorsBlendController.java
alpha/MyBox/src/main/java/mara/mybox/controller/ColorsBlendController.java
package mara.mybox.controller; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.Tab; import javafx.scene.input.KeyEvent; import javafx.scene.paint.Color; import mara.mybox.data.StringTable; import mara.mybox.db.data.ColorData; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.fxml.WindowTools; import mara.mybox.fxml.image.FxColorTools; import static mara.mybox.fxml.image.FxColorTools.color2css; import mara.mybox.image.data.PixelsBlend; import mara.mybox.image.data.PixelsBlendFactory; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2025-6-7 * @License Apache License Version 2.0 */ public class ColorsBlendController extends ColorQueryController { protected ColorData colorOverlay, colorBlended; protected String separator; @FXML protected Tab overlayTab, blendTab; @FXML protected ControlColorInput colorOverlayController; @FXML protected ControlColorsBlend blendController; public ColorsBlendController() { baseTitle = message("BlendColors"); } @Override public void initMore() { try { colorController.setParameter(baseName + "Base", Color.YELLOW); colorController.updateNotify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { goAction(); } }); colorOverlayController.setParameter(baseName + "Overlay", Color.SKYBLUE); colorOverlayController.updateNotify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { goAction(); } }); blendController.setParameters(this); blendController.changeNotify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { goAction(); } }); goAction(); } catch (Exception e) { MyBoxLog.error(e); } } @FXML @Override public void okAction() { goAction(); } public boolean pickColors() { try { separator = pickSeparator(); if (separator == null || separator.isEmpty()) { popError(message("InvalidParamter") + ": " + message("ValueSeparator")); return false; } colorData = colorController.colorData; if (colorData == null || colorData.getRgba() == null) { popError(message("SelectToHandle") + ": " + message("BaseColor")); return false; } colorData = new ColorData(colorData.getRgba()) .setColorName(blendController.baseAboveCheck.isSelected() ? message("OverlayColor") : message("BaseColor")) .setvSeparator(separator).convert(); colorOverlay = colorOverlayController.colorData; if (colorOverlay == null || colorOverlay.getRgba() == null) { popError(message("SelectToHandle") + ": " + message("OverlayColor")); return false; } colorOverlay = new ColorData(colorOverlay.getRgba()) .setColorName(blendController.baseAboveCheck.isSelected() ? message("BaseColor") : message("OverlayColor")) .setvSeparator(separator).convert(); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } @FXML @Override public void goAction() { try { if (!pickColors()) { return; } PixelsBlend blender = blendController.pickValues(-1f); if (blender == null) { popError(message("SelectToHandle") + ": " + message("BlendMode")); return; } colorBlended = new ColorData(blender.blend(colorOverlay.getColorValue(), colorData.getColorValue())) .setColorName(blender.modeName()) .setvSeparator(separator).convert(); String html = "<html><body contenteditable=\"false\">\n" + "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" + "<svg xmlns=\"http://www.w3.org/2000/svg\" height=\"400\" width=\"600\">\n" + " <circle cx=\"200\" cy=\"200\" fill=\"" + colorData.css() + "\" r=\"198\"/>\n" + " <circle cx=\"400\" cy=\"200\" fill=\"" + colorOverlay.css() + "\" r=\"198\"/>\n" + " <path d=\"M 299.50,372.34 A 199.00 199.00 0 0 0 300 28 A 199.00 199.00 0 0 0 300 372\" " + " fill=\"" + colorBlended.css() + "\" />\n" + "</svg>\n"; StringTable table = new StringTable(); List<String> row = new ArrayList<>(); row.addAll(Arrays.asList(message("BlendMode"), blender.modeName())); table.add(row); row = new ArrayList<>(); row.addAll(Arrays.asList(message("Weight2"), blender.getWeight() + "")); table.add(row); html += table.div(); List<String> names = new ArrayList<>(); names.addAll(Arrays.asList(message("Data"), message("Base"), message("Overlay"), message("BlendColors"))); table = new StringTable(names); table = blendController.baseAboveCheck.isSelected() ? FxColorTools.colorsTable(table, colorOverlay, colorData, colorBlended) : FxColorTools.colorsTable(table, colorData, colorOverlay, colorBlended); html += table.div(); html += "</body></html>"; htmlController.displayHtml(html); } catch (Exception e) { MyBoxLog.error(e); } } @FXML public void addColor() { if (colorBlended == null) { return; } ColorsManageController.addOneColor(colorBlended.getColor()); } @FXML public void demo() { if (!pickColors()) { return; } FxSingletonTask demoTask = new FxSingletonTask<Void>(this) { private String html; @Override protected boolean handle() { try { StringTable table = new StringTable(message("BlendColors")); List<String> row = new ArrayList<>(); row.addAll(Arrays.asList(message("Color"), message("Name"), message("Weight"), message("BaseImageAboveOverlay"), message("Hue"), message("Saturation"), message("Brightness"), message("RYBAngle"), message("Opacity"), message("RGBA"), message("RGB"), message("sRGB"), message("HSBA"), message("CalculatedCMYK"), "Adobe RGB", "Apple RGB", "ECI RGB", "sRGB Linear", "Adobe RGB Linear", "Apple RGB Linear", "ECI CMYK", "Adobe CMYK Uncoated FOGRA29", "XYZ", "CIE-L*ab", "LCH(ab)", "CIE-L*uv", "LCH(uv)", message("Value"))); table.add(row); table.add(colorRow(colorData, -1, false)); table.add(colorRow(colorOverlay, -1, false)); PixelsBlend blender; PixelsBlend.ImagesBlendMode mode; int v1 = colorOverlay.getColorValue(), v2 = colorData.getColorValue(); for (String name : PixelsBlendFactory.blendModes()) { if (!isWorking()) { return false; } mode = PixelsBlendFactory.blendMode(name); blender = PixelsBlendFactory.create(mode).setBlendMode(mode); blender.setWeight(1.0F).setBaseAbove(false); ColorData blended = new ColorData(blender.blend(v1, v2)) .setColorName(blender.modeName()) .setvSeparator(separator).convert(); table.add(colorRow(blended, 1.0f, false)); blender.setWeight(0.5F).setBaseAbove(false); blended = new ColorData(blender.blend(v1, v2)) .setColorName(blender.modeName()) .setvSeparator(separator).convert(); table.add(colorRow(blended, 0.5f, false)); blender.setWeight(1.0F).setBaseAbove(true); blended = new ColorData(blender.blend(v1, v2)) .setColorName(blender.modeName()) .setvSeparator(separator).convert(); table.add(colorRow(blended, 1.0f, true)); blender.setWeight(0.5F).setBaseAbove(true); blended = new ColorData(blender.blend(v1, v2)) .setColorName(blender.modeName()) .setvSeparator(separator).convert(); table.add(colorRow(blended, 0.5f, true)); } html = table.html(); return html != null; } catch (Exception e) { error = e.toString(); return false; } } protected List<String> colorRow(ColorData color, float weight, boolean above) { List<String> row = new ArrayList<>(); row.add("<DIV style=\"width: 50px; background-color:" + color2css(color.getColor()) + "; \">&nbsp;&nbsp;&nbsp;</DIV>"); row.addAll(Arrays.asList(color.getColorName(), weight >= 0 ? weight + "" : "", above ? message("Yes") : "", color.getHue(), color.getSaturation(), color.getBrightness(), color.getRybAngle(), color.getOpacity(), color.getRgba(), color.getRgb(), color.getSrgb(), color.getHsb(), color.getCalculatedCMYK(), color.getAdobeRGB(), color.getAppleRGB(), color.getEciRGB(), color.getSRGBLinear(), color.getAdobeRGBLinear(), color.getAppleRGBLinear(), color.getEciCMYK(), color.getAdobeCMYK(), color.getXyz(), color.getCieLab(), color.getLchab(), color.getCieLuv(), color.getLchuv(), color.getColorValue() + "")); return row; } @Override protected void whenSucceeded() { HtmlPopController.showHtml(myController, html); } }; start(demoTask); } @Override public boolean handleKeyEvent(KeyEvent event) { if (overlayTab.isSelected()) { if (colorOverlayController.handleKeyEvent(event)) { return true; } } else if (blendTab.isSelected()) { if (blendController.handleKeyEvent(event)) { return true; } } return super.handleKeyEvent(event); } /* static */ public static ColorsBlendController open() { try { ColorsBlendController controller = (ColorsBlendController) WindowTools.openStage(Fxmls.ColorsBlendFxml); controller.requestMouse(); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/ControlImageScope.java
alpha/MyBox/src/main/java/mara/mybox/controller/ControlImageScope.java
package mara.mybox.controller; import java.util.Arrays; import javafx.beans.binding.Bindings; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.ListChangeListener; import javafx.fxml.FXML; import javafx.scene.Cursor; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.control.SelectionMode; import javafx.scene.control.Toggle; import javafx.scene.control.Tooltip; import javafx.scene.image.Image; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.paint.Color; import javafx.util.Callback; import mara.mybox.data.DoublePoint; import mara.mybox.db.table.TableColor; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.HelpTools; import mara.mybox.fxml.ValidationTools; import mara.mybox.fxml.cell.ListColorCell; import mara.mybox.fxml.image.ImageViewTools; import mara.mybox.fxml.style.NodeStyleTools; import mara.mybox.fxml.style.StyleTools; import mara.mybox.image.data.ImageScope.ShapeType; import static mara.mybox.image.data.ImageScope.ShapeType.Matting4; import static mara.mybox.image.data.ImageScope.ShapeType.Matting8; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2020-9-15 * @License Apache License Version 2.0 */ public class ControlImageScope extends ControlImageScope_Load { protected BaseImageController imageEditor; protected ControlDataImageScope dataEditor; public void setImageEditor(BaseImageController parent) { try { this.parentController = parent; imageEditor = parent; } catch (Exception e) { MyBoxLog.debug(e); } } public void setDataEditor(ControlDataImageScope parent) { try { parentController = parent; dataEditor = parent; } catch (Exception e) { MyBoxLog.debug(e); } } @Override public Image srcImage() { if (imageEditor != null) { image = imageEditor.imageView.getImage(); sourceFile = imageEditor.sourceFile; } else if (dataEditor != null) { image = dataEditor.srcImage; sourceFile = dataEditor.sourceFile; } return image; } @Override public void initControls() { try { super.initControls(); initOptions(); initShapeTab(); initColorsTab(); initMatchTab(); thisPane.disableProperty().bind(Bindings.isNull(imageView.imageProperty())); } catch (Exception e) { MyBoxLog.error(e); } } @Override public void setControlsStyle() { try { super.setControlsStyle(); NodeStyleTools.setTooltip(opacitySelector, new Tooltip(message("Opacity"))); } catch (Exception e) { MyBoxLog.debug(e); } } public void initOptions() { try { tableColor = new TableColor(); popShapeMenu = true; shapeStyle = null; needFixSize = true; showNotify = new SimpleBooleanProperty(false); changedNotify = new SimpleBooleanProperty(false); scopeExcludeCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if (!isSettingValues) { indicateScope(); changedNotify.set(!changedNotify.get()); } } }); handleTransparentCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if (!isSettingValues) { indicateScope(); changedNotify.set(!changedNotify.get()); } } }); maskColorController.init(this, baseName + "MaskColor", Color.TRANSPARENT); maskColor = maskColorController.awtColor(); maskColorController.setNotify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { if (!isSettingValues) { maskColor = maskColorController.awtColor(); scope.setMaskColor(maskColor); indicateScope(); } } }); maskOpacity = UserConfig.getFloat(baseName + "ScopeOpacity", 0.5f); opacitySelector.getItems().addAll( Arrays.asList("0.5", "0.2", "1", "0", "0.8", "0.3", "0.6", "0.7", "0.9", "0.4") ); opacitySelector.setValue(maskOpacity + ""); opacitySelector.valueProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> ov, String oldVal, String newVal) { try { if (isSettingValues || newVal == null) { return; } float f = Float.parseFloat(newVal); if (f >= 0 && f <= 1.0) { maskOpacity = f; ValidationTools.setEditorNormal(opacitySelector); UserConfig.setFloat(baseName + "ScopeOpacity", f); scope.setMaskOpacity(maskOpacity); indicateScope(); } else { ValidationTools.setEditorBadStyle(opacitySelector); } } catch (Exception e) { ValidationTools.setEditorBadStyle(opacitySelector); } } }); clearDataWhenLoadImageCheck.setSelected(UserConfig.getBoolean(baseName + "ClearDataWhenLoadImage", true)); clearDataWhenLoadImageCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean oldVal, Boolean newVal) { if (!isSettingValues) { UserConfig.setBoolean(baseName + "ClearDataWhenLoadImage", clearDataWhenLoadImageCheck.isSelected()); } } }); } catch (Exception e) { MyBoxLog.error(e); } } public void initShapeTab() { try { tabPane.getTabs().remove(controlsTab); shapeTypeGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue ov, Toggle oldValue, Toggle newValue) { if (!isSettingValues) { pickScope(); changedNotify.set(!changedNotify.get()); } } }); shapeExcludedCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if (!isSettingValues) { indicateScope(); changedNotify.set(!changedNotify.get()); } } }); pointsController.tableData.addListener(new ListChangeListener<DoublePoint>() { @Override public void onChanged(ListChangeListener.Change<? extends DoublePoint> c) { if (isSettingValues || pointsController.isSettingValues || pointsController.isSettingTable) { return; } indicateScope(); changedNotify.set(!changedNotify.get()); } }); outlineController.setParameter(this, StyleTools.getIconFile("iconAdd.png").toString(), null); outlineController.notify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { indicateOutline(true); changedNotify.set(!changedNotify.get()); } }); } catch (Exception e) { MyBoxLog.error(e); } } public void initColorsTab() { try { colorsList.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); colorsList.setCellFactory(new Callback<ListView<Color>, ListCell<Color>>() { @Override public ListCell<Color> call(ListView<Color> p) { return new ListColorCell(); } }); deleteColorsButton.disableProperty().bind(colorsList.getSelectionModel().selectedItemProperty().isNull()); saveColorsButton.disableProperty().bind(colorsList.getSelectionModel().selectedItemProperty().isNull()); colorController.init(this, baseName + "Color", Color.GOLD); colorController.setNotify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { addColor((Color) colorController.rect.getFill()); changedNotify.set(!changedNotify.get()); } }); colorExcludedCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if (!isSettingValues) { indicateScope(); changedNotify.set(!changedNotify.get()); } } }); } catch (Exception e) { MyBoxLog.error(e); } } public void initMatchTab() { try { matchController.changeNotify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { if (!isSettingValues) { indicateScope(); changedNotify.set(!changedNotify.get()); } } }); } catch (Exception e) { MyBoxLog.error(e); } } @Override public boolean afterImageLoaded() { if (super.afterImageLoaded()) { if (UserConfig.getBoolean(baseName + "ClearDataWhenLoadImage", true)) { pointsController.isSettingValues = true; pointsController.tableData.clear(); pointsController.isSettingValues = false; isSettingValues = true; colorsList.getItems().clear(); isSettingValues = false; if (scope != null) { scope.resetParameters(); } } pickScope(); return true; } else { return false; } } @Override public void fitView() { } @FXML @Override public void createAction() { if (!checkBeforeNextAction()) { return; } ImageCanvasInputController controller = ImageCanvasInputController.open(this, baseTitle); controller.notify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { Image canvas = controller.getCanvas(); if (canvas != null) { loadImage(canvas); } controller.close(); } }); } @FXML @Override public boolean popAction() { ImageScopeViewsController.open(this); return true; } @FXML @Override public void refreshAction() { isSettingValues = false; indicateScope(); } @FXML @Override public boolean withdrawAction() { if (scope == null || isSettingValues) { return false; } try { switch (scope.getShapeType()) { case Matting4: case Matting8: case Polygon: pointsController.removeLastItem(); return true; } return false; } catch (Exception e) { } return false; } @FXML @Override public void clearAction() { if (scope == null || isSettingValues) { return; } try { switch (scope.getShapeType()) { case Matting4: case Matting8: case Polygon: pointsController.clear(); break; case Whole: clearColors(); break; } } catch (Exception e) { } } @Override public void paneClicked(MouseEvent event, DoublePoint p) { if (p == null || imageView.getImage() == null) { imageView.setCursor(Cursor.OPEN_HAND); return; } if (isPickingColor) { Color color = ImageViewTools.imagePixel(p, srcImage()); if (color != null) { addColor(color); changedNotify.set(!changedNotify.get()); } } else if (event.getClickCount() == 1) { if (event.getButton() == MouseButton.PRIMARY) { if (addPointWhenClick) { if (scope.getShapeType() == ShapeType.Matting4 || scope.getShapeType() == ShapeType.Matting8) { int x = (int) Math.round(p.getX()); int y = (int) Math.round(p.getY()); isSettingValues = true; pointsController.addPoint(x, y); isSettingValues = false; indicateScope(); changedNotify.set(!changedNotify.get()); } else if (scope.getShapeType() == ShapeType.Polygon && !maskControlDragged) { maskPolygonData.add(p.getX(), p.getY()); maskShapeDataChanged(); changedNotify.set(!changedNotify.get()); } } } else if (event.getButton() == MouseButton.SECONDARY) { popEventMenu(event, maskShapeMenu(event, currentMaskShapeData(), p)); } } maskControlDragged = false; } @Override public void maskShapeDataChanged() { try { if (isSettingValues || !isValidScope()) { return; } switch (scope.getShapeType()) { case Rectangle: rectLeftTopXInput.setText(scale(maskRectangleData.getX(), 2) + ""); rectLeftTopYInput.setText(scale(maskRectangleData.getY(), 2) + ""); rightBottomXInput.setText(scale(maskRectangleData.getMaxX(), 2) + ""); rightBottomYInput.setText(scale(maskRectangleData.getMaxY(), 2) + ""); scope.setRectangle(maskRectangleData.copy()); break; case Ellipse: rectLeftTopXInput.setText(scale(maskEllipseData.getX(), 2) + ""); rectLeftTopYInput.setText(scale(maskEllipseData.getY(), 2) + ""); rightBottomXInput.setText(scale(maskEllipseData.getMaxX(), 2) + ""); rightBottomYInput.setText(scale(maskEllipseData.getMaxY(), 2) + ""); scope.setEllipse(maskEllipseData.copy()); break; case Circle: circleCenterXInput.setText(scale(maskCircleData.getCenterX(), 2) + ""); circleCenterYInput.setText(scale(maskCircleData.getCenterY(), 2) + ""); circleRadiusInput.setText(scale(maskCircleData.getRadius(), 2) + ""); scope.setCircle(maskCircleData.copy()); break; case Polygon: pointsController.loadList(maskPolygonData.getPoints()); scope.setPolygon(maskPolygonData.copy()); break; case Outline: scope.setRectangle(maskRectangleData.copy()); } indicateScope(); changedNotify.set(!changedNotify.get()); } catch (Exception e) { MyBoxLog.error(e); } } @Override protected void checkPickingColor() { if (!tabPane.getTabs().contains(colorsTab)) { isPickingColor = false; } if (isPickingColor) { tabPane.getSelectionModel().select(colorsTab); } super.checkPickingColor(); } @FXML public void aboutScope() { openHtml(HelpTools.aboutImageScope()); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/ControlImageText.java
alpha/MyBox/src/main/java/mara/mybox/controller/ControlImageText.java
package mara.mybox.controller; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.sql.Connection; import java.util.Arrays; import java.util.List; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.RadioButton; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleGroup; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.text.FontPosture; import javafx.scene.text.FontWeight; import mara.mybox.image.data.PixelsBlend; import mara.mybox.data.ShapeStyle; import mara.mybox.db.DerbyBase; import mara.mybox.db.table.TableStringValues; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.PopTools; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2019-9-10 * @License Apache License Version 2.0 */ public class ControlImageText extends BaseController { protected int margin, rowHeight, x, y, fontSize, shadow, angle, baseX, baseY, textY, textWidth, textHeight, bordersStrokeWidth, bordersArc, bordersMargin; protected String text, fontFamily, fontName; protected FontPosture fontPosture; protected FontWeight fontWeight; protected PixelsBlend blend; protected ShapeStyle borderStyle; @FXML protected TextArea textArea; @FXML protected TextField xInput, yInput, marginInput, bordersMarginInput; @FXML protected ComboBox<String> rowHeightSelector, fontSizeSelector, fontStyleSelector, fontFamilySelector, angleSelector, shadowSelector, bordersStrokeWidthSelector, bordersArcSelector; @FXML protected CheckBox outlineCheck, verticalCheck, rightToLeftCheck, bordersCheck, bordersFillCheck, bordersStrokeDottedCheck; @FXML protected ControlColorSet fontColorController, shadowColorController, bordersFillColorController, bordersStrokeColorController; @FXML protected ToggleGroup positionGroup; @FXML protected RadioButton rightBottomRadio, rightTopRadio, leftBottomRadio, leftTopRadio, centerRadio, customRadio; @FXML protected ControlColorsBlend blendController; @FXML protected VBox bordersBox; @FXML protected Label sizeLabel; public void setParameters(BaseController parent) { parentController = parent; baseName = parentController.baseName; try (Connection conn = DerbyBase.getConnection()) { initText(conn); initStyle(conn); initBorders(conn); initPosition(conn); blendController.setParameters(conn, parent); } catch (Exception e) { MyBoxLog.error(e); } } public void initText(Connection conn) { try { textArea.setText(UserConfig.getString(conn, baseName + "TextValue", "MyBox")); } catch (Exception e) { MyBoxLog.error(e); } } public void initPosition(Connection conn) { try { margin = UserConfig.getInt(conn, baseName + "Margin", 20); marginInput.setText(margin + ""); positionGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> v, Toggle ov, Toggle nv) { checkPositionType(); } }); checkPositionType(); } catch (Exception e) { MyBoxLog.error(e); } } public boolean checkPositionType() { xInput.setDisable(true); yInput.setDisable(true); marginInput.setDisable(true); if (rightBottomRadio.isSelected()) { marginInput.setDisable(false); } else if (rightTopRadio.isSelected()) { marginInput.setDisable(false); } else if (leftBottomRadio.isSelected()) { marginInput.setDisable(false); } else if (leftTopRadio.isSelected()) { marginInput.setDisable(false); } else if (centerRadio.isSelected()) { } else if (customRadio.isSelected()) { xInput.setDisable(false); yInput.setDisable(false); } return true; } public void initStyle(Connection conn) { try { rowHeight = UserConfig.getInt(conn, baseName + "TextRowHeight", -1); List<String> heights = Arrays.asList( message("Automatic"), "18", "15", "9", "10", "12", "14", "17", "24", "36", "48", "64", "96"); rowHeightSelector.getItems().addAll(heights); if (rowHeight <= 0) { rowHeightSelector.setValue(message("Automatic")); } else { rowHeightSelector.setValue(rowHeight + ""); } fontColorController.setConn(conn).init(this, baseName + "TextColor", Color.ORANGE); fontFamilySelector.getItems().addAll(javafx.scene.text.Font.getFamilies()); fontFamily = UserConfig.getString(conn, baseName + "TextFontFamily", "Arial"); fontFamilySelector.getSelectionModel().select(fontFamily); fontWeight = FontWeight.NORMAL; fontPosture = FontPosture.REGULAR; List<String> styles = Arrays.asList(message("Regular"), message("Bold"), message("Italic"), message("Bold Italic")); fontStyleSelector.getItems().addAll(styles); fontStyleSelector.getSelectionModel().select(0); List<String> sizes = Arrays.asList( "72", "18", "15", "9", "10", "12", "14", "17", "24", "36", "48", "64", "96"); fontSizeSelector.getItems().addAll(sizes); fontSize = UserConfig.getInt(conn, baseName + "TextFontSize", 72); fontSizeSelector.getSelectionModel().select(fontSize + ""); shadowSelector.getItems().addAll(Arrays.asList("0", "4", "5", "3", "2", "1", "6")); shadow = UserConfig.getInt(conn, baseName + "TextShadow", 0); shadowSelector.getSelectionModel().select(shadow + ""); shadowColorController.setConn(conn).init(this, baseName + "ShadowColor", Color.GREY); angleSelector.getItems().addAll(Arrays.asList("0", "90", "180", "270", "45", "135", "225", "315", "60", "150", "240", "330", "15", "105", "195", "285", "30", "120", "210", "300")); angle = UserConfig.getInt(conn, baseName + "TextAngle", 0); angleSelector.getSelectionModel().select(angle + ""); outlineCheck.setSelected(UserConfig.getBoolean(conn, baseName + "TextOutline", false)); verticalCheck.setSelected(UserConfig.getBoolean(conn, baseName + "TextVertical", false)); rightToLeftCheck.setSelected(UserConfig.getBoolean(conn, baseName + "TextRightToLeft", false)); rightToLeftCheck.visibleProperty().bind(verticalCheck.selectedProperty()); } catch (Exception e) { MyBoxLog.error(e); } } public void initBorders(Connection conn) { try { bordersBox.disableProperty().bind(bordersCheck.selectedProperty().not()); bordersCheck.setSelected(UserConfig.getBoolean(conn, baseName + "Borders", true)); bordersFillCheck.setSelected(UserConfig.getBoolean(conn, baseName + "BordersFill", true)); bordersFillColorController.setConn(conn).init(this, baseName + "BordersFillColor", Color.WHITE); bordersStrokeColorController.setConn(conn).init(this, baseName + "BordersStrokeColor", Color.WHITE); bordersStrokeWidth = UserConfig.getInt(conn, baseName + "BordersStrokeWidth", 0); if (bordersStrokeWidth < 0) { bordersStrokeWidth = 0; } bordersStrokeWidthSelector.getItems().addAll(Arrays.asList("0", "1", "2", "4", "3", "5", "10", "6")); bordersStrokeWidthSelector.setValue(bordersStrokeWidth + ""); bordersStrokeDottedCheck.setSelected(UserConfig.getBoolean(conn, baseName + "BordersStrokeDotted", false)); bordersArc = UserConfig.getInt(conn, baseName + "BordersArc", 0); if (bordersArc < 0) { bordersArc = 0; } bordersArcSelector.getItems().addAll(Arrays.asList( "0", "3", "5", "2", "1", "8", "10", "15", "20", "30", "48", "64", "96")); bordersArcSelector.setValue(bordersArc + ""); bordersMargin = UserConfig.getInt(conn, baseName + "BordersMargin", 10); bordersMarginInput.setText(bordersMargin + ""); } catch (Exception e) { MyBoxLog.error(e); } } public boolean checkText() { text = text(); if (text == null || text.isEmpty()) { popError(message("InvalidParameters") + ": " + message("Text")); return false; } return true; } public boolean checkLocation() { if (customRadio.isSelected()) { try { x = Integer.parseInt(xInput.getText().trim()); } catch (Exception e) { popError(message("InvalidParameters") + ": x"); return false; } try { y = Integer.parseInt(yInput.getText().trim()); } catch (Exception e) { popError(message("InvalidParameters") + ": y"); return false; } } if (!marginInput.isDisable()) { try { margin = Integer.parseInt(marginInput.getText().trim()); } catch (Exception e) { popError(message("InvalidParameters") + ": y" + message("Margins")); return false; } } return true; } public boolean checkStyle() { try { String s = rowHeightSelector.getValue(); if (message("Automatic").equals(s)) { rowHeight = -1; } else { int v = Integer.parseInt(s); if (v >= 0) { rowHeight = v; } else { rowHeight = -1; } } } catch (Exception e) { popError(message("InvalidParameters") + ": " + message("RowHeightPx")); return false; } fontFamily = fontFamilySelector.getValue(); String s = fontStyleSelector.getValue(); if (message("Bold").equals(s)) { fontWeight = FontWeight.BOLD; fontPosture = FontPosture.REGULAR; } else if (message("Italic").equals(s)) { fontWeight = FontWeight.NORMAL; fontPosture = FontPosture.ITALIC; } else if (message("Bold Italic").equals(s)) { fontWeight = FontWeight.BOLD; fontPosture = FontPosture.ITALIC; } else { fontWeight = FontWeight.NORMAL; fontPosture = FontPosture.REGULAR; } int v = -1; try { v = Integer.parseInt(fontSizeSelector.getValue()); } catch (Exception e) { } if (v > 0) { fontSize = v; } else { popError(message("InvalidParameters") + ": " + message("FontSize")); return false; } v = -1; try { v = Integer.parseInt(shadowSelector.getValue()); } catch (Exception e) { } if (v >= 0) { shadow = v; } else { popError(message("InvalidParameters") + ": " + message("Shadow")); return false; } v = -1; try { v = Integer.parseInt(angleSelector.getValue()); } catch (Exception e) { } if (v >= 0) { angle = v; } else { popError(message("InvalidParameters") + ": " + message("Angle")); return false; } return true; } public boolean checkBorders() { int v = -1; try { v = Integer.parseInt(bordersMarginInput.getText()); } catch (Exception e) { } if (v < 0) { popError(message("InvalidParameters") + ": " + message("BordersMargin")); return false; } bordersMargin = v; v = -1; try { v = Integer.parseInt(bordersStrokeWidthSelector.getValue()); } catch (Exception e) { } if (v < 0) { popError(message("InvalidParameters") + ": " + message("StrokeWidth")); return false; } bordersStrokeWidth = v; v = -1; try { v = Integer.parseInt(bordersArcSelector.getValue()); } catch (Exception e) { } if (v < 0) { popError(message("InvalidParameters") + ": " + message("Arc")); return false; } bordersArc = v; return true; } public boolean checkBlend() { return blendController.checkValues(); } public boolean checkValues() { return checkText() && checkLocation() && checkStyle() && checkBorders() && checkBlend(); } public boolean pickValues() { blend = null; borderStyle = null; try (Connection conn = DerbyBase.getConnection()) { conn.setAutoCommit(false); UserConfig.setString(conn, baseName + "TextValue", text); TableStringValues.add(conn, "ImageTextHistories", text); UserConfig.setInt(conn, baseName + "TextRowHeight", rowHeight); UserConfig.setInt(conn, baseName + "TextAngle", angle); UserConfig.setInt(conn, baseName + "TextShadow", shadow); UserConfig.setString(conn, baseName + "TextFontFamily", fontFamily); UserConfig.setInt(conn, baseName + "TextFontSize", fontSize); UserConfig.setInt(conn, baseName + "Margin", margin); UserConfig.setBoolean(conn, baseName + "TextOutline", outlineCheck.isSelected()); UserConfig.setBoolean(conn, baseName + "TextVertical", verticalCheck.isSelected()); UserConfig.setBoolean(conn, baseName + "TextRightToLeft", rightToLeftCheck.isSelected()); UserConfig.setInt(conn, baseName + "BordersArc", bordersArc); UserConfig.setInt(conn, baseName + "BordersStrokeWidth", bordersStrokeWidth); UserConfig.setInt(conn, baseName + "BordersMargin", bordersMargin); UserConfig.setBoolean(conn, baseName + "BordersFill", bordersFillCheck.isSelected()); UserConfig.setBoolean(conn, baseName + "BordersStrokeDotted", bordersStrokeDottedCheck.isSelected()); UserConfig.setBoolean(conn, baseName + "Borders", bordersCheck.isSelected()); blend = blendController.pickValues(conn); if (bordersCheck.isSelected()) { borderStyle = new ShapeStyle(conn, "Text") .setStrokeColor(bordersStrokeColorController.color()) .setStrokeWidth(bordersStrokeWidth) .setIsFillColor(bordersFillCheck.isSelected()) .setFillColor(bordersFillColorController.color()) .setStrokeDashed(bordersStrokeDottedCheck.isSelected()); } conn.commit(); } catch (Exception e) { MyBoxLog.error(e); return false; } return blend != null; } public void setLocation(double x, double y) { xInput.setText((int) x + ""); yInput.setText((int) y + ""); customRadio.setSelected(true); } public void countValues(Graphics2D g, FontMetrics metrics, double imageWidth, double imageHeight) { countTextBound(g, metrics); if (rightBottomRadio.isSelected()) { baseX = (int) imageWidth - margin - textWidth; baseY = (int) imageHeight - margin - textHeight; } else if (rightTopRadio.isSelected()) { baseX = (int) imageWidth - margin - textWidth; baseY = margin; } else if (leftBottomRadio.isSelected()) { baseX = margin; baseY = (int) imageHeight - margin - textHeight; } else if (leftTopRadio.isSelected()) { baseX = margin; baseY = margin; } else if (centerRadio.isSelected()) { baseX = (int) ((imageWidth - textWidth) / 2); baseY = (int) ((imageHeight - textHeight) / 2); } else if (customRadio.isSelected()) { baseX = x; baseY = y; } else { baseX = 0; baseY = 0; } textY = baseY + metrics.getAscent(); } public void countTextBound(Graphics2D g, FontMetrics metrics) { String[] lines = text().split("\n", -1); int lend = lines.length - 1, heightMax = 0, charWidthMax = 0; textWidth = 0; textHeight = 0; if (isVertical()) { for (int r = 0; r <= lend; r++) { String line = lines[r]; int rHeight = 0; charWidthMax = 0; for (int i = 0; i < line.length(); i++) { String c = line.charAt(i) + ""; Rectangle2D cBound = metrics.getStringBounds(c, g); rHeight += (int) cBound.getHeight(); if (rowHeight <= 0) { int charWidth = (int) cBound.getWidth(); if (charWidth > charWidthMax) { charWidthMax = charWidth; } } } if (rowHeight > 0) { textWidth += rowHeight; } else { textWidth += charWidthMax; } if (rHeight > heightMax) { heightMax = rHeight; } } textHeight = heightMax; } else { for (String line : lines) { Rectangle2D sBound = metrics.getStringBounds(line, g); if (rowHeight > 0) { textHeight += rowHeight; } else { textHeight += sBound.getHeight(); } int sWidth = (int) sBound.getWidth(); if (sWidth > charWidthMax) { charWidthMax = sWidth; } } textWidth = charWidthMax; } if (parentController instanceof ImageEditorController) { Platform.runLater(new Runnable() { @Override public void run() { sizeLabel.setText(message("TextSize") + ": " + textWidth + "x" + textHeight); } }); } } @FXML protected void showTextHistories(Event event) { PopTools.popSavedValues(this, textArea, event, "ImageTextHistories"); } @FXML public void popTextHistories(Event event) { if (UserConfig.getBoolean("ImageTextHistoriesPopWhenMouseHovering", false)) { showTextHistories(event); } } /* refer */ public String text() { return textArea.getText(); } public Font font() { if (fontWeight == FontWeight.BOLD) { if (fontPosture == FontPosture.REGULAR) { return new java.awt.Font(fontFamily, java.awt.Font.BOLD, fontSize); } else { return new java.awt.Font(fontFamily, java.awt.Font.BOLD + java.awt.Font.ITALIC, fontSize); } } else { if (fontPosture == FontPosture.REGULAR) { return new java.awt.Font(fontFamily, java.awt.Font.PLAIN, fontSize); } else { return new java.awt.Font(fontFamily, java.awt.Font.ITALIC, fontSize); } } } public javafx.scene.text.Font fxFont() { if (fontWeight == FontWeight.BOLD) { if (fontPosture == FontPosture.REGULAR) { return javafx.scene.text.Font.font(fontFamily, FontWeight.BOLD, FontPosture.REGULAR, fontSize); } else { return javafx.scene.text.Font.font(fontFamily, FontWeight.BOLD, FontPosture.ITALIC, fontSize); } } else { if (fontPosture == FontPosture.REGULAR) { return javafx.scene.text.Font.font(fontFamily, FontWeight.NORMAL, FontPosture.REGULAR, fontSize); } else { return javafx.scene.text.Font.font(fontFamily, FontWeight.NORMAL, FontPosture.ITALIC, fontSize); } } } public java.awt.Color textColor() { return fontColorController.awtColor(); } public java.awt.Color shadowColor() { return shadowColorController.awtColor(); } public boolean isVertical() { return verticalCheck.isSelected(); } public boolean isLeftToRight() { return !rightToLeftCheck.isSelected(); } public boolean isOutline() { return outlineCheck.isSelected(); } public PixelsBlend getBlend() { return blend; } public ShapeStyle getBorderStyle() { return borderStyle; } public boolean showBorders() { return bordersCheck.isSelected(); } public boolean bordersDotted() { return bordersStrokeDottedCheck.isSelected(); } public boolean bordersFilled() { return bordersFillCheck.isSelected(); } public java.awt.Color bordersStrokeColor() { return bordersStrokeColorController.awtColor(); } public java.awt.Color bordersFillColor() { return bordersFillColorController.awtColor(); } /* get */ public int getRowHeight() { return rowHeight; } public int getX() { return x; } public int getY() { return y; } public int getFontSize() { return fontSize; } public int getShadow() { return shadow; } public int getAngle() { return angle; } public String getFontFamily() { return fontFamily; } public String getFontName() { return fontName; } public int getMargin() { return margin; } public int getBaseX() { return baseX; } public int getBaseY() { return baseY; } public int getTextWidth() { return textWidth; } public int getTextHeight() { return textHeight; } public int getTextY() { return textY; } public int getBordersStrokeWidth() { return bordersStrokeWidth; } public int getBordersArc() { return bordersArc; } public int getBordersMargin() { return bordersMargin; } /* set */ public ControlImageText setBlend(PixelsBlend blend) { this.blend = blend; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/Data2DExportController.java
alpha/MyBox/src/main/java/mara/mybox/controller/Data2DExportController.java
package mara.mybox.controller; import java.util.ArrayList; import java.util.List; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.CheckBox; import javafx.scene.control.Tab; import javafx.scene.layout.VBox; import mara.mybox.data2d.operate.Data2DExport; import mara.mybox.data2d.tools.Data2DColumnTools; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.fxml.SoundTools; import mara.mybox.fxml.WindowTools; import mara.mybox.tools.DateTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2021-12-8 * @License Apache License Version 2.0 */ public class Data2DExportController extends BaseData2DTaskController { protected Data2DExport export; protected String filePrefix; @FXML protected BaseData2DRowsColumnsController rowsColumnsController; @FXML protected VBox dataBox, filterVBox, formatVBox, targetVBox; @FXML protected ControlDataExport convertController; @FXML protected Tab targetTab; @FXML protected CheckBox displayedNameCheck; public Data2DExportController() { baseTitle = message("Export"); } @Override public void initValues() { try { super.initValues(); sourceController = rowsColumnsController; formatValuesCheck = convertController.formatValuesCheck; rowNumberCheck = convertController.rowNumberCheck; } catch (Exception e) { MyBoxLog.error(e); } } @Override public void setParameters(BaseData2DLoadController controller) { try { super.setParameters(controller); convertController.setParameters(this); displayedNameCheck.setSelected(UserConfig.getBoolean(baseName + "ExportLabelAsColumn", true)); displayedNameCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { if (isSettingValues) { return; } UserConfig.setBoolean(baseName + "ExportLabelAsColumn", displayedNameCheck.isSelected()); } }); } catch (Exception e) { MyBoxLog.error(e); } } @Override public boolean checkOptions() { try { if (isSettingValues) { return true; } if (!super.checkOptions()) { return false; } targetPath = targetPathController.pickFile(); if (targetPath == null) { popError(message("InvalidParameters") + ": " + message("TargetPath")); tabPane.getSelectionModel().select(targetTab); return false; } filePrefix = data2D.getName(); if (filePrefix == null || filePrefix.isBlank()) { filePrefix = DateTools.nowFileString(); } export = convertController.pickParameters(data2D); export.setPathController(targetPathController) .setColumns(checkedColumns) .setColumnNames(Data2DColumnTools.toNames(checkedColumns, displayedNameCheck.isSelected())) .setInvalidAs(invalidAs) .setController(this); return export.initExport(filePrefix); } catch (Exception e) { MyBoxLog.error(e); return false; } } @Override public void beforeTask() { try { super.beforeTask(); dataBox.setDisable(true); filterVBox.setDisable(true); formatVBox.setDisable(true); targetVBox.setDisable(true); } catch (Exception e) { MyBoxLog.error(e); } } @Override protected void startOperation() { if (task != null) { task.cancel(); } taskSuccessed = false; task = new FxSingletonTask<Void>(this) { @Override protected boolean handle() { try { data2D.startTask(task, filterController.filter); if (!isAllPages() || !data2D.isMutiplePages()) { List<Integer> filteredRowsIndices = sourceController.filteredRowsIndices; export.openWriters(); for (Integer row : filteredRowsIndices) { List<String> dataRow = sourceController.tableData.get(row); List<String> exportRow = new ArrayList<>(); for (Integer col : checkedColsIndices) { exportRow.add(dataRow.get(col + 1)); } export.writeRow(exportRow); } export.end(); } else { export.setCols(checkedColsIndices).setTask(task).start(); } taskSuccessed = !export.isFailed(); return taskSuccessed; } catch (Exception e) { error = e.toString(); return false; } } @Override protected void whenSucceeded() { afterSuccess(); } @Override protected void finalAction() { super.finalAction(); closeTask(ok); } }; start(task, false); } @Override public void afterSuccess() { try { SoundTools.miao3(); if (openCheck.isSelected()) { export.openResults(); } if (targetPath != null && targetPath.exists()) { browseURI(targetPath.toURI()); recordFileOpened(targetPath); } else { popInformation(message("NoFileGenerated")); } } catch (Exception e) { MyBoxLog.error(e); } } @Override public void closeTask(boolean ok) { try { if (export != null) { export.end(); export = null; } super.closeTask(ok); dataBox.setDisable(false); filterVBox.setDisable(false); formatVBox.setDisable(false); targetVBox.setDisable(false); } catch (Exception e) { MyBoxLog.error(e); } } /* static */ public static Data2DExportController open(BaseData2DLoadController tableController) { try { Data2DExportController controller = (Data2DExportController) WindowTools.referredStage( tableController, Fxmls.Data2DExportFxml); controller.setParameters(tableController); controller.requestMouse(); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/BaseImageController_Base.java
alpha/MyBox/src/main/java/mara/mybox/controller/BaseImageController_Base.java
package mara.mybox.controller; import javafx.beans.property.SimpleBooleanProperty; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.VBox; import javafx.scene.shape.Rectangle; import javafx.scene.text.Text; import javafx.scene.text.TextAlignment; import mara.mybox.image.data.ImageAttributes; import mara.mybox.image.data.ImageInformation; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.image.ImageViewTools; import mara.mybox.fxml.FxTask; import mara.mybox.fxml.LocateTools; import mara.mybox.tools.DateTools; import mara.mybox.tools.FileTools; import mara.mybox.tools.StringTools; import static mara.mybox.value.AppVariables.sceneFontSize; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2021-8-10 * @License Apache License Version 2.0 */ public abstract class BaseImageController_Base extends BaseFileController { protected ImageInformation imageInformation; protected Image image; protected ImageAttributes attributes; protected final SimpleBooleanProperty loadNotify, sizeNotify; protected boolean imageChanged, isPickingColor, backgroundLoad; protected int loadWidth, defaultLoadWidth, framesNumber, frameIndex, // 0-based sizeChangeAware, zoomStep, xZoomStep, yZoomStep; protected FxTask loadTask; protected double mouseX, mouseY; protected ColorsPickingController paletteController; @FXML protected VBox imageBox; @FXML protected ScrollPane scrollPane; @FXML protected AnchorPane maskPane; @FXML protected ImageView imageView; @FXML protected Rectangle borderLine; @FXML protected Text sizeText, xyText; @FXML protected Label imageLabel; @FXML protected Button imageSizeButton, paneSizeButton, zoomInButton, zoomOutButton, selectPixelsButton; @FXML protected CheckBox pickColorCheck, rulerXCheck, gridCheck, coordinateCheck; @FXML protected ComboBox<String> zoomStepSelector, loadWidthSelector; public BaseImageController_Base() { loadNotify = new SimpleBooleanProperty(false); sizeNotify = new SimpleBooleanProperty(false); } public void notifyLoad() { loadNotify.set(!loadNotify.get()); } public void notifySize() { sizeNotify.set(!sizeNotify.get()); } public void fitSize() { if (scrollPane == null || imageView == null || imageView.getImage() == null) { return; } try { if (scrollPane.getHeight() < imageHeight() || scrollPane.getWidth() < imageWidth()) { paneSize(); } else { loadedSize(); } } catch (Exception e) { MyBoxLog.error(e); } } @FXML public void paneSize() { if (imageView == null || imageView.getImage() == null || scrollPane == null) { return; } try { ImageViewTools.paneSize(scrollPane, imageView); refinePane(); } catch (Exception e) { MyBoxLog.error(e); } } @FXML public void loadedSize() { if (imageView == null || imageView.getImage() == null || scrollPane == null) { return; } try { ImageViewTools.imageSize(scrollPane, imageView); refinePane(); } catch (Exception e) { MyBoxLog.error(e); } } protected void popContextMenu(double x, double y) { if (imageView == null || imageView.getImage() == null) { return; } MenuImageViewController.imageViewMenu((BaseImageController) this, x, y); } /* status */ protected void zoomStepChanged() { xZoomStep = zoomStep; yZoomStep = zoomStep; } protected void setZoomStep(Image image) { if (image == null) { return; } zoomStep = (int) image.getWidth() / 10; if (zoomStepSelector != null) { zoomStepSelector.setValue(zoomStep + ""); } else { xZoomStep = (int) image.getWidth() / 10; yZoomStep = (int) image.getHeight() / 10; } } public void viewSizeChanged(double change) { if (isSettingValues || change < sizeChangeAware || imageView == null || imageView.getImage() == null) { return; } refinePane(); notifySize(); } public void paneSizeChanged(double change) { viewSizeChanged(change); } public void refinePane() { if (isSettingValues || scrollPane == null || imageView == null || imageView.getImage() == null) { return; } LocateTools.moveCenter(scrollPane, imageView); scrollPane.setVvalue(scrollPane.getVmin()); updateLabelsTitle(); } public synchronized void updateLabelsTitle() { try { updateStageTitle(); updateImageLabel(); updateSizeLabel(); } catch (Exception e) { MyBoxLog.debug(e); } } public void updateStageTitle() { try { if (getMyStage() == null || !isTopPane) { return; } myStage.setTitle(getBaseTitle() + fileTitle()); } catch (Exception e) { MyBoxLog.debug(e); } } public String fileTitle() { try { String title; if (sourceFile != null) { title = " " + sourceFile.getAbsolutePath(); if (framesNumber > 1 && frameIndex >= 0) { title += " - " + message("Frame") + " " + (frameIndex + 1); } if (imageInformation != null && imageInformation.isIsScaled()) { title += " - " + message("Scaled"); } } else { title = ""; } if (imageChanged) { title += " " + "*"; } return title; } catch (Exception e) { MyBoxLog.debug(e); return ""; } } public void updateImageLabel() { try { if (imageLabel == null) { return; } String imageInfo = "", fileInfo = "", loadInfo = ""; if (sourceFile != null) { fileInfo = message("File") + ":" + sourceFile.getAbsolutePath() + "\n" + message("FileSize") + ":" + FileTools.showFileSize(sourceFile.length()) + "\n" + message("ModifyTime") + ":" + DateTools.datetimeToString(sourceFile.lastModified()); } if (framesNumber > 1) { imageInfo = message("FramesNumber") + ":" + framesNumber + "\n"; if (frameIndex >= 0) { imageInfo += message("CurrentFrame") + ":" + (frameIndex + 1) + "\n"; } } if (imageInformation != null) { imageInfo += message("Format") + ":" + imageInformation.getImageFormat() + "\n" + message("Pixels") + ":" + (int) imageInformation.getWidth() + "x" + (int) imageInformation.getHeight(); if (imageInformation.isIsScaled()) { imageInfo += "\n" + message("Scaled"); } } else if (imageView != null && imageView.getImage() != null) { imageInfo += message("Pixels") + ":" + (int) imageView.getImage().getWidth() + "x" + (int) imageView.getImage().getHeight(); } if (imageView != null && imageView.getImage() != null) { loadInfo = message("LoadedSize") + ":" + (int) imageView.getImage().getWidth() + "x" + (int) imageView.getImage().getHeight() + "\n" + message("DisplayedSize") + ":" + (int) imageView.getBoundsInParent().getWidth() + "x" + (int) imageView.getBoundsInParent().getHeight(); } String more = moreDisplayInfo(); loadInfo += (!loadInfo.isBlank() && !more.isBlank() ? "\n" : "") + more; if (imageChanged) { loadInfo += "\n" + message("ImageChanged"); } String finalInfo = fileInfo + "\n" + imageInfo + "\n" + loadInfo; imageLabel.setText(StringTools.replaceLineBreak(finalInfo)); } catch (Exception e) { MyBoxLog.debug(e); } } public void updateSizeLabel() { try { if (imageView == null || imageView.getImage() == null) { return; } if (borderLine != null) { borderLine.setLayoutX(imageView.getLayoutX() - 1); borderLine.setLayoutY(imageView.getLayoutY() - 1); borderLine.setWidth(viewWidth() + 2); borderLine.setHeight(viewHeight() + 2); } if (sizeText != null) { sizeText.setText((int) (imageView.getImage().getWidth()) + "x" + (int) (imageView.getImage().getHeight())); sizeText.setTextAlignment(TextAlignment.LEFT); if (imageView.getImage().getWidth() >= imageView.getImage().getHeight()) { sizeText.setX(borderLine.getBoundsInParent().getMinX()); sizeText.setY(borderLine.getBoundsInParent().getMinY() - sceneFontSize - 1); } else { sizeText.setX(borderLine.getBoundsInParent().getMinX() - sizeText.getBoundsInParent().getWidth() - sceneFontSize); sizeText.setY(borderLine.getBoundsInParent().getMaxY() - sceneFontSize - 1); } } } catch (Exception e) { MyBoxLog.debug(e); } } protected String moreDisplayInfo() { return ""; } /* values */ public double imageWidth() { if (imageView != null && imageView.getImage() != null) { return imageView.getImage().getWidth(); } else if (image != null) { return image.getWidth(); } else if (imageInformation != null) { return imageInformation.getWidth(); } else { return -1; } } public double imageHeight() { if (imageView != null && imageView.getImage() != null) { return imageView.getImage().getHeight(); } else if (image != null) { return image.getHeight(); } else if (imageInformation != null) { return imageInformation.getHeight(); } else { return -1; } } public double viewWidth() { return imageView.getBoundsInParent().getWidth(); } public double viewHeight() { return imageView.getBoundsInParent().getHeight(); } protected boolean operateOriginalSize() { return (this instanceof ImageSplitController) || (this instanceof ImageSampleController); } public double widthRatio() { if (!operateOriginalSize() || imageInformation == null || image == null) { return 1; } double ratio = imageWidth() / imageInformation.getWidth(); return ratio; } public double heightRatio() { if (!operateOriginalSize() || imageInformation == null || image == null) { return 1; } double ratio = imageHeight() / imageInformation.getHeight(); return ratio; } public int operationWidth() { return (int) (imageWidth() / widthRatio()); } public int operationHeight() { return (int) (imageHeight() / heightRatio()); } protected int getRulerStep(double width) { if (width <= 1000) { return 10; } else if (width <= 10000) { return (int) (width / 1000) * 10; } else { return (int) (width / 10000) * 10; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/ControlImageRound.java
alpha/MyBox/src/main/java/mara/mybox/controller/ControlImageRound.java
package mara.mybox.controller; import java.util.Arrays; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.ComboBox; import javafx.scene.control.RadioButton; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleGroup; import javafx.scene.paint.Color; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.ValidationTools; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2019-8-13 * @License Apache License Version 2.0 */ public class ControlImageRound extends BaseController { protected int w, h, wPer, hPer; @FXML protected ComboBox<String> wSelector, hSelector, wPerSelector, hPerSelector; @FXML protected ControlColorSet colorController; @FXML protected RadioButton wPerRadio, hPerRadio; @FXML protected ToggleGroup wGroup, hGroup; @Override public void initControls() { try { super.initControls(); colorController.init(this, baseName + "Color", Color.TRANSPARENT); w = UserConfig.getInt(baseName + "Width", 20); if (w <= 0) { w = 20; } wSelector.getItems().addAll(Arrays.asList("20", "15", "30", "50", "150", "300", "10", "3")); wSelector.setValue(w + ""); wSelector.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue ov, String oldValue, String newValue) { checkWidth(); } }); wPer = UserConfig.getInt(baseName + "WidthPercent", 10); if (wPer <= 0) { wPer = 10; } wPerSelector.getItems().addAll(Arrays.asList("10", "15", "5", "8", "20", "30", "25")); wPerSelector.setValue(wPer + ""); wPerSelector.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue ov, String oldValue, String newValue) { checkWidthPercent(); } }); wGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> v, Toggle ov, Toggle nv) { checkWidthType(); } }); checkWidthType(); h = UserConfig.getInt(baseName + "Height", 20); if (h <= 0) { h = 20; } hSelector.getItems().addAll(Arrays.asList("20", "15", "30", "50", "150", "300", "10", "3")); hSelector.setValue(h + ""); hSelector.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue ov, String oldValue, String newValue) { checkHeight(); } }); hPer = UserConfig.getInt(baseName + "HeightPercent", 10); if (hPer <= 0) { hPer = 10; } hPerSelector.getItems().addAll(Arrays.asList("10", "15", "5", "8", "20", "30", "25")); hPerSelector.setValue(hPer + ""); hPerSelector.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue ov, String oldValue, String newValue) { checkHeightPercent(); } }); hGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> v, Toggle ov, Toggle nv) { checkHeightType(); } }); checkHeightType(); } catch (Exception e) { MyBoxLog.error(e); } } private boolean checkWidthType() { wSelector.setDisable(true); wPerSelector.setDisable(true); wSelector.getEditor().setStyle(null); wPerSelector.getEditor().setStyle(null); if (wPerRadio.isSelected()) { wPerSelector.setDisable(false); return checkWidthPercent(); } else { wSelector.setDisable(false); return checkWidth(); } } private boolean checkWidthPercent() { int v; try { v = Integer.parseInt(wPerSelector.getValue()); } catch (Exception e) { v = -1; } if (v > 0 && v <= 100) { wPer = v; UserConfig.setInt(baseName + "WidthPercent", wPer); ValidationTools.setEditorNormal(wPerSelector); return true; } else { popError(message("InvalidParameter") + ": " + message("ImageWidthPercentage")); ValidationTools.setEditorBadStyle(wPerSelector); return false; } } private boolean checkWidth() { int v; try { v = Integer.parseInt(wSelector.getValue()); } catch (Exception e) { v = -1; } if (v > 0) { w = v; UserConfig.setInt(baseName + "Width", w); ValidationTools.setEditorNormal(wSelector); return true; } else { popError(message("InvalidParameter") + ": " + message("Width")); ValidationTools.setEditorBadStyle(wSelector); return false; } } private boolean checkHeightType() { hSelector.setDisable(true); hPerSelector.setDisable(true); hSelector.getEditor().setStyle(null); hPerSelector.getEditor().setStyle(null); if (hPerRadio.isSelected()) { hPerSelector.setDisable(false); return checkHeightPercent(); } else { hSelector.setDisable(false); return checkHeight(); } } private boolean checkHeightPercent() { int v; try { v = Integer.parseInt(hPerSelector.getValue()); } catch (Exception e) { v = -1; } if (v > 0 && v <= 100) { hPer = v; UserConfig.setInt(baseName + "HeightPercent", hPer); ValidationTools.setEditorNormal(hPerSelector); return true; } else { popError(message("InvalidParameter") + ": " + message("ImageHeightPercentage")); ValidationTools.setEditorBadStyle(hPerSelector); return false; } } private boolean checkHeight() { int v; try { v = Integer.parseInt(hSelector.getValue()); } catch (Exception e) { v = -1; } if (v > 0) { h = v; UserConfig.setInt(baseName + "Height", h); ValidationTools.setEditorNormal(hSelector); return true; } else { popError(message("InvalidParameter") + ": " + message("Height")); ValidationTools.setEditorBadStyle(hSelector); return false; } } public boolean wPercenatge() { return wPerRadio.isSelected(); } public boolean hPercenatge() { return hPerRadio.isSelected(); } public java.awt.Color awtColor() { return colorController.awtColor(); } public Color color() { return colorController.color(); } public boolean pickValues() { return checkWidthType() && checkHeightType(); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/TextEditorFormatController.java
alpha/MyBox/src/main/java/mara/mybox/controller/TextEditorFormatController.java
package mara.mybox.controller; import javafx.fxml.FXML; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.WindowTools; import mara.mybox.tools.TextTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2023-7-19 * @License Apache License Version 2.0 */ public class TextEditorFormatController extends BaseChildController { protected TextEditorController fileController; @FXML protected ComboBox<String> charsetSelector; @FXML protected Label bomLabel; public void setParameters(TextEditorController parent) { try { fileController = parent; if (fileController == null || fileController.sourceInformation == null) { close(); return; } baseName = fileController.baseName; setFileType(fileController.TargetFileType); setTitle(message("Format") + " - " + fileController.getTitle()); charsetSelector.getItems().addAll(TextTools.getCharsetNames()); charsetSelector.setValue(fileController.sourceInformation.getCharset().name()); if (fileController.sourceInformation.isWithBom()) { bomLabel.setText(message("WithBom")); } else { bomLabel.setText(""); } } catch (Exception e) { MyBoxLog.error(e); } } @FXML @Override public void okAction() { UserConfig.setString(baseName + "SourceCharset", charsetSelector.getValue()); fileController.refreshAction(); if (closeAfterCheck.isSelected()) { close(); } } /* static methods */ public static TextEditorFormatController open(TextEditorController parent) { try { if (parent == null) { return null; } TextEditorFormatController controller = (TextEditorFormatController) WindowTools.referredTopStage( parent, Fxmls.TextEditorFormatFxml); controller.setParameters(parent); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/ControlCircle.java
alpha/MyBox/src/main/java/mara/mybox/controller/ControlCircle.java
package mara.mybox.controller; import javafx.fxml.FXML; import javafx.scene.control.TextField; import mara.mybox.data.DoubleCircle; import mara.mybox.dev.MyBoxLog; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2019-8-13 * @License Apache License Version 2.0 */ public class ControlCircle extends BaseController { protected BaseShapeController shapeController; @FXML protected TextField circleXInput, circleYInput, circleRadiusInput; protected void setParameters(BaseShapeController parent) { try { if (parent == null) { return; } shapeController = parent; } catch (Exception e) { MyBoxLog.error(e); } } public void loadValues() { if (isSettingValues || shapeController.maskCircleData == null) { return; } try { circleXInput.setText(shapeController.scale(shapeController.maskCircleData.getCenterX()) + ""); circleYInput.setText(shapeController.scale(shapeController.maskCircleData.getCenterY()) + ""); circleRadiusInput.setText(shapeController.scale(shapeController.maskCircleData.getRadius()) + ""); } catch (Exception e) { MyBoxLog.error(e); } } public boolean pickValues() { try { float x, y, r; try { x = Float.parseFloat(circleXInput.getText()); } catch (Exception e) { popError(message("InvalidParameter") + ": x"); return false; } try { y = Float.parseFloat(circleYInput.getText()); } catch (Exception e) { popError(message("InvalidParameter") + ": y"); return false; } try { r = Float.parseFloat(circleRadiusInput.getText()); } catch (Exception e) { r = -1f; } if (r <= 0) { popError(message("InvalidParameter") + ": " + message("Radius")); return false; } shapeController.maskCircleData = new DoubleCircle(x, y, r); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/DateInputController.java
alpha/MyBox/src/main/java/mara/mybox/controller/DateInputController.java
package mara.mybox.controller; import java.util.Date; import javafx.fxml.FXML; import javafx.scene.control.TextField; import javafx.scene.input.MouseEvent; import mara.mybox.db.data.ColumnDefinition.ColumnType; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.PopTools; import mara.mybox.fxml.WindowTools; import mara.mybox.tools.DateTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2022-10-2 * @License Apache License Version 2.0 */ public class DateInputController extends BaseInputController { protected ColumnType timeType; @FXML protected TextField timeInput; public DateInputController() { } public void setParameters(BaseController parent, String title, String initValue, ColumnType timeType) { try { super.setParameters(parent, title); this.timeType = timeType; if (initValue != null) { timeInput.setText(initValue); } } catch (Exception e) { MyBoxLog.debug(e); } } public Date getDate() { return DateTools.encodeDate(timeInput.getText()); } @Override public String getInputString() { return timeInput.getText(); } @Override public boolean checkInput() { String s = timeInput.getText(); if (s == null || s.isBlank()) { return true; } if (getDate() == null) { popError(message("InvalidFormat")); return false; } return true; } @FXML public void popTimeExample(MouseEvent mouseEvent) { if (timeType == null) { timeType = ColumnType.Datetime; } switch (timeType) { case Datetime: popMenu = PopTools.popDatetimeExamples(this, popMenu, timeInput, mouseEvent); break; case Date: popMenu = PopTools.popDateExamples(this, popMenu, timeInput, mouseEvent); break; case Era: PopTools.popEraExamples(this, timeInput, mouseEvent); break; } } public static DateInputController open(BaseController parent, String title, String initValue, ColumnType timeType) { try { DateInputController controller = (DateInputController) WindowTools.childStage( parent, Fxmls.DateInputFxml); controller.setParameters(parent, title, initValue, timeType); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/ControlPdfPageAttributes.java
alpha/MyBox/src/main/java/mara/mybox/controller/ControlPdfPageAttributes.java
package mara.mybox.controller; import java.awt.Color; import java.io.File; import java.util.Arrays; import java.util.List; import javafx.fxml.FXML; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.TextField; import javafx.util.StringConverter; import mara.mybox.db.data.VisitHistory; import mara.mybox.dev.MyBoxLog; import mara.mybox.tools.PdfTools; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.pdmodel.font.PDFont; import org.apache.pdfbox.pdmodel.graphics.blend.BlendMode; /** * @Author Mara * @CreateDate 2024-4-24 * @License Apache License Version 2.0 */ public class ControlPdfPageAttributes extends BaseController { protected String waterText, waterImageFile, header, footer, waterTextFontFile, headerFontFile, footerFontFile, numberFontFile; protected boolean setWaterText, setWaterImage, setHeader, setFooter, setNumber; protected int waterTextSize, headerSize, footerSize, numberSize, waterTextMargin, waterTextRotate, waterTextOpacity, waterTextRows, waterTextColumns, waterImageWidth, waterImageHeight, waterImageRotate, waterImageOpacity, waterImageMargin, waterImageRows, waterImageColumns; protected BlendMode waterTextBlend, waterImageBlend; protected Color waterTextColor, headerColor, footerColor, numberColor; @FXML protected CheckBox waterTextCheck, waterImageCheck, headerCheck, footerCheck, numberCheck; @FXML protected ControlTTFSelector waterTextFontController, headerFontController, footerFontController, numberFontController; @FXML protected TextField waterTextInput, waterTextRotateInput, waterTextOpacityInput, waterTextMarginInput, waterTextRowsInput, waterTextColumnsInput, waterImageWidthInput, waterImageHeightInput, waterImageRotateInput, waterImageOpacityInput, waterImageMarginInput, waterImageRowsInput, waterImageColumnsInput, headerInput, footerInput; @FXML protected ComboBox<String> waterTextSizeSelector, headerSizeSelector, footerSizeSelector, numberSizeSelector; @FXML protected ComboBox<BlendMode> waterTextBlendSelector, waterImageBlendSelector; @FXML protected ControlColorSet waterTextColorController, headerColorController, footerColorController, numberColorController; @Override public void setFileType() { setFileType(VisitHistory.FileType.Image); } @Override public void initControls() { try { super.initControls(); List<String> fsize = Arrays.asList( "20", "14", "18", "15", "9", "10", "12", "17", "22", "24", "36", "48", "64", "72", "96"); List<BlendMode> modes = PdfTools.pdfBlendModes(); initWaterText(fsize, modes); initWaterImage(modes); initHeader(fsize); initFooter(fsize); initNumber(fsize); } catch (Exception e) { MyBoxLog.error(e, baseName); } } protected void initWaterText(List<String> fsize, List<BlendMode> modes) { try { setWaterText = UserConfig.getBoolean(baseName + "SetWaterText", true); waterTextCheck.setSelected(setWaterText); waterTextFontController.name(baseName); waterTextSizeSelector.getItems().addAll(fsize); waterTextSize = UserConfig.getInt(baseName + "WaterTextSize", 20); waterTextSizeSelector.setValue(waterTextSize + ""); waterText = UserConfig.getString(baseName + "WaterText", ""); waterTextInput.setText(waterText); waterTextColorController.init(this, baseName + "WaterTextColor", javafx.scene.paint.Color.BLACK); waterTextMargin = UserConfig.getInt(baseName + "WaterTextMargin", 20); waterTextMarginInput.setText(waterTextMargin + ""); waterTextRotate = UserConfig.getInt(baseName + "WaterTextRotate", 45); waterTextRotateInput.setText(waterTextRotate + ""); waterTextOpacity = UserConfig.getInt(baseName + "WaterTextOpacity", 100); waterTextOpacityInput.setText(waterTextOpacity + ""); waterTextBlend = BlendMode.NORMAL; waterTextBlendSelector.getItems().addAll(modes); waterTextBlendSelector.setConverter(new StringConverter<BlendMode>() { @Override public String toString(BlendMode object) { return object.getCOSName().getName(); // return BlendMode.getCOSName(object).getName(); } @Override public BlendMode fromString(String string) { return BlendMode.getInstance(COSName.getPDFName(string)); } }); waterTextBlendSelector.setValue(waterTextBlend); waterTextRows = UserConfig.getInt(baseName + "WaterTextRows", 3); waterTextRowsInput.setText(waterTextRows + ""); waterTextColumns = UserConfig.getInt(baseName + "WaterTextColumns", 3); waterTextColumnsInput.setText(waterTextColumns + ""); } catch (Exception e) { MyBoxLog.error(e, baseName); } } protected void initWaterImage(List<BlendMode> modes) { try { setWaterImage = UserConfig.getBoolean(baseName + "SetWaterImage", true); waterImageCheck.setSelected(setWaterImage); waterImageFile = UserConfig.getString(baseName + "WaterImageFile", null); sourceFileInput.setText(waterImageFile); sourceFileInput.setStyle(null); waterImageWidth = UserConfig.getInt(baseName + "WaterImageWidth", 100); waterImageWidthInput.setText(waterImageWidth + ""); waterImageHeight = UserConfig.getInt(baseName + "WaterImageHeight", 100); waterImageHeightInput.setText(waterImageHeight + ""); waterImageMargin = UserConfig.getInt(baseName + "WaterImageMargin", 20); waterImageMarginInput.setText(waterImageMargin + ""); waterImageRotate = UserConfig.getInt(baseName + "WaterImageRotate", 45); waterImageRotateInput.setText(waterImageRotate + ""); waterImageOpacity = UserConfig.getInt(baseName + "WaterImageOpacity", 100); waterImageOpacityInput.setText(waterImageOpacity + ""); waterImageBlend = BlendMode.NORMAL; waterImageBlendSelector.getItems().addAll(modes); waterImageBlendSelector.setConverter(new StringConverter<BlendMode>() { @Override public String toString(BlendMode object) { return object.getCOSName().getName(); // return BlendMode.getCOSName(object).getName(); } @Override public BlendMode fromString(String string) { return BlendMode.getInstance(COSName.getPDFName(string)); } }); waterImageBlendSelector.setValue(waterImageBlend); waterImageRows = UserConfig.getInt(baseName + "WaterImageRows", 3); waterImageRowsInput.setText(waterImageRows + ""); waterImageColumns = UserConfig.getInt(baseName + "WaterImageColumns", 3); waterImageColumnsInput.setText(waterImageColumns + ""); } catch (Exception e) { MyBoxLog.error(e, baseName); } } protected void initHeader(List<String> fsize) { try { setHeader = UserConfig.getBoolean(baseName + "SetHeader", true); headerCheck.setSelected(setHeader); headerFontController.name(baseName); headerSizeSelector.getItems().addAll(fsize); headerSize = UserConfig.getInt(baseName + "HeaderSize", 20); headerSizeSelector.setValue(headerSize + ""); header = UserConfig.getString(baseName + "Header", ""); headerInput.setText(header); headerColorController.init(this, baseName + "HeaderColor", javafx.scene.paint.Color.BLACK); } catch (Exception e) { MyBoxLog.error(e, baseName); } } protected void initFooter(List<String> fsize) { try { setFooter = UserConfig.getBoolean(baseName + "SetFooter", true); footerCheck.setSelected(setFooter); footerFontController.name(baseName); footerSizeSelector.getItems().addAll(fsize); footerSize = UserConfig.getInt(baseName + "FooterSize", 20); footerSizeSelector.setValue(footerSize + ""); footer = UserConfig.getString(baseName + "Footer", ""); footerInput.setText(footer); footerColorController.init(this, baseName + "FooterColor", javafx.scene.paint.Color.BLACK); } catch (Exception e) { MyBoxLog.error(e, baseName); } } protected void initNumber(List<String> fsize) { try { setNumber = UserConfig.getBoolean(baseName + "SetNumber", true); numberCheck.setSelected(setNumber); numberFontController.name(baseName); numberSizeSelector.getItems().addAll(fsize); numberSize = UserConfig.getInt(baseName + "NumberSize", 20); numberSizeSelector.setValue(numberSize + ""); numberColorController.init(this, baseName + "NumberColor", javafx.scene.paint.Color.BLACK); } catch (Exception e) { MyBoxLog.error(e, baseName); } } public boolean pickWaterText() { try { setWaterText = waterTextCheck.isSelected(); UserConfig.setBoolean(baseName + "SetWaterText", setWaterText); if (!setWaterText) { return true; } String sv = waterTextInput.getText(); if (sv != null && !sv.isBlank()) { waterText = sv.trim(); UserConfig.setString(baseName + "WaterText", waterText); } else { popError(message("InvalidParameter") + ": " + message("WatermarkText")); return false; } int iv; waterTextFontFile = waterTextFontController.ttfFile; if (waterTextFontFile != null && !waterTextFontFile.isBlank()) { try { iv = Integer.parseInt(waterTextSizeSelector.getValue()); } catch (Exception e) { iv = -1; } if (iv > 0) { waterTextSize = iv; UserConfig.setInt(baseName + "WaterTextSize", iv); } else { popError(message("InvalidParameter") + ": " + message("WatermarkText") + "-" + message("FontSize")); return false; } } try { iv = Integer.parseInt(waterTextMarginInput.getText()); } catch (Exception e) { popError(message("InvalidParameter") + ": " + message("WatermarkText") + "-" + message("Margin")); return false; } waterTextMargin = iv; UserConfig.setInt(baseName + "WaterTextMargin", iv); try { iv = Integer.parseInt(waterTextRotateInput.getText()); } catch (Exception e) { popError(message("InvalidParameter") + ": " + message("WatermarkText") + "-" + message("Rotate")); return false; } waterTextRotate = iv; UserConfig.setInt(baseName + "WaterTextRotate", iv); try { iv = Integer.parseInt(waterTextOpacityInput.getText()); } catch (Exception e) { iv = -1; } if (iv >= 0) { waterTextOpacity = iv; UserConfig.setInt(baseName + "WaterTextOpacity", iv); } else { popError(message("InvalidParameter") + ": " + message("WatermarkText") + "-" + message("Opacity")); return false; } try { iv = Integer.parseInt(waterTextRowsInput.getText()); } catch (Exception e) { iv = -1; } if (iv > 0) { waterTextRows = iv; UserConfig.setInt(baseName + "WaterTextRows", iv); } else { popError(message("InvalidParameter") + ": " + message("WatermarkText") + "-" + message("RowsNumber")); return false; } try { iv = Integer.parseInt(waterTextColumnsInput.getText()); } catch (Exception e) { iv = -1; } if (iv > 0) { waterTextColumns = iv; UserConfig.setInt(baseName + "WaterTextColumns", iv); } else { popError(message("InvalidParameter") + ": " + message("WatermarkText") + "-" + message("ColumnsNumber")); return false; } waterTextBlend = waterTextBlendSelector.getValue(); waterTextColor = waterTextColorController.awtColor(); return true; } catch (Exception e) { MyBoxLog.error(e, baseName); return false; } } public boolean pickWaterImage() { try { setWaterImage = waterImageCheck.isSelected(); UserConfig.setBoolean(baseName + "SetWaterImage", setWaterImage); sourceFileInput.setStyle(null); if (!setWaterImage) { return true; } String sv = sourceFileInput.getText(); if (sv != null && !sv.isBlank()) { File file = new File(sv); if (!file.exists() || !file.isFile()) { popError(message("InvalidParameter") + ": " + message("WatermarkImage")); return false; } waterImageFile = file.getAbsolutePath(); UserConfig.setString(baseName + "WaterImageFile", waterImageFile); } else { popError(message("InvalidParameter") + ": " + message("WatermarkImage")); return false; } int iv; try { iv = Integer.parseInt(waterImageWidthInput.getText()); } catch (Exception e) { iv = -1; } if (iv > 0) { waterImageWidth = iv; UserConfig.setInt(baseName + "WaterImageWidth", iv); } else { popError(message("InvalidParameter") + ": " + message("WatermarkImage") + "-" + message("Width")); return false; } try { iv = Integer.parseInt(waterImageHeightInput.getText()); } catch (Exception e) { iv = -1; } if (iv > 0) { waterImageHeight = iv; UserConfig.setInt(baseName + "WaterImageHeight", iv); } else { popError(message("InvalidParameter") + ": " + message("WatermarkImage") + "-" + message("Height")); return false; } try { iv = Integer.parseInt(waterImageMarginInput.getText()); } catch (Exception e) { popError(message("InvalidParameter") + ": " + message("WatermarkImage") + "-" + message("Margin")); return false; } waterImageMargin = iv; UserConfig.setInt(baseName + "WaterImageMargin", iv); try { iv = Integer.parseInt(waterImageRotateInput.getText()); } catch (Exception e) { popError(message("InvalidParameter") + ": " + message("WatermarkImage") + "-" + message("Rotate")); return false; } waterImageRotate = iv; UserConfig.setInt(baseName + "WaterImageRotate", iv); try { iv = Integer.parseInt(waterImageOpacityInput.getText()); } catch (Exception e) { iv = -1; } if (iv >= 0) { waterImageOpacity = iv; UserConfig.setInt(baseName + "WaterImageOpacity", iv); } else { popError(message("InvalidParameter") + ": " + message("WatermarkImage") + "-" + message("Opacity")); return false; } try { iv = Integer.parseInt(waterImageRowsInput.getText()); } catch (Exception e) { iv = -1; } if (iv > 0) { waterImageRows = iv; UserConfig.setInt(baseName + "WaterImageRows", iv); } else { popError(message("InvalidParameter") + ": " + message("WatermarkImage") + "-" + message("RowsNumber")); return false; } try { iv = Integer.parseInt(waterImageColumnsInput.getText()); } catch (Exception e) { iv = -1; } if (iv > 0) { waterImageColumns = iv; UserConfig.setInt(baseName + "WaterImageColumns", iv); } else { popError(message("InvalidParameter") + ": " + message("WatermarkImage") + "-" + message("ColumnsNumber")); return false; } waterImageBlend = waterImageBlendSelector.getValue(); return true; } catch (Exception e) { MyBoxLog.error(e, baseName); return false; } } public boolean pickHeader() { try { setHeader = headerCheck.isSelected(); UserConfig.setBoolean(baseName + "SetHeader", setHeader); if (!setHeader) { return true; } String sv = headerInput.getText(); if (sv != null && !sv.isBlank()) { header = sv.trim(); UserConfig.setString(baseName + "Header", header); } else { popError(message("InvalidParameter") + ": " + message("Header")); return false; } headerFontFile = headerFontController.ttfFile; int iv; if (headerFontFile != null && !headerFontFile.isBlank()) { try { iv = Integer.parseInt(headerSizeSelector.getValue()); } catch (Exception e) { iv = -1; } if (iv > 0) { headerSize = iv; UserConfig.setInt(baseName + "HeaderSize", iv); } else { popError(message("InvalidParameter") + ": " + message("WatermarkText") + "-" + message("FontSize")); return false; } } headerColor = headerColorController.awtColor(); return true; } catch (Exception e) { MyBoxLog.error(e, baseName); return false; } } public boolean pickFooter() { try { setFooter = footerCheck.isSelected(); UserConfig.setBoolean(baseName + "SetFooter", setFooter); if (!setFooter) { return true; } String sv = footerInput.getText(); if (sv != null && !sv.isBlank()) { footer = sv.trim(); UserConfig.setString(baseName + "Footer", footer); } else { popError(message("InvalidParameter") + ": " + message("Footer")); return false; } footerFontFile = footerFontController.ttfFile; int iv; if (footerFontFile != null && !footerFontFile.isBlank()) { try { iv = Integer.parseInt(footerSizeSelector.getValue()); } catch (Exception e) { iv = -1; } if (iv > 0) { footerSize = iv; UserConfig.setInt(baseName + "FooterSize", iv); } else { popError(message("InvalidParameter") + ": " + message("WatermarkText") + "-" + message("FontSize")); return false; } } footerColor = footerColorController.awtColor(); return true; } catch (Exception e) { MyBoxLog.error(e, baseName); return false; } } public boolean pickNumber() { try { setNumber = numberCheck.isSelected(); UserConfig.setBoolean(baseName + "SetNumber", setNumber); if (!setNumber) { return true; } numberFontFile = numberFontController.ttfFile; int iv; if (numberFontFile != null && !numberFontFile.isBlank()) { try { iv = Integer.parseInt(numberSizeSelector.getValue()); } catch (Exception e) { iv = -1; } if (iv > 0) { numberSize = iv; UserConfig.setInt(baseName + "NumberSize", iv); } else { popError(message("InvalidParameter") + ": " + message("WatermarkText") + "-" + message("FontSize")); return false; } } numberColor = numberColorController.awtColor(); return true; } catch (Exception e) { MyBoxLog.error(e, baseName); return false; } } public boolean pickValues() { try { if (!pickWaterText() || !pickWaterImage() || !pickHeader() || !pickFooter() || !pickNumber()) { return false; } if (!setWaterText && !setWaterImage && !setHeader && !setFooter && !setNumber) { popError(message("NothingHandled")); return false; } return true; } catch (Exception e) { MyBoxLog.error(e, baseName); return false; } } public float waterTextWidth(PDFont font) { return PdfTools.fontWidth(font, waterText, waterTextSize); } public float waterTextHeight(PDFont font) { return PdfTools.fontHeight(font, waterTextSize); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/ControlImageSepia.java
alpha/MyBox/src/main/java/mara/mybox/controller/ControlImageSepia.java
package mara.mybox.controller; import java.util.Arrays; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.ComboBox; import mara.mybox.image.data.PixelsOperation; import mara.mybox.image.data.PixelsOperationFactory; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.ValidationTools; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2019-9-2 * @License Apache License Version 2.0 */ public class ControlImageSepia extends BaseController { protected int intensity; @FXML protected ComboBox<String> intensitySelector; @Override public void initControls() { try { super.initControls(); intensity = UserConfig.getInt(baseName + "Intensity", 60); if (intensity <= 0 || intensity >= 255) { intensity = 60; } intensitySelector.getItems().addAll(Arrays.asList("60", "80", "20", "50", "10", "5", "100", "15", "20")); intensitySelector.setValue(intensity + ""); intensitySelector.valueProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue ov, String oldValue, String newValue) { checkIntensity(); } }); } catch (Exception e) { MyBoxLog.error(e); } } public boolean checkIntensity() { int v; try { v = Integer.parseInt(intensitySelector.getValue()); } catch (Exception e) { v = -1; } if (v >= 0 && v <= 255) { intensity = v; ValidationTools.setEditorNormal(intensitySelector); return true; } else { popError(message("InvalidParameter") + ": " + message("Intensity")); ValidationTools.setEditorBadStyle(intensitySelector); return false; } } public PixelsOperation pickValues() { if (!checkIntensity()) { return null; } try { PixelsOperation pixelsOperation = PixelsOperationFactory.create( null, null, PixelsOperation.OperationType.Sepia) .setIntPara1(intensity); return pixelsOperation; } catch (Exception e) { displayError(e.toString()); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/ControlSvgNodeEdit.java
alpha/MyBox/src/main/java/mara/mybox/controller/ControlSvgNodeEdit.java
package mara.mybox.controller; import java.util.List; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.control.MenuItem; import javafx.scene.control.Tab; import javafx.scene.control.TextArea; import javafx.scene.control.TreeItem; import javafx.scene.layout.FlowPane; import mara.mybox.data.DoubleShape; import mara.mybox.data.XmlTreeNode; import static mara.mybox.data.XmlTreeNode.NodeType.Element; import mara.mybox.db.table.TableStringValues; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.HelpTools; import mara.mybox.fxml.menu.MenuTools; import mara.mybox.fxml.PopTools; import mara.mybox.tools.StringTools; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; /** * @Author Mara * @CreateDate 2023-6-13 * @License Apache License Version 2.0 */ public class ControlSvgNodeEdit extends ControlXmlNodeEdit { protected SvgEditorController editor; @FXML protected Tab pathTab, styleTab; @FXML protected TextArea styleArea; @FXML protected ControlPath2D pathController; @FXML protected FlowPane shapeOpPane; @Override public void editNode(TreeItem<XmlTreeNode> item) { super.editNode(item); if (treeItem != null) { XmlTreeNode currentTreeNode = treeItem.getValue(); if (currentTreeNode != null && currentTreeNode.getType() == Element) { String name = currentTreeNode.getNode().getNodeName(); if (!name.equalsIgnoreCase("svg")) { if (name.equalsIgnoreCase("path")) { tabPane.getTabs().add(0, pathTab); tabPane.getTabs().add(2, styleTab); } else { tabPane.getTabs().add(1, styleTab); } tabPane.getSelectionModel().select(0); refreshStyle(tabPane); } } } Node focusedNode = null; try { focusedNode = treeItem.getValue().getNode(); } catch (Exception e) { } editor.drawSVG(focusedNode); shapeOpPane.setVisible(item != null && item.getValue() != null && item.getValue().isSvgShape()); } @Override public void setAttributes() { if (node == null) { return; } boolean isPath = "path".equalsIgnoreCase(node.getNodeName()); NamedNodeMap attrs = node.getAttributes(); if (attrs != null) { for (int i = 0; i < attrs.getLength(); i++) { Node attr = attrs.item(i); String attrName = attr.getNodeName(); String value = attr.getNodeValue(); if (isPath && "d".equalsIgnoreCase(attrName)) { pathController.loadPath(value); continue; } if ("style".equalsIgnoreCase(attrName)) { styleArea.setText(value); continue; } tableData.add(attrs.item(i)); } } } @Override public Node pickValue() { try { if (node == null) { return null; } super.pickValue(); if (node.getNodeType() != Node.ELEMENT_NODE) { return node; } Element element = (Element) node; String style = styleArea.getText(); if (style != null && !style.isBlank()) { style = StringTools.trimBlanks(style); element.setAttribute("style", style); TableStringValues.add("SvgStyleHistories", style); } else { element.removeAttribute("style"); } if ("path".equalsIgnoreCase(node.getNodeName())) { pathController.pickValue(); String path = pathController.getText(); if (path != null && !path.isBlank()) { path = StringTools.trimBlanks(path); element.setAttribute("d", path); } else { element.removeAttribute("d"); } } return node; } catch (Exception e) { MyBoxLog.error(e); return null; } } @Override public void clearNode() { super.clearNode(); pathController.loadPath(""); styleArea.clear(); tabPane.getTabs().removeAll(pathTab, styleTab); } /* style */ @FXML public void popExamplesStyleMenu(Event event) { if (UserConfig.getBoolean("SvgStyleExamplesPopWhenMouseHovering", false)) { showExamplesStyleMenu(event); } } @FXML public void showExamplesStyleMenu(Event event) { PopTools.popMappedValues(this, styleArea, "SvgStyleExamples", HelpTools.svgStyleExamples(), event); } @FXML protected void popStyleHistories(Event event) { if (UserConfig.getBoolean("SvgStyleHistoriesPopWhenMouseHovering", false)) { showStyleHistories(event); } } @FXML protected void showStyleHistories(Event event) { PopTools.popSavedValues(this, styleArea, event, "SvgStyleHistories"); } @FXML protected void clearStyle() { styleArea.clear(); } /* shape */ @FXML public void popShapeMenu(Event event) { if (MenuTools.isPopMenu("SvgNodeShape")) { showShapeMenu(event); } } @FXML public void showShapeMenu(Event event) { if (node == null || !(node instanceof Element)) { return; } List<MenuItem> items = DoubleShape.elementMenu(this, (Element) node); if (items == null) { return; } items.add(MenuTools.popCheckMenu("SvgNodeShape")); popEventMenu(event, items); } public void loadPath(String content) { if (content == null || content.isBlank()) { popError(message("NoData")); return; } pathController.loadPath(content); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/GameEliminationController.java
alpha/MyBox/src/main/java/mara/mybox/controller/GameEliminationController.java
package mara.mybox.controller; import java.io.File; import java.sql.Connection; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import javafx.animation.FadeTransition; import javafx.animation.PathTransition; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.event.Event; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.ListView; import javafx.scene.control.RadioButton; import javafx.scene.control.ScrollPane; import javafx.scene.control.SelectionMode; import javafx.scene.control.Tab; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.ToggleButton; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.effect.DropShadow; import javafx.scene.input.MouseEvent; import javafx.scene.layout.FlowPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Priority; import javafx.scene.layout.Region; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.shape.LineTo; import javafx.scene.shape.Path; import javafx.stage.Popup; import javafx.stage.Stage; import javafx.util.Callback; import javafx.util.Duration; import mara.mybox.data.ImageItem; import mara.mybox.data.IntPoint; import mara.mybox.db.DerbyBase; import mara.mybox.db.data.VisitHistory; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.fxml.LocateTools; import mara.mybox.fxml.menu.MenuTools; import mara.mybox.fxml.PopTools; import mara.mybox.fxml.RecentVisitMenu; import mara.mybox.fxml.SoundTools; import mara.mybox.fxml.cell.ListImageItemCell; import mara.mybox.fxml.cell.TableAutoCommitCell; import mara.mybox.fxml.converter.IntegerStringFromatConverter; import mara.mybox.fxml.style.NodeStyleTools; import mara.mybox.tools.DateTools; import mara.mybox.tools.FileNameTools; import mara.mybox.tools.HtmlWriteTools; import mara.mybox.value.AppVariables; import mara.mybox.value.FileFilters; import mara.mybox.value.InternalImages; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2019-12-30 * @License Apache License Version 2.0 */ public class GameEliminationController extends BaseController { protected int boardSize, chessWidth, minimumAdjacent, totalScore, autoSpeed, flushDuration, eliminateDelay, flushTimes; protected Map<String, VBox> chessBoard; protected List<Integer> countedChesses; protected IntPoint firstClick; protected boolean countScore, isEliminating, autoPlaying, stopped; protected Random random; protected ObservableList<ScoreRuler> scoreRulersData; protected Map<Integer, Integer> scoreRulers; protected Map<Integer, Integer> scoreRecord; protected Date startTime; protected Adjacent lastElimination, lastRandom; protected String currentStyle, focusStyle, defaultStyle, arcStyle, shadowStyle; protected File soundFile; @FXML protected Tab playTab, chessesTab, rulersTab, settingsTab; @FXML protected VBox chessboardPane; @FXML protected Label chessesLabel, scoreLabel, autoLabel, soundFileLabel; @FXML protected ListView<ImageItem> imagesListview; @FXML protected FlowPane countedImagesPane; @FXML protected CheckBox shadowCheck, arcCheck, scoreCheck; @FXML protected ComboBox<String> chessSizeSelector; @FXML protected TableView<ScoreRuler> rulersTable; @FXML protected TableColumn<ScoreRuler, Integer> numberColumn, scoreColumn; @FXML protected RadioButton guaiRadio, benRadio, guaiBenRadio, muteRadio, customizedSoundRadio, deadRenewRadio, deadChanceRadio, deadPromptRadio, speed1Radio, speed2Radio, speed3Radio, speed5Radio, flush0Radio, flush1Radio, flush2Radio, flush3Radio; @FXML protected HBox selectSoundBox; @FXML protected Button helpMeButton; @FXML protected ToggleButton catButton; @FXML protected ScrollPane scrollPane; @FXML protected ControlWebView imageInfoController; @FXML protected ControlColorSet colorSetController; public GameEliminationController() { baseTitle = message("GameElimniation"); TipsLabelKey = "GameEliminationComments"; } @Override public void initControls() { try { super.initControls(); chessBoard = new HashMap(); scoreRulers = new HashMap(); scoreRecord = new HashMap(); scoreRulersData = FXCollections.observableArrayList(); countedChesses = new ArrayList(); random = new Random(); defaultStyle = "-fx-background-color: transparent; -fx-border-style: solid inside;" + "-fx-border-width: 2; -fx-border-radius: 3; -fx-border-color: transparent;"; arcStyle = "-fx-background-color: white; -fx-border-style: solid inside;" + "-fx-border-width: 2; -fx-border-radius: 10;-fx-background-radius: 10; -fx-border-color: transparent;"; shadowStyle = "-fx-background-color: white;-fx-border-style: solid inside;" + "-fx-border-width: 2; -fx-border-radius: 3; -fx-border-color: white;"; focusStyle = "-fx-border-style: solid inside;-fx-border-width: 2;" + "-fx-border-radius: 3;" + "-fx-border-color: blue;"; flushDuration = 200; minimumAdjacent = 3; colorSetController.init(this, baseName + "Color", Color.RED); colorSetController.setNotify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { String name = "color:" + colorSetController.name(); addImageAddress(name); } }); catButton.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldVal, Boolean newVal) { if (firstClick != null) { recoverStyle(firstClick.getX(), firstClick.getY()); firstClick = null; } autoPlaying = catButton.isSelected(); if (autoPlaying) { autoLabel.setText(message("Autoplaying")); findAdjacentAndEliminate(); } else { autoLabel.setText(""); } } }); imagesListview.setCellFactory((ListView<ImageItem> param) -> { ListImageItemCell cell = new ListImageItemCell(); return cell; }); imagesListview.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); imagesListview.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<ImageItem>() { @Override public void changed(ObservableValue ov, ImageItem oldVal, ImageItem newVal) { viewImage(); } }); imagesListview.getItems().addListener(new ListChangeListener<ImageItem>() { @Override public void onChanged(ListChangeListener.Change<? extends ImageItem> c) { chessesLabel.setText(message("Count") + ": " + imagesListview.getItems().size()); } }); chessWidth = 50; chessSizeSelector.getItems().addAll(Arrays.asList( "50", "40", "60", "30", "80" )); shadowCheck.setSelected(UserConfig.getBoolean("GameEliminationShadow", false)); arcCheck.setSelected(UserConfig.getBoolean("GameEliminationArc", false)); chessSizeSelector.getSelectionModel().select(UserConfig.getString("GameEliminationChessImageSize", "50")); imageInfoController.setParent(this); } catch (Exception e) { MyBoxLog.debug(e); } } @Override public void setControlsStyle() { try { super.setControlsStyle(); NodeStyleTools.setTooltip(createButton, message("NewGame") + "\nn / Ctrl+n"); NodeStyleTools.setTooltip(helpMeButton, message("HelpMeFindExchange") + "\nh / Ctrl+h"); NodeStyleTools.setTooltip(catButton, message("AutoPlayGame") + "\np / Ctrl+p"); } catch (Exception e) { MyBoxLog.debug(e); } } @Override public boolean afterSceneLoaded() { if (!super.afterSceneLoaded()) { return false; } loadChesses(true); return true; } public void loadChesses(boolean resetGame) { if (task != null) { task.cancel(); } task = new FxSingletonTask<Void>(this) { private List<ImageItem> items; @Override protected boolean handle() { try { items = new ArrayList<>(); List<ImageItem> predefinedItems = InternalImages.allWithColors(); List<String> addresses = null; String savedNames = UserConfig.getString("GameEliminationChessImages", null); if (savedNames != null) { addresses = Arrays.asList(savedNames.split(",")); } if (addresses != null) { for (String address : addresses) { boolean predefined = false; for (ImageItem item : predefinedItems) { if (address.equals(item.getAddress())) { items.add(item); predefined = true; break; } } if (!predefined) { items.add(new ImageItem(address)); } } } if (items.size() <= minimumAdjacent) { for (ImageItem pitem : predefinedItems) { boolean existed = false; for (ImageItem eitem : items) { if (eitem.getAddress().equals(pitem.getAddress())) { existed = true; break; } } if (!existed) { items.add(pitem); } if (items.size() > minimumAdjacent) { break; } } } return true; } catch (Exception e) { error = e.toString(); return false; } } @Override protected void whenSucceeded() { imagesListview.getItems().setAll(items); if (resetGame) { okChessesAction(); initRulersTab(); initSettingsTab(); } } }; start(task); } protected void initRulersTab() { try { rulersTable.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); rulersTable.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() { @Override public void changed(ObservableValue ov, Object t, Object t1) { if (!isSettingValues) { } } }); rulersTable.setItems(scoreRulersData); numberColumn.setCellValueFactory(new PropertyValueFactory<>("adjacentNumber")); scoreColumn.setCellValueFactory(new PropertyValueFactory<>("score")); scoreColumn.setCellFactory(new Callback<TableColumn<ScoreRuler, Integer>, TableCell<ScoreRuler, Integer>>() { @Override public TableCell<ScoreRuler, Integer> call(TableColumn<ScoreRuler, Integer> param) { TableAutoCommitCell<ScoreRuler, Integer> cell = new TableAutoCommitCell<ScoreRuler, Integer>(new IntegerStringFromatConverter()) { @Override public boolean valid(Integer value) { return value != null && value >= 0; } @Override public boolean setCellValue(Integer value) { try { if (!valid(value) || !isEditingRow()) { cancelEdit(); return false; } ScoreRuler row = scoreRulersData.get(editingRow); if (row == null || value == null || value < 0) { cancelEdit(); return false; } row.score = value; return super.setCellValue(value); } catch (Exception e) { MyBoxLog.debug(e); return false; } } }; return cell; } }); scoreColumn.getStyleClass().add("editable-column"); } catch (Exception e) { MyBoxLog.debug(e); } } protected void initSettingsTab() { try { isSettingValues = true; guaiRadio.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldVal, Boolean newVal) { if (isSettingValues) { return; } if (newVal) { UserConfig.setString("GameEliminationSound", "Guai"); } } }); benRadio.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldVal, Boolean newVal) { if (isSettingValues) { return; } if (newVal) { UserConfig.setString("GameEliminationSound", "Ben"); } } }); guaiBenRadio.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldVal, Boolean newVal) { if (isSettingValues) { return; } if (newVal) { UserConfig.setString("GameEliminationSound", "GuaiBen"); } } }); muteRadio.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldVal, Boolean newVal) { if (isSettingValues) { return; } if (newVal) { UserConfig.setString("GameEliminationSound", "Mute"); } } }); customizedSoundRadio.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldVal, Boolean newVal) { if (isSettingValues) { return; } if (newVal) { UserConfig.setString("GameEliminationSound", "Customized"); } } }); String sound = UserConfig.getString("GameEliminationSound", "Guai"); switch (sound) { case "Ben": benRadio.setSelected(true); break; case "GuaiBen": guaiBenRadio.setSelected(true); break; case "Mute": muteRadio.setSelected(true); break; case "Customized": customizedSoundRadio.setSelected(true); break; default: guaiRadio.setSelected(true); break; } deadRenewRadio.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldVal, Boolean newVal) { if (isSettingValues) { return; } UserConfig.setString("GameEliminationDead", "Renew"); } }); deadChanceRadio.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldVal, Boolean newVal) { if (isSettingValues) { return; } UserConfig.setString("GameEliminationDead", "Chance"); } }); deadPromptRadio.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldVal, Boolean newVal) { if (isSettingValues) { return; } UserConfig.setString("GameEliminationDead", "Prompt"); } }); String dead = UserConfig.getString("GameEliminationDead", "Renew"); switch (dead) { case "Chance": deadChanceRadio.setSelected(true); break; case "Prompt": deadPromptRadio.setSelected(true); break; default: deadRenewRadio.setSelected(true); break; } speed1Radio.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldVal, Boolean newVal) { autoSpeed = 1000; UserConfig.setString("GameEliminationAutoSpeed", "1"); } }); speed2Radio.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldVal, Boolean newVal) { autoSpeed = 2000; UserConfig.setString("GameEliminationAutoSpeed", "2"); } }); speed3Radio.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldVal, Boolean newVal) { autoSpeed = 3000; UserConfig.setString("GameEliminationAutoSpeed", "3"); } }); speed5Radio.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldVal, Boolean newVal) { autoSpeed = 5000; UserConfig.setString("GameEliminationAutoSpeed", "5"); } }); autoSpeed = 2000; String speed = UserConfig.getString("GameEliminationAutoSpeed", "2"); switch (speed) { case "1": speed1Radio.setSelected(true); break; case "3": speed3Radio.setSelected(true); break; case "5": speed5Radio.setSelected(true); break; default: speed2Radio.setSelected(true); break; } flush0Radio.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldVal, Boolean newVal) { flushTimes = 0; eliminateDelay = flushDuration * (2 * flushTimes + 1); UserConfig.setString("GameEliminationFlushTime", "0"); } }); flush1Radio.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldVal, Boolean newVal) { flushTimes = 1; eliminateDelay = flushDuration * (2 * flushTimes + 1); UserConfig.setString("GameEliminationFlushTime", "1"); } }); flush2Radio.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldVal, Boolean newVal) { flushTimes = 2; eliminateDelay = flushDuration * (2 * flushTimes + 1); UserConfig.setString("GameEliminationFlushTime", "2"); } }); flush3Radio.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldVal, Boolean newVal) { flushTimes = 3; eliminateDelay = flushDuration * (2 * flushTimes + 1); UserConfig.setString("GameEliminationFlushTime", "3"); } }); flushTimes = 2; eliminateDelay = flushDuration * (2 * flushTimes + 1); String flush = UserConfig.getString("GameEliminationFlushTime", "2"); switch (flush) { case "1": flush1Radio.setSelected(true); break; case "3": flush3Radio.setSelected(true); break; case "0": flush0Radio.setSelected(true); break; default: flush2Radio.setSelected(true); break; } scoreCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldVal, Boolean newVal) { UserConfig.setBoolean("GameEliminationPopScores", scoreCheck.isSelected()); } }); scoreCheck.setSelected(UserConfig.getBoolean("GameEliminationPopScores", true)); selectSoundBox.disableProperty().bind(customizedSoundRadio.selectedProperty().not()); String sfile = UserConfig.getString("GameEliminationSoundFile", null); if (sfile != null) { soundFile = new File(sfile); if (soundFile.exists()) { soundFileLabel.setText(soundFile.getAbsolutePath()); } else { soundFile = null; } } isSettingValues = false; } catch (Exception e) { MyBoxLog.debug(e); } } public void viewImage() { if (isSettingValues) { return; } imageInfoController.clear(); ImageItem selected = imagesListview.getSelectionModel().getSelectedItem(); if (selected == null || selected.isColor()) { return; } File file = selected.getFile(); if (file == null || !file.exists()) { return; } String body = "<Img src='" + file.toURI().toString() + "' width=" + selected.getWidth() + ">\n"; String comments = selected.getComments(); if (comments != null && !comments.isBlank()) { body += "<BR>" + message(comments); } imageInfoController.loadContent(HtmlWriteTools.html(body)); } @Override public void selectSourceFileDo(File file) { if (file == null) { return; } recordFileOpened(file); addImageAddress(file.getAbsolutePath()); } @FXML protected void okChessesAction() { makeChesses(); } @FXML protected void okRulersAction() { if (isSettingValues) { return; } catButton.setSelected(false); try { countedChesses.clear(); String s = ""; for (Node node : countedImagesPane.getChildren()) { CheckBox cbox = (CheckBox) node; if (cbox.isSelected()) { int index = (int) cbox.getUserData(); countedChesses.add(index); ImageItem item = getImageItem(index); if (s.isBlank()) { s += item.getAddress(); } else { s += "," + item.getAddress(); } } } if (countedChesses.isEmpty()) { if (!PopTools.askSure(getTitle(), message("SureNoScore"))) { return; } } UserConfig.setString("GameEliminationCountedImages", s); scoreRulers.clear(); s = ""; for (int i = 0; i < scoreRulersData.size(); ++i) { ScoreRuler r = scoreRulersData.get(i); scoreRulers.put(r.adjacentNumber, r.score); if (!s.isEmpty()) { s += ","; } s += r.adjacentNumber + "," + r.score; } UserConfig.setString("GameElimniationScoreRulers", s); tabPane.getSelectionModel().select(playTab); newGame(true); } catch (Exception e) { MyBoxLog.debug(e); } } public boolean addImageAddress(String address) { if (isSettingValues || address == null) { return false; } for (ImageItem item : imagesListview.getItems()) { if (item.getAddress().equals(address)) { popError(message("AlreadyExisted")); return false; } } ImageItem item = new ImageItem().setAddress(address); imagesListview.getItems().add(0, item); imagesListview.scrollTo(0); return true; } @FXML protected void clearChessesAction() { imagesListview.getItems().clear(); } @FXML protected void deleteChessesAction() { List<ImageItem> selected = imagesListview.getSelectionModel().getSelectedItems(); if (selected == null || selected.isEmpty()) { popError(message("SelectToHandle")); return; } imagesListview.getItems().removeAll(selected); } @FXML protected void recoverChessesAction() { loadChesses(false); } @FXML protected void chessExamples() { ImageExampleSelectController controller = ImageExampleSelectController.open(this, true); controller.notify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { List<ImageItem> items = controller.selectedItems(); if (items == null || items.isEmpty()) { controller.popError(message("SelectToHandle")); return; } controller.close(); for (ImageItem item : items) { String address = item.getAddress(); for (ImageItem litem : imagesListview.getItems()) { if (litem.getAddress().equals(address)) { address = null; break; } } if (address != null) { imagesListview.getItems().add(0, item); } } imagesListview.scrollTo(0); } }); } @FXML protected void clearCountedImagesAction() { if (isSettingValues) { return; } for (Node node : countedImagesPane.getChildren()) { CheckBox cbox = (CheckBox) node; cbox.setSelected(false); } } @FXML protected void allCountedImagesAction() { if (isSettingValues) { return; } for (Node node : countedImagesPane.getChildren()) { CheckBox cbox = (CheckBox) node; cbox.setSelected(true); } } @FXML @Override public void createAction() { if (isSettingValues) { return; } catButton.setSelected(false); newGame(true); } @FXML protected void settingsAction() { tabPane.getSelectionModel().select(settingsTab); } @FXML public void helpMeAction() { if (isSettingValues || autoPlaying) { return; } Adjacent adjacent = findValidExchange(); if (adjacent != null) { flush(adjacent.exchangei1, adjacent.exchangej1); flush(adjacent.exchangei2, adjacent.exchangej2); } else { promptDeadlock(); } } protected void setAutoplay() { catButton.setSelected(!catButton.isSelected()); } @FXML public void selectSoundFile() { try { if (!checkBeforeNextAction()) { return; } File file = mara.mybox.fxml.FxFileTools.selectFile(this, UserConfig.getPath("MusicPath"), FileFilters.Mp3WavExtensionFilter); if (file == null) { return; } selectSoundFile(file); } catch (Exception e) { // MyBoxLog.error(e); } } public void selectSoundFile(File file) { recordFileOpened(file); String suffix = FileNameTools.ext(file.getName()); if (suffix == null || (!"mp3".equals(suffix.toLowerCase()) && !"wav".equals(suffix.toLowerCase()))) { alertError(message("OnlySupportMp3Wav")); return; } soundFile = file; UserConfig.setString("MusicPath", file.getParent()); UserConfig.setString("GameEliminationSoundFile", file.getAbsolutePath()); soundFileLabel.setText(file.getAbsolutePath()); SoundTools.mp3(soundFile); } @FXML public void showSoundFileMenu(Event event) { if (AppVariables.fileRecentNumber <= 0) {
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
true
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/ChromaticityBaseController.java
alpha/MyBox/src/main/java/mara/mybox/controller/ChromaticityBaseController.java
package mara.mybox.controller; import java.io.File; import java.util.List; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.control.RadioButton; import javafx.scene.control.TextField; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleGroup; import mara.mybox.color.ChromaticAdaptation; import mara.mybox.db.data.VisitHistory; import mara.mybox.db.data.VisitHistoryTools; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.fxml.HelpTools; import mara.mybox.fxml.menu.MenuTools; import mara.mybox.fxml.RecentVisitMenu; import mara.mybox.tools.TextFileTools; import mara.mybox.value.AppVariables; import mara.mybox.value.FileFilters; import mara.mybox.value.Languages; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2019-6-2 10:59:16 * @License Apache License Version 2.0 */ public class ChromaticityBaseController extends BaseWebViewController { protected int scale = 8; protected double sourceX, sourceY, sourceZ, targetX, targetY, targetZ; protected ChromaticAdaptation.ChromaticAdaptationAlgorithm algorithm; protected String exportName; @FXML protected TextField scaleInput; @FXML protected ToggleGroup algorithmGroup; public ChromaticityBaseController() { baseTitle = Languages.message("Chromaticity"); exportName = "ChromaticityData"; } @Override public void setFileType() { setFileType(VisitHistory.FileType.Text); } @Override public void initControls() { try { super.initControls(); initOptions(); } catch (Exception e) { } } public void initOptions() { if (algorithmGroup != null) { algorithmGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> ov, Toggle old_toggle, Toggle new_toggle) { checkAlgorithm(); } }); checkAlgorithm(); } if (scaleInput != null) { scaleInput.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { checkScale(); } }); int p = UserConfig.getInt("MatrixDecimalScale", 8); scaleInput.setText(p + ""); } } public void checkAlgorithm() { try { RadioButton selected = (RadioButton) algorithmGroup.getSelectedToggle(); switch (selected.getText()) { case "Bradford": algorithm = ChromaticAdaptation.ChromaticAdaptationAlgorithm.Bradford; break; case "XYZ Scaling": algorithm = ChromaticAdaptation.ChromaticAdaptationAlgorithm.XYZScaling; break; case "Von Kries": algorithm = ChromaticAdaptation.ChromaticAdaptationAlgorithm.VonKries; break; default: algorithm = ChromaticAdaptation.ChromaticAdaptationAlgorithm.Bradford; } } catch (Exception e) { algorithm = ChromaticAdaptation.ChromaticAdaptationAlgorithm.Bradford; } } public void checkScale() { try { int p = Integer.parseInt(scaleInput.getText()); if (p < 0) { scaleInput.setStyle(UserConfig.badStyle()); } else { scale = p; scaleInput.setStyle(null); UserConfig.setInt("MatrixDecimalScale", scale); } } catch (Exception e) { scaleInput.setStyle(UserConfig.badStyle()); } } @FXML public void aboutColor() { openHtml(HelpTools.aboutColor()); } public void showExportPathMenu(Event event) { if (AppVariables.fileRecentNumber <= 0) { return; } new RecentVisitMenu(this, event, true) { @Override public List<VisitHistory> recentPaths() { return VisitHistoryTools.getRecentPathWrite(VisitHistory.FileType.Text); } @Override public void handleSelect() { exportAction(); } @Override public void handlePath(String fname) { handleTargetPath(fname); } }.pop(); } @FXML public void pickExportPath(Event event) { if (MenuTools.isPopMenu("RecentVisit") || AppVariables.fileRecentNumber <= 0) { exportAction(); } else { showExportPathMenu(event); } } @FXML public void popExportPath(Event event) { if (MenuTools.isPopMenu("RecentVisit")) { showExportPathMenu(event); } } // should rewrite this public String exportTexts() { return ""; } @FXML public void exportAction() { final File file = chooseFile(defaultTargetPath(), exportName, FileFilters.TextExtensionFilter); if (file == null) { return; } if (task != null && !task.isQuit()) { return; } task = new FxSingletonTask<Void>(this) { @Override protected boolean handle() { if (TextFileTools.writeFile(file, exportTexts()) == null) { return false; } recordFileWritten(file, VisitHistory.FileType.Text); return true; } @Override protected void whenSucceeded() { view(file); popSuccessful(); } }; start(task); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/DevTmpController.java
alpha/MyBox/src/main/java/mara/mybox/controller/DevTmpController.java
package mara.mybox.controller; import java.io.File; import java.nio.charset.Charset; import java.util.Arrays; import java.util.List; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.fxml.WindowTools; import mara.mybox.tools.TextFileTools; import mara.mybox.value.Fxmls; /** * @Author Mara * @CreateDate 2024-12-3 * @License Apache License Version 2.0 */ public class DevTmpController extends BaseTaskController { @Override public void initControls() { try { super.initControls(); // refineFxmls(); // refineFxmls2(); } catch (Exception e) { MyBoxLog.error(e); } } public void refineFxmls() { task = new FxTask<Void>(this) { private File targetPath; private String name; @Override protected boolean handle() { try { int count = 0; File srcPath = new File("D:\\MyBox\\src\\main\\resources\\fxml\\"); targetPath = new File("D:\\tmp\\1\\"); updateLogs(srcPath.getAbsolutePath()); List<File> fxmls = Arrays.asList(srcPath.listFiles()); String scrollImport = "<?import javafx.scene.control.ScrollPane?>"; String controlImport = "<?import javafx.scene.control.*?>"; String newControlPrefx = "<ScrollPane fitToHeight=\"true\" fitToWidth=\"true\" " + "maxHeight=\"1.7976931348623157E308\" maxWidth=\"1.7976931348623157E308\" " + "pannable=\"true\" xmlns=\"http://javafx.com/javafx/23.0.1\" " + "xmlns:fx=\"http://javafx.com/fxml/1\" "; String newSuffix = "\n </content>\n</ScrollPane>\n"; Charset utf8 = Charset.forName("UTF-8"); for (File fxml : fxmls) { name = fxml.getName(); String texts = TextFileTools.readTexts(this, fxml, utf8); int menuPos = texts.indexOf("<fx:include fx:id=\"mainMenu\" source=\"MainMenu.fxml\""); if (menuPos < 0) { // MyBoxLog.console("No menu: " + fxml); continue; } int startPos = texts.indexOf("<BorderPane fx:id=\"thisPane\""); if (startPos < 0) { startPos = texts.indexOf("<VBox fx:id=\"thisPane\""); if (startPos < 0) { startPos = texts.indexOf("<StackPane fx:id=\"thisPane\""); if (startPos < 0) { MyBoxLog.console(fxml); continue; } } } int nsPos = texts.indexOf("xmlns=", startPos); if (nsPos < 0) { MyBoxLog.console(fxml); continue; } int controlPos = texts.indexOf("fx:controller=", startPos); if (nsPos < 0) { MyBoxLog.console(fxml); continue; } int endPos = texts.indexOf(">", startPos); if (endPos < 0) { MyBoxLog.console(fxml); continue; } String newFxml = texts.substring(0, startPos); if (!texts.contains(scrollImport) && !texts.contains(controlImport)) { newFxml += "\n" + scrollImport + "\n"; // MyBoxLog.console("no import:" + fxml); } newFxml += newControlPrefx + texts.substring(controlPos, endPos) + ">\n <content>\n" + texts.substring(startPos, nsPos) + ">" + texts.substring(endPos + 1) + newSuffix; File file = new File(targetPath + File.separator + name); TextFileTools.writeFile(file, newFxml, utf8); updateLogs(++count + ": " + file); } return true; } catch (Exception e) { error = name + " - " + e.toString(); return false; } } @Override protected void whenSucceeded() { browse(targetPath); } }; start(task); } public void refineFxmls2() { task = new FxTask<Void>(this) { private File targetPath; private String name; @Override protected boolean handle() { try { int count = 0; File srcPath = new File("D:\\MyBox\\src\\main\\resources\\fxml\\"); targetPath = new File("D:\\tmp\\1\\"); updateLogs(srcPath.getAbsolutePath()); List<File> fxmls = Arrays.asList(srcPath.listFiles()); String scrollPrefix = "<ScrollPane fitToHeight=\"true\" fitToWidth=\"true\" " + "maxHeight=\"1.7976931348623157E308\" maxWidth=\"1.7976931348623157E308\" " + "pannable=\"true\" xmlns=\"http://javafx.com/javafx/23.0.1\" " + "xmlns:fx=\"http://javafx.com/fxml/1\" "; Charset utf8 = Charset.forName("UTF-8"); int startPane, endPane, startHeight; boolean isBorderPane; String newFxml; for (File fxml : fxmls) { name = fxml.getName(); String texts = TextFileTools.readTexts(this, fxml, utf8); int scrollStart = texts.indexOf(scrollPrefix); if (scrollStart < 0) { // MyBoxLog.console("No menu: " + fxml); continue; } int scrollEnd = texts.indexOf(">", scrollStart); startPane = texts.indexOf("<BorderPane fx:id=\"thisPane\"", scrollEnd); if (startPane > 0) { isBorderPane = true; } else { startPane = texts.indexOf("<StackPane fx:id=\"thisPane\"", scrollEnd); if (startPane > 0) { isBorderPane = false; } else { MyBoxLog.console(fxml); continue; } } endPane = texts.indexOf(">", startPane); startHeight = texts.indexOf("prefHeight=", startPane, endPane); newFxml = texts.substring(0, startPane); if (startHeight > 0) { newFxml = newFxml.replaceFirst("ScrollPane fitToHeight", "ScrollPane " + texts.substring(startHeight, endPane) + " fitToHeight"); } newFxml += isBorderPane ? "<BorderPane" : "<StackPane"; newFxml += " fx:id=\"thisPane\" maxHeight=\"1.7976931348623157E308\" maxWidth=\"1.7976931348623157E308\"" + texts.substring(endPane); File file = new File(targetPath + File.separator + name); TextFileTools.writeFile(file, newFxml, utf8); updateLogs(++count + ": " + file); } return true; } catch (Exception e) { error = name + " - " + e.toString(); return false; } } @Override protected void whenSucceeded() { browse(targetPath); } }; start(task); } /* static */ public static DevTmpController open() { try { DevTmpController controller = (DevTmpController) WindowTools.openStage(Fxmls.DevTmpFxml); controller.requestMouse(); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/ControlDataRowExpression.java
alpha/MyBox/src/main/java/mara/mybox/controller/ControlDataRowExpression.java
package mara.mybox.controller; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.control.CheckBox; import javafx.scene.control.TextArea; import javafx.scene.input.MouseEvent; import mara.mybox.db.data.VisitHistory; import mara.mybox.db.table.TableNodeRowExpression; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.HelpTools; import mara.mybox.fxml.PopTools; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2022-10-15 * @License Apache License Version 2.0 */ public class ControlDataRowExpression extends BaseDataValuesController { @FXML protected TextArea scriptInput; @FXML protected CheckBox wrapCheck; @Override public void setFileType() { setFileType(VisitHistory.FileType.Javascript); } @Override public void initControls() { try { baseName = "DataRowExpression"; valueInput = scriptInput; valueWrapCheck = wrapCheck; valueName = "script"; super.initControls(); } catch (Exception e) { MyBoxLog.error(e); } } public void edit(String script) { if (!checkBeforeNextAction()) { return; } isSettingValues = true; scriptInput.setText(script); isSettingValues = false; valueChanged(true); } @FXML public void scriptAction() { DataSelectJavaScriptController.open(this, scriptInput); } @FXML protected void popExamples(MouseEvent mouseEvent) { if (UserConfig.getBoolean(baseName + "ExamplesPopWhenMouseHovering", false)) { showExamples(mouseEvent); } } @FXML protected void showExamples(Event event) { PopTools.popJavaScriptExamples(this, event, scriptInput, baseName + "Examples", null); } @FXML public void popHelps(Event event) { if (UserConfig.getBoolean("RowExpressionsHelpsPopWhenMouseHovering", false)) { showHelps(event); } } @FXML public void showHelps(Event event) { popEventMenu(event, HelpTools.rowExpressionHelps()); } /* static */ public static DataTreeNodeEditorController open(BaseController parent, String script) { try { DataTreeNodeEditorController controller = DataTreeNodeEditorController.openTable(parent, new TableNodeRowExpression()); ((ControlDataRowExpression) controller.valuesController).edit(script); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/BaseLogsController.java
alpha/MyBox/src/main/java/mara/mybox/controller/BaseLogsController.java
package mara.mybox.controller; import java.util.Date; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.CheckBox; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import mara.mybox.dev.MyBoxLog; import mara.mybox.tools.DateTools; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2022-11-4 * @License Apache License Version 2.0 */ public class BaseLogsController extends BaseController { protected long logsMaxChars, logsTotalLines, logsTotalchars, logsNewlines; protected StringBuffer newLogs; protected long lastLogTime; protected final Object lock = new Object(); @FXML protected TextArea logsTextArea; @FXML protected TextField maxCharsinput; @FXML protected CheckBox verboseCheck; @FXML protected BaseLogsController logsController; @Override public void initValues() { try { super.initValues(); if (logsController != null) { if (logsTextArea == null) { logsTextArea = logsController.logsTextArea; } if (maxCharsinput == null) { maxCharsinput = logsController.maxCharsinput; } if (verboseCheck == null) { verboseCheck = logsController.verboseCheck; } } } catch (Exception e) { MyBoxLog.debug(e); } } @Override public void initControls() { try { super.initControls(); logsMaxChars = UserConfig.getLong("TaskMaxLinesNumber", 5000); if (logsMaxChars <= 0) { logsMaxChars = 5000; } if (maxCharsinput != null) { maxCharsinput.setText(logsMaxChars + ""); maxCharsinput.focusedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { try { if (nv) { return; } long iv = Long.parseLong(maxCharsinput.getText()); if (iv > 0) { logsMaxChars = iv; maxCharsinput.setStyle(null); UserConfig.setLong("TaskMaxLinesNumber", logsMaxChars); } else { maxCharsinput.setStyle(UserConfig.badStyle()); } } catch (Exception e) { maxCharsinput.setStyle(UserConfig.badStyle()); } } }); } if (verboseCheck != null) { verboseCheck.setSelected(UserConfig.getBoolean(interfaceName + "LogVerbose", true)); verboseCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue v, Boolean ov, Boolean nv) { UserConfig.setBoolean(interfaceName + "LogVerbose", verboseCheck.isSelected()); } }); } clearLogs(); } catch (Exception e) { MyBoxLog.debug(e); } } public boolean isLogsVerbose() { return verboseCheck != null ? verboseCheck.isSelected() : false; } @FXML public void clearLogs() { if (logsTextArea == null) { return; } try { synchronized (lock) { newLogs = new StringBuffer(); logsNewlines = 0; logsTotalLines = 0; logsTotalchars = 0; lastLogTime = new Date().getTime(); logsTextArea.setText(""); } } catch (Exception e) { MyBoxLog.debug(e); } } public void initLogs() { if (logsTextArea == null) { return; } if (logsTotalchars > 0) { updateLogs("\n", false, true); } else { clearLogs(); } } public void showLogs(String line) { updateLogs(line, true, true); } public void updateLogs(String line) { updateLogs(line, true, false); } protected void updateLogs(String line, boolean immediate) { updateLogs(line, true, immediate); } public void updateLogs(String line, boolean showTime, boolean immediate) { if (line == null) { return; } if (Platform.isFxApplicationThread()) { handleLogs(line, showTime, immediate); } else { Platform.runLater(() -> { handleLogs(line, showTime, immediate); }); } } protected void handleLogs(String line, boolean showTime, boolean immediate) { if (line == null) { return; } if (logsTextArea == null) { popInformation(line); } else { writeLogs(line, showTime, immediate); } } public void writeLogs(String line, boolean showTime, boolean immediate) { try { synchronized (lock) { if (newLogs == null) { newLogs = new StringBuffer(); } if (showTime) { newLogs.append(DateTools.datetimeToString(new Date())).append(" "); } newLogs.append(line).append("\n"); logsNewlines++; long ctime = new Date().getTime(); if (immediate || logsNewlines > 50 || ctime - lastLogTime > 3000) { String s = newLogs.toString(); logsTotalchars += s.length(); logsTextArea.appendText(s); newLogs = new StringBuffer(); logsTotalLines += logsNewlines; logsNewlines = 0; lastLogTime = ctime; int extra = (int) (logsTotalchars - logsMaxChars); if (extra > 0) { logsTextArea.deleteText(0, extra); logsTotalchars = logsMaxChars; } logsTextArea.selectEnd(); logsTextArea.deselect(); } } } catch (Exception e) { MyBoxLog.debug(e); } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/DataTreeImportController.java
alpha/MyBox/src/main/java/mara/mybox/controller/DataTreeImportController.java
package mara.mybox.controller; import java.io.File; import java.sql.Connection; import java.util.List; import java.util.Stack; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.control.RadioButton; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleGroup; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import mara.mybox.db.Database; import mara.mybox.db.DerbyBase; import mara.mybox.db.data.DataNode; import mara.mybox.db.data.DataNodeTag; import mara.mybox.db.data.DataTag; import mara.mybox.db.data.VisitHistory; import mara.mybox.db.table.BaseNodeTable; import mara.mybox.db.table.TableDataNodeTag; import mara.mybox.db.table.TableDataTag; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.fxml.HelpTools; import mara.mybox.fxml.WindowTools; import mara.mybox.tools.FileTools; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; import org.xml.sax.Attributes; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; /** * @Author Mara * @CreateDate 2022-3-9 * @License Apache License Version 2.0 */ public class DataTreeImportController extends BaseBatchFileController { protected BaseDataTreeController dataController; protected BaseNodeTable nodeTable; protected String dataName, chainName; protected TableDataNodeTag nodeTagsTable; protected TableDataTag tagTable; protected DataNode parentNode; protected boolean isExample; @FXML protected ToggleGroup existedGroup; @FXML protected RadioButton updateRadio, skipRadio, createRadio; @FXML protected Label parentLabel, formatLabel; @Override public void setFileType() { setFileType(VisitHistory.FileType.XML); } public void setParamters(BaseDataTreeController controller, DataNode node) { try { if (controller == null) { close(); return; } dataController = controller; setData(dataController.nodeTable, node != null ? node : dataController.rootNode, node); } catch (Exception e) { MyBoxLog.error(e); } } public void setData(BaseNodeTable table, DataNode parent, DataNode node) { try { if (table == null) { close(); return; } nodeTable = table; tagTable = new TableDataTag(nodeTable); nodeTagsTable = new TableDataNodeTag(nodeTable); dataName = nodeTable.getTableName(); parentNode = parent; if (parentNode == null) { parentNode = nodeTable.getRoot(); } if (parentNode == null) { close(); return; } baseName = baseName + "_" + dataName; baseTitle = dataName + " - " + message("Import") + " : " + parentNode.getTitle(); chainName = parentNode.shortDescription(); setControls(); } catch (Exception e) { MyBoxLog.error(e); } } public void setControls() { try { setTitle(baseTitle); parentLabel.setText(message("ParentNode") + ": " + chainName); String existed = UserConfig.getString(baseName + "Existed", "Update"); if ("Create".equalsIgnoreCase(existed)) { createRadio.setSelected(true); } else if ("Skip".equalsIgnoreCase(existed)) { skipRadio.setSelected(true); } else { updateRadio.setSelected(true); } existedGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> v, Toggle ov, Toggle bv) { if (isSettingValues) { return; } if (createRadio.isSelected()) { UserConfig.setString(baseName + "Existed", "Create"); } else if (skipRadio.isSelected()) { UserConfig.setString(baseName + "Existed", "Skip"); } else { UserConfig.setString(baseName + "Existed", "Update"); } } }); } catch (Exception e) { MyBoxLog.error(e); } } public void importExamples(BaseDataTreeController controller, DataNode node) { setParamters(controller, node); File file = nodeTable.exampleFile(); isSettingValues = true; updateRadio.setSelected(true); isSettingValues = false; isExample = true; startFile(file); } public void importExamples(BaseNodeTable nodeTable, DataNode node, File inFile) { setData(nodeTable, node, node); File file = inFile; if (file == null) { file = nodeTable.exampleFile(); } isSettingValues = true; updateRadio.setSelected(true); miaoCheck.setSelected(false); isSettingValues = false; isExample = true; startFile(file); } @Override public String handleFile(FxTask currentTask, File srcFile, File targetPath) { File validFile = FileTools.removeBOM(currentTask, srcFile); if (validFile == null) { return message("Failed"); } try { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); saxParser.parse(validFile, new DataTreeParser()); return totalItemsHandled > 0 ? message("Successful") : message("Failed"); } catch (Exception e) { return e.toString(); } } class DataTreeParser extends DefaultHandler { protected Connection conn; protected String currentTag; protected StringBuilder value; protected DataNode dataNode; protected DataTag dataTag; protected List<String> columnNames; protected long parentid; protected Stack<Long> parentStack; protected float orderNumber; protected Stack<Float> orderStack; @Override public void startDocument() { try { conn = DerbyBase.getConnection(); conn.setAutoCommit(false); columnNames = nodeTable.dataColumnNames(); totalItemsHandled = 0; parentStack = new Stack<>(); parentid = parentNode.getNodeid(); orderStack = new Stack<>(); orderNumber = 0f; value = new StringBuilder(); showLogs(message("ParentNode") + ": " + chainName); } catch (Exception e) { showLogs(e.toString()); } } @Override public void startElement(String uri, String localName, String qName, Attributes attrs) { try { if (qName == null || qName.isBlank()) { return; } currentTag = qName; switch (currentTag) { case "TreeNode": dataNode = new DataNode(); dataNode.setParentid(parentid).setOrderNumber(++orderNumber); parentStack.push(parentid); orderStack.push(orderNumber); // if (isLogsVerbose()) { // showLogs("New node starting. parentid= " + parentid + ", and it is pushed in stack"); // } break; } value.setLength(0); } catch (Exception e) { showLogs(e.toString()); } } @Override public void characters(char ch[], int start, int length) { try { if (ch == null) { return; } value.append(ch, start, length); } catch (Exception e) { showLogs(e.toString()); } } @Override public void endElement(String uri, String localName, String qName) { try { if (dataNode == null || qName == null || qName.isBlank()) { return; } String s = value.toString().trim(); boolean written = false; switch (qName) { case "title": dataNode.setTitle(s); break; case "NodeTag": if (!s.isBlank()) { dataTag = tagTable.queryTag(conn, s); if (dataTag == null) { dataTag = DataTag.create().setTag(s); dataTag = tagTable.insertData(conn, dataTag); } nodeTagsTable.insertData(conn, new DataNodeTag(dataNode.getNodeid(), dataTag.getTagid())); written = true; } break; case "NodeAttributes": dataNode = saveNode(conn, dataNode); if (isLogsVerbose()) { showLogs("New node saved. parentid=" + dataNode.getParentid() + " nodeid=" + dataNode.getNodeid() + " title=" + dataNode.getTitle()); } parentid = dataNode.getNodeid(); orderNumber = 0f; written = true; // if (isLogsVerbose()) { // showLogs("Now parentid " + parentid); // } break; case "TreeNode": parentid = parentStack.pop(); orderNumber = orderStack.pop(); // if (isLogsVerbose()) { // showLogs("The node ended. " + parentid + " is popped from stack"); // } break; default: if (columnNames.contains(qName)) { dataNode.setValue(qName, nodeTable.importValue(nodeTable.column(qName), s)); // if (isLogsVerbose()) { // showLogs(qName + "=" + s); // } } } if (written && (++totalItemsHandled % Database.BatchSize == 0)) { conn.commit(); } } catch (Exception e) { showLogs(e.toString()); } } public DataNode saveNode(Connection conn, DataNode node) { try { if (createRadio.isSelected()) { return nodeTable.insertData(conn, node); } DataNode existed = nodeTable.find(conn, node.getParentid(), node.getTitle()); if (existed == null) { return nodeTable.insertData(conn, node); } if (skipRadio.isSelected()) { return node; } return nodeTable.updateData(conn, existed); } catch (Exception e) { MyBoxLog.error(e); return null; } } @Override public void endDocument() { try { if (conn != null) { conn.commit(); conn.close(); } } catch (Exception e) { showLogs(e.toString()); } } @Override public void warning(SAXParseException e) { showLogs(e.toString()); } @Override public void error(SAXParseException e) { showLogs(e.toString()); } @Override public void fatalError(SAXParseException e) { showLogs(e.toString()); } } @Override public void afterTask(boolean ok) { super.afterTask(ok); if (WindowTools.isRunning(dataController)) { dataController.refreshNode(parentNode, true); if (isExample) { close(); } } } @FXML public void exampleData() { File file = nodeTable.exampleFile(); if (file == null) { file = nodeTable.exampleFile("TextTree"); } XmlEditorController.open(file); } @FXML public void manageAction() { DataTreeController.open(null, false, nodeTable); setIconified(true); } @FXML public void aboutTreeInformation() { openHtml(HelpTools.aboutTreeInformation()); } @Override public boolean needStageVisitHistory() { return false; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/BaseDataTreeHandleController.java
alpha/MyBox/src/main/java/mara/mybox/controller/BaseDataTreeHandleController.java
package mara.mybox.controller; import javafx.fxml.FXML; import mara.mybox.db.table.BaseNodeTable; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.WindowTools; /** * @Author Mara * @CreateDate 2022-3-14 * @License Apache License Version 2.0 */ public abstract class BaseDataTreeHandleController extends BaseTaskController { protected BaseDataTreeController dataController; protected BaseNodeTable nodeTable; protected String dataName, chainName; public void setParameters(BaseDataTreeController parent) { try { if (parent == null) { close(); return; } dataController = parent; parentController = parent; nodeTable = dataController.nodeTable; dataName = nodeTable.getDataName(); baseName = baseName + "_" + dataName; } catch (Exception e) { MyBoxLog.error(e); } } public boolean dataRunning() { return WindowTools.isRunning(dataController); } public boolean parentRunning() { return WindowTools.isRunning(parentController); } @FXML public void manageAction() { DataTreeController.open(null, false, nodeTable); setIconified(true); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/ImageRoundBatchController.java
alpha/MyBox/src/main/java/mara/mybox/controller/ImageRoundBatchController.java
package mara.mybox.controller; import java.awt.image.BufferedImage; import java.io.File; import java.util.List; import javafx.fxml.FXML; import mara.mybox.image.tools.BufferedImageTools; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.image.ImageDemos; import mara.mybox.fxml.FxTask; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2018-9-25 * @License Apache License Version 2.0 */ public class ImageRoundBatchController extends BaseImageEditBatchController { @FXML protected ControlImageRound roundController; public ImageRoundBatchController() { baseTitle = message("ImageBatch") + " - " + message("Round"); } @Override public boolean makeMoreParameters() { return super.makeMoreParameters() && roundController.pickValues(); } @Override protected BufferedImage handleImage(FxTask currentTask, BufferedImage source) { try { int w, h; if (roundController.wPercenatge()) { w = source.getWidth() * roundController.wPer / 100; } else { w = roundController.w; } if (roundController.hPercenatge()) { h = source.getHeight() * roundController.hPer / 100; } else { h = roundController.h; } BufferedImage target = BufferedImageTools.setRound(currentTask, source, w, h, roundController.awtColor()); return target; } catch (Exception e) { MyBoxLog.error(e); return null; } } @Override public void makeDemoFiles(FxTask currentTask, List<String> files, File demoFile, BufferedImage demoImage) { ImageDemos.round(currentTask, files, demoImage, roundController.awtColor(), demoFile); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/PptSplitController.java
alpha/MyBox/src/main/java/mara/mybox/controller/PptSplitController.java
package mara.mybox.controller; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.text.MessageFormat; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import javafx.beans.binding.Bindings; import javafx.fxml.FXML; import mara.mybox.db.data.VisitHistory; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.tools.FileNameTools; import static mara.mybox.value.Languages.message; import org.apache.poi.hslf.usermodel.HSLFShape; import org.apache.poi.hslf.usermodel.HSLFSlide; import org.apache.poi.hslf.usermodel.HSLFSlideShow; import org.apache.poi.sl.usermodel.SlideShow; import org.apache.poi.sl.usermodel.SlideShowFactory; import org.apache.poi.xslf.usermodel.XMLSlideShow; import org.apache.poi.xslf.usermodel.XSLFSlide; /** * @Author Mara * @CreateDate 2021-5-20 * @License Apache License Version 2.0 */ public class PptSplitController extends BaseBatchFileController { @FXML protected ControlSplit splitController; public PptSplitController() { baseTitle = message("PptSplit"); } @Override public void setFileType() { setFileType(VisitHistory.FileType.PPTS, VisitHistory.FileType.PPTS); } @Override public void initControls() { try { super.initControls(); splitController.setParameters(this); startButton.disableProperty().unbind(); startButton.disableProperty().bind( Bindings.isEmpty(tableView.getItems()) .or(splitController.valid) ); } catch (Exception e) { MyBoxLog.error(e); } } @Override public String handleFile(FxTask currentTask, File srcFile, File targetPath) { try { int total; try (SlideShow ppt = SlideShowFactory.create(srcFile)) { total = ppt.getSlides().size(); } catch (Exception e) { MyBoxLog.error(e); return e.toString(); } if (currentTask == null || !currentTask.isWorking()) { return message("Canceled"); } targetFilesCount = 0; targetFiles = new LinkedHashMap<>(); String suffix = FileNameTools.ext(srcFile.getName()); switch (splitController.splitType) { case Size: splitByPagesSize(currentTask, srcFile, targetPath, total, suffix, splitController.size); break; case Number: splitByPagesSize(currentTask, srcFile, targetPath, total, suffix, splitController.size(total, splitController.number)); break; case List: splitByList(currentTask, srcFile, targetPath, suffix); break; default: break; } if (currentTask == null || !currentTask.isWorking()) { return message("Canceled"); } updateInterface("CompleteFile"); totalItemsHandled += total; return MessageFormat.format(message("HandlePagesGenerateNumber"), totalItemsHandled, targetFilesCount); } catch (Exception e) { MyBoxLog.error(e); return e.toString(); } } protected void splitByPagesSize(FxTask currentTask, File srcFile, File targetPath, int total, String suffix, int pagesSize) { try { int start = 0, end, index = 0; boolean pptx = "pptx".equalsIgnoreCase(suffix); while (start < total) { if (currentTask == null || !currentTask.isWorking()) { return; } end = start + pagesSize; targetFile = makeTargetFile(srcFile, ++index, suffix, targetPath); if (pptx) { if (savePPTX(currentTask, srcFile, targetFile, start, end)) { targetFileGenerated(targetFile); } } else { if (savePPT(currentTask, srcFile, targetFile, start, end)) { targetFileGenerated(targetFile); } } start = end; } } catch (Exception e) { MyBoxLog.error(e); } } protected void splitByList(FxTask currentTask, File srcFile, File targetPath, String suffix) { try { int start = 0, end, index = 0; boolean pptx = "pptx".equalsIgnoreCase(suffix); List<Integer> list = splitController.list; for (int i = 0; i < list.size();) { if (currentTask == null || !currentTask.isWorking()) { return; } // To user, both start and end are 1-based. To codes, both start and end are 0-based. // To user, both start and end are included. To codes, start is included while end is excluded. start = list.get(i++) - 1; end = list.get(i++); targetFile = makeTargetFile(srcFile, ++index, suffix, targetPath); if (pptx) { if (savePPTX(currentTask, srcFile, targetFile, start, end)) { targetFileGenerated(targetFile); } } else { if (savePPT(currentTask, srcFile, targetFile, start, end)) { targetFileGenerated(targetFile); } } } } catch (Exception e) { MyBoxLog.error(e); } } public File makeTargetFile(File srcFile, int index, String ext, File targetPath) { try { String filePrefix = FileNameTools.prefix(srcFile.getName()); String splitPrefix = filePrefix + "_" + index; String splitSuffix = (ext.startsWith(".") ? "" : ".") + ext; File slidePath = targetPath; if (targetSubdirCheck.isSelected()) { slidePath = new File(targetPath, filePrefix); } return makeTargetFile(splitPrefix, splitSuffix, slidePath); } catch (Exception e) { MyBoxLog.error(e); return null; } } // Include start, and exlucde end. Both start and end are 0-based protected boolean savePPT(FxTask currentTask, File srcFile, File targetFile, int start, int end) { try (HSLFSlideShow ppt = new HSLFSlideShow(new FileInputStream(srcFile))) { List<HSLFSlide> slides = ppt.getSlides(); int total = slides.size(); if (start > end || start >= total) { return false; } if (currentTask == null || !currentTask.isWorking()) { return false; } // https://stackoverflow.com/questions/51419421/split-pptx-slideshow-with-apache-poi // Need delete shapes for ppt for (int i = total - 1; i >= end; i--) { if (currentTask == null || !currentTask.isWorking()) { return false; } HSLFSlide slide = slides.get(i); Iterator<HSLFShape> iterator = slide.iterator(); if (iterator != null) { while (iterator.hasNext()) { if (currentTask == null || !currentTask.isWorking()) { return false; } slide.removeShape(iterator.next()); } } ppt.removeSlide(i); } for (int i = 0; i < start; i++) { if (currentTask == null || !currentTask.isWorking()) { return false; } HSLFSlide slide = slides.get(0); Iterator<HSLFShape> iterator = slide.iterator(); if (iterator != null) { while (iterator.hasNext()) { if (currentTask == null || !currentTask.isWorking()) { return false; } slide.removeShape(iterator.next()); } } ppt.removeSlide(0); } if (currentTask == null || !currentTask.isWorking()) { return false; } ppt.write(targetFile); return targetFile.exists(); } catch (Exception e) { MyBoxLog.error(e); return false; } } // Include start, and exlucde end. Both start and end are 0-based protected boolean savePPTX(FxTask currentTask, File srcFile, File targetFile, int start, int end) { try (XMLSlideShow ppt = new XMLSlideShow(new FileInputStream(srcFile)); FileOutputStream out = new FileOutputStream(targetFile)) { List<XSLFSlide> slides = ppt.getSlides(); if (currentTask == null || !currentTask.isWorking()) { return false; } int total = slides.size(); // Looks need not remove shapes for pptx in current version for (int i = total - 1; i >= end; i--) { if (currentTask == null || !currentTask.isWorking()) { return false; } ppt.removeSlide(i); } for (int i = 0; i < start; i++) { if (currentTask == null || !currentTask.isWorking()) { return false; } ppt.removeSlide(0); } if (currentTask == null || !currentTask.isWorking()) { return false; } ppt.write(out); } catch (Exception e) { MyBoxLog.error(e); return false; } return targetFile != null && targetFile.exists(); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/ImageScopeViewsController.java
alpha/MyBox/src/main/java/mara/mybox/controller/ImageScopeViewsController.java
package mara.mybox.controller; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.Tab; import javafx.scene.image.Image; import javafx.scene.input.KeyEvent; import javafx.scene.layout.VBox; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.fxml.WindowTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2023-11-12 * @License Apache License Version 2.0 */ public class ImageScopeViewsController extends BaseChildController { protected ControlImageScope scopeController; @FXML protected ControlImageView selectedController, sourceController, maskController; @FXML protected Tab selectedTab, sourceTab, maskTab; @FXML protected VBox selectedBox, pixelsBox, sourceBox; public ImageScopeViewsController() { baseTitle = message("Scope"); } protected void setParameters(ControlImageScope parent) { try { scopeController = parent; scopeController.showNotify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { refreshAction(); } }); refreshAction(); } catch (Exception e) { MyBoxLog.error(e); } } @FXML @Override public void refreshAction() { refreshSource(); refreshMask(); refreshScope(); } public Image srcImage() { return scopeController.srcImage(); } @FXML public void refreshSource() { Image srcImage = srcImage(); if (srcImage == null) { return; } sourceController.loadImage(srcImage); } @FXML public void refreshMask() { Image srcImage = srcImage(); if (srcImage == null) { return; } maskController.loadImage(scopeController.imageView.getImage()); } @FXML public void refreshScope() { Image srcImage = srcImage(); if (srcImage == null) { return; } if (task != null) { task.cancel(); } task = new FxSingletonTask<Void>(this) { private Image selectedScope; @Override protected boolean handle() { try { selectedScope = scopeController.scopeImage(this); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } @Override protected void whenSucceeded() { selectedController.loadImage(selectedScope); } }; start(task, selectedBox); } @Override public boolean handleKeyEvent(KeyEvent event) { Tab tab = tabPane.getSelectionModel().getSelectedItem(); if (tab == sourceTab) { if (sourceController.handleKeyEvent(event)) { return true; } } else if (tab == selectedTab) { if (selectedController.handleKeyEvent(event)) { return true; } } else if (tab == maskTab) { if (maskController.handleKeyEvent(event)) { return true; } } return super.handleKeyEvent(event); } /* static methods */ public static ImageScopeViewsController open(ControlImageScope parent) { try { if (parent == null || !parent.isShowing()) { return null; } ImageScopeViewsController controller = (ImageScopeViewsController) WindowTools.referredTopStage( parent, Fxmls.ImageScopeViewsFxml); controller.setParameters(parent); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/ControlData2DMultipleLinearRegressionTable.java
alpha/MyBox/src/main/java/mara/mybox/controller/ControlData2DMultipleLinearRegressionTable.java
package mara.mybox.controller; import java.util.ArrayList; import java.util.List; import javafx.fxml.FXML; import mara.mybox.db.data.ColumnDefinition.ColumnType; import mara.mybox.db.data.Data2DColumn; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.WindowTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2022-4-21 * @License Apache License Version 2.0 */ public class ControlData2DMultipleLinearRegressionTable extends ControlData2DSimpleLinearRegressionTable { @Override public List<Data2DColumn> createColumns() { try { List<Data2DColumn> cols = new ArrayList<>(); cols.add(new Data2DColumn(message("DependentVariable"), ColumnType.String, 100)); cols.add(new Data2DColumn(message("IndependentVariable"), ColumnType.String, 200)); cols.add(new Data2DColumn(message("AdjustedRSquared"), ColumnType.Double, 80)); cols.add(new Data2DColumn(message("CoefficientOfDetermination"), ColumnType.Double, 80)); cols.add(new Data2DColumn(message("Coefficients"), ColumnType.Double, 80)); cols.add(new Data2DColumn(message("Intercept"), ColumnType.Double, 100)); return cols; } catch (Exception e) { MyBoxLog.error(e); return null; } } @FXML @Override public void editAction() { if (regressController == null) { return; } List<String> selected = selected(); if (selected == null) { Data2DMultipleLinearRegressionController.open(regressController.dataController); } else { try { Data2DMultipleLinearRegressionController controller = (Data2DMultipleLinearRegressionController) WindowTools .referredStage(regressController.parentController, Fxmls.Data2DMultipleLinearRegressionFxml); controller.categoryColumnSelector.setValue(selected.get(1)); List<Integer> cols = new ArrayList<>(); List<String> names = ((Data2DMultipleLinearRegressionCombinationController) regressController).namesMap.get(selected.get(2)); for (String name : names) { cols.add(regressController.data2D.colOrder(name)); } controller.checkedColsIndices = cols; controller.interceptCheck.setSelected(regressController.interceptCheck.isSelected()); controller.cloneOptions(regressController); controller.setParameters(regressController.dataController); controller.startAction(); controller.requestMouse(); } catch (Exception e) { MyBoxLog.error(e); } } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/Data2DStatisticController.java
alpha/MyBox/src/main/java/mara/mybox/controller/Data2DStatisticController.java
package mara.mybox.controller; import java.util.List; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.ComboBox; import javafx.scene.layout.FlowPane; import javafx.scene.layout.VBox; import mara.mybox.calculation.DescriptiveStatistic; import mara.mybox.calculation.DescriptiveStatistic.StatisticObject; import mara.mybox.calculation.DoubleStatistic; import mara.mybox.data2d.DataTable; import mara.mybox.data2d.TmpTable; import mara.mybox.data2d.tools.Data2DConvertTools; import mara.mybox.data2d.writer.Data2DWriter; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.fxml.FxTask; import mara.mybox.fxml.WindowTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2021-12-12 * @License Apache License Version 2.0 */ public class Data2DStatisticController extends BaseData2DTaskTargetsController { protected DescriptiveStatistic calculation; protected int categorysCol; protected String selectedCategory; @FXML protected ControlStatisticSelection statisticController; @FXML protected VBox dataOptionsBox; @FXML protected FlowPane categoryColumnsPane; @FXML protected ComboBox<String> categoryColumnSelector; public Data2DStatisticController() { baseTitle = message("DescriptiveStatistics"); } @Override public void initOptions() { try { super.initOptions(); categoryColumnSelector.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue ov, String oldValue, String newValue) { checkOptions(); } }); } catch (Exception e) { MyBoxLog.error(e); } } @Override public void dataChanged() { try { super.dataChanged(); List<String> names = data2D.columnNames(); if (names == null || names.isEmpty()) { return; } isSettingValues = true; selectedCategory = categoryColumnSelector.getSelectionModel().getSelectedItem(); names.add(0, message("RowNumber")); categoryColumnSelector.getItems().setAll(names); if (selectedCategory != null && names.contains(selectedCategory)) { categoryColumnSelector.setValue(selectedCategory); } else { categoryColumnSelector.getSelectionModel().select(0); } isSettingValues = false; } catch (Exception e) { MyBoxLog.error(e); } } @Override public void objectChanged() { super.objectChanged(); if (rowsRadio.isSelected()) { if (!dataOptionsBox.getChildren().contains(categoryColumnsPane)) { dataOptionsBox.getChildren().add(1, categoryColumnsPane); } } else { if (dataOptionsBox.getChildren().contains(categoryColumnsPane)) { dataOptionsBox.getChildren().remove(categoryColumnsPane); } } } @Override public boolean checkOptions() { try { if (!super.checkOptions()) { return false; } categorysCol = -1; if (rowsRadio.isSelected()) { selectedCategory = categoryColumnSelector.getSelectionModel().getSelectedItem(); if (selectedCategory != null && categoryColumnSelector.getSelectionModel().getSelectedIndex() != 0) { categorysCol = data2D.colOrder(selectedCategory); } } calculation = statisticController.pickValues() .setScale(scale) .setInvalidAs(invalidAs) .setTaskController(this) .setData2D(data2D) .setColsIndices(checkedColsIndices) .setColsNames(checkedColsNames) .setCategoryName(categorysCol >= 0 ? selectedCategory : null); switch (objectType) { case Rows: calculation.setStatisticObject(StatisticObject.Rows); break; case All: calculation.setStatisticObject(StatisticObject.All); break; default: calculation.setStatisticObject(StatisticObject.Columns); break; } UserConfig.setBoolean(baseName + "SkipNonnumeric", skipInvalidRadio.isSelected()); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } @Override protected void startOperation() { try { if (!calculation.prepare()) { return; } data2D.resetStatistic(); if (isAllPages()) { switch (objectType) { case Rows: handleAllTask(); break; case All: handleAllByAllTask(); break; default: handleAllByColumnsTask(); break; } } else { handleRowsTask(); } } catch (Exception e) { MyBoxLog.debug(e); } } @Override public boolean handleRows() { List<Integer> colsIndices = checkedColsIndices; if (rowsRadio.isSelected() && categorysCol >= 0) { colsIndices.add(0, categorysCol); } if (!calculation.statisticData(sourceController.rowsFiltered(colsIndices, rowsRadio.isSelected() && categorysCol < 0))) { return false; } outputColumns = calculation.getOutputColumns(); outputData = calculation.getOutputData(); return true; } public void handleAllByColumnsTask() { if (task != null) { task.cancel(); } taskSuccessed = false; task = new FxSingletonTask<Void>(this) { @Override protected boolean handle() { try { data2D.startTask(this, filterController.filter); calculation.setTask(this); if (calculation.needStored()) { TmpTable tmpTable = TmpTable.toStatisticTable(data2D, this, checkedColsIndices, invalidAs); if (tmpTable == null) { return false; } tmpTable.startTask(this, null); calculation.setData2D(tmpTable) .setColsIndices(tmpTable.columnIndices().subList(1, tmpTable.columnsNumber())) .setColsNames(tmpTable.columnNames().subList(1, tmpTable.columnsNumber())); taskSuccessed = calculation.statisticAllByColumns(); tmpTable.stopFilter(); tmpTable.drop(); } else { taskSuccessed = calculation.statisticAllByColumnsWithoutStored(); } data2D.stopFilter(); return taskSuccessed; } catch (Exception e) { error = e.toString(); return false; } } @Override protected void whenSucceeded() { outputColumns = calculation.getOutputColumns(); outputData = calculation.getOutputData(); if (targetController.inTable()) { updateTable(); } else { outputRowsToExternal(); } } @Override protected void finalAction() { super.finalAction(); calculation.setTask(null); closeTask(ok); } }; start(task, false); } public void handleAllByAllTask() { if (task != null) { task.cancel(); } taskSuccessed = false; task = new FxSingletonTask<Void>(this) { @Override protected boolean handle() { try { data2D.startTask(this, filterController.filter); calculation.setTask(this); if (calculation.needStored()) { DataTable dataTable = Data2DConvertTools.singleColumn(this, data2D, checkedColsIndices); if (dataTable == null) { return false; } dataTable.startTask(this, null); calculation.setTask(this); calculation.setData2D(dataTable) .setColsIndices(dataTable.columnIndices().subList(1, 2)) .setColsNames(dataTable.columnNames().subList(1, 2)); taskSuccessed = calculation.statisticAllByColumns(); } else { DoubleStatistic statisticData = data2D.statisticByAllWithoutStored(checkedColsIndices, calculation); if (statisticData == null) { return false; } calculation.statisticByColumnsWrite(statisticData); taskSuccessed = true; } data2D.stopFilter(); return taskSuccessed; } catch (Exception e) { error = e.toString(); return false; } } @Override protected void whenSucceeded() { outputColumns = calculation.getOutputColumns(); outputData = calculation.getOutputData(); if (targetController.inTable()) { updateTable(); } else { outputRowsToExternal(); } } @Override protected void finalAction() { super.finalAction(); calculation.setTask(null); closeTask(ok); } }; start(task, false); } @Override public boolean handleAllData(FxTask currentTask, Data2DWriter writer) { List<Integer> colsIndices = checkedColsIndices; if (rowsRadio.isSelected() && categorysCol >= 0) { colsIndices.add(0, categorysCol); } return data2D.statisticByRows(currentTask, writer, calculation.getOutputNames(), colsIndices, calculation); } /* static */ public static Data2DStatisticController open(BaseData2DLoadController tableController) { try { Data2DStatisticController controller = (Data2DStatisticController) WindowTools.referredStage( tableController, Fxmls.Data2DStatisticFxml); controller.setParameters(tableController); controller.requestMouse(); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/ImageConvolutionBatchController.java
alpha/MyBox/src/main/java/mara/mybox/controller/ImageConvolutionBatchController.java
package mara.mybox.controller; import java.awt.image.BufferedImage; import javafx.fxml.FXML; import mara.mybox.image.data.ImageConvolution; import mara.mybox.db.data.ConvolutionKernel; import mara.mybox.fxml.FxTask; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2018-9-23 * @License Apache License Version 2.0 */ public class ImageConvolutionBatchController extends BaseImageEditBatchController { protected ConvolutionKernel kernel; @FXML protected ControlImageConvolution convolutionController; public ImageConvolutionBatchController() { baseTitle = message("ImageBatch") + " - " + message("Convolution"); } @Override public boolean makeMoreParameters() { if (!super.makeMoreParameters()) { return false; } kernel = convolutionController.pickValues(); return kernel != null; } @Override protected BufferedImage handleImage(FxTask currentTask, BufferedImage source) { try { ImageConvolution convolution = ImageConvolution.create(); convolution.setImage(source).setKernel(kernel).setTask(currentTask); return convolution.start(); } catch (Exception e) { displayError(e.toString()); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/SvgPathController.java
alpha/MyBox/src/main/java/mara/mybox/controller/SvgPathController.java
package mara.mybox.controller; import javafx.fxml.FXML; import javafx.scene.control.TreeItem; import mara.mybox.data.DoublePath; import mara.mybox.data.XmlTreeNode; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.WindowTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; import org.w3c.dom.Element; /** * @Author Mara * @CreateDate 2024-1-2 * @License Apache License Version 2.0 */ public class SvgPathController extends BaseSvgShapeController { protected DoublePath initData; @FXML protected ControlPath2D pathController; @Override public void initMore() { try { shapeName = message("SVGPath"); anchorCheck.setSelected(true); showAnchors = true; popShapeMenu = true; } catch (Exception e) { MyBoxLog.error(e); } } public void setInitData(DoublePath initData) { this.initData = initData; } @Override public boolean afterImageLoaded() { try { if (!super.afterImageLoaded()) { return false; } if (initData != null) { loadSvgPath(initData); initData = null; } return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } @Override public boolean elementToShape(Element node) { try { String d = node.getAttribute("d"); maskPathData = new DoublePath(this, d); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } @Override public void showShape() { showMaskPath(); } @Override public void setShapeInputs() { if (maskPathData != null) { pathController.loadPath(maskPathData.getContent()); } else { pathController.loadPath(null); } } @Override public boolean shape2Element() { try { if (maskPathData == null) { return false; } if (shapeElement == null) { shapeElement = doc.createElement("path"); } shapeElement.setAttribute("d", maskPathData.getContent()); return true; } catch (Exception e) { MyBoxLog.error(e); } return false; } @Override public boolean pickShape() { try { if (!pathController.pickValue()) { return false; } maskPathData.setContent(pathController.getText()); maskPathData.setSegments(pathController.getSegments()); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } @FXML @Override public boolean withdrawAction() { if (imageView == null || imageView.getImage() == null) { return false; } pathController.removeLastItem(); goShape(); return true; } @FXML @Override public void clearAction() { if (imageView == null || imageView.getImage() == null) { return; } pathController.clear(); goShape(); } /* static */ public static SvgPathController drawShape(SvgEditorController editor, TreeItem<XmlTreeNode> item, Element element) { try { if (editor == null || item == null) { return null; } SvgPathController controller = (SvgPathController) WindowTools.childStage( editor, Fxmls.SvgPathFxml); controller.setParameters(editor, item, element); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static SvgPathController loadPath(SvgEditorController editor, TreeItem<XmlTreeNode> item, DoublePath pathData) { try { if (editor == null || item == null) { return null; } SvgPathController controller = (SvgPathController) WindowTools.childStage( editor, Fxmls.SvgPathFxml); controller.setInitData(pathData); controller.setParameters(editor, item, null); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/MyBoxLanguagesController.java
alpha/MyBox/src/main/java/mara/mybox/controller/MyBoxLanguagesController.java
package mara.mybox.controller; import java.io.File; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.CheckBox; import javafx.scene.control.Label; import javafx.scene.control.ListView; import javafx.scene.control.MenuItem; import javafx.scene.control.SelectionMode; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.control.Tooltip; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.MouseEvent; import javafx.scene.layout.Region; import javafx.stage.Stage; import javafx.util.Callback; import javafx.util.converter.DefaultStringConverter; import mara.mybox.controller.MyBoxLanguagesController.LanguageItem; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.fxml.PopTools; import mara.mybox.fxml.WindowTools; import mara.mybox.fxml.cell.TableAutoCommitCell; import mara.mybox.fxml.style.NodeStyleTools; import mara.mybox.tools.ConfigTools; import mara.mybox.tools.FileDeleteTools; import mara.mybox.value.AppVariables; import static mara.mybox.value.AppVariables.useChineseWhenBlankTranslation; import mara.mybox.value.Languages; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2019-12-27 * @License Apache License Version 2.0 */ public class MyBoxLanguagesController extends BaseTableViewController<LanguageItem> { protected String langName; protected boolean changed; @FXML protected ListView<String> listView; @FXML protected TableColumn<LanguageItem, String> keyColumn, englishColumn, chineseColumn, valueColumn; @FXML protected Label langLabel; @FXML protected Button addLangButton, useLangButton, deleteLangButton, editLangButton; @FXML protected CheckBox chineseCheck; public MyBoxLanguagesController() { baseTitle = message("ManageLanguages"); TipsLabelKey = "MyBoxLanguagesTips"; } @Override public void initControls() { try { super.initControls(); chineseCheck.selectedProperty().addListener(new ChangeListener() { @Override public void changed(ObservableValue ov, Object t, Object t1) { useChineseWhenBlankTranslation = chineseCheck.isSelected(); UserConfig.setBoolean("UseChineseWhenBlankTranslation", useChineseWhenBlankTranslation); } }); chineseCheck.setSelected(useChineseWhenBlankTranslation); listView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); listView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() { @Override public void changed(ObservableValue ov, Object t, Object t1) { checkListSelected(); } }); listView.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { if (event.getClickCount() > 1) { editLang(); } } }); refreshLang(); checkListSelected(); changed = false; } catch (Exception e) { MyBoxLog.error(e); } } @Override public void setControlsStyle() { try { super.setControlsStyle(); NodeStyleTools.setTooltip(useLangButton, new Tooltip(message("SetAsInterfaceLanguage"))); NodeStyleTools.setTooltip(editLangButton, new Tooltip(message("Edit") + "\n" + message("DoubleClick"))); NodeStyleTools.setTooltip(chineseCheck, new Tooltip(message("BlankAsChinese"))); } catch (Exception e) { MyBoxLog.error(e); } } /* Languages List */ @FXML public void refreshLang() { try { isSettingValues = true; listView.getItems().clear(); listView.getItems().addAll(Languages.userLanguages()); isSettingValues = false; } catch (Exception e) { MyBoxLog.error(e); } } @FXML public void addLang() { if (changed) { Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle(getTitle()); alert.setHeaderText(getTitle()); alert.setContentText(Languages.message("NeedSaveBeforeAction")); alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE); ButtonType buttonSave = new ButtonType(Languages.message("Save")); ButtonType buttonNotSave = new ButtonType(Languages.message("NotSave")); ButtonType buttonCancel = new ButtonType(Languages.message("Cancel")); alert.getButtonTypes().setAll(buttonSave, buttonNotSave, buttonCancel); Stage stage = (Stage) alert.getDialogPane().getScene().getWindow(); stage.setAlwaysOnTop(true); stage.toFront(); Optional<ButtonType> result = alert.showAndWait(); if (result == null || !result.isPresent()) { return; } if (result.get() == buttonSave) { saveAction(); return; } else if (result.get() == buttonCancel) { return; } } String name = PopTools.askValue(getTitle(), message("InputLanguageComments"), message("InputLanguageName"), null); if (name == null || name.isBlank()) { return; } if ("en".equalsIgnoreCase(name) || "zh".equalsIgnoreCase(name) || name.startsWith("en_") || name.startsWith("zh_")) { popError(message("InputLanguageComments")); return; } langName = name.trim(); langLabel.setText(langName); loadLanguage(null); } @FXML public void editLang() { String selected = listView.getSelectionModel().getSelectedItem(); if (selected == null) { popError(message("SelectToHandle")); return; } langName = selected; loadLanguage(selected); } @FXML public void deleteLang() { List<String> selected = listView.getSelectionModel().getSelectedItems(); if (selected == null || selected.isEmpty()) { popError(message("SelectToHandle")); return; } if (!PopTools.askSure(getTitle(), Languages.message("SureDelete"))) { return; } String currentLang = Languages.getLangName(); for (String name : selected) { File interfaceFile = Languages.interfaceLanguageFile(name); FileDeleteTools.delete(interfaceFile); if (name.equals(currentLang)) { UserConfig.deleteValue("language"); } } isSettingValues = true; listView.getItems().removeAll(selected); langName = null; langLabel.setText(""); tableData.clear(); isSettingValues = false; checkListSelected(); Languages.refreshBundle(); popSuccessful(); } @FXML public void useLang() { String selected = listView.getSelectionModel().getSelectedItem(); if (selected == null) { popError(message("SelectToHandle")); return; } Languages.setLanguage(selected); WindowTools.reloadAll(); } protected void checkListSelected() { if (isSettingValues) { return; } String selected = listView.getSelectionModel().getSelectedItem(); if (selected == null) { deleteLangButton.setDisable(true); editLangButton.setDisable(true); useLangButton.setDisable(true); } else { deleteLangButton.setDisable(false); editLangButton.setDisable(false); useLangButton.setDisable(false); } } @FXML public void openPath() { browseURI(AppVariables.MyBoxLanguagesPath.toURI()); } /* Language Items */ @Override public void initColumns() { try { keyColumn.setCellValueFactory(new PropertyValueFactory<>("key")); englishColumn.setCellValueFactory(new PropertyValueFactory<>("english")); chineseColumn.setCellValueFactory(new PropertyValueFactory<>("chinese")); valueColumn.setCellValueFactory(new PropertyValueFactory<>("value")); valueColumn.setCellFactory(new Callback<TableColumn<LanguageItem, String>, TableCell<LanguageItem, String>>() { @Override public TableCell<LanguageItem, String> call(TableColumn<LanguageItem, String> param) { return new LanguageCell(); } }); valueColumn.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<LanguageItem, String>>() { @Override public void handle(TableColumn.CellEditEvent<LanguageItem, String> t) { if (t == null) { return; } LanguageItem row = t.getRowValue(); if (row == null) { return; } String v = t.getNewValue(); String o = row.getValue(); if (v == null && o == null || v != null && v.equals(o)) { return; } row.setValue(v); tableChanged(true); } }); valueColumn.setEditable(true); valueColumn.getStyleClass().add("editable-column"); } catch (Exception e) { MyBoxLog.error(e); } } @Override public void tableChanged(boolean changed) { if (isSettingValues) { return; } this.changed = changed; updateStatus(); } @Override public void updateStatus() { setTitle(baseTitle + " - " + langName + (changed ? "*" : "")); langLabel.setText(langName + (changed ? "*" : "")); boolean isEmpty = tableData == null || tableData.isEmpty(); boolean none = isNoneSelected(); copyItemsButton.setDisable(none); saveButton.setDisable(isEmpty); chineseCheck.setDisable(isEmpty); lostFocusCommitCheck.setDisable(isEmpty); } public void loadLanguage(String name) { if (task != null) { task.cancel(); } task = new FxSingletonTask<Void>(this) { private List<LanguageItem> items; @Override protected boolean handle() { try { error = null; Map<String, String> interfaceItems = null; File interfaceFile = Languages.interfaceLanguageFile(name); if (interfaceFile != null && interfaceFile.exists()) { interfaceItems = ConfigTools.readValues(interfaceFile); } Enumeration<String> interfaceKeys = Languages.BundleEn.getKeys(); items = new ArrayList<>(); while (interfaceKeys.hasMoreElements()) { String key = interfaceKeys.nextElement(); LanguageItem item = new LanguageItem(key, Languages.BundleEn.getString(key), Languages.BundleZhCN.getString(key)); if (interfaceItems != null) { item.setValue(interfaceItems.get(key)); } items.add(item); } } catch (Exception e) { error = e.toString(); } return true; } @Override protected void whenSucceeded() { if (error == null) { isSettingValues = true; tableData.setAll(items); isSettingValues = false; tableChanged(name == null); } else { popError(error); } } }; start(task); } @FXML public void copyEnglish() { List<LanguageItem> selected = tableView.getSelectionModel().getSelectedItems(); if (selected == null || selected.isEmpty()) { return; } for (LanguageItem item : selected) { item.setValue(item.getEnglish()); } tableView.refresh(); } @FXML public void copyChinese() { List<LanguageItem> selected = tableView.getSelectionModel().getSelectedItems(); if (selected == null || selected.isEmpty()) { return; } for (LanguageItem item : selected) { item.setValue(item.getChinese()); } tableView.refresh(); } @FXML @Override public void saveAction() { if (langName == null) { return; } if (task != null) { task.cancel(); } task = new FxSingletonTask<Void>(this) { @Override protected boolean handle() { try { error = null; Map<String, String> interfaceItems = new HashMap(); File interfaceFile = Languages.interfaceLanguageFile(langName); for (LanguageItem item : tableView.getItems()) { String value = item.getValue(); if (value != null && !value.isBlank()) { interfaceItems.put(item.getKey(), value); } } ConfigTools.writeValues(interfaceFile, interfaceItems); } catch (Exception e) { error = e.toString(); } return true; } @Override protected void whenSucceeded() { if (error == null) { if (!listView.getItems().contains(langName)) { listView.getItems().add(0, langName); } tableChanged(false); popSuccessful(); if (langName.equals(Languages.getLangName())) { WindowTools.reloadAll(); } } else { popError(error); } } }; start(task); } @Override public boolean controlAltE() { copyEnglish(); return true; } @FXML public void popCopyMenu(MouseEvent event) { popTableMenu(event); } @Override protected List<MenuItem> makeTableContextMenu() { List<MenuItem> items = new ArrayList<>(); MenuItem menu; menu = new MenuItem(Languages.message("CopyEnglish")); menu.setOnAction((ActionEvent menuItemEvent) -> { copyEnglish(); }); items.add(menu); menu = new MenuItem(Languages.message("CopyChinese")); menu.setOnAction((ActionEvent menuItemEvent) -> { copyChinese(); }); items.add(menu); return items; } public class LanguageCell extends TableAutoCommitCell { public LanguageCell() { super(new DefaultStringConverter()); } protected void setCellValue(int rowIndex, String value) { if (isSettingValues || rowIndex < 0 || rowIndex >= tableData.size()) { return; } LanguageItem item = tableData.get(rowIndex); String currentValue = item.getValue(); if ((currentValue == null && value == null) || (currentValue != null && currentValue.equals(value))) { return; } item.setValue(value); tableData.set(rowIndex, item); } @Override public void editCell() { LanguageItem item = tableData.get(editingRow); String en = item.getEnglish(); String value = item.getValue(); if (value != null && value.contains("\n") || en != null && en.contains("\n")) { MyBoxLanguageInputController inputController = MyBoxLanguageInputController.open((MyBoxLanguagesController) myController, item); inputController.getNotify().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { String value = inputController.getInput(); setCellValue(editingRow, value); inputController.close(); } }); } else { super.editCell(); } } } public class LanguageItem { protected String key, english, chinese, value; public LanguageItem(String key, String english, String chinese) { this.key = key; this.english = english; this.chinese = chinese; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getEnglish() { return english; } public void setEnglish(String english) { this.english = english; } public String getChinese() { return chinese; } public void setChinese(String chinese) { this.chinese = chinese; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/HtmlToPdfController.java
alpha/MyBox/src/main/java/mara/mybox/controller/HtmlToPdfController.java
package mara.mybox.controller; import java.io.File; import javafx.fxml.FXML; import mara.mybox.db.data.VisitHistory; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.tools.TextFileTools; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2020-10-17 * @License Apache License Version 2.0 */ public class HtmlToPdfController extends BaseBatchFileController { @FXML protected ControlHtml2PdfOptions optionsController; public HtmlToPdfController() { baseTitle = message("HtmlToPdf"); targetFileSuffix = "pdf"; } @Override public void setFileType() { setFileType(VisitHistory.FileType.Html, VisitHistory.FileType.PDF); } @Override public void initControls() { try { super.initControls(); optionsController.setControls(baseName, true); } catch (Exception e) { MyBoxLog.error(e); } } @Override public String handleFile(FxTask currentTask, File srcFile, File targetPath) { try { File target = makeTargetFile(srcFile, targetPath); if (target == null) { return message("Skip"); } String html = TextFileTools.readTexts(currentTask, srcFile); if (currentTask == null || !currentTask.isWorking()) { return message("Canceled"); } if (html == null) { return message("Failed"); } String result = optionsController.html2pdf(currentTask, html, target); if (currentTask == null || !currentTask.isWorking()) { return message("Canceled"); } if (message("Successful").equals(result)) { targetFileGenerated(target); } return result; } catch (Exception e) { updateLogs(e.toString()); return e.toString(); } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/ControlDataTreeSource.java
alpha/MyBox/src/main/java/mara/mybox/controller/ControlDataTreeSource.java
package mara.mybox.controller; import javafx.fxml.FXML; import javafx.scene.control.Label; import mara.mybox.db.data.DataNode; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2024-12-2 * @License Apache License Version 2.0 */ public class ControlDataTreeSource extends BaseDataTreeController { @FXML protected Label topLabel; public void setParameters(BaseDataTreeController parent, DataNode node) { try { selectionType = DataNode.SelectionType.Multiple; initDataTree(parent.nodeTable, node); } catch (Exception e) { MyBoxLog.error(e); } } public void setLabel(String label) { topLabel.setText(label); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/ControlFFmpegOptions.java
alpha/MyBox/src/main/java/mara/mybox/controller/ControlFFmpegOptions.java
package mara.mybox.controller; //import com.github.kokorin.jaffree.ffprobe.FFprobeResult; //import com.github.kokorin.jaffree.ffprobe.Stream; import java.io.BufferedReader; import java.io.File; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.RadioButton; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.control.TitledPane; import javafx.scene.control.ToggleGroup; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxFileTools; import mara.mybox.fxml.FxTask; import mara.mybox.fxml.HelpTools; import mara.mybox.fxml.style.NodeStyleTools; import mara.mybox.tools.FileDeleteTools; import mara.mybox.tools.StringTools; import mara.mybox.tools.SystemTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2020-06-02 * @License Apache License Version 2.0 */ // http://trac.ffmpeg.org/wiki/Encode/H.264 // http://trac.ffmpeg.org/wiki/Capture/Desktop // https://slhck.info/video/2017/02/24/crf-guide.html // https://slhck.info/video/2017/03/01/rate-control.html // https://www.cnblogs.com/sunny-li/p/9979796.html // http://www.luyixian.cn/news_show_306225.aspx public class ControlFFmpegOptions extends BaseTaskController { protected BaseTaskController ffmpegController; protected String executableName, executableDefault; protected File executable; protected List<String> dataTypes; protected FxTask encoderTask, muxerTask, queryTask; protected String muxer, videoCodec, audioCodec, subtitleCodec, aspect, x264preset, volumn, rtbufsize; protected boolean disableVideo, disableAudio, disableSubtitle; protected long mediaStart; protected int width, height, crf; protected float videoFrameRate, videoBitrate, audioBitrate, audioSampleRate; @FXML protected Label executableLabel; @FXML protected TextField executableInput, extensionInput, rtbufsizeInput, moreInput; @FXML protected VBox functionBox; @FXML protected ToggleGroup rotateGroup; @FXML protected RadioButton noRotateRadio, rightRotateRadio, leftRotateRadio; @FXML protected TextArea tipsArea; @FXML protected TitledPane ffmpegPane, optionsPane; @FXML protected ComboBox<String> muxerSelector, audioEncoderSelector, videoEncoderSelector, crfSelector, x264presetSelector, subtitleEncoderSelector, aspectSelector, resolutionSelector, videoFrameRateSelector, videoBitrateSelector, audioBitrateSelector, audioSampleRateSelector, volumnSelector; @FXML protected CheckBox stereoCheck; @FXML protected Button helpMeButton; @FXML protected HBox durationBox; @FXML protected CheckBox shortestCheck; public ControlFFmpegOptions() { baseTitle = message("FFmpegOptions"); TipsLabelKey = "FFmpegOptionsTips"; } @Override public void initValues() { try { super.initValues(); executableName = "FFmpegExecutable"; executableDefault = "win".equals(SystemTools.os()) ? "D:\\Programs\\ffmpeg\\bin\\ffmpeg.exe" : "/home/ffmpeg"; disableVideo = disableAudio = disableSubtitle = false; width = height = -1; videoFrameRate = 24f; videoBitrate = 5000 * 1000; audioBitrate = 192; audioSampleRate = 44100; crf = -1; } catch (Exception e) { MyBoxLog.error(e); } } @Override public void initControls() { try { super.initControls(); if (executableInput == null) { return; } executableInput.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue observable, String oldValue, String newValue) { checkExecutableInput(); } }); if (functionBox != null) { functionBox.disableProperty().bind(executableInput.styleProperty().isEqualTo(UserConfig.badStyle())); } if (durationBox != null) { durationBox.setVisible(false); } rtbufsize = UserConfig.getString("FFmpegRtbufsize", ""); if (rtbufsizeInput != null) { rtbufsizeInput.setText(rtbufsize); rtbufsizeInput.focusedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { if (!nv) { rtbufsize = rtbufsizeInput.getText(); UserConfig.setString("FFmpegRtbufsize", rtbufsize); } } }); } } catch (Exception e) { MyBoxLog.error(e); } } @Override public void setControlsStyle() { try { super.setControlsStyle(); NodeStyleTools.setTooltip(executableInput, message("FFmpegExeComments")); if (moreInput != null) { NodeStyleTools.setTooltip(moreInput, message("SeparateBySpace")); } if (tipsArea != null) { tipsArea.setText(message("FFmpegArgumentsTips")); } if (crfSelector != null) { NodeStyleTools.setTooltip(crfSelector, message("CRFComments")); } if (x264presetSelector != null) { NodeStyleTools.setTooltip(x264presetSelector, message("X264PresetComments")); } } catch (Exception e) { MyBoxLog.debug(e); } } public void setParameters(BaseTaskController ffmpegController) { try { this.ffmpegController = ffmpegController; executableInput.setText(UserConfig.getString(executableName, executableDefault)); } catch (Exception e) { MyBoxLog.error(e); } } @FXML public void selectExecutable() { try { File file = FxFileTools.selectFile(this); if (file == null) { return; } executableInput.setText(file.getAbsolutePath()); } catch (Exception e) { // MyBoxLog.error(e); } } public void checkExecutableInput() { executable = null; if (helpMeButton != null) { helpMeButton.setDisable(true); } String v = executableInput.getText(); if (v == null || v.isEmpty()) { executableInput.setStyle(UserConfig.badStyle()); return; } final File file = new File(v); if (!file.exists()) { executableInput.setStyle(UserConfig.badStyle()); return; } executable = file; executableInput.setStyle(null); UserConfig.setString(executableName, file.getAbsolutePath()); readMuxers(); readEncoders(); if (helpMeButton != null) { helpMeButton.setDisable(false); } } public void readMuxers() { if (muxerSelector == null) { return; } muxerSelector.getItems().clear(); if (executable == null) { return; } // ffmpegController.tabPane.getSelectionModel().select(ffmpegController.logsTab); if (muxerTask != null) { muxerTask.cancel(); } try { List<String> command = new ArrayList<>(); command.add(executable.getAbsolutePath()); command.add("-muxers"); showCmd(command); ProcessBuilder pb = new ProcessBuilder(command).redirectErrorStream(true); final Process process = pb.start(); muxerTask = new FxTask<Void>(this) { private List<String> muxers, commons; @Override protected boolean handle() { error = null; muxers = new ArrayList(); commons = new ArrayList(); List<String> commonNames = new ArrayList(); commonNames.addAll(Arrays.asList("mp4", "mp3", "aiff", "au", "avi", "flv", "mov", "wav", "m4v", "hls", "rtsp")); try (BufferedReader inReader = process.inputReader(Charset.defaultCharset())) { String line; int count = 0; while ((line = inReader.readLine()) != null) { ffmpegController.showLogs(line); count++; if (count < 4 || line.length() < 5) { continue; } String muxer = line.substring(4); for (String common : commonNames) { if (muxer.startsWith(common + " ")) { commons.add(muxer); break; } } muxers.add(muxer); } } catch (Exception e) { error = e.toString(); } return true; } @Override protected void whenSucceeded() { if (error != null) { popError(error); } muxerSelector.getItems().addAll(commons); muxerSelector.getItems().addAll(muxers); muxerSelector.getItems().add(0, message("OriginalFormat")); muxerSelector.getSelectionModel().selectedItemProperty().addListener( (ObservableValue<? extends String> ov, String oldValue, String newValue) -> { if (newValue != null && !newValue.isEmpty()) { UserConfig.setString("ffmpegDefaultMuter", newValue); } if (newValue == null || newValue.isEmpty() || message("OriginalFormat").equals(newValue) || message("NotSet").equals(newValue)) { extensionInput.setText(message("OriginalFormat")); muxer = null; return; } int pos = newValue.indexOf(' '); if (pos < 0) { muxer = newValue; } else { muxer = newValue.substring(0, pos); } if (muxer.equals("hls")) { extensionInput.setText("m3u8"); } else { extensionInput.setText(muxer); } }); muxerSelector.getSelectionModel().select(UserConfig.getString("ffmpegDefaultMuter", "mp4")); } @Override protected void finalAction() { super.finalAction(); muxerTask = null; } }; start(muxerTask); process.waitFor(); } catch (Exception e) { MyBoxLog.debug(e); popError(e.toString()); } finally { muxerTask = null; } } public void readEncoders() { if (executable == null) { return; } if (audioEncoderSelector != null) { audioEncoderSelector.getItems().clear(); } if (videoEncoderSelector != null) { videoEncoderSelector.getItems().clear(); } if (subtitleEncoderSelector != null) { subtitleEncoderSelector.getItems().clear(); } if (encoderTask != null) { encoderTask.cancel(); } // ffmpegController.tabPane.getSelectionModel().select(ffmpegController.logsTab); try { List<String> command = new ArrayList<>(); command.add(executable.getAbsolutePath()); command.add("-hide_banner"); command.add("-encoders"); showCmd(command); ProcessBuilder pb = new ProcessBuilder(command).redirectErrorStream(true); final Process process = pb.start(); encoderTask = new FxTask<Void>(this) { private List<String> aEncoders, vEncoders, sEncoders, videoCommons; @Override protected boolean handle() { error = null; aEncoders = new ArrayList(); vEncoders = new ArrayList(); sEncoders = new ArrayList(); videoCommons = new ArrayList(); List<String> commonVideoNames = new ArrayList(); commonVideoNames.addAll(Arrays.asList("flv", "x264", "x265", "libvpx", "h264")); try (BufferedReader inReader = process.inputReader(Charset.defaultCharset())) { String line; int count = 0; while ((line = inReader.readLine()) != null) { ffmpegController.showLogs(line); count++; if (count < 10 || line.length() < 9) { continue; } String type = line.substring(0, 8); String encoder = line.substring(8); if (type.contains("V")) { for (String common : commonVideoNames) { if (encoder.contains(common)) { videoCommons.add(encoder); break; } } vEncoders.add(encoder); } else if (type.contains("A")) { aEncoders.add(encoder); } else if (type.contains("S")) { sEncoders.add(encoder); } } return true; } catch (Exception e) { error = e.toString(); return false; } } @Override protected void whenSucceeded() { if (audioEncoderSelector != null) { audioEncoderSelector.getItems().addAll(aEncoders); audioEncoderSelector.getItems().add(0, message("DisableAudio")); audioEncoderSelector.getItems().add(0, message("CopyAudio")); audioEncoderSelector.getItems().add(0, message("NotSet")); initAudioControls(); } if (videoEncoderSelector != null) { videoEncoderSelector.getItems().addAll(videoCommons); videoEncoderSelector.getItems().addAll(vEncoders); videoEncoderSelector.getItems().add(0, message("DisableVideo")); videoEncoderSelector.getItems().add(0, message("CopyVideo")); videoEncoderSelector.getItems().add(0, message("NotSet")); initVideoControls(); } if (subtitleEncoderSelector != null) { subtitleEncoderSelector.getItems().addAll(sEncoders); subtitleEncoderSelector.getItems().add(0, message("DisableSubtitle")); subtitleEncoderSelector.getItems().add(0, message("CopySubtitle")); subtitleEncoderSelector.getItems().add(0, message("NotSet")); initSubtitleControls(); } } @Override protected void finalAction() { super.finalAction(); encoderTask = null; } }; start(encoderTask); process.waitFor(); } catch (Exception e) { MyBoxLog.debug(e); popError(e.toString()); } finally { encoderTask = null; } } public void initAudioControls() { try { if (audioEncoderSelector != null) { audioEncoderSelector.getSelectionModel().selectedItemProperty().addListener( (ObservableValue<? extends String> ov, String oldValue, String newValue) -> { if (newValue != null && !newValue.isEmpty()) { UserConfig.setString("ffmpegDefaultAudioEncoder", newValue); } disableAudio = false; if (newValue == null || newValue.isEmpty() || message("NotSet").equals(newValue)) { audioCodec = null; return; } if (message("DisableAudio").equals(newValue)) { disableAudio = true; audioCodec = null; return; } if (message("CopyAudio").equals(newValue)) { audioCodec = "copy"; return; } int pos = newValue.indexOf(' '); if (pos < 0) { audioCodec = newValue; } else { audioCodec = newValue.substring(0, pos); } }); audioEncoderSelector.getSelectionModel().select(UserConfig.getString("ffmpegDefaultAudioEncoder", "aac")); } if (audioBitrateSelector != null) { audioBitrateSelector.getItems().add(message("NotSet")); audioBitrateSelector.getItems().addAll(Arrays.asList( "192kbps", "128kbps", "96kbps", "64kbps", "256kbps", "320kbps", "32kbps", "1411.2kbps", "328kbps" )); audioBitrateSelector.getSelectionModel().selectedItemProperty().addListener( (ObservableValue<? extends String> ov, String oldValue, String newValue) -> { if (newValue != null && !newValue.isEmpty()) { UserConfig.setString("ffmpegDefaultAudioBitrate", newValue); } if (newValue == null || newValue.isEmpty() || message("NotSet").equals(newValue)) { audioBitrate = 192; return; } try { int pos = newValue.indexOf("kbps"); String value; if (pos < 0) { value = newValue; } else { value = newValue.substring(0, pos); } float v = Float.parseFloat(value.trim()); if (v > 0) { audioBitrate = v; audioBitrateSelector.getEditor().setStyle(null); } else { audioBitrateSelector.getEditor().setStyle(UserConfig.badStyle()); } } catch (Exception e) { audioBitrateSelector.getEditor().setStyle(UserConfig.badStyle()); } }); audioBitrateSelector.getSelectionModel().select(UserConfig.getString("ffmpegDefaultAudioBitrate", "192kbps")); } if (audioSampleRateSelector != null) { audioSampleRateSelector.getItems().add(message("NotSet")); audioSampleRateSelector.getItems().addAll(Arrays.asList(message("48000Hz"), message("44100Hz"), message("96000Hz"), message("8000Hz"), message("11025Hz"), message("22050Hz"), message("24000Hz"), message("32000Hz"), message("50000Hz"), message("47250Hz"), message("192000Hz") )); audioSampleRateSelector.getSelectionModel().selectedItemProperty().addListener( (ObservableValue<? extends String> ov, String oldValue, String newValue) -> { if (newValue != null && !newValue.isEmpty()) { UserConfig.setString("ffmpegDefaultAudioSampleRate", newValue); } if (newValue == null || newValue.isEmpty() || message("NotSet").equals(newValue)) { audioSampleRate = 44100; return; } try { int pos = newValue.indexOf("Hz"); String value; if (pos < 0) { value = newValue; } else { value = newValue.substring(0, pos); } int v = Integer.parseInt(value.trim()); if (v > 0) { audioSampleRate = v; audioSampleRateSelector.getEditor().setStyle(null); } else { audioSampleRateSelector.getEditor().setStyle(UserConfig.badStyle()); } } catch (Exception e) { audioSampleRateSelector.getEditor().setStyle(UserConfig.badStyle()); } }); audioSampleRateSelector.getSelectionModel().select(UserConfig.getString("ffmpegDefaultAudioSampleRate", message("44100Hz"))); } if (volumnSelector != null) { volumnSelector.getItems().addAll(Arrays.asList(message("NotSet"), message("10dB"), message("20dB"), message("5dB"), message("30dB"), message("-10dB"), message("-20dB"), message("-5dB"), message("-30dB"), message("1.5"), message("1.25"), message("2"), message("3"), message("0.5"), message("0.8"), message("0.6") )); volumnSelector.getSelectionModel().selectedItemProperty().addListener( (ObservableValue<? extends String> ov, String oldValue, String newValue) -> { if (newValue != null && !newValue.isEmpty()) { UserConfig.setString("ffmpegDefaultAudioVolumn", newValue); } if (newValue == null || newValue.isEmpty() || message("NotSet").equals(newValue)) { volumn = null; return; } volumn = newValue; }); volumnSelector.getSelectionModel().select(UserConfig.getString("ffmpegDefaultAudioVolumn", message("NotSet"))); } } catch (Exception e) { MyBoxLog.error(e); } } public void initVideoControls() { try { setH264(); setCRF(); if (videoEncoderSelector != null) { videoEncoderSelector.getSelectionModel().selectedItemProperty().addListener( (ObservableValue<? extends String> ov, String oldValue, String newValue) -> { setVcodec(newValue); setH264(); setCRF(); }); videoEncoderSelector.getSelectionModel().select(UserConfig.getString("ffmpegDefaultVideoEncoder", defaultVideoEcodec())); } if (aspectSelector != null) { aspectSelector.getItems().addAll(Arrays.asList(message("NotSet"), "4:3", "16:9" )); aspectSelector.getSelectionModel().selectedItemProperty().addListener( (ObservableValue<? extends String> ov, String oldValue, String newValue) -> { if (newValue != null && !newValue.isEmpty()) { UserConfig.setString("ffmpegDefaultAspect", newValue); } if (newValue == null || newValue.isEmpty() || message("NotSet").equals(newValue)) { aspect = null; return; } aspect = newValue; }); aspectSelector.getSelectionModel().select(UserConfig.getString("ffmpegDefaultAspect", message("NotSet"))); } // http://ffmpeg.org/ffmpeg-utils.html if (resolutionSelector != null) { resolutionSelector.getItems().add(message("NotSet")); resolutionSelector.getItems().addAll(Arrays.asList( "ntsc 720x480", "pal 720x576", "qntsc 352x240", "qpal 352x288", "sntsc 640x480", "spal 768x576", "film 352x240", "ntsc-film 352x240", "sqcif 128x96", "qcif 176x144", "cif 352x288", "4cif 704x576", "16cif 1408x1152", "qqvga 160x120", "qvga 320x240", "vga 640x480", "svga 800x600", "xga 1024x768", "uxga 1600x1200", "qxga 2048x1536", "sxga 1280x1024", "qsxga 2560x2048", "hsxga 5120x4096", "wvga 852x480", "wxga 1366x768", "wsxga 1600x1024", "wuxga 1920x1200", "woxga 2560x1600", "wqsxga 3200x2048", "wquxga 3840x2400", "whsxga 6400x4096", "whuxga 7680x4800", "cga 320x200", "ega 640x350", "hd480 852x480", "hd720 1280x720", "hd1080 1920x1080", "2k 2048x1080", "2kflat 1998x1080", "2kscope 2048x858", "4k 4096x2160", "4kflat 3996x2160", "4kscope 4096x1716", "nhd 640x360", "hqvga 240x160", "wqvga 400x240", "fwqvga 432x240", "hvga 480x320", "qhd 960x540", "2kdci 2048x1080", "4kdci 4096x2160", "uhd2160 3840x2160", "uhd4320 7680x4320" )); resolutionSelector.getSelectionModel().selectedItemProperty().addListener( (ObservableValue<? extends String> ov, String oldValue, String newValue) -> { if (newValue != null && !newValue.isEmpty()) { UserConfig.setString("ffmpegDefaultResolution", newValue); } if (newValue == null || newValue.isEmpty() || message("NotSet").equals(newValue)) { width = height = -1; return; } try { String value = newValue.substring(newValue.lastIndexOf(' ') + 1); int pos = value.indexOf('x'); width = Integer.parseInt(value.substring(0, pos)); height = Integer.parseInt(value.substring(pos + 1)); } catch (Exception e) { } }); String dres = UserConfig.getString("ffmpegDefaultResolution", "ntsc 720x480"); resolutionSelector.getSelectionModel().select(dres); } if (videoFrameRateSelector != null) { videoFrameRateSelector.getItems().add(message("NotSet")); videoFrameRateSelector.getItems().addAll(Arrays.asList( "ntsc 30000/1001", "pal 25/1", "qntsc 30000/1001", "qpal 25/1", "sntsc 30000/1001", "spal 25/1", "film 24/1", "ntsc-film 24000/1001" )); videoFrameRateSelector.getSelectionModel().selectedItemProperty().addListener( (ObservableValue<? extends String> ov, String oldValue, String newValue) -> { if (newValue != null && !newValue.isEmpty()) { UserConfig.setString("ffmpegDefaultFrameRate", newValue); } if (newValue == null || newValue.isEmpty() || message("NotSet").equals(newValue)) { videoFrameRate = 24f; return; } try { String value = newValue.substring(newValue.lastIndexOf(' ') + 1); int pos = value.indexOf('/'); videoFrameRate = Integer.parseInt(value.substring(0, pos)) * 1f / Integer.parseInt(value.substring(pos + 1)); } catch (Exception e) { } }); videoFrameRateSelector.getSelectionModel().select(UserConfig.getString("ffmpegDefaultFrameRate", "ntsc 30000/1001")); } if (videoBitrateSelector != null) { videoBitrateSelector.getItems().add(message("NotSet")); videoBitrateSelector.getItems().addAll(Arrays.asList( "1800kbps", "1600kbps", "1300kbps", "2400kbps", "1150kbps", "5mbps", "6mbps", "8mbps", "16mbps", "4mbps", "40mbps", "65mbps", "10mbps", "20mbps", "15mbps", "3500kbps", "3000kbps", "2000kbps", "1000kbps", "800kbps", "500kbps", "250kbps", "120kbps", "60kbps", "30kbps" )); videoBitrateSelector.getSelectionModel().selectedItemProperty().addListener( (ObservableValue<? extends String> ov, String oldValue, String newValue) -> { if (newValue != null && !newValue.isEmpty()) { UserConfig.setString("ffmpegDefaultVideoBitrate", newValue); } if (newValue == null || newValue.isEmpty() || message("NotSet").equals(newValue)) { videoBitrate = 1800; return; } try { int pos = newValue.indexOf("kbps"); if (pos < 0) { pos = newValue.indexOf("mbps"); if (pos < 0) {
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
true
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/alpha/MyBox/src/main/java/mara/mybox/controller/Data2DPasteContentInSystemClipboardController.java
alpha/MyBox/src/main/java/mara/mybox/controller/Data2DPasteContentInSystemClipboardController.java
package mara.mybox.controller; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.input.KeyEvent; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.WindowTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2021-11-27 * @License Apache License Version 2.0 */ public class Data2DPasteContentInSystemClipboardController extends BaseData2DPasteController { @FXML protected ControlData2DSystemClipboard boardController; public Data2DPasteContentInSystemClipboardController() { baseTitle = message("PasteContentInSystemClipboard"); } public void setParameters(Data2DManufactureController target, String text) { try { this.parentController = target; setParameters(target); boardController.loadNotify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { loadDef(boardController.textData); } }); boardController.load(text); } catch (Exception e) { MyBoxLog.error(e); } } @Override public boolean handleKeyEvent(KeyEvent event) { if (boardController.handleKeyEvent(event)) { return true; } return super.handleKeyEvent(event); } /* static */ public static Data2DPasteContentInSystemClipboardController open(Data2DManufactureController parent, String text) { try { Data2DPasteContentInSystemClipboardController controller = (Data2DPasteContentInSystemClipboardController) WindowTools.referredTopStage( parent, Fxmls.Data2DPasteContentInSystemClipboardFxml); controller.setParameters(parent, text); controller.requestMouse(); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false