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
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/okhttp/ws_ret.java
architecture/src/main/java/com/jiang/android/architecture/okhttp/ws_ret.java
/** * created by jiang, 15/10/19 * Copyright (c) 2015, jyuesong@gmail.com All Rights Reserved. * * # # * # _oo0oo_ # * # o8888888o # * # 88" . "88 # * # (| -_- |) # * # 0\ = /0 # * # ___/`---'\___ # * # .' \\| |# '. # * # / \\||| : |||# \ # * # / _||||| -:- |||||- \ # * # | | \\\ - #/ | | # * # | \_| ''\---/'' |_/ | # * # \ .-\__ '-' ___/-. / # * # ___'. .' /--.--\ `. .'___ # * # ."" '< `.___\_<|>_/___.' >' "". # * # | | : `- \`.;`\ _ /`;.`/ - ` : | | # * # \ \ `_. \_ __\ /__ _/ .-` / / # * # =====`-.____`.___ \_____/___.-`___.-'===== # * # `=---=' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # * # # * # 佛祖保佑 永无BUG # * # # */ package com.jiang.android.architecture.okhttp; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; /** * 网络请求失败或者没数据的时候,调用的类 * Created by jiang on 15/10/16. */ public class ws_ret { @SerializedName("status") @Expose private int state; @Expose private String msg; public ws_ret() { } public ws_ret(int state, String msg) { this.state = state; this.msg = msg; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public int getState() { return state; } public void setState(int state) { this.state = state; } @Override public String toString() { return "ws_ret{" + "state=" + state + ", msg='" + msg + '\'' + '}'; } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/okhttp/Param.java
architecture/src/main/java/com/jiang/android/architecture/okhttp/Param.java
/** * created by jiang, 10/26/15 * Copyright (c) 2015, jyuesong@gmail.com All Rights Reserved. * * # # * # _oo0oo_ # * # o8888888o # * # 88" . "88 # * # (| -_- |) # * # 0\ = /0 # * # ___/`---'\___ # * # .' \\| |# '. # * # / \\||| : |||# \ # * # / _||||| -:- |||||- \ # * # | | \\\ - #/ | | # * # | \_| ''\---/'' |_/ | # * # \ .-\__ '-' ___/-. / # * # ___'. .' /--.--\ `. .'___ # * # ."" '< `.___\_<|>_/___.' >' "". # * # | | : `- \`.;`\ _ /`;.`/ - ` : | | # * # \ \ `_. \_ __\ /__ _/ .-` / / # * # =====`-.____`.___ \_____/___.-`___.-'===== # * # `=---=' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # * # # * # 佛祖保佑 永无BUG # * # # */ package com.jiang.android.architecture.okhttp; /** * Created by jiang on 10/26/15. */ public class Param { public Param(String key,String value) { this.key = key; this.value = value; } public String key; public String value; @Override public String toString() { return key + "=" + value; } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/okhttp/WS_State.java
architecture/src/main/java/com/jiang/android/architecture/okhttp/WS_State.java
/** * created by jiang, 15/10/19 * Copyright (c) 2015, jyuesong@gmail.com All Rights Reserved. * * # # * # _oo0oo_ # * # o8888888o # * # 88" . "88 # * # (| -_- |) # * # 0\ = /0 # * # ___/`---'\___ # * # .' \\| |# '. # * # / \\||| : |||# \ # * # / _||||| -:- |||||- \ # * # | | \\\ - #/ | | # * # | \_| ''\---/'' |_/ | # * # \ .-\__ '-' ___/-. / # * # ___'. .' /--.--\ `. .'___ # * # ."" '< `.___\_<|>_/___.' >' "". # * # | | : `- \`.;`\ _ /`;.`/ - ` : | | # * # \ \ `_. \_ __\ /__ _/ .-` / / # * # =====`-.____`.___ \_____/___.-`___.-'===== # * # `=---=' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # * # # * # 佛祖保佑 永无BUG # * # # */ package com.jiang.android.architecture.okhttp; /** * 网络请求的状态 * Created by jiang on 15/10/16. */ public class WS_State { public static final int SUCCESS = 200; public static final int NODATA = 204; public static final int OTHERS = 400; public static final int EXCEPTION = 450; public static final int SERVER_ERROR = 500; public static final int NONET = 1000; }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/okhttp/OkHttpTask.java
architecture/src/main/java/com/jiang/android/architecture/okhttp/OkHttpTask.java
/** * created by jiang, 16/5/14 * Copyright (c) 2016, jyuesong@gmail.com All Rights Reserved. * * # # * # _oo0oo_ # * # o8888888o # * # 88" . "88 # * # (| -_- |) # * # 0\ = /0 # * # ___/`---'\___ # * # .' \\| |# '. # * # / \\||| : |||# \ # * # / _||||| -:- |||||- \ # * # | | \\\ - #/ | | # * # | \_| ''\---/'' |_/ | # * # \ .-\__ '-' ___/-. / # * # ___'. .' /--.--\ `. .'___ # * # ."" '< `.___\_<|>_/___.' >' "". # * # | | : `- \`.;`\ _ /`;.`/ - ` : | | # * # \ \ `_. \_ __\ /__ _/ .-` / / # * # =====`-.____`.___ \_____/___.-`___.-'===== # * # `=---=' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # * # # * # 佛祖保佑 永无BUG # * # # */ package com.jiang.android.architecture.okhttp; import android.os.Handler; import android.os.Looper; import android.text.TextUtils; import com.apkfuns.logutils.LogUtils; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.jiang.android.architecture.okhttp.callback.BaseCallBack; import com.jiang.android.architecture.okhttp.cookie.CookieJarImpl; import com.jiang.android.architecture.okhttp.cookie.store.CookieStore; import com.jiang.android.architecture.okhttp.cookie.store.HasCookieStore; import com.jiang.android.architecture.okhttp.cookie.store.MemoryCookieStore; import com.jiang.android.architecture.okhttp.exception.Exceptions; import com.jiang.android.architecture.okhttp.log.HttpLoggingInterceptor; import com.jiang.android.architecture.okhttp.request.CountingRequestBody; import com.jiang.android.architecture.okhttp.request.DeleteRequest; import com.jiang.android.architecture.okhttp.request.PostRequest; import com.jiang.android.architecture.okhttp.request.PutRequest; import com.jiang.android.architecture.okhttp.request.UploadRequest; import com.jiang.android.architecture.okhttp.request.getRequest; import com.jiang.android.architecture.okhttp.utils.HttpsUtils; import org.greenrobot.eventbus.EventBus; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import okhttp3.Call; import okhttp3.Callback; import okhttp3.CookieJar; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; /** * Created by jiang on 16/5/14. */ public class OkHttpTask { public static final int TYPE_GET = 30; //get请求 public static final int TYPE_POST = 60; // post请求 public static final int TYPE_PUT = 70; // post请求 public static final int TYPE_DELETE = 90; // delete请求 public static final int EXIT_LOGIN = 1010; private static int[] exitLoginCode = null; private static OkHttpTask mInstance; private OkHttpClient mOkHttpClient; private Handler mDelivery; private Gson mGson; private static boolean isDebug = false; final static class ERROR_OPTIONS { public static final String EROR_REQUEST_ERROR = "请求失败,请重试"; public static final String EROR_REQUEST_UNKNOWN = "未知错误"; public static final String EROR_REQUEST_CREATEDIRFAIL = "创建文件失败,请检查权限"; public static final String EROR_REQUEST_IO = "IO异常,或者本次任务被取消"; public static final String EROR_REQUEST_EXITLOGIN = "请重新登录"; } public static OkHttpTask getInstance() { if (mInstance == null) { synchronized (OkHttpTask.class) { if (mInstance == null) { mInstance = new OkHttpTask(null); } } } return mInstance; } public static OkHttpTask getInstance(OkHttpClient okHttpClient) { if (mInstance == null) { synchronized (OkHttpTask.class) { if (mInstance == null) { mInstance = new OkHttpTask(okHttpClient); } } } return mInstance; } private OkHttpTask(OkHttpClient okHttpClient) { if (okHttpClient == null) { OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder(); //cookie enabled okHttpClientBuilder.cookieJar(new CookieJarImpl(new MemoryCookieStore())); okHttpClientBuilder.hostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); if (isDebug) { HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() { @Override public void log(String message, String json) { LogUtils.i(message); if (!TextUtils.isEmpty(json)) { LogUtils.i("--------json---------\n"); LogUtils.json(json); LogUtils.i("--------end----------\n"); } } }); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); okHttpClientBuilder.addInterceptor(loggingInterceptor); } mOkHttpClient = okHttpClientBuilder.build(); } else { mOkHttpClient = okHttpClient; } init(); } public Gson getmGson() { return mGson; } public static void debug(boolean isdebug) { isDebug = isdebug; } public static void exitLoginCode(int... code) { exitLoginCode = code; } private void init() { mDelivery = new Handler(Looper.getMainLooper()); mGson = new GsonBuilder().serializeNulls().excludeFieldsWithoutExposeAnnotation().create(); } public OkHttpClient getOkHttpClient() { return mOkHttpClient; } /** * @param url url * @param params 需要传递的参数 get请求? 后面的参数也可以通过param传递 * @param callBack 返回的回调 * @param tag 唯一的key, 可以通过这个唯一的key来取消网络请求 * @param type 请求的类型 * @param headers 需要特殊处理的请求头 */ public void filterData(String url, Object tag, Map<String, String> params, final BaseCallBack callBack, Map<String, String> headers, int type) { doJobNormal(url, params, callBack, tag, type, headers); } /** * 上传文件 * * @param url url * @param headers 验证 * @param callBack 回调 * @param tag tag */ void uploadFile(String url, Map<String, String> headers, List<String> files, final BaseCallBack callBack, Object tag) { if (isDebug) { StringBuilder logBuilder = new StringBuilder(); logBuilder.append("------upload file-------").append("\n") .append("url: ").append(url).append("\n"); if (headers != null) { logBuilder.append("headers: ").append(headers.toString()).append("\n"); } if (files != null) { logBuilder.append("files: ").append(files.toString()).append("\n"); } LogUtils.i(logBuilder.toString()); } MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM); if (files != null && files.size() > 0) { final int fileSize = files.size(); final long fileProgress[] = new long[fileSize]; for (int i = 0; i < fileSize; i++) { final File file = new File(files.get(i)); CountingRequestBody countingRequestBody = new CountingRequestBody(RequestBody.create(MediaType.parse("application/octet-stream"), file), new CountingRequestBody.Listener() { @Override public void onRequestProgress(final long bytesWritten, final long contentLength, final int position) { long progress = bytesWritten * 100 / contentLength; if (progress < 95 && progress - fileProgress[position] < 4) return; //为了尽量少走回调 fileProgress[position] = progress; int result = 0; for (int i = 0; i < fileProgress.length; i++) { result += fileProgress[i]; } result = result / fileSize; progressCallBack(result, callBack); } }, i); // 索引到最后一个斜杠 String resultName = files.get(i).substring(files.get(i).lastIndexOf("/") + 1); builder.addFormDataPart("upload", resultName, countingRequestBody); if (isDebug) { LogUtils.i("开始上传文件 file: " + file.toString()); } } } else { failCallBack(WS_State.OTHERS, "没有文件可上传", callBack); return; } final Call call = mOkHttpClient.newCall(UploadRequest.buildPostRequest(url, headers, tag, builder.build())); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { dealFailResponse(ERROR_OPTIONS.EROR_REQUEST_ERROR, callBack); } @Override public void onResponse(Call call, Response response) throws IOException { int code = response.code(); if (code == 200) { dealSuccessResponse(response, callBack); } else { String msg = response.message(); if (TextUtils.isEmpty(msg)) { msg = "上传失败,请重试"; } failCallBack(code, msg, callBack); } } }); } public void downLoadFile(final String url, final String destFileDir, final String fileName, final BaseCallBack callback, Object tag, Map<String, String> headers) { if (isDebug) { StringBuilder logBuilder = new StringBuilder(); logBuilder.append("------download file-------").append("\n") .append("url: ").append(url).append("\n") .append("destFileDir: ").append(destFileDir).append("\n") .append("fileName: ").append(fileName).append("\n"); if (headers != null) { logBuilder.append("headers: ").append(headers.toString()).append("\n"); } LogUtils.i(logBuilder.toString()); } int type = TYPE_GET; if (TextUtils.isEmpty(url) || TextUtils.isEmpty(destFileDir) || callback == null || TextUtils.isEmpty(fileName)) return; callback.onBefore(); doJob(url, null, tag, type, new Callback() { @Override public void onFailure(Call call, IOException e) { dealFailResponse(ERROR_OPTIONS.EROR_REQUEST_ERROR, callback); } @Override public void onResponse(Call call, Response response) throws IOException { int code = response.code(); if (code == 200) { FileOutputStream fos = null; InputStream is = null; try { byte[] buf = new byte[2048]; is = response.body().byteStream(); long fileLongth = (int) response.body().contentLength(); int len; long totalLength = 0; long lastProgress = -1; File dir = new File(destFileDir); if (!dir.exists()) { boolean createDirSuccess = dir.mkdirs(); if (!createDirSuccess) { //创建文件夹失败 failCallBack(WS_State.EXCEPTION, ERROR_OPTIONS.EROR_REQUEST_CREATEDIRFAIL, callback); return; } } File file = new File(dir, fileName); fos = new FileOutputStream(file); while ((len = is.read(buf)) != -1) { fos.write(buf, 0, len); totalLength += len; long progress = totalLength * 100 / fileLongth; if (lastProgress != progress) { progressCallBack(progress, callback); } lastProgress = progress; } fos.flush(); //如果下载文件成功,第一个参数为文件的绝对路径 successCallBack("下载成功", callback); } catch (IOException e) { failCallBack(WS_State.EXCEPTION, ERROR_OPTIONS.EROR_REQUEST_IO, callback); } catch (Exception e) { failCallBack(WS_State.EXCEPTION, ERROR_OPTIONS.EROR_REQUEST_UNKNOWN, callback); } finally { try { if (is != null) is.close(); } catch (IOException e) { e.printStackTrace(); } try { if (fos != null) fos.close(); } catch (IOException e) { e.printStackTrace(); } } } else { failCallBack(code, ERROR_OPTIONS.EROR_REQUEST_ERROR, callback); } } }, headers); } public void doJobNormal(final String url, Map<String, String> params, final BaseCallBack callBack, Object tag, final int TYPE, Map<String, String> headers) { callBack.onBefore(); doJob(url, params, tag, TYPE, new Callback() { @Override public void onFailure(Call call, IOException e) { dealFailResponse(ERROR_OPTIONS.EROR_REQUEST_ERROR, callBack); } @Override public void onResponse(Call call, Response response) throws IOException { callBack.onFinishResponse(response); dealSuccessResponse(response, callBack); } }, headers); } private void doJob(String url, Map<String, String> params, Object tag, int type, Callback callback, Map<String, String> headers) { Request request = null; if (type == TYPE_POST) { request = PostRequest.buildPostRequest(url, params, tag, headers); //拿到一个post的request } else if (TYPE_GET == type) { request = getRequest.buildGetRequest(url, params, tag, headers);//拿到一个get的request } else if (TYPE_PUT == type) { request = PutRequest.buildOtherRequest(url, params, tag, headers, type); } else if (type == TYPE_DELETE) { request = DeleteRequest.buildDeleteRequest(url, params, tag, headers); } else { Exceptions.illegalArgument("只支持 get post put delete"); } final Call call = mOkHttpClient.newCall(request); //获得一个 call, 这是okhttp核心的类 call.enqueue(callback); //加入队列 } //*********************************处理返回的结果******************************************************** private void dealSuccessResponse(Response response, BaseCallBack callBack) { try { int status = response.code(); if (containExitLoginCode(status)) { EventBus.getDefault().post(exitLoginCode); failCallBack(EXIT_LOGIN, ERROR_OPTIONS.EROR_REQUEST_EXITLOGIN, callBack); } else { final String string = response.body().string(); if (status == 200) { Object o = mGson.fromJson(string, callBack.mType); successCallBack(o, callBack); } else if (status == 204) { emptyCallBack(WS_State.NODATA, "暂无数据", callBack); } else { ws_ret o = mGson.fromJson(string, ws_ret.class); if (TextUtils.isEmpty(o.getMsg())) { failCallBack(status, ERROR_OPTIONS.EROR_REQUEST_ERROR, callBack); } else { failCallBack(status, o.getMsg(), callBack); } } } } catch (Exception e) { e.printStackTrace(); if (isDebug) { LogUtils.d("exception info: " + e.toString()); } failCallBack(WS_State.EXCEPTION, ERROR_OPTIONS.EROR_REQUEST_ERROR, callBack); } finally { try { response.body().close(); } catch (Exception e) { if (isDebug) { LogUtils.d("解析Body失败: " + e.toString()); } } } } private boolean containExitLoginCode(int status) { if (exitLoginCode == null) return false; for (int i = 0; i < exitLoginCode.length; i++) { if (status == exitLoginCode[i]) { return true; } } return false; } private void dealFailResponse(String msg, BaseCallBack callBack) { failCallBack(WS_State.SERVER_ERROR, msg, callBack); } private void failCallBack(final int state, final String msg, final BaseCallBack callback) { mDelivery.post(new Runnable() { @Override public void run() { ws_ret ret = new ws_ret(state, msg); callback.onFail(ret); callback.onAfter(); } }); } private void successCallBack(final Object o, final BaseCallBack ret) { mDelivery.post(new Runnable() { @Override public void run() { ret.onSuccess(o); ret.onAfter(); } }); } private void progressCallBack(final long l, final BaseCallBack callback) { mDelivery.post(new Runnable() { @Override public void run() { callback.onProgress(l); } }); } private void emptyCallBack(final int state, final String msg, final BaseCallBack callback) { mDelivery.post(new Runnable() { @Override public void run() { ws_ret ret = new ws_ret(state, msg); callback.onNoData(ret); callback.onAfter(); } }); } public void cancelTask(Object tag) { for (Call call : mOkHttpClient.dispatcher().queuedCalls()) { if (tag.equals(call.request().tag())) { call.cancel(); } } for (Call call : mOkHttpClient.dispatcher().runningCalls()) { if (tag.equals(call.request().tag())) { call.cancel(); } } } public CookieStore getCookieStore() { final CookieJar cookieJar = mOkHttpClient.cookieJar(); if (cookieJar == null) { Exceptions.illegalArgument("you should invoked okHttpClientBuilder.cookieJar() to set a cookieJar."); } if (cookieJar instanceof HasCookieStore) { return ((HasCookieStore) cookieJar).getCookieStore(); } else { return null; } } /** * for https-way authentication * * @param certificates */ public void setCertificates(InputStream... certificates) { SSLSocketFactory sslSocketFactory = HttpsUtils.getSslSocketFactory(certificates, null, null); OkHttpClient.Builder builder = getOkHttpClient().newBuilder(); builder = builder.sslSocketFactory(sslSocketFactory); mOkHttpClient = builder.build(); } /** * for https mutual authentication * * @param certificates * @param bksFile * @param password */ public void setCertificates(InputStream[] certificates, InputStream bksFile, String password) { mOkHttpClient = getOkHttpClient().newBuilder() .sslSocketFactory(HttpsUtils.getSslSocketFactory(certificates, bksFile, password)) .build(); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/okhttp/cookie/CookieJarImpl.java
architecture/src/main/java/com/jiang/android/architecture/okhttp/cookie/CookieJarImpl.java
package com.jiang.android.architecture.okhttp.cookie; import com.jiang.android.architecture.okhttp.cookie.store.CookieStore; import com.jiang.android.architecture.okhttp.cookie.store.HasCookieStore; import com.jiang.android.architecture.okhttp.exception.Exceptions; import java.util.List; import okhttp3.Cookie; import okhttp3.CookieJar; import okhttp3.HttpUrl; /** * Created by zhy on 16/3/10. */ public class CookieJarImpl implements CookieJar, HasCookieStore { private CookieStore cookieStore; public CookieJarImpl(CookieStore cookieStore) { if (cookieStore == null) Exceptions.illegalArgument("cookieStore can not be null."); this.cookieStore = cookieStore; } @Override public synchronized void saveFromResponse(HttpUrl url, List<Cookie> cookies) { cookieStore.add(url, cookies); } @Override public synchronized List<Cookie> loadForRequest(HttpUrl url) { return cookieStore.get(url); } @Override public CookieStore getCookieStore() { return cookieStore; } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/okhttp/cookie/store/SerializableHttpCookie.java
architecture/src/main/java/com/jiang/android/architecture/okhttp/cookie/store/SerializableHttpCookie.java
package com.jiang.android.architecture.okhttp.cookie.store; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import okhttp3.Cookie; /** * from http://stackoverflow.com/questions/25461792/persistent-cookie-store-using-okhttp-2-on-android * and<br/> * http://www.geebr.com/post/okHttp3%E4%B9%8BCookies%E7%AE%A1%E7%90%86%E5%8F%8A%E6%8C%81%E4%B9%85%E5%8C%96 */ public class SerializableHttpCookie implements Serializable { private static final long serialVersionUID = 6374381323722046732L; private transient final Cookie cookie; private transient Cookie clientCookie; public SerializableHttpCookie(Cookie cookie) { this.cookie = cookie; } public Cookie getCookie() { Cookie bestCookie = cookie; if (clientCookie != null) { bestCookie = clientCookie; } return bestCookie; } private void writeObject(ObjectOutputStream out) throws IOException { out.writeObject(cookie.name()); out.writeObject(cookie.value()); out.writeLong(cookie.expiresAt()); out.writeObject(cookie.domain()); out.writeObject(cookie.path()); out.writeBoolean(cookie.secure()); out.writeBoolean(cookie.httpOnly()); out.writeBoolean(cookie.hostOnly()); out.writeBoolean(cookie.persistent()); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { String name = (String) in.readObject(); String value = (String) in.readObject(); long expiresAt = in.readLong(); String domain = (String) in.readObject(); String path = (String) in.readObject(); boolean secure = in.readBoolean(); boolean httpOnly = in.readBoolean(); boolean hostOnly = in.readBoolean(); boolean persistent = in.readBoolean(); Cookie.Builder builder = new Cookie.Builder(); builder = builder.name(name); builder = builder.value(value); builder = builder.expiresAt(expiresAt); builder = hostOnly ? builder.hostOnlyDomain(domain) : builder.domain(domain); builder = builder.path(path); builder = secure ? builder.secure() : builder; builder = httpOnly ? builder.httpOnly() : builder; clientCookie = builder.build(); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/okhttp/cookie/store/PersistentCookieStore.java
architecture/src/main/java/com/jiang/android/architecture/okhttp/cookie/store/PersistentCookieStore.java
package com.jiang.android.architecture.okhttp.cookie.store; import android.content.Context; import android.content.SharedPreferences; import android.text.TextUtils; import android.util.Log; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import okhttp3.Cookie; import okhttp3.HttpUrl; /** * <pre> * OkHttpClient client = new OkHttpClient.Builder() * .cookieJar(new JavaNetCookieJar(new CookieManager( * new PersistentCookieStore(getApplicationContext()), * CookiePolicy.ACCEPT_ALL)) * .build(); * * </pre> * <p/> * from http://stackoverflow.com/questions/25461792/persistent-cookie-store-using-okhttp-2-on-android * <p/> * <br/> * A persistent cookie store which implements the Apache HttpClient CookieStore interface. * Cookies are stored and will persist on the user's device between application sessions since they * are serialized and stored in SharedPreferences. Instances of this class are * designed to be used with AsyncHttpClient#setCookieStore, but can also be used with a * regular old apache HttpClient/HttpContext if you prefer. */ public class PersistentCookieStore implements CookieStore { private static final String LOG_TAG = "PersistentCookieStore"; private static final String COOKIE_PREFS = "CookiePrefsFile"; private static final String COOKIE_NAME_PREFIX = "cookie_"; private final HashMap<String, ConcurrentHashMap<String, Cookie>> cookies; private final SharedPreferences cookiePrefs; /** * Construct a persistent cookie store. * * @param context Context to attach cookie store to */ public PersistentCookieStore(Context context) { cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0); cookies = new HashMap<String, ConcurrentHashMap<String, Cookie>>(); // Load any previously stored cookies into the store Map<String, ?> prefsMap = cookiePrefs.getAll(); for (Map.Entry<String, ?> entry : prefsMap.entrySet()) { if (((String) entry.getValue()) != null && !((String) entry.getValue()).startsWith(COOKIE_NAME_PREFIX)) { String[] cookieNames = TextUtils.split((String) entry.getValue(), ","); for (String name : cookieNames) { String encodedCookie = cookiePrefs.getString(COOKIE_NAME_PREFIX + name, null); if (encodedCookie != null) { Cookie decodedCookie = decodeCookie(encodedCookie); if (decodedCookie != null) { if (!cookies.containsKey(entry.getKey())) cookies.put(entry.getKey(), new ConcurrentHashMap<String, Cookie>()); cookies.get(entry.getKey()).put(name, decodedCookie); } } } } } } protected void add(HttpUrl uri, Cookie cookie) { String name = getCookieToken(cookie); if (cookie.persistent()) { if (!cookies.containsKey(uri.host())) cookies.put(uri.host(), new ConcurrentHashMap<String, Cookie>()); cookies.get(uri.host()).put(name, cookie); } // Save cookie into persistent store SharedPreferences.Editor prefsWriter = cookiePrefs.edit(); prefsWriter.putString(uri.host(), TextUtils.join(",", cookies.get(uri.host()).keySet())); prefsWriter.putString(COOKIE_NAME_PREFIX + name, encodeCookie(new SerializableHttpCookie(cookie))); prefsWriter.commit(); } protected String getCookieToken(Cookie cookie) { return cookie.name() + cookie.domain(); } @Override public void add(HttpUrl uri, List<Cookie> cookies) { for (Cookie cookie : cookies) { add(uri, cookie); } } @Override public List<Cookie> get(HttpUrl uri) { ArrayList<Cookie> ret = new ArrayList<Cookie>(); if (cookies.containsKey(uri.host())) { Collection<Cookie> cookies = this.cookies.get(uri.host()).values(); for (Cookie cookie : cookies) { if (isCookieExpired(cookie)) { remove(uri, cookie); } else { ret.add(cookie); } } } return ret; } private static boolean isCookieExpired(Cookie cookie) { return cookie.expiresAt() < System.currentTimeMillis(); } @Override public boolean removeAll() { SharedPreferences.Editor prefsWriter = cookiePrefs.edit(); prefsWriter.clear(); prefsWriter.commit(); cookies.clear(); return true; } @Override public boolean remove(HttpUrl uri, Cookie cookie) { String name = getCookieToken(cookie); if (cookies.containsKey(uri.host()) && cookies.get(uri.host()).containsKey(name)) { cookies.get(uri.host()).remove(name); SharedPreferences.Editor prefsWriter = cookiePrefs.edit(); if (cookiePrefs.contains(COOKIE_NAME_PREFIX + name)) { prefsWriter.remove(COOKIE_NAME_PREFIX + name); } prefsWriter.putString(uri.host(), TextUtils.join(",", cookies.get(uri.host()).keySet())); prefsWriter.commit(); return true; } else { return false; } } @Override public List<Cookie> getCookies() { ArrayList<Cookie> ret = new ArrayList<Cookie>(); for (String key : cookies.keySet()) ret.addAll(cookies.get(key).values()); return ret; } protected String encodeCookie(SerializableHttpCookie cookie) { if (cookie == null) return null; ByteArrayOutputStream os = new ByteArrayOutputStream(); try { ObjectOutputStream outputStream = new ObjectOutputStream(os); outputStream.writeObject(cookie); } catch (IOException e) { Log.d(LOG_TAG, "IOException in encodeCookie", e); return null; } return byteArrayToHexString(os.toByteArray()); } protected Cookie decodeCookie(String cookieString) { byte[] bytes = hexStringToByteArray(cookieString); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); Cookie cookie = null; try { ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); cookie = ((SerializableHttpCookie) objectInputStream.readObject()).getCookie(); } catch (IOException e) { Log.d(LOG_TAG, "IOException in decodeCookie", e); } catch (ClassNotFoundException e) { Log.d(LOG_TAG, "ClassNotFoundException in decodeCookie", e); } return cookie; } /** * Using some super basic byte array &lt;-&gt; hex conversions so we don't have to rely on any * large Base64 libraries. Can be overridden if you like! * * @param bytes byte array to be converted * @return string containing hex values */ protected String byteArrayToHexString(byte[] bytes) { StringBuilder sb = new StringBuilder(bytes.length * 2); for (byte element : bytes) { int v = element & 0xff; if (v < 16) { sb.append('0'); } sb.append(Integer.toHexString(v)); } return sb.toString().toUpperCase(Locale.US); } /** * Converts hex values from strings to byte arra * * @param hexString string of hex-encoded values * @return decoded byte array */ protected byte[] hexStringToByteArray(String hexString) { int len = hexString.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i + 1), 16)); } return data; } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/okhttp/cookie/store/CookieStore.java
architecture/src/main/java/com/jiang/android/architecture/okhttp/cookie/store/CookieStore.java
package com.jiang.android.architecture.okhttp.cookie.store; import java.util.List; import okhttp3.Cookie; import okhttp3.HttpUrl; public interface CookieStore { public void add(HttpUrl uri, List<Cookie> cookie); public List<Cookie> get(HttpUrl uri); public List<Cookie> getCookies(); public boolean remove(HttpUrl uri, Cookie cookie); public boolean removeAll(); }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/okhttp/cookie/store/HasCookieStore.java
architecture/src/main/java/com/jiang/android/architecture/okhttp/cookie/store/HasCookieStore.java
package com.jiang.android.architecture.okhttp.cookie.store; /** * Created by zhy on 16/3/10. */ public interface HasCookieStore { CookieStore getCookieStore(); }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/okhttp/cookie/store/MemoryCookieStore.java
architecture/src/main/java/com/jiang/android/architecture/okhttp/cookie/store/MemoryCookieStore.java
package com.jiang.android.architecture.okhttp.cookie.store; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Set; import okhttp3.Cookie; import okhttp3.HttpUrl; /** * Created by zhy on 16/3/10. */ public class MemoryCookieStore implements CookieStore { private final HashMap<String, List<Cookie>> allCookies = new HashMap<>(); @Override public void add(HttpUrl url, List<Cookie> cookies) { List<Cookie> oldCookies = allCookies.get(url.host()); Iterator<Cookie> itNew = cookies.iterator(); Iterator<Cookie> itOld = oldCookies.iterator(); while (itNew.hasNext()) { String va = itNew.next().name(); while (va != null && itOld.hasNext()) { String v = itOld.next().name(); if (v != null && va.equals(v)) { itOld.remove(); } } } oldCookies.addAll(cookies); } @Override public List<Cookie> get(HttpUrl uri) { List<Cookie> cookies = allCookies.get(uri.host()); if (cookies == null) { cookies = new ArrayList<>(); allCookies.put(uri.host(), cookies); } return cookies; } @Override public boolean removeAll() { allCookies.clear(); return true; } @Override public List<Cookie> getCookies() { List<Cookie> cookies = new ArrayList<>(); Set<String> httpUrls = allCookies.keySet(); for (String url : httpUrls) { cookies.addAll(allCookies.get(url)); } return cookies; } @Override public boolean remove(HttpUrl uri, Cookie cookie) { List<Cookie> cookies = allCookies.get(uri); if (cookie != null) { return cookies.remove(cookie); } return false; } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/okhttp/exception/NotPermissionException.java
architecture/src/main/java/com/jiang/android/architecture/okhttp/exception/NotPermissionException.java
/** * created by jiang, 12/5/15 * Copyright (c) 2015, jyuesong@gmail.com All Rights Reserved. * * # # * # _oo0oo_ # * # o8888888o # * # 88" . "88 # * # (| -_- |) # * # 0\ = /0 # * # ___/`---'\___ # * # .' \\| |# '. # * # / \\||| : |||# \ # * # / _||||| -:- |||||- \ # * # | | \\\ - #/ | | # * # | \_| ''\---/'' |_/ | # * # \ .-\__ '-' ___/-. / # * # ___'. .' /--.--\ `. .'___ # * # ."" '< `.___\_<|>_/___.' >' "". # * # | | : `- \`.;`\ _ /`;.`/ - ` : | | # * # \ \ `_. \_ __\ /__ _/ .-` / / # * # =====`-.____`.___ \_____/___.-`___.-'===== # * # `=---=' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # * # # * # 佛祖保佑 永无BUG # * # # */ package com.jiang.android.architecture.okhttp.exception; /** * Created by jiang on 12/5/15. */ public class NotPermissionException extends RuntimeException { private static final long serialVersionUID = 110L; public NotPermissionException() { } public NotPermissionException(String detailMessage) { super(detailMessage); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/okhttp/exception/Exceptions.java
architecture/src/main/java/com/jiang/android/architecture/okhttp/exception/Exceptions.java
package com.jiang.android.architecture.okhttp.exception; public class Exceptions { public static void illegalArgument(String msg, Object... params) { throw new IllegalArgumentException(String.format(msg, params)); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/okhttp/callback/NormalCallBack.java
architecture/src/main/java/com/jiang/android/architecture/okhttp/callback/NormalCallBack.java
package com.jiang.android.architecture.okhttp.callback; import com.jiang.android.architecture.okhttp.ws_ret; import okhttp3.Response; /** * Created by jiang on 2016/11/29. */ public abstract class NormalCallBack<T> extends BaseCallBack<T> { @Override public void onNoData(ws_ret ret) { } @Override public void onBefore() { } @Override public void onAfter() { } @Override public void onFinishResponse(Response response) { } @Override public void onProgress(long progress) { } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/okhttp/callback/BaseCallBack.java
architecture/src/main/java/com/jiang/android/architecture/okhttp/callback/BaseCallBack.java
/** * created by jiang, 10/25/15 * Copyright (c) 2015, jyuesong@gmail.com All Rights Reserved. * * # # * # _oo0oo_ # * # o8888888o # * # 88" . "88 # * # (| -_- |) # * # 0\ = /0 # * # ___/`---'\___ # * # .' \\| |# '. # * # / \\||| : |||# \ # * # / _||||| -:- |||||- \ # * # | | \\\ - #/ | | # * # | \_| ''\---/'' |_/ | # * # \ .-\__ '-' ___/-. / # * # ___'. .' /--.--\ `. .'___ # * # ."" '< `.___\_<|>_/___.' >' "". # * # | | : `- \`.;`\ _ /`;.`/ - ` : | | # * # \ \ `_. \_ __\ /__ _/ .-` / / # * # =====`-.____`.___ \_____/___.-`___.-'===== # * # `=---=' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # * # # * # 佛祖保佑 永无BUG # * # # */ package com.jiang.android.architecture.okhttp.callback; import com.google.gson.internal.$Gson$Types; import com.jiang.android.architecture.okhttp.ws_ret; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import okhttp3.Response; /** * 所有网络请求的统一回调 * Created by jiang on 10/25/15. */ public abstract class BaseCallBack<T> { /** * 失败 * * @param ret 数据 */ public abstract void onFail(ws_ret ret); //失败 /** * 成功 * * @param t 数据 */ public abstract void onSuccess(T t); //成功 /** * 无数据, 只在get中用到 * * @param ret 数据 */ public abstract void onNoData(ws_ret ret); //无数据, 注意: 当是post请求的时候该方法不会回调 /** * 网络请求开始时执行 */ public abstract void onBefore(); /** * 网络请求结束时执行, 比如停止下拉刷新控件的执行 */ public abstract void onAfter(); /** * 所有的网络请求成功以后都会走这个方法, * * @param response 数据 */ public abstract void onFinishResponse(Response response); /** * 下载文件事 的进度 * * @param progress 进度 */ public abstract void onProgress(long progress); /** * 获得泛型的类型 */ public Type mType; public BaseCallBack() { mType = getSuperclassTypeParameter(getClass()); } static Type getSuperclassTypeParameter(Class<?> subclass) { Type superclass = subclass.getGenericSuperclass(); if (superclass instanceof Class) { throw new RuntimeException("泛型参数不能为空"); } ParameterizedType parameterized = (ParameterizedType) superclass; return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/okhttp/utils/HttpUtils.java
architecture/src/main/java/com/jiang/android/architecture/okhttp/utils/HttpUtils.java
/** * created by jiang, 15/10/19 * Copyright (c) 2015, jyuesong@gmail.com All Rights Reserved. * * # # * # _oo0oo_ # * # o8888888o # * # 88" . "88 # * # (| -_- |) # * # 0\ = /0 # * # ___/`---'\___ # * # .' \\| |# '. # * # / \\||| : |||# \ # * # / _||||| -:- |||||- \ # * # | | \\\ - #/ | | # * # | \_| ''\---/'' |_/ | # * # \ .-\__ '-' ___/-. / # * # ___'. .' /--.--\ `. .'___ # * # ."" '< `.___\_<|>_/___.' >' "". # * # | | : `- \`.;`\ _ /`;.`/ - ` : | | # * # \ \ `_. \_ __\ /__ _/ .-` / / # * # =====`-.____`.___ \_____/___.-`___.-'===== # * # `=---=' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # * # # * # 佛祖保佑 永无BUG # * # # */ package com.jiang.android.architecture.okhttp.utils; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.text.TextUtils; import com.jiang.android.architecture.okhttp.Param; import java.util.Map; import java.util.Set; /** * 相关网络请求的工具类 * Created by jiang on 15/10/16. */ public class HttpUtils { public static String parseParams2String(Map<String, String> param) { if (param == null || param.size() == 0) return ""; StringBuffer buffer = new StringBuffer(); Set<Map.Entry<String, String>> entrySet = param.entrySet(); for (Map.Entry<String, String> entry : entrySet) { Param par = new Param(entry.getKey(), entry.getValue()); buffer.append(par.toString()).append("&"); } return buffer.substring(0, buffer.length() - 1); } public static boolean isNetworkConnected(Context ct) { ConnectivityManager cm = (ConnectivityManager) ct.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ni = cm.getActiveNetworkInfo(); return ni != null && ni.isConnectedOrConnecting(); } public static final int NETTYPE_WIFI = 0x01; public static final int NETTYPE_CMWAP = 0x02; public static final int NETTYPE_CMNET = 0x03; public static int getNetworkType(Context ct) { int netType = 0; ConnectivityManager connectivityManager = (ConnectivityManager) ct.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); if (networkInfo == null) { return netType; } int nType = networkInfo.getType(); if (nType == ConnectivityManager.TYPE_MOBILE) { String extraInfo = networkInfo.getExtraInfo(); if (!TextUtils.isEmpty(extraInfo)) { if (extraInfo.toLowerCase().equals("cmnet")) { netType = NETTYPE_CMNET; } else { netType = NETTYPE_CMWAP; } } } else if (nType == ConnectivityManager.TYPE_WIFI) { netType = NETTYPE_WIFI; } return netType; } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/okhttp/utils/HeaderUtils.java
architecture/src/main/java/com/jiang/android/architecture/okhttp/utils/HeaderUtils.java
/** * created by jiang, 10/23/15 * Copyright (c) 2015, jyuesong@gmail.com All Rights Reserved. * * # # * # _oo0oo_ # * # o8888888o # * # 88" . "88 # * # (| -_- |) # * # 0\ = /0 # * # ___/`---'\___ # * # .' \\| |# '. # * # / \\||| : |||# \ # * # / _||||| -:- |||||- \ # * # | | \\\ - #/ | | # * # | \_| ''\---/'' |_/ | # * # \ .-\__ '-' ___/-. / # * # ___'. .' /--.--\ `. .'___ # * # ."" '< `.___\_<|>_/___.' >' "". # * # | | : `- \`.;`\ _ /`;.`/ - ` : | | # * # \ \ `_. \_ __\ /__ _/ .-` / / # * # =====`-.____`.___ \_____/___.-`___.-'===== # * # `=---=' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # * # # * # 佛祖保佑 永无BUG # * # # */ package com.jiang.android.architecture.okhttp.utils; import com.jiang.android.architecture.okhttp.Param; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; /** * Created by jiang on 10/23/15. */ public class HeaderUtils { public static List<Param> validateHeaders(Map<String, String> header) { if (header == null || header.size() == 0) return null; List<Param> results = new LinkedList<>(); Set<Map.Entry<String, String>> entrySet = header.entrySet(); for (Map.Entry<String, String> entry : entrySet) { Param param = new Param(entry.getKey(), entry.getValue()); results.add(param); } return results; } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/okhttp/utils/HttpsUtils.java
architecture/src/main/java/com/jiang/android/architecture/okhttp/utils/HttpsUtils.java
package com.jiang.android.architecture.okhttp.utils; import java.io.IOException; import java.io.InputStream; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; /** * Created by zhy on 15/12/14. */ public class HttpsUtils { public static SSLSocketFactory getSslSocketFactory(InputStream[] certificates, InputStream bksFile, String password) { try { TrustManager[] trustManagers = prepareTrustManager(certificates); KeyManager[] keyManagers = prepareKeyManager(bksFile, password); SSLContext sslContext = SSLContext.getInstance("TLS"); TrustManager trustManager = null; if (trustManagers != null) { trustManager = new MyTrustManager(chooseTrustManager(trustManagers)); } else { trustManager = new UnSafeTrustManager(); } sslContext.init(keyManagers, new TrustManager[]{trustManager}, new SecureRandom()); return sslContext.getSocketFactory(); } catch (NoSuchAlgorithmException e) { throw new AssertionError(e); } catch (KeyManagementException e) { throw new AssertionError(e); } catch (KeyStoreException e) { throw new AssertionError(e); } } private class UnSafeHostnameVerifier implements HostnameVerifier { @Override public boolean verify(String hostname, SSLSession session) { return true; } } private static class UnSafeTrustManager implements X509TrustManager { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[]{}; } } private static TrustManager[] prepareTrustManager(InputStream... certificates) { if (certificates == null || certificates.length <= 0) return null; try { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null); int index = 0; for (InputStream certificate : certificates) { String certificateAlias = Integer.toString(index++); keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate)); try { if (certificate != null) certificate.close(); } catch (IOException e) { } } TrustManagerFactory trustManagerFactory = null; trustManagerFactory = TrustManagerFactory. getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); return trustManagers; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return null; } private static KeyManager[] prepareKeyManager(InputStream bksFile, String password) { try { if (bksFile == null || password == null) return null; KeyStore clientKeyStore = KeyStore.getInstance("BKS"); clientKeyStore.load(bksFile, password.toCharArray()); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(clientKeyStore, password.toCharArray()); return keyManagerFactory.getKeyManagers(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnrecoverableKeyException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return null; } private static X509TrustManager chooseTrustManager(TrustManager[] trustManagers) { for (TrustManager trustManager : trustManagers) { if (trustManager instanceof X509TrustManager) { return (X509TrustManager) trustManager; } } return null; } private static class MyTrustManager implements X509TrustManager { private X509TrustManager defaultTrustManager; private X509TrustManager localTrustManager; public MyTrustManager(X509TrustManager localTrustManager) throws NoSuchAlgorithmException, KeyStoreException { TrustManagerFactory var4 = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); var4.init((KeyStore) null); defaultTrustManager = chooseTrustManager(var4.getTrustManagers()); this.localTrustManager = localTrustManager; } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { try { defaultTrustManager.checkServerTrusted(chain, authType); } catch (CertificateException ce) { localTrustManager.checkServerTrusted(chain, authType); } } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/okhttp/log/HttpLoggingInterceptor.java
architecture/src/main/java/com/jiang/android/architecture/okhttp/log/HttpLoggingInterceptor.java
package com.jiang.android.architecture.okhttp.log; import java.io.EOFException; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.UnsupportedCharsetException; import java.util.concurrent.TimeUnit; import okhttp3.Connection; import okhttp3.Headers; import okhttp3.Interceptor; import okhttp3.MediaType; import okhttp3.Protocol; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.ResponseBody; import okhttp3.internal.http.HttpHeaders; import okhttp3.internal.platform.Platform; import okio.Buffer; import okio.BufferedSource; import static okhttp3.internal.platform.Platform.INFO; /** * Created by jiang on 2016/10/11. */ public class HttpLoggingInterceptor implements Interceptor { private static final Charset UTF8 = Charset.forName("UTF-8"); public enum Level { /** * No logs. */ NONE, /** * Logs request and response lines. * <p> * <p>Example: * <pre>{@code * --> POST /greeting http/1.1 (3-byte body) * * <-- 200 OK (22ms, 6-byte body) * }</pre> */ BASIC, /** * Logs request and response lines and their respective headers. * <p> * <p>Example: * <pre>{@code * --> POST /greeting http/1.1 * Host: example.com * Content-Type: plain/text * Content-Length: 3 * --> END POST * * <-- 200 OK (22ms) * Content-Type: plain/text * Content-Length: 6 * <-- END HTTP * }</pre> */ HEADERS, /** * Logs request and response lines and their respective headers and bodies (if present). * <p> * <p>Example: * <pre>{@code * --> POST /greeting http/1.1 * Host: example.com * Content-Type: plain/text * Content-Length: 3 * * Hi? * --> END POST * * <-- 200 OK (22ms) * Content-Type: plain/text * Content-Length: 6 * * Hello! * <-- END HTTP * }</pre> */ BODY } public interface Logger { void log(String message, String json); /** * A {@link Logger} defaults output appropriate for the current platform. */ Logger DEFAULT = new Logger() { @Override public void log(String message, String json) { Platform.get().log(INFO, message, null); } }; } public HttpLoggingInterceptor() { this(Logger.DEFAULT); } public HttpLoggingInterceptor(Logger logger) { this.logger = logger; } private final Logger logger; private volatile Level level = Level.NONE; /** * Change the level at which this interceptor logs. */ public HttpLoggingInterceptor setLevel(Level level) { if (level == null) throw new NullPointerException("level == null. Use Level.NONE instead."); this.level = level; return this; } public Level getLevel() { return level; } @Override public Response intercept(Chain chain) throws IOException { Level level = this.level; Request request = chain.request(); if (level == Level.NONE) { return chain.proceed(request); } StringBuilder logBuilder = new StringBuilder(); String responseJson = null; logBuilder.append("\n").append("------------request--------------").append("\n"); boolean logBody = level == Level.BODY; boolean logHeaders = logBody || level == Level.HEADERS; RequestBody requestBody = request.body(); boolean hasRequestBody = requestBody != null; Connection connection = chain.connection(); Protocol protocol = connection != null ? connection.protocol() : Protocol.HTTP_1_1; logBuilder.append("url: ").append(request.url()).append("\n").append("method: ").append(request.method()) .append("\n").append("protocol: ").append(protocol).append("\n"); if (!logHeaders && hasRequestBody) { logBuilder.append(" (" + requestBody.contentLength() + "-byte body)"); } if (logHeaders) { if (hasRequestBody) { // Request body headers are only present when installed as a network interceptor. Force // them to be included (when available) so there values are known. if (requestBody.contentType() != null) { logBuilder.append("Content-Type: " + requestBody.contentType()).append("\n"); } if (requestBody.contentLength() != -1) { logBuilder.append("Content-Length: " + requestBody.contentLength()).append("\n"); } } Headers headers = request.headers(); logBuilder.append("--------headers----------").append("\n"); for (int i = 0, count = headers.size(); i < count; i++) { String name = headers.name(i); // Skip headers from the request body as they are explicitly logged above. if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) { logBuilder.append(name + ": " + headers.value(i)).append("\n"); } } if (!logBody || !hasRequestBody) { logBuilder.append("------------end--------------").append("\n"); } else if (bodyEncoded(request.headers())) { logBuilder.append("------------end--------------" + " (encoded body omitted)").append("\n"); } else { logBuilder.append("--------body----------").append("\n"); Buffer buffer = new Buffer(); requestBody.writeTo(buffer); Charset charset = UTF8; MediaType contentType = requestBody.contentType(); if (contentType != null) { charset = contentType.charset(UTF8); } if (isPlaintext(buffer)) { logBuilder.append(buffer.readString(charset)).append("\n"); logBuilder.append(" (" + requestBody.contentLength() + "-byte body)").append("\n"); } else { logBuilder.append(" (binary " + requestBody.contentLength() + "-byte body omitted)").append("\n"); } } } logBuilder.append("\n").append("------------response--------------").append("\n"); long startNs = System.nanoTime(); Response response; try { response = chain.proceed(request); } catch (Exception e) { logBuilder.append("HTTP FAILED: " + e).append("\n"); throw e; } long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); ResponseBody responseBody = response.body(); long contentLength = responseBody.contentLength(); String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length"; logBuilder.append("code: ").append(response.code()).append("\n") .append("message: ").append(response.message()).append("\n") .append("time: ").append(tookMs).append("ms \n") .append(!logHeaders ? "bodySize: " + bodySize : "").append("\n"); if (logHeaders) { Headers headers = response.headers(); logBuilder.append("--------headers----------").append("\n"); for (int i = 0, count = headers.size(); i < count; i++) { logBuilder.append(headers.name(i) + ": " + headers.value(i)).append("\n"); } if (!logBody || !HttpHeaders.hasBody(response)) { logBuilder.append("------------end--------------").append("\n"); } else if (bodyEncoded(response.headers())) { logBuilder.append("------------end--------------(encoded body omitted)").append("\n"); } else { BufferedSource source = responseBody.source(); source.request(Long.MAX_VALUE); // Buffer the entire body. Buffer buffer = source.buffer(); Charset charset = UTF8; MediaType contentType = responseBody.contentType(); if (contentType != null) { try { charset = contentType.charset(UTF8); } catch (UnsupportedCharsetException e) { logBuilder.append("Couldn't decode the response body; charset is likely malformed.").append("\n"); logBuilder.append("------------end--------------").append("\n"); logger.log(logBuilder.toString(), null); return response; } } if (!isPlaintext(buffer)) { logBuilder.append("(binary " + buffer.size() + "-byte body omitted)").append("\n"); logBuilder.append("------------end--------------").append("\n"); return response; } if (contentLength != 0) { responseJson = buffer.clone().readString(charset); } } } logger.log(logBuilder.toString(), responseJson); return response; } /** * Returns true if the body in question probably contains human readable text. Uses a small sample * of code points to detect unicode control characters commonly used in binary file signatures. */ static boolean isPlaintext(Buffer buffer) { try { Buffer prefix = new Buffer(); long byteCount = buffer.size() < 64 ? buffer.size() : 64; buffer.copyTo(prefix, 0, byteCount); for (int i = 0; i < 16; i++) { if (prefix.exhausted()) { break; } int codePoint = prefix.readUtf8CodePoint(); if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) { return false; } } return true; } catch (EOFException e) { return false; // Truncated UTF-8 sequence. } } private boolean bodyEncoded(Headers headers) { String contentEncoding = headers.get("Content-Encoding"); return contentEncoding != null && !contentEncoding.equalsIgnoreCase("identity"); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/okhttp/request/DeleteRequest.java
architecture/src/main/java/com/jiang/android/architecture/okhttp/request/DeleteRequest.java
/** * created by jiang, 15/10/19 * Copyright (c) 2015, jyuesong@gmail.com All Rights Reserved. * * # # * # _oo0oo_ # * # o8888888o # * # 88" . "88 # * # (| -_- |) # * # 0\ = /0 # * # ___/`---'\___ # * # .' \\| |# '. # * # / \\||| : |||# \ # * # / _||||| -:- |||||- \ # * # | | \\\ - #/ | | # * # | \_| ''\---/'' |_/ | # * # \ .-\__ '-' ___/-. / # * # ___'. .' /--.--\ `. .'___ # * # ."" '< `.___\_<|>_/___.' >' "". # * # | | : `- \`.;`\ _ /`;.`/ - ` : | | # * # \ \ `_. \_ __\ /__ _/ .-` / / # * # =====`-.____`.___ \_____/___.-`___.-'===== # * # `=---=' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # * # # * # 佛祖保佑 永无BUG # * # # */ package com.jiang.android.architecture.okhttp.request; import com.jiang.android.architecture.okhttp.Param; import com.jiang.android.architecture.okhttp.utils.HeaderUtils; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import okhttp3.MultipartBody; import okhttp3.Request; import okhttp3.RequestBody; /** * delete * Created by jiang on 15/10/16. */ public class DeleteRequest { public static Request buildDeleteRequest(String url, Map<String, String> params, Object tag, Map<String, String> headers) { if (params == null) { params = new HashMap<>(); } Request.Builder reqBuilder = new Request.Builder(); if (params != null && params.size() > 0) { MultipartBody.Builder builder = new MultipartBody.Builder() .setType(MultipartBody.FORM); Set<Map.Entry<String, String>> entrySet = params.entrySet(); for (Map.Entry<String, String> entry : entrySet) { builder.addFormDataPart(entry.getKey(), entry.getValue()); } RequestBody requestBody = builder.build(); reqBuilder.delete(requestBody); } else { reqBuilder.delete(); } reqBuilder.url(url); List<Param> valdatedHeaders = HeaderUtils.validateHeaders(headers); if (valdatedHeaders != null && valdatedHeaders.size() > 0) { for (int i = 0; i < valdatedHeaders.size(); i++) { Param param = valdatedHeaders.get(i); String key = param.key; String value = param.value; reqBuilder.addHeader(key, value); } } if (tag != null) { reqBuilder.tag(tag); } return reqBuilder.build(); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/okhttp/request/PostRequest.java
architecture/src/main/java/com/jiang/android/architecture/okhttp/request/PostRequest.java
/** * created by jiang, 15/10/19 * Copyright (c) 2015, jyuesong@gmail.com All Rights Reserved. * * # # * # _oo0oo_ # * # o8888888o # * # 88" . "88 # * # (| -_- |) # * # 0\ = /0 # * # ___/`---'\___ # * # .' \\| |# '. # * # / \\||| : |||# \ # * # / _||||| -:- |||||- \ # * # | | \\\ - #/ | | # * # | \_| ''\---/'' |_/ | # * # \ .-\__ '-' ___/-. / # * # ___'. .' /--.--\ `. .'___ # * # ."" '< `.___\_<|>_/___.' >' "". # * # | | : `- \`.;`\ _ /`;.`/ - ` : | | # * # \ \ `_. \_ __\ /__ _/ .-` / / # * # =====`-.____`.___ \_____/___.-`___.-'===== # * # `=---=' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # * # # * # 佛祖保佑 永无BUG # * # # */ package com.jiang.android.architecture.okhttp.request; import com.jiang.android.architecture.okhttp.Param; import com.jiang.android.architecture.okhttp.utils.HeaderUtils; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import okhttp3.MultipartBody; import okhttp3.Request; import okhttp3.RequestBody; /** * 生成post需要的request * Created by jiang on 15/10/16. */ public class PostRequest { public static Request buildPostRequest(String url, Map<String, String> params, Object tag, Map<String, String> headers) { if (params == null) { params = new HashMap<>(); } RequestBody requestBody = null; if (params == null || params.size() == 0) { requestBody = RequestBody.create(null, new byte[0]); } else { MultipartBody.Builder builder = new MultipartBody.Builder() .setType(MultipartBody.FORM); Set<Map.Entry<String, String>> entrySet = params.entrySet(); for (Map.Entry<String, String> entry : entrySet) { builder.addFormDataPart(entry.getKey(), entry.getValue()); } requestBody = builder.build(); } Request.Builder reqBuilder = new Request.Builder(); reqBuilder.post(requestBody).url(url); List<Param> valdatedHeaders = HeaderUtils.validateHeaders(headers); if (valdatedHeaders != null && valdatedHeaders.size() > 0) { for (int i = 0; i < valdatedHeaders.size(); i++) { Param param = valdatedHeaders.get(i); String key = param.key; String value = param.value; reqBuilder.addHeader(key, value); } } if (tag != null) { reqBuilder.tag(tag); } return reqBuilder.build(); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/okhttp/request/UploadRequest.java
architecture/src/main/java/com/jiang/android/architecture/okhttp/request/UploadRequest.java
package com.jiang.android.architecture.okhttp.request; import com.jiang.android.architecture.okhttp.Param; import com.jiang.android.architecture.okhttp.utils.HeaderUtils; import java.util.List; import java.util.Map; import okhttp3.Request; import okhttp3.RequestBody; /** * Created by jiang on 16/7/28. */ public class UploadRequest { public static Request buildPostRequest(String url, Map<String, String> headers, Object tab, RequestBody requestBody) { Request.Builder reqBuilder = new Request.Builder(); reqBuilder.post(requestBody).url(url); reqBuilder.tag(tab); List<Param> valdatedHeaders = HeaderUtils.validateHeaders(headers); if (valdatedHeaders != null && valdatedHeaders.size() > 0) { for (int i = 0; i < valdatedHeaders.size(); i++) { Param param = valdatedHeaders.get(i); String key = param.key; String value = param.value; reqBuilder.addHeader(key, value); } } return reqBuilder.build(); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/okhttp/request/PutRequest.java
architecture/src/main/java/com/jiang/android/architecture/okhttp/request/PutRequest.java
/** * created by jiang, 16/5/14 * Copyright (c) 2016, jyuesong@gmail.com All Rights Reserved. * * # # * # _oo0oo_ # * # o8888888o # * # 88" . "88 # * # (| -_- |) # * # 0\ = /0 # * # ___/`---'\___ # * # .' \\| |# '. # * # / \\||| : |||# \ # * # / _||||| -:- |||||- \ # * # | | \\\ - #/ | | # * # | \_| ''\---/'' |_/ | # * # \ .-\__ '-' ___/-. / # * # ___'. .' /--.--\ `. .'___ # * # ."" '< `.___\_<|>_/___.' >' "". # * # | | : `- \`.;`\ _ /`;.`/ - ` : | | # * # \ \ `_. \_ __\ /__ _/ .-` / / # * # =====`-.____`.___ \_____/___.-`___.-'===== # * # `=---=' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # * # # * # 佛祖保佑 永无BUG # * # # */ package com.jiang.android.architecture.okhttp.request; import com.jiang.android.architecture.okhttp.OkHttpTask; import com.jiang.android.architecture.okhttp.Param; import com.jiang.android.architecture.okhttp.utils.HeaderUtils; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import okhttp3.MultipartBody; import okhttp3.Request; import okhttp3.RequestBody; /** * Created by jiang on 16/5/14. */ public class PutRequest { public static Request buildOtherRequest(String url, Map<String, String> params, Object tag, Map<String, String> headers, int type) { if (params == null) { params = new HashMap<>(); } RequestBody requestBody = null; if (params == null || params.size() == 0) { requestBody = RequestBody.create(null, new byte[0]); } else { MultipartBody.Builder builder = new MultipartBody.Builder() .setType(MultipartBody.FORM); Set<Map.Entry<String, String>> entrySet = params.entrySet(); for (Map.Entry<String, String> entry : entrySet) { builder.addFormDataPart(entry.getKey(), entry.getValue()); } requestBody = builder.build(); } Request.Builder reqBuilder = new Request.Builder(); if (type == OkHttpTask.TYPE_DELETE) { reqBuilder.delete(requestBody).url(url); } else if (type == OkHttpTask.TYPE_PUT) { reqBuilder.put(requestBody).url(url); } List<Param> valdatedHeaders = HeaderUtils.validateHeaders(headers); if (valdatedHeaders != null && valdatedHeaders.size() > 0) { for (int i = 0; i < valdatedHeaders.size(); i++) { Param param = valdatedHeaders.get(i); String key = param.key; String value = param.value; reqBuilder.addHeader(key, value); } } if (tag != null) { reqBuilder.tag(tag); } return reqBuilder.build(); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/okhttp/request/CountingRequestBody.java
architecture/src/main/java/com/jiang/android/architecture/okhttp/request/CountingRequestBody.java
package com.jiang.android.architecture.okhttp.request; import java.io.IOException; import okhttp3.MediaType; import okhttp3.RequestBody; import okio.Buffer; import okio.BufferedSink; import okio.ForwardingSink; import okio.Okio; import okio.Sink; /** * Decorates an OkHttp request body to count the number of bytes written when writing it. Can * decorate any request body, but is most useful for tracking the upload progress of large * multipart requests. * * @author Leo Nikkilä */ public class CountingRequestBody extends RequestBody { protected RequestBody delegate; protected Listener listener; protected int position; protected CountingSink countingSink; public CountingRequestBody(RequestBody delegate, Listener listener, int position) { this.delegate = delegate; this.listener = listener; this.position = position; } @Override public MediaType contentType() { return delegate.contentType(); } @Override public long contentLength() { try { return delegate.contentLength(); } catch (IOException e) { e.printStackTrace(); } return -1; } @Override public void writeTo(BufferedSink sink) throws IOException { countingSink = new CountingSink(sink); BufferedSink bufferedSink = Okio.buffer(countingSink); delegate.writeTo(bufferedSink); bufferedSink.flush(); } protected final class CountingSink extends ForwardingSink { private long bytesWritten = 0; public CountingSink(Sink delegate) { super(delegate); } @Override public void write(Buffer source, long byteCount) throws IOException { super.write(source, byteCount); bytesWritten += byteCount; listener.onRequestProgress(bytesWritten, contentLength(), position); } } public static interface Listener { public void onRequestProgress(long bytesWritten, long contentLength, int position); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/okhttp/request/getRequest.java
architecture/src/main/java/com/jiang/android/architecture/okhttp/request/getRequest.java
/** * created by jiang, 15/10/19 * Copyright (c) 2015, jyuesong@gmail.com All Rights Reserved. * * # # * # _oo0oo_ # * # o8888888o # * # 88" . "88 # * # (| -_- |) # * # 0\ = /0 # * # ___/`---'\___ # * # .' \\| |# '. # * # / \\||| : |||# \ # * # / _||||| -:- |||||- \ # * # | | \\\ - #/ | | # * # | \_| ''\---/'' |_/ | # * # \ .-\__ '-' ___/-. / # * # ___'. .' /--.--\ `. .'___ # * # ."" '< `.___\_<|>_/___.' >' "". # * # | | : `- \`.;`\ _ /`;.`/ - ` : | | # * # \ \ `_. \_ __\ /__ _/ .-` / / # * # =====`-.____`.___ \_____/___.-`___.-'===== # * # `=---=' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # * # # * # 佛祖保佑 永无BUG # * # # */ package com.jiang.android.architecture.okhttp.request; import com.jiang.android.architecture.okhttp.Param; import com.jiang.android.architecture.okhttp.utils.HeaderUtils; import com.jiang.android.architecture.okhttp.utils.HttpUtils; import java.util.List; import java.util.Map; import okhttp3.Request; /** * 生成get请求需要的request * Created by jiang on 15/10/16. */ public class getRequest { public static Request buildGetRequest(String url, Map<String, String> params, Object tag, Map<String, String> headers) { Request.Builder builder = new Request.Builder(); List<Param> valdatedHeaders = HeaderUtils.validateHeaders(headers); if (valdatedHeaders != null && valdatedHeaders.size() != 0) { for (int i = 0; i < valdatedHeaders.size(); i++) { Param param = valdatedHeaders.get(i); String key = param.key; String value = param.value; builder.addHeader(key, value); } } if (params != null && params.size() != 0) { String par = HttpUtils.parseParams2String(params); String api = new StringBuffer().append(url).append("?").append(par).toString(); builder.url(api); } else { builder.url(url); } if (tag != null) { builder.tag(tag); } return builder.build(); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/adapter/BaseViewHolder.java
architecture/src/main/java/com/jiang/android/architecture/adapter/BaseViewHolder.java
/** * created by jiang, 12/3/15 * Copyright (c) 2015, jyuesong@gmail.com All Rights Reserved. * * # # * # _oo0oo_ # * # o8888888o # * # 88" . "88 # * # (| -_- |) # * # 0\ = /0 # * # ___/`---'\___ # * # .' \\| |# '. # * # / \\||| : |||# \ # * # / _||||| -:- |||||- \ # * # | | \\\ - #/ | | # * # | \_| ''\---/'' |_/ | # * # \ .-\__ '-' ___/-. / # * # ___'. .' /--.--\ `. .'___ # * # ."" '< `.___\_<|>_/___.' >' "". # * # | | : `- \`.;`\ _ /`;.`/ - ` : | | # * # \ \ `_. \_ __\ /__ _/ .-` / / # * # =====`-.____`.___ \_____/___.-`___.-'===== # * # `=---=' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # * # # * # 佛祖保佑 永无BUG # * # # */ package com.jiang.android.architecture.adapter; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.annotation.IdRes; import android.support.annotation.IntDef; import android.support.annotation.RequiresApi; import android.support.v7.widget.RecyclerView; import android.util.SparseArray; import android.view.View; import android.widget.TextView; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Created by jiang on 12/3/15. */ public class BaseViewHolder extends RecyclerView.ViewHolder { protected final SparseArray<View> mViews; protected View mConvertView; public BaseViewHolder(View itemView) { super(itemView); mViews = new SparseArray<>(); mConvertView = itemView; } /** * 通过控件的Id获取对应的控件,如果没有则加入mViews,则从item根控件中查找并保存到mViews中 * * @param viewId * @return */ public <T extends View> T getView(@IdRes int viewId) { View view = mViews.get(viewId); if (view == null) { view = mConvertView.findViewById(viewId); mViews.put(viewId, view); } return (T) view; } public View getConvertView() { return mConvertView; } public BaseViewHolder setBgColor(@IdRes int resID, int color) { getView(resID).setBackgroundColor(color); return this; } @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) public BaseViewHolder setBgDrawable(@IdRes int resID, Drawable drawable) { getView(resID).setBackground(drawable); return this; } public BaseViewHolder setTextColor(@IdRes int resID, int color) { ((TextView) getView(resID)).setTextColor(color); return this; } public BaseViewHolder setText(@IdRes int resID, String text) { ((TextView) getView(resID)).setText(text); return this; } public BaseViewHolder setTextSize(@IdRes int resID, int spSize) { ((TextView) getView(resID)).setTextSize(spSize); return this; } public BaseViewHolder setVisibility(@IdRes int resID, @Visibility int visibility) { switch (visibility) { case VISIBLE: getView(resID).setVisibility(View.VISIBLE); break; case INVISIBLE: getView(resID).setVisibility(View.INVISIBLE); break; case GONE: getView(resID).setVisibility(View.GONE); break; } return this; } @IntDef({VISIBLE, INVISIBLE, GONE}) @Retention(RetentionPolicy.SOURCE) public @interface Visibility { } public static final int VISIBLE = 0x00000000; public static final int INVISIBLE = 0x00000004; public static final int GONE = 0x00000008; }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/adapter/BaseAdapter.java
architecture/src/main/java/com/jiang/android/architecture/adapter/BaseAdapter.java
package com.jiang.android.architecture.adapter; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; /** * Created by jiang on 16/8/29. */ public abstract class BaseAdapter extends RecyclerView.Adapter<BaseViewHolder> { @Override public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { final BaseViewHolder holder = new BaseViewHolder(LayoutInflater.from(parent.getContext()).inflate(viewType, parent, false)); if (clickable()) { holder.getConvertView().setClickable(true); holder.getConvertView().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onItemClick(v, holder.getLayoutPosition()); } }); } return holder; } @Override public void onBindViewHolder(final BaseViewHolder holder, final int position) { onBindView(holder, holder.getLayoutPosition()); } public abstract void onBindView(BaseViewHolder holder, int position); @Override public int getItemViewType(int position) { return getLayoutID(position); } public abstract int getLayoutID(int position); public abstract boolean clickable(); public void onItemClick(View v, int position) { } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/adapter/BaseExpandAdapter.java
architecture/src/main/java/com/jiang/android/architecture/adapter/BaseExpandAdapter.java
package com.jiang.android.architecture.adapter; import android.support.v7.widget.RecyclerView; import com.jiang.android.architecture.adapter.expand.StickyRecyclerHeadersAdapter; /** * Created by jiang on 2016/11/29. */ public abstract class BaseExpandAdapter extends BaseAdapter implements StickyRecyclerHeadersAdapter<RecyclerView.ViewHolder> { }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/adapter/expand/HeaderPositionCalculator.java
architecture/src/main/java/com/jiang/android/architecture/adapter/expand/HeaderPositionCalculator.java
package com.jiang.android.architecture.adapter.expand; import android.graphics.Rect; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; /** * Calculates the position and location of header views */ public class HeaderPositionCalculator { private final StickyRecyclerHeadersAdapter mAdapter; private final OrientationProvider mOrientationProvider; private final HeaderProvider mHeaderProvider; private final DimensionCalculator mDimensionCalculator; /** * The following fields are used as buffers for internal calculations. Their sole purpose is to avoid * allocating new Rect every time we need one. */ private final Rect mTempRect1 = new Rect(); private final Rect mTempRect2 = new Rect(); public HeaderPositionCalculator(StickyRecyclerHeadersAdapter adapter, HeaderProvider headerProvider, OrientationProvider orientationProvider, DimensionCalculator dimensionCalculator) { mAdapter = adapter; mHeaderProvider = headerProvider; mOrientationProvider = orientationProvider; mDimensionCalculator = dimensionCalculator; } /** * Determines if a view should have a sticky header. * The view has a sticky header if: * 1. It is the first element in the recycler view * 2. It has a valid ID associated to its position * * @param itemView given by the RecyclerView * @param orientation of the Recyclerview * @param position of the list item in question * @return True if the view should have a sticky header */ public boolean hasStickyHeader(View itemView, int orientation, int position) { int offset, margin; mDimensionCalculator.initMargins(mTempRect1, itemView); if (orientation == LinearLayout.VERTICAL) { offset = itemView.getTop(); margin = mTempRect1.top; } else { offset = itemView.getLeft(); margin = mTempRect1.left; } return offset <= margin && mAdapter.getHeaderId(position) >= 0; } /** * Determines if an item in the list should have a header that is different than the item in the * list that immediately precedes it. Items with no headers will always return false. * * @param position of the list item in questions * @param isReverseLayout TRUE if layout manager has flag isReverseLayout * @return true if this item has a different header than the previous item in the list * @see {@link StickyRecyclerHeadersAdapter#getHeaderId(int)} */ public boolean hasNewHeader(int position, boolean isReverseLayout) { if (indexOutOfBounds(position)) { return false; } long headerId = mAdapter.getHeaderId(position); if (headerId < 0) { return false; } long nextItemHeaderId = -1; int nextItemPosition = position + (isReverseLayout? 1: -1); if (!indexOutOfBounds(nextItemPosition)){ nextItemHeaderId = mAdapter.getHeaderId(nextItemPosition); } int firstItemPosition = isReverseLayout? mAdapter.getItemCount()-1 : 0; return position == firstItemPosition || headerId != nextItemHeaderId; } private boolean indexOutOfBounds(int position) { return position < 0 || position >= mAdapter.getItemCount(); } public void initHeaderBounds(Rect bounds, RecyclerView recyclerView, View header, View firstView, boolean firstHeader) { int orientation = mOrientationProvider.getOrientation(recyclerView); initDefaultHeaderOffset(bounds, recyclerView, header, firstView, orientation); if (firstHeader && isStickyHeaderBeingPushedOffscreen(recyclerView, header)) { View viewAfterNextHeader = getFirstViewUnobscuredByHeader(recyclerView, header); int firstViewUnderHeaderPosition = recyclerView.getChildAdapterPosition(viewAfterNextHeader); View secondHeader = mHeaderProvider.getHeader(recyclerView, firstViewUnderHeaderPosition); translateHeaderWithNextHeader(recyclerView, mOrientationProvider.getOrientation(recyclerView), bounds, header, viewAfterNextHeader, secondHeader); } } private void initDefaultHeaderOffset(Rect headerMargins, RecyclerView recyclerView, View header, View firstView, int orientation) { int translationX, translationY; mDimensionCalculator.initMargins(mTempRect1, header); ViewGroup.LayoutParams layoutParams = firstView.getLayoutParams(); int leftMargin = 0; int topMargin = 0; if (layoutParams instanceof ViewGroup.MarginLayoutParams) { ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) layoutParams; leftMargin = marginLayoutParams.leftMargin; topMargin = marginLayoutParams.topMargin; } if (orientation == LinearLayoutManager.VERTICAL) { translationX = firstView.getLeft() - leftMargin + mTempRect1.left; translationY = Math.max( firstView.getTop() - topMargin - header.getHeight() - mTempRect1.bottom, getListTop(recyclerView) + mTempRect1.top); } else { translationY = firstView.getTop() - topMargin + mTempRect1.top; translationX = Math.max( firstView.getLeft() - leftMargin - header.getWidth() - mTempRect1.right, getListLeft(recyclerView) + mTempRect1.left); } headerMargins.set(translationX, translationY, translationX + header.getWidth(), translationY + header.getHeight()); } private boolean isStickyHeaderBeingPushedOffscreen(RecyclerView recyclerView, View stickyHeader) { View viewAfterHeader = getFirstViewUnobscuredByHeader(recyclerView, stickyHeader); int firstViewUnderHeaderPosition = recyclerView.getChildAdapterPosition(viewAfterHeader); if (firstViewUnderHeaderPosition == RecyclerView.NO_POSITION) { return false; } boolean isReverseLayout = mOrientationProvider.isReverseLayout(recyclerView); if (firstViewUnderHeaderPosition > 0 && hasNewHeader(firstViewUnderHeaderPosition, isReverseLayout)) { View nextHeader = mHeaderProvider.getHeader(recyclerView, firstViewUnderHeaderPosition); mDimensionCalculator.initMargins(mTempRect1, nextHeader); mDimensionCalculator.initMargins(mTempRect2, stickyHeader); if (mOrientationProvider.getOrientation(recyclerView) == LinearLayoutManager.VERTICAL) { int topOfNextHeader = viewAfterHeader.getTop() - mTempRect1.bottom - nextHeader.getHeight() - mTempRect1.top; int bottomOfThisHeader = recyclerView.getPaddingTop() + stickyHeader.getBottom() + mTempRect2.top + mTempRect2.bottom; if (topOfNextHeader < bottomOfThisHeader) { return true; } } else { int leftOfNextHeader = viewAfterHeader.getLeft() - mTempRect1.right - nextHeader.getWidth() - mTempRect1.left; int rightOfThisHeader = recyclerView.getPaddingLeft() + stickyHeader.getRight() + mTempRect2.left + mTempRect2.right; if (leftOfNextHeader < rightOfThisHeader) { return true; } } } return false; } private void translateHeaderWithNextHeader(RecyclerView recyclerView, int orientation, Rect translation, View currentHeader, View viewAfterNextHeader, View nextHeader) { mDimensionCalculator.initMargins(mTempRect1, nextHeader); mDimensionCalculator.initMargins(mTempRect2, currentHeader); if (orientation == LinearLayoutManager.VERTICAL) { int topOfStickyHeader = getListTop(recyclerView) + mTempRect2.top + mTempRect2.bottom; int shiftFromNextHeader = viewAfterNextHeader.getTop() - nextHeader.getHeight() - mTempRect1.bottom - mTempRect1.top - currentHeader.getHeight() - topOfStickyHeader; if (shiftFromNextHeader < topOfStickyHeader) { translation.top += shiftFromNextHeader; } } else { int leftOfStickyHeader = getListLeft(recyclerView) + mTempRect2.left + mTempRect2.right; int shiftFromNextHeader = viewAfterNextHeader.getLeft() - nextHeader.getWidth() - mTempRect1.right - mTempRect1.left - currentHeader.getWidth() - leftOfStickyHeader; if (shiftFromNextHeader < leftOfStickyHeader) { translation.left += shiftFromNextHeader; } } } /** * Returns the first item currently in the RecyclerView that is not obscured by a header. * * @param parent Recyclerview containing all the list items * @return first item that is fully beneath a header */ private View getFirstViewUnobscuredByHeader(RecyclerView parent, View firstHeader) { boolean isReverseLayout = mOrientationProvider.isReverseLayout(parent); int step = isReverseLayout? -1 : 1; int from = isReverseLayout? parent.getChildCount()-1 : 0; for (int i = from; i >= 0 && i <= parent.getChildCount() - 1; i += step) { View child = parent.getChildAt(i); if (!itemIsObscuredByHeader(parent, child, firstHeader, mOrientationProvider.getOrientation(parent))) { return child; } } return null; } /** * Determines if an item is obscured by a header * * * @param parent * @param item to determine if obscured by header * @param header that might be obscuring the item * @param orientation of the {@link RecyclerView} * @return true if the item view is obscured by the header view */ private boolean itemIsObscuredByHeader(RecyclerView parent, View item, View header, int orientation) { RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) item.getLayoutParams(); mDimensionCalculator.initMargins(mTempRect1, header); int adapterPosition = parent.getChildAdapterPosition(item); if (adapterPosition == RecyclerView.NO_POSITION || mHeaderProvider.getHeader(parent, adapterPosition) != header) { // Resolves https://github.com/timehop/sticky-headers-recyclerview/issues/36 // Handles an edge case where a trailing header is smaller than the current sticky header. return false; } if (orientation == LinearLayoutManager.VERTICAL) { int itemTop = item.getTop() - layoutParams.topMargin; int headerBottom = header.getBottom() + mTempRect1.bottom + mTempRect1.top; if (itemTop > headerBottom) { return false; } } else { int itemLeft = item.getLeft() - layoutParams.leftMargin; int headerRight = header.getRight() + mTempRect1.right + mTempRect1.left; if (itemLeft > headerRight) { return false; } } return true; } private int getListTop(RecyclerView view) { if (view.getLayoutManager().getClipToPadding()) { return view.getPaddingTop(); } else { return 0; } } private int getListLeft(RecyclerView view) { if (view.getLayoutManager().getClipToPadding()) { return view.getPaddingLeft(); } else { return 0; } } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/adapter/expand/OrientationProvider.java
architecture/src/main/java/com/jiang/android/architecture/adapter/expand/OrientationProvider.java
package com.jiang.android.architecture.adapter.expand; import android.support.v7.widget.RecyclerView; /** * Interface for getting the orientation of a RecyclerView from its LayoutManager */ public interface OrientationProvider { public int getOrientation(RecyclerView recyclerView); public boolean isReverseLayout(RecyclerView recyclerView); }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/adapter/expand/DimensionCalculator.java
architecture/src/main/java/com/jiang/android/architecture/adapter/expand/DimensionCalculator.java
package com.jiang.android.architecture.adapter.expand; import android.graphics.Rect; import android.view.View; import static android.view.ViewGroup.LayoutParams; import static android.view.ViewGroup.MarginLayoutParams; /** * Helper to calculate various view dimensions */ public class DimensionCalculator { /** * Populates {@link Rect} with margins for any view. * * * @param margins rect to populate * @param view for which to get margins */ public void initMargins(Rect margins, View view) { LayoutParams layoutParams = view.getLayoutParams(); if (layoutParams instanceof MarginLayoutParams) { MarginLayoutParams marginLayoutParams = (MarginLayoutParams) layoutParams; initMarginRect(margins, marginLayoutParams); } else { margins.set(0, 0, 0, 0); } } /** * Converts {@link MarginLayoutParams} into a representative {@link Rect}. * * @param marginRect Rect to be initialized with margins coordinates, where * {@link MarginLayoutParams#leftMargin} is equivalent to {@link Rect#left}, etc. * @param marginLayoutParams margins to populate the Rect with */ private void initMarginRect(Rect marginRect, MarginLayoutParams marginLayoutParams) { marginRect.set( marginLayoutParams.leftMargin, marginLayoutParams.topMargin, marginLayoutParams.rightMargin, marginLayoutParams.bottomMargin ); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/adapter/expand/HeaderRenderer.java
architecture/src/main/java/com/jiang/android/architecture/adapter/expand/HeaderRenderer.java
package com.jiang.android.architecture.adapter.expand; import android.graphics.Canvas; import android.graphics.Rect; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.LinearLayout; /** * Responsible for drawing headers to the canvas provided by the item decoration */ public class HeaderRenderer { private final DimensionCalculator mDimensionCalculator; private final OrientationProvider mOrientationProvider; /** * The following field is used as a buffer for internal calculations. Its sole purpose is to avoid * allocating new RDimensionCalculator.javaDimensionCalculator.javaect every time we need one. */ private final Rect mTempRect = new Rect(); public HeaderRenderer(OrientationProvider orientationProvider) { this(orientationProvider, new DimensionCalculator()); } private HeaderRenderer(OrientationProvider orientationProvider, DimensionCalculator dimensionCalculator) { mOrientationProvider = orientationProvider; mDimensionCalculator = dimensionCalculator; } /** * Draws a header to a canvas, offsetting by some x and y amount * * @param recyclerView the parent recycler view for drawing the header into * @param canvas the canvas on which to draw the header * @param header the view to draw as the header * @param offset a Rect used to define the x/y offset of the header. Specify x/y offset by setting * the {@link Rect#left} and {@link Rect#top} properties, respectively. */ public void drawHeader(RecyclerView recyclerView, Canvas canvas, View header, Rect offset) { canvas.save(); if (recyclerView.getLayoutManager().getClipToPadding()) { // Clip drawing of headers to the padding of the RecyclerView. Avoids drawing in the padding initClipRectForHeader(mTempRect, recyclerView, header); canvas.clipRect(mTempRect); } canvas.translate(offset.left, offset.top); header.draw(canvas); canvas.restore(); } /** * Initializes a clipping rect for the header based on the margins of the header and the padding of the * recycler. * FIXME: Currently right margin in VERTICAL orientation and bottom margin in HORIZONTAL * orientation are clipped so they look accurate, but the headers are not being drawn at the * correctly smaller width and height respectively. * * @param clipRect {@link Rect} for clipping a provided header to the padding of a recycler view * @param recyclerView for which to provide a header * @param header for clipping */ private void initClipRectForHeader(Rect clipRect, RecyclerView recyclerView, View header) { mDimensionCalculator.initMargins(clipRect, header); if (mOrientationProvider.getOrientation(recyclerView) == LinearLayout.VERTICAL) { clipRect.set( recyclerView.getPaddingLeft(), recyclerView.getPaddingTop(), recyclerView.getWidth() - recyclerView.getPaddingRight() - clipRect.right, recyclerView.getHeight() - recyclerView.getPaddingBottom()); } else { clipRect.set( recyclerView.getPaddingLeft(), recyclerView.getPaddingTop(), recyclerView.getWidth() - recyclerView.getPaddingRight(), recyclerView.getHeight() - recyclerView.getPaddingBottom() - clipRect.bottom); } } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/adapter/expand/LinearLayoutOrientationProvider.java
architecture/src/main/java/com/jiang/android/architecture/adapter/expand/LinearLayoutOrientationProvider.java
package com.jiang.android.architecture.adapter.expand; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; /** * OrientationProvider for ReyclerViews who use a LinearLayoutManager */ public class LinearLayoutOrientationProvider implements OrientationProvider { @Override public int getOrientation(RecyclerView recyclerView) { RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager(); throwIfNotLinearLayoutManager(layoutManager); return ((LinearLayoutManager) layoutManager).getOrientation(); } @Override public boolean isReverseLayout(RecyclerView recyclerView) { RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager(); throwIfNotLinearLayoutManager(layoutManager); return ((LinearLayoutManager) layoutManager).getReverseLayout(); } private void throwIfNotLinearLayoutManager(RecyclerView.LayoutManager layoutManager){ if (!(layoutManager instanceof LinearLayoutManager)) { throw new IllegalStateException("StickyListHeadersDecoration can only be used with a " + "LinearLayoutManager."); } } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/adapter/expand/HeaderProvider.java
architecture/src/main/java/com/jiang/android/architecture/adapter/expand/HeaderProvider.java
package com.jiang.android.architecture.adapter.expand; import android.support.v7.widget.RecyclerView; import android.view.View; /** * Implemented by objects that provide header views for decoration */ public interface HeaderProvider { /** * Will provide a header view for a given position in the RecyclerView * * @param recyclerView that will display the header * @param position that will be headed by the header * @return a header view for the given position and list */ public View getHeader(RecyclerView recyclerView, int position); /** * TODO: describe this functionality and its necessity */ void invalidate(); }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/adapter/expand/StickyRecyclerHeadersTouchListener.java
architecture/src/main/java/com/jiang/android/architecture/adapter/expand/StickyRecyclerHeadersTouchListener.java
package com.jiang.android.architecture.adapter.expand; import android.support.v7.widget.RecyclerView; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.SoundEffectConstants; import android.view.View; public class StickyRecyclerHeadersTouchListener implements RecyclerView.OnItemTouchListener { private final GestureDetector mTapDetector; private final RecyclerView mRecyclerView; private final StickyRecyclerHeadersDecoration mDecor; private OnHeaderClickListener mOnHeaderClickListener; public interface OnHeaderClickListener { void onHeaderClick(View header, int position, long headerId); } public StickyRecyclerHeadersTouchListener(final RecyclerView recyclerView, final StickyRecyclerHeadersDecoration decor) { mTapDetector = new GestureDetector(recyclerView.getContext(), new SingleTapDetector()); mRecyclerView = recyclerView; mDecor = decor; } public StickyRecyclerHeadersAdapter getAdapter() { if (mRecyclerView.getAdapter() instanceof StickyRecyclerHeadersAdapter) { return (StickyRecyclerHeadersAdapter) mRecyclerView.getAdapter(); } else { throw new IllegalStateException("A RecyclerView with " + StickyRecyclerHeadersTouchListener.class.getSimpleName() + " requires a " + StickyRecyclerHeadersAdapter.class.getSimpleName()); } } public void setOnHeaderClickListener(OnHeaderClickListener listener) { mOnHeaderClickListener = listener; } @Override public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) { if (this.mOnHeaderClickListener != null) { boolean tapDetectorResponse = this.mTapDetector.onTouchEvent(e); if (tapDetectorResponse) { // Don't return false if a single tap is detected return true; } if (e.getAction() == MotionEvent.ACTION_DOWN) { int position = mDecor.findHeaderPositionUnder((int)e.getX(), (int)e.getY()); return position != -1; } } return false; } @Override public void onTouchEvent(RecyclerView view, MotionEvent e) { /* do nothing? */ } @Override public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { // do nothing } private class SingleTapDetector extends GestureDetector.SimpleOnGestureListener { @Override public boolean onSingleTapUp(MotionEvent e) { int position = mDecor.findHeaderPositionUnder((int) e.getX(), (int) e.getY()); if (position != -1) { View headerView = mDecor.getHeaderView(mRecyclerView, position); long headerId = getAdapter().getHeaderId(position); mOnHeaderClickListener.onHeaderClick(headerView, position, headerId); mRecyclerView.playSoundEffect(SoundEffectConstants.CLICK); headerView.onTouchEvent(e); return true; } return false; } @Override public boolean onDoubleTap(MotionEvent e) { return true; } } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/adapter/expand/StickyRecyclerHeadersAdapter.java
architecture/src/main/java/com/jiang/android/architecture/adapter/expand/StickyRecyclerHeadersAdapter.java
package com.jiang.android.architecture.adapter.expand; import android.support.v7.widget.RecyclerView; import android.view.ViewGroup; public interface StickyRecyclerHeadersAdapter<VH extends RecyclerView.ViewHolder> { /** * Get the ID of the header associated with this item. For example, if your headers group * items by their first letter, you could return the character representation of the first letter. * Return a value < 0 if the view should not have a header (like, a header view or footer view) * * @param position * @return */ public long getHeaderId(int position); /** * Creates a new ViewHolder for a header. This works the same way onCreateViewHolder in * Recycler.Adapter, ViewHolders can be reused for different views. This is usually a good place * to inflate the layout for the header. * * @param parent * @return */ public VH onCreateHeaderViewHolder(ViewGroup parent); /** * Binds an existing ViewHolder to the specified adapter position. * * @param holder * @param position */ public void onBindHeaderViewHolder(VH holder, int position); public int getItemCount(); }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/adapter/expand/StickyRecyclerHeadersDecoration.java
architecture/src/main/java/com/jiang/android/architecture/adapter/expand/StickyRecyclerHeadersDecoration.java
package com.jiang.android.architecture.adapter.expand; import android.graphics.Canvas; import android.graphics.Rect; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.SparseArray; import android.view.View; public class StickyRecyclerHeadersDecoration extends RecyclerView.ItemDecoration { private final StickyRecyclerHeadersAdapter mAdapter; private final SparseArray<Rect> mHeaderRects = new SparseArray<>(); private final HeaderProvider mHeaderProvider; private final OrientationProvider mOrientationProvider; private final HeaderPositionCalculator mHeaderPositionCalculator; private final HeaderRenderer mRenderer; private final DimensionCalculator mDimensionCalculator; /** * The following field is used as a buffer for internal calculations. Its sole purpose is to avoid * allocating new Rect every time we need one. */ private final Rect mTempRect = new Rect(); // TODO: Consider passing in orientation to simplify orientation accounting within calculation public StickyRecyclerHeadersDecoration(StickyRecyclerHeadersAdapter adapter) { this(adapter, new LinearLayoutOrientationProvider(), new DimensionCalculator()); } private StickyRecyclerHeadersDecoration(StickyRecyclerHeadersAdapter adapter, OrientationProvider orientationProvider, DimensionCalculator dimensionCalculator) { this(adapter, orientationProvider, dimensionCalculator, new HeaderRenderer(orientationProvider), new HeaderViewCache(adapter, orientationProvider)); } private StickyRecyclerHeadersDecoration(StickyRecyclerHeadersAdapter adapter, OrientationProvider orientationProvider, DimensionCalculator dimensionCalculator, HeaderRenderer headerRenderer, HeaderProvider headerProvider) { this(adapter, headerRenderer, orientationProvider, dimensionCalculator, headerProvider, new HeaderPositionCalculator(adapter, headerProvider, orientationProvider, dimensionCalculator)); } private StickyRecyclerHeadersDecoration(StickyRecyclerHeadersAdapter adapter, HeaderRenderer headerRenderer, OrientationProvider orientationProvider, DimensionCalculator dimensionCalculator, HeaderProvider headerProvider, HeaderPositionCalculator headerPositionCalculator) { mAdapter = adapter; mHeaderProvider = headerProvider; mOrientationProvider = orientationProvider; mRenderer = headerRenderer; mDimensionCalculator = dimensionCalculator; mHeaderPositionCalculator = headerPositionCalculator; } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { super.getItemOffsets(outRect, view, parent, state); int itemPosition = parent.getChildAdapterPosition(view); if (itemPosition == RecyclerView.NO_POSITION) { return; } if (mHeaderPositionCalculator.hasNewHeader(itemPosition, mOrientationProvider.isReverseLayout(parent))) { View header = getHeaderView(parent, itemPosition); setItemOffsetsForHeader(outRect, header, mOrientationProvider.getOrientation(parent)); } } /** * Sets the offsets for the first item in a section to make room for the header view * * @param itemOffsets rectangle to define offsets for the item * @param header view used to calculate offset for the item * @param orientation used to calculate offset for the item */ private void setItemOffsetsForHeader(Rect itemOffsets, View header, int orientation) { mDimensionCalculator.initMargins(mTempRect, header); if (orientation == LinearLayoutManager.VERTICAL) { itemOffsets.top = header.getHeight() + mTempRect.top + mTempRect.bottom; } else { itemOffsets.left = header.getWidth() + mTempRect.left + mTempRect.right; } } @Override public void onDrawOver(Canvas canvas, RecyclerView parent, RecyclerView.State state) { super.onDrawOver(canvas, parent, state); final int childCount = parent.getChildCount(); if (childCount <= 0 || mAdapter.getItemCount() <= 0) { return; } for (int i = 0; i < childCount; i++) { View itemView = parent.getChildAt(i); int position = parent.getChildAdapterPosition(itemView); if (position == RecyclerView.NO_POSITION) { continue; } boolean hasStickyHeader = mHeaderPositionCalculator.hasStickyHeader(itemView, mOrientationProvider.getOrientation(parent), position); if (hasStickyHeader || mHeaderPositionCalculator.hasNewHeader(position, mOrientationProvider.isReverseLayout(parent))) { View header = mHeaderProvider.getHeader(parent, position); //re-use existing Rect, if any. Rect headerOffset = mHeaderRects.get(position); if (headerOffset == null) { headerOffset = new Rect(); mHeaderRects.put(position, headerOffset); } mHeaderPositionCalculator.initHeaderBounds(headerOffset, parent, header, itemView, hasStickyHeader); mRenderer.drawHeader(parent, canvas, header, headerOffset); } } } /** * Gets the position of the header under the specified (x, y) coordinates. * * @param x x-coordinate * @param y y-coordinate * @return position of header, or -1 if not found */ public int findHeaderPositionUnder(int x, int y) { for (int i = 0; i < mHeaderRects.size(); i++) { Rect rect = mHeaderRects.get(mHeaderRects.keyAt(i)); if (rect.contains(x, y)) { return mHeaderRects.keyAt(i); } } return -1; } /** * Gets the header view for the associated position. If it doesn't exist yet, it will be * created, measured, and laid out. * * @param parent * @param position * @return Header view */ public View getHeaderView(RecyclerView parent, int position) { return mHeaderProvider.getHeader(parent, position); } /** * Invalidates cached headers. This does not invalidate the recyclerview, you should do that manually after * calling this method. */ public void invalidateHeaders() { mHeaderProvider.invalidate(); mHeaderRects.clear(); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
jiang111/ZhiHu-TopAnswer
https://github.com/jiang111/ZhiHu-TopAnswer/blob/0937f43c34fba9f53cc21f7109b153d944c3c72b/architecture/src/main/java/com/jiang/android/architecture/adapter/expand/HeaderViewCache.java
architecture/src/main/java/com/jiang/android/architecture/adapter/expand/HeaderViewCache.java
package com.jiang.android.architecture.adapter.expand; import android.support.v4.util.LongSparseArray; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; /** * An implementation of {@link HeaderProvider} that creates and caches header views */ public class HeaderViewCache implements HeaderProvider { private final StickyRecyclerHeadersAdapter mAdapter; private final LongSparseArray<View> mHeaderViews = new LongSparseArray<>(); private final OrientationProvider mOrientationProvider; public HeaderViewCache(StickyRecyclerHeadersAdapter adapter, OrientationProvider orientationProvider) { mAdapter = adapter; mOrientationProvider = orientationProvider; } @Override public View getHeader(RecyclerView parent, int position) { long headerId = mAdapter.getHeaderId(position); View header = mHeaderViews.get(headerId); if (header == null) { //TODO - recycle views RecyclerView.ViewHolder viewHolder = mAdapter.onCreateHeaderViewHolder(parent); mAdapter.onBindHeaderViewHolder(viewHolder, position); header = viewHolder.itemView; if (header.getLayoutParams() == null) { header.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); } int widthSpec; int heightSpec; if (mOrientationProvider.getOrientation(parent) == LinearLayoutManager.VERTICAL) { widthSpec = View.MeasureSpec.makeMeasureSpec(parent.getWidth(), View.MeasureSpec.EXACTLY); heightSpec = View.MeasureSpec.makeMeasureSpec(parent.getHeight(), View.MeasureSpec.UNSPECIFIED); } else { widthSpec = View.MeasureSpec.makeMeasureSpec(parent.getWidth(), View.MeasureSpec.UNSPECIFIED); heightSpec = View.MeasureSpec.makeMeasureSpec(parent.getHeight(), View.MeasureSpec.EXACTLY); } int childWidth = ViewGroup.getChildMeasureSpec(widthSpec, parent.getPaddingLeft() + parent.getPaddingRight(), header.getLayoutParams().width); int childHeight = ViewGroup.getChildMeasureSpec(heightSpec, parent.getPaddingTop() + parent.getPaddingBottom(), header.getLayoutParams().height); header.measure(childWidth, childHeight); header.layout(0, 0, header.getMeasuredWidth(), header.getMeasuredHeight()); mHeaderViews.put(headerId, header); } return header; } @Override public void invalidate() { mHeaderViews.clear(); } }
java
Apache-2.0
0937f43c34fba9f53cc21f7109b153d944c3c72b
2026-01-05T02:41:32.344044Z
false
nisrulz/packagehunter
https://github.com/nisrulz/packagehunter/blob/71296e0b4b379a82bbb7fcbb9edb956a285254c5/app/src/test/java/github/nisrulz/projectpackagehunter/ExampleUnitTest.java
app/src/test/java/github/nisrulz/projectpackagehunter/ExampleUnitTest.java
/* * Copyright (C) 2016 Nishant Srivastava * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package github.nisrulz.projectpackagehunter; import static org.junit.Assert.*; import org.junit.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
java
Apache-2.0
71296e0b4b379a82bbb7fcbb9edb956a285254c5
2026-01-05T02:41:43.347440Z
false
nisrulz/packagehunter
https://github.com/nisrulz/packagehunter/blob/71296e0b4b379a82bbb7fcbb9edb956a285254c5/app/src/main/java/github/nisrulz/projectpackagehunter/SplashActivity.java
app/src/main/java/github/nisrulz/projectpackagehunter/SplashActivity.java
/* * Copyright (C) 2016 Nishant Srivastava * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package github.nisrulz.projectpackagehunter; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.AppCompatActivity; public class SplashActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { startActivity(new Intent(SplashActivity.this, MainActivity.class)); overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out); finish(); } }, 600); } }
java
Apache-2.0
71296e0b4b379a82bbb7fcbb9edb956a285254c5
2026-01-05T02:41:43.347440Z
false
nisrulz/packagehunter
https://github.com/nisrulz/packagehunter/blob/71296e0b4b379a82bbb7fcbb9edb956a285254c5/app/src/main/java/github/nisrulz/projectpackagehunter/MainActivity.java
app/src/main/java/github/nisrulz/projectpackagehunter/MainActivity.java
/* * Copyright (C) 2016 Nishant Srivastava * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package github.nisrulz.projectpackagehunter; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import github.nisrulz.packagehunter.PackageHunter; import github.nisrulz.packagehunter.PkgInfo; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private RVMainAdapter adapter; private PackageHunter packageHunter; private ArrayList<PkgInfo> pkgInfoArrayList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); packageHunter = new PackageHunter(this); RecyclerView rv = (RecyclerView) findViewById(R.id.rv_pkglist); pkgInfoArrayList = packageHunter.getInstalledPackages(); adapter = new RVMainAdapter(this, pkgInfoArrayList); rv.hasFixedSize(); rv.setLayoutManager(new LinearLayoutManager(this)); rv.setAdapter(adapter); // Set On Click rv.addOnItemTouchListener( new RVItemClickListener(this, new RVItemClickListener.OnItemClickListener() { @Override public void onItemClick(View view, int position) { Intent i = new Intent(MainActivity.this, DetailActivity.class); i.putExtra("data", pkgInfoArrayList.get(position).getPackageName()); startActivity(i); overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right); } })); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_main, menu); MenuItem searchViewItem = menu.findItem(R.id.action_search); final SearchView searchViewAndroidActionBar = (SearchView) MenuItemCompat.getActionView(searchViewItem); searchViewAndroidActionBar.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { searchViewAndroidActionBar.clearFocus(); return true; } @Override public boolean onQueryTextChange(String query) { pkgInfoArrayList = packageHunter.searchInList(query, PackageHunter.PACKAGES); adapter.updateWithNewListData(pkgInfoArrayList); return false; } }); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_refresh: { pkgInfoArrayList = packageHunter.getInstalledPackages(); adapter.updateWithNewListData(pkgInfoArrayList); break; } case R.id.action_about: { startActivity(new Intent(MainActivity.this, AboutActivity.class)); overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right); break; } case R.id.action_privacy: { Uri uri = Uri.parse( "https://cdn.rawgit.com/nisrulz/f142e91b83497ae254499d1d44b4afad/raw/1c46f779a80db0bd4946273acdf8109874984eac/PackageHunterPrivacyPolicy.html"); Intent browserIntent = new Intent(Intent.ACTION_VIEW, uri); startActivity(browserIntent); } } return super.onOptionsItemSelected(item); } }
java
Apache-2.0
71296e0b4b379a82bbb7fcbb9edb956a285254c5
2026-01-05T02:41:43.347440Z
false
nisrulz/packagehunter
https://github.com/nisrulz/packagehunter/blob/71296e0b4b379a82bbb7fcbb9edb956a285254c5/app/src/main/java/github/nisrulz/projectpackagehunter/RVMainAdapter.java
app/src/main/java/github/nisrulz/projectpackagehunter/RVMainAdapter.java
/* * Copyright (C) 2016 Nishant Srivastava * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package github.nisrulz.projectpackagehunter; import android.content.Context; import android.graphics.drawable.Drawable; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import github.nisrulz.packagehunter.PackageHunter; import github.nisrulz.packagehunter.PkgInfo; import java.util.List; class RVMainAdapter extends RecyclerView.Adapter<RVMainAdapter.ItemViewHolder> { public class ItemViewHolder extends RecyclerView.ViewHolder { final ImageView icon; final TextView txt_appname; final TextView txt_pkgname; public ItemViewHolder(View itemView) { super(itemView); txt_appname = (TextView) itemView.findViewById(R.id.txtvw_appname); txt_pkgname = (TextView) itemView.findViewById(R.id.txtvw_pkgname); icon = (ImageView) itemView.findViewById(R.id.imgvw_icn); } } private List<PkgInfo> dataList; private final PackageHunter packageHunter; public RVMainAdapter(Context context, List<PkgInfo> dataList) { packageHunter = new PackageHunter(context); this.dataList = dataList; } @Override public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_main_item, parent, false); return new ItemViewHolder(view); } @Override public void onBindViewHolder(ItemViewHolder holder, int position) { holder.txt_appname.setText(dataList.get(position).getAppName()); holder.txt_pkgname.setText(dataList.get(position).getPackageName()); Drawable icon = packageHunter.getIconForPkg(dataList.get(position).getPackageName()); holder.icon.setImageDrawable(icon); } @Override public int getItemCount() { return dataList.size(); } public void updateWithNewListData(List<PkgInfo> newDataList) { dataList.clear(); dataList = null; dataList = newDataList; notifyDataSetChanged(); } }
java
Apache-2.0
71296e0b4b379a82bbb7fcbb9edb956a285254c5
2026-01-05T02:41:43.347440Z
false
nisrulz/packagehunter
https://github.com/nisrulz/packagehunter/blob/71296e0b4b379a82bbb7fcbb9edb956a285254c5/app/src/main/java/github/nisrulz/projectpackagehunter/AboutActivity.java
app/src/main/java/github/nisrulz/projectpackagehunter/AboutActivity.java
/* * Copyright (C) 2016 Nishant Srivastava * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package github.nisrulz.projectpackagehunter; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; public class AboutActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_about); } @Override public void onBackPressed() { super.onBackPressed(); overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right); finish(); } }
java
Apache-2.0
71296e0b4b379a82bbb7fcbb9edb956a285254c5
2026-01-05T02:41:43.347440Z
false
nisrulz/packagehunter
https://github.com/nisrulz/packagehunter/blob/71296e0b4b379a82bbb7fcbb9edb956a285254c5/app/src/main/java/github/nisrulz/projectpackagehunter/ElementInfo.java
app/src/main/java/github/nisrulz/projectpackagehunter/ElementInfo.java
/* * Copyright (C) 2016 Nishant Srivastava * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package github.nisrulz.projectpackagehunter; class ElementInfo { private String[] details; private String header; public ElementInfo(String header, String[] details) { this.details = details; this.header = header; } public String[] getDetails() { return details; } public void setDetails(String[] details) { this.details = details; } public String getHeader() { return header; } public void setHeader(String header) { this.header = header; } @Override public String toString() { if (details != null) { super.toString(); StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < details.length; i++) { stringBuilder.append(details[i]).append("\n"); } return stringBuilder.toString(); } else { super.toString(); return "NA"; } } }
java
Apache-2.0
71296e0b4b379a82bbb7fcbb9edb956a285254c5
2026-01-05T02:41:43.347440Z
false
nisrulz/packagehunter
https://github.com/nisrulz/packagehunter/blob/71296e0b4b379a82bbb7fcbb9edb956a285254c5/app/src/main/java/github/nisrulz/projectpackagehunter/DetailActivity.java
app/src/main/java/github/nisrulz/projectpackagehunter/DetailActivity.java
/* * Copyright (C) 2016 Nishant Srivastava * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package github.nisrulz.projectpackagehunter; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.widget.ImageView; import android.widget.TextView; import github.nisrulz.packagehunter.PackageHunter; import java.util.ArrayList; import java.util.Locale; public class DetailActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); if (toolbar != null) { setSupportActionBar(toolbar); } String packageName = getIntent().getStringExtra("data"); PackageHunter packageHunter = new PackageHunter(this); String version = packageHunter.getVersionForPkg(packageName); String versionCode = packageHunter.getVersionCodeForPkg(packageName); String appName = packageHunter.getAppNameForPkg(packageName); long firstInstallTime = packageHunter.getFirstInstallTimeForPkg(packageName); long lastUpdateTime = packageHunter.getLastUpdatedTimeForPkg(packageName); Drawable icon = packageHunter.getIconForPkg(packageName); String[] permissions = packageHunter.getPermissionForPkg(packageName); String[] activities = packageHunter.getActivitiesForPkg(packageName); String[] services = packageHunter.getServicesForPkg(packageName); String[] providers = packageHunter.getProvidersForPkg(packageName); String[] receivers = packageHunter.getReceiverForPkg(packageName); TextView txt_version = (TextView) findViewById(R.id.txtvw_vname); TextView txt_versioncode = (TextView) findViewById(R.id.txtvw_vc); TextView txt_pkg = (TextView) findViewById(R.id.txtvw_pkgname); ImageView img_icon = (ImageView) findViewById(R.id.imgvw_icn); TextView txt_firsttime = (TextView) findViewById(R.id.txtvw_firsttime); TextView txt_lastupdated = (TextView) findViewById(R.id.txtvw_lastupdated); img_icon.setImageDrawable(icon); txt_version.setText("Version : " + version); txt_versioncode.setText("Version Code : " + versionCode); txt_pkg.setText(packageName); txt_firsttime.setText("First Install Time : " + getFormattedUpTime(firstInstallTime)); txt_lastupdated.setText("Last Update Time : " + getFormattedUpTime(lastUpdateTime)); if (getSupportActionBar() != null) { getSupportActionBar().setTitle(appName); } RecyclerView rv = (RecyclerView) findViewById(R.id.rv_detaillist); ArrayList<ElementInfo> elementInfoArrayList = new ArrayList<>(); elementInfoArrayList.add(new ElementInfo("Permissions", permissions)); elementInfoArrayList.add(new ElementInfo("Services", services)); elementInfoArrayList.add(new ElementInfo("Activities", activities)); elementInfoArrayList.add(new ElementInfo("Providers", providers)); elementInfoArrayList.add(new ElementInfo("Receivers", receivers)); RVDetailsAdapter adapter = new RVDetailsAdapter(elementInfoArrayList); rv.setHasFixedSize(true); rv.setLayoutManager(new LinearLayoutManager(this)); rv.setAdapter(adapter); } @Override public void onBackPressed() { super.onBackPressed(); overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right); finish(); } private String getFormattedUpTime(long millis) { int sec = (int) (millis / 1000) % 60; int min = (int) ((millis / (1000 * 60)) % 60); int hr = (int) ((millis / (1000 * 60 * 60)) % 24); return String.format(Locale.US, "%02d:%02d:%02d", hr, min, sec); } }
java
Apache-2.0
71296e0b4b379a82bbb7fcbb9edb956a285254c5
2026-01-05T02:41:43.347440Z
false
nisrulz/packagehunter
https://github.com/nisrulz/packagehunter/blob/71296e0b4b379a82bbb7fcbb9edb956a285254c5/app/src/main/java/github/nisrulz/projectpackagehunter/RVDetailsAdapter.java
app/src/main/java/github/nisrulz/projectpackagehunter/RVDetailsAdapter.java
/* * Copyright (C) 2016 Nishant Srivastava * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package github.nisrulz.projectpackagehunter; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.List; class RVDetailsAdapter extends RecyclerView.Adapter<RVDetailsAdapter.ItemViewHolder> { public class ItemViewHolder extends RecyclerView.ViewHolder { final TextView txtvw_details; final TextView txtvw_header; public ItemViewHolder(View itemView) { super(itemView); txtvw_header = (TextView) itemView.findViewById(R.id.txtvw_header); txtvw_details = (TextView) itemView.findViewById(R.id.txtvw_details); } } private List<ElementInfo> dataList; public RVDetailsAdapter(List<ElementInfo> dataList) { this.dataList = dataList; } @Override public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_details_item, parent, false); return new ItemViewHolder(view); } @Override public void onBindViewHolder(ItemViewHolder holder, int position) { holder.txtvw_header.setText(dataList.get(position).getHeader()); holder.txtvw_details.setText(dataList.get(position).toString()); } @Override public int getItemCount() { return dataList.size(); } }
java
Apache-2.0
71296e0b4b379a82bbb7fcbb9edb956a285254c5
2026-01-05T02:41:43.347440Z
false
nisrulz/packagehunter
https://github.com/nisrulz/packagehunter/blob/71296e0b4b379a82bbb7fcbb9edb956a285254c5/app/src/main/java/github/nisrulz/projectpackagehunter/RVItemClickListener.java
app/src/main/java/github/nisrulz/projectpackagehunter/RVItemClickListener.java
/* * Copyright (C) 2016 Nishant Srivastava * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package github.nisrulz.projectpackagehunter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; class RVItemClickListener implements RecyclerView.OnItemTouchListener { public interface OnItemClickListener { void onItemClick(View view, int position); } private final GestureDetector mGestureDetector; private final OnItemClickListener mListener; public RVItemClickListener(Context context, OnItemClickListener listener) { mListener = listener; mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() { @Override public boolean onSingleTapUp(MotionEvent e) { return true; } }); } @Override public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) { View childView = view.findChildViewUnder(e.getX(), e.getY()); if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) { mListener.onItemClick(childView, view.getChildAdapterPosition(childView)); return true; } return false; } @Override public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) { } @Override public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { } }
java
Apache-2.0
71296e0b4b379a82bbb7fcbb9edb956a285254c5
2026-01-05T02:41:43.347440Z
false
nisrulz/packagehunter
https://github.com/nisrulz/packagehunter/blob/71296e0b4b379a82bbb7fcbb9edb956a285254c5/app/src/androidTest/java/github/nisrulz/projectpackagehunter/ApplicationTest.java
app/src/androidTest/java/github/nisrulz/projectpackagehunter/ApplicationTest.java
/* * Copyright (C) 2016 Nishant Srivastava * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package github.nisrulz.projectpackagehunter; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
java
Apache-2.0
71296e0b4b379a82bbb7fcbb9edb956a285254c5
2026-01-05T02:41:43.347440Z
false
nisrulz/packagehunter
https://github.com/nisrulz/packagehunter/blob/71296e0b4b379a82bbb7fcbb9edb956a285254c5/packagehunter/src/test/java/github/nisrulz/packagehunter/ExampleUnitTest.java
packagehunter/src/test/java/github/nisrulz/packagehunter/ExampleUnitTest.java
/* * Copyright (C) 2016 Nishant Srivastava * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package github.nisrulz.packagehunter; import static org.junit.Assert.*; import org.junit.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
java
Apache-2.0
71296e0b4b379a82bbb7fcbb9edb956a285254c5
2026-01-05T02:41:43.347440Z
false
nisrulz/packagehunter
https://github.com/nisrulz/packagehunter/blob/71296e0b4b379a82bbb7fcbb9edb956a285254c5/packagehunter/src/main/java/github/nisrulz/packagehunter/PackageHunter.java
packagehunter/src/main/java/github/nisrulz/packagehunter/PackageHunter.java
/* * Copyright (C) 2016 Nishant Srivastava * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package github.nisrulz.packagehunter; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.graphics.drawable.Drawable; import android.os.Build; import android.util.Log; import java.util.ArrayList; import java.util.List; public class PackageHunter { // Flags public static final int APPLICATIONS = 0; public static final int PACKAGES = 1; public static final int PERMISSIONS = 2; public static final int SERVICES = 3; public static final int RECEIVERS = 4; public static final int ACTIVITIES = 5; public static final int PROVIDERS = 6; private static final String TAG = "PackageHunter"; private final Context context; private final PackageManager packageManager; public PackageHunter(Context context) { packageManager = context.getPackageManager(); this.context = context; } public String[] getActivitiesForPkg(String packageName) { PackageInfo packageInfo = getPkgInfo(packageName, PackageManager.GET_ACTIVITIES); if (packageInfo.activities != null) { ArrayList<String> data = new ArrayList<>(packageInfo.activities.length); for (int i = 0; i < packageInfo.activities.length; i++) { data.add(packageInfo.activities[i].name); } return data.toArray(new String[data.size()]); } else { return null; } } public String getAppNameForPkg(String packageName) { PackageInfo packageInfo = getPkgInfo(packageName, 0); return packageInfo != null ? packageInfo.applicationInfo.loadLabel(packageManager).toString() : null; } public long getFirstInstallTimeForPkg(String packageName) { PackageInfo packageInfo = getPkgInfo(packageName, 0); return packageInfo != null ? packageInfo.firstInstallTime : 0; } public Drawable getIconForPkg(String packageName) { Drawable icon; try { icon = packageManager.getApplicationIcon(packageName); } catch (PackageManager.NameNotFoundException ex) { Log.e(TAG, "Error", ex); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { icon = context.getResources().getDrawable(android.R.drawable.ic_menu_help, context.getTheme()); } else { //noinspection deprecation icon = context.getResources().getDrawable(android.R.drawable.ic_menu_help); } } return icon; } public ArrayList<PkgInfo> getInstalledPackages() { return getAllPackagesInfo(PACKAGES); } public long getLastUpdatedTimeForPkg(String packageName) { PackageInfo packageInfo = getPkgInfo(packageName, 0); return packageInfo != null ? packageInfo.lastUpdateTime : 0; } public String[] getPermissionForPkg(String packageName) { PackageInfo packageInfo = getPkgInfo(packageName, PackageManager.GET_PERMISSIONS); if (packageInfo.requestedPermissions != null) { return packageInfo.requestedPermissions; } else { return null; } } public String[] getProvidersForPkg(String packageName) { PackageInfo packageInfo = getPkgInfo(packageName, PackageManager.GET_PROVIDERS); if (packageInfo.providers != null) { ArrayList<String> data = new ArrayList<>(packageInfo.providers.length); for (int i = 0; i < packageInfo.providers.length; i++) { data.add(packageInfo.providers[i].name); } return data.toArray(new String[data.size()]); } else { return null; } } public String[] getReceiverForPkg(String packageName) { PackageInfo packageInfo = getPkgInfo(packageName, PackageManager.GET_RECEIVERS); if (packageInfo.receivers != null) { ArrayList<String> data = new ArrayList<>(packageInfo.receivers.length); for (int i = 0; i < packageInfo.receivers.length; i++) { data.add(packageInfo.receivers[i].name); } return data.toArray(new String[data.size()]); } else { return null; } } public String[] getServicesForPkg(String packageName) { PackageInfo packageInfo = getPkgInfo(packageName, PackageManager.GET_SERVICES); if (packageInfo.services != null) { ArrayList<String> data = new ArrayList<>(packageInfo.services.length); for (int i = 0; i < packageInfo.services.length; i++) { data.add(packageInfo.services[i].name); } return data.toArray(new String[data.size()]); } else { return null; } } public String getVersionCodeForPkg(String packageName) { PackageInfo packageInfo = getPkgInfo(packageName, 0); return String.valueOf(packageInfo.versionCode); } public String getVersionForPkg(String packageName) { PackageInfo packageInfo = getPkgInfo(packageName, 0); return packageInfo != null ? packageInfo.versionName : null; } public ArrayList<PkgInfo> searchInList(String query, int flag) { String query_lowercase = query.toLowerCase(); ArrayList<PkgInfo> pkgInfoArrayList = new ArrayList<>(); ArrayList<PkgInfo> installed_packages_list = getAllPackagesInfo(flag); for (int i = 0; i < installed_packages_list.size(); i++) { PkgInfo pkgInfo = installed_packages_list.get(i); switch (flag) { case APPLICATIONS: String appname = pkgInfo.getAppName(); if (appname != null && appname.toLowerCase().contains(query_lowercase)) { pkgInfoArrayList.add(pkgInfo); } break; case PACKAGES: String packagename = pkgInfo.getPackageName(); if (packagename != null && packagename.toLowerCase().contains(query_lowercase)) { pkgInfoArrayList.add(pkgInfo); } break; case PERMISSIONS: { String[] permissions = getPermissionForPkg(pkgInfo.getPackageName()); if (permissions != null) { for (int j = 0; j < permissions.length; j++) { if (permissions[j].toLowerCase().contains(query_lowercase)) { pkgInfoArrayList.add(pkgInfo); break; } } } break; } case SERVICES: { String[] services = getServicesForPkg(pkgInfo.getPackageName()); if (services != null) { for (int j = 0; j < services.length; j++) { if (services[j].toLowerCase().contains(query_lowercase)) { pkgInfoArrayList.add(pkgInfo); break; } } } break; } case RECEIVERS: { String[] recievers = getReceiverForPkg(pkgInfo.getPackageName()); if (recievers != null) { for (int j = 0; j < recievers.length; j++) { if (recievers[j].toLowerCase().contains(query_lowercase)) { pkgInfoArrayList.add(pkgInfo); break; } } } break; } case ACTIVITIES: { String[] activities = getActivitiesForPkg(pkgInfo.getPackageName()); if (activities != null) { for (int j = 0; j < activities.length; j++) { if (activities[j].toLowerCase().contains(query_lowercase)) { pkgInfoArrayList.add(pkgInfo); break; } } } break; } case PROVIDERS: { String[] providers = getProvidersForPkg(pkgInfo.getPackageName()); if (providers != null) { for (int j = 0; j < providers.length; j++) { if (providers[j].toLowerCase().contains(query_lowercase)) { pkgInfoArrayList.add(pkgInfo); break; } } } break; } default: { String packagename1 = pkgInfo.getPackageName(); if (packagename1 != null && packagename1.toLowerCase().contains(query_lowercase)) { pkgInfoArrayList.add(pkgInfo); } break; } } } return pkgInfoArrayList; } private ArrayList<PkgInfo> getAllPackagesInfo(int flag) { ArrayList<PkgInfo> pkgInfoArrayList = new ArrayList<>(); List<PackageInfo> installed_packages_list; switch (flag) { case PACKAGES: installed_packages_list = packageManager.getInstalledPackages(0); break; case PERMISSIONS: installed_packages_list = packageManager.getInstalledPackages(PackageManager.GET_PERMISSIONS); break; case SERVICES: installed_packages_list = packageManager.getInstalledPackages(PackageManager.GET_SERVICES); break; case RECEIVERS: installed_packages_list = packageManager.getInstalledPackages(PackageManager.GET_RECEIVERS); break; case ACTIVITIES: installed_packages_list = packageManager.getInstalledPackages(PackageManager.GET_ACTIVITIES); break; case PROVIDERS: installed_packages_list = packageManager.getInstalledPackages(PackageManager.GET_PROVIDERS); break; default: installed_packages_list = packageManager.getInstalledPackages(0); break; } //get a list of installed packages. for (int i = 0; i < installed_packages_list.size(); i++) { PackageInfo packageInfo = installed_packages_list.get(i); if (!packageInfo.packageName.contains("com.android.")) { pkgInfoArrayList.add(getPkgInfoModel(packageInfo, flag)); } } return pkgInfoArrayList; } private PackageInfo getPkgInfo(String packageName, int flag) { try { return packageManager.getPackageInfo(packageName, flag); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return null; } private PkgInfo getPkgInfoModel(PackageInfo p, int flag) { // Always available PkgInfo newInfo = new PkgInfo(); if (p != null) { newInfo.setAppName(p.applicationInfo.loadLabel(packageManager).toString()); newInfo.setPackageName(p.packageName); newInfo.setVersionCode(p.versionCode); newInfo.setVersionName(p.versionName); newInfo.setLastUpdateTime(p.lastUpdateTime); newInfo.setFirstInstallTime(p.firstInstallTime); } return newInfo; } }
java
Apache-2.0
71296e0b4b379a82bbb7fcbb9edb956a285254c5
2026-01-05T02:41:43.347440Z
false
nisrulz/packagehunter
https://github.com/nisrulz/packagehunter/blob/71296e0b4b379a82bbb7fcbb9edb956a285254c5/packagehunter/src/main/java/github/nisrulz/packagehunter/PkgInfo.java
packagehunter/src/main/java/github/nisrulz/packagehunter/PkgInfo.java
/* * Copyright (C) 2016 Nishant Srivastava * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package github.nisrulz.packagehunter; import android.os.Parcel; import android.os.Parcelable; public class PkgInfo implements Parcelable { public static final Creator<PkgInfo> CREATOR = new Creator<PkgInfo>() { @Override public PkgInfo createFromParcel(Parcel in) { return new PkgInfo(in); } @Override public PkgInfo[] newArray(int size) { return new PkgInfo[size]; } }; private String appName; private long firstInstallTime; private long lastUpdateTime; private String packageName; private int versionCode = 0; private String versionName; public PkgInfo() { versionName = "0.0"; versionCode = 0; firstInstallTime = 0; lastUpdateTime = 0; } protected PkgInfo(Parcel in) { appName = in.readString(); packageName = in.readString(); versionName = in.readString(); versionCode = in.readInt(); firstInstallTime = in.readLong(); lastUpdateTime = in.readLong(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int i) { parcel.writeString(appName); parcel.writeString(packageName); parcel.writeString(versionName); parcel.writeInt(versionCode); parcel.writeLong(firstInstallTime); parcel.writeLong(lastUpdateTime); } public String getAppName() { return appName; } public void setAppName(String appName) { this.appName = appName; } public long getFirstInstallTime() { return firstInstallTime; } public void setFirstInstallTime(long firstInstallTime) { this.firstInstallTime = firstInstallTime; } public long getLastUpdateTime() { return lastUpdateTime; } public void setLastUpdateTime(long lastUpdateTime) { this.lastUpdateTime = lastUpdateTime; } public String getPackageName() { return packageName; } public void setPackageName(String packageName) { this.packageName = packageName; } public int getVersionCode() { return versionCode; } public void setVersionCode(int versionCode) { this.versionCode = versionCode; } public String getVersionName() { return versionName; } public void setVersionName(String versionName) { this.versionName = versionName; } @Override public String toString() { super.toString(); return "AppName : " + appName + " | PackageName :" + packageName + "\nVersion :" + versionName + " | VersionCode :" + versionCode; } }
java
Apache-2.0
71296e0b4b379a82bbb7fcbb9edb956a285254c5
2026-01-05T02:41:43.347440Z
false
nisrulz/packagehunter
https://github.com/nisrulz/packagehunter/blob/71296e0b4b379a82bbb7fcbb9edb956a285254c5/packagehunter/src/androidTest/java/github/nisrulz/packagehunter/ApplicationTest.java
packagehunter/src/androidTest/java/github/nisrulz/packagehunter/ApplicationTest.java
/* * Copyright (C) 2016 Nishant Srivastava * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package github.nisrulz.packagehunter; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
java
Apache-2.0
71296e0b4b379a82bbb7fcbb9edb956a285254c5
2026-01-05T02:41:43.347440Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/docking-multi-app/src/module-info.java
docking-multi-app/src/module-info.java
/** * Module for the Modern Docking framework */ module modern_docking.multi_app { requires modern_docking.api; requires java.desktop; requires java.logging; exports io.github.andrewauclair.moderndocking.app; }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/docking-multi-app/src/io/github/andrewauclair/moderndocking/app/LayoutsMenu.java
docking-multi-app/src/io/github/andrewauclair/moderndocking/app/LayoutsMenu.java
/* Copyright (c) 2022 Andrew Auclair Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 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 the Software. 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. */ package io.github.andrewauclair.moderndocking.app; import io.github.andrewauclair.moderndocking.api.DockingAPI; import io.github.andrewauclair.moderndocking.event.DockingLayoutEvent; import io.github.andrewauclair.moderndocking.event.DockingLayoutListener; import io.github.andrewauclair.moderndocking.layouts.DockingLayouts; import javax.swing.JMenu; import javax.swing.JMenuItem; /** * Custom JMenu that displays all the layouts in DockingLayouts as menu items */ public class LayoutsMenu extends JMenu implements DockingLayoutListener { private final DockingAPI docking; /** * Create a new layouts menu. Add a listener for when layouts change. */ public LayoutsMenu(DockingAPI docking) { super("Layouts"); this.docking = docking; DockingLayouts.addLayoutsListener(this); rebuildOptions(); } private void rebuildOptions() { removeAll(); for (String name : DockingLayouts.getLayoutNames()) { JMenuItem item = new JMenuItem(name); item.addActionListener(e -> docking.getDockingState().restoreApplicationLayout(DockingLayouts.getLayout(name))); add(item); } } @Override public void layoutChange(DockingLayoutEvent e) { rebuildOptions(); } }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/docking-multi-app/src/io/github/andrewauclair/moderndocking/app/WindowLayoutBuilder.java
docking-multi-app/src/io/github/andrewauclair/moderndocking/app/WindowLayoutBuilder.java
/* Copyright (c) 2023 Andrew Auclair Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 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 the Software. 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. */ package io.github.andrewauclair.moderndocking.app; import io.github.andrewauclair.moderndocking.api.DockingAPI; import io.github.andrewauclair.moderndocking.api.WindowLayoutBuilderAPI; public class WindowLayoutBuilder extends WindowLayoutBuilderAPI { public WindowLayoutBuilder(DockingAPI docking, String firstID) { super(docking, firstID); } }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/docking-multi-app/src/io/github/andrewauclair/moderndocking/app/DockableMenuItem.java
docking-multi-app/src/io/github/andrewauclair/moderndocking/app/DockableMenuItem.java
/* Copyright (c) 2022-2025 Andrew Auclair Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 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 the Software. 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. */ package io.github.andrewauclair.moderndocking.app; import io.github.andrewauclair.moderndocking.Dockable; import io.github.andrewauclair.moderndocking.api.DockingAPI; import io.github.andrewauclair.moderndocking.internal.DockingInternal; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.function.Supplier; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JCheckBoxMenuItem; /** * Special JCheckBoxMenuItem that handles updating the checkbox for us based on the docking state of the dockable */ public class DockableMenuItem extends JCheckBoxMenuItem implements ActionListener { private static final Logger logger = Logger.getLogger(DockableMenuItem.class.getPackageName()); /** * Persistent ID provider. Used when the persistent ID isn't known at compile time. * Used when this menu item is added to a menu (using addNotify) */ private final Supplier<String> persistentIDProvider; /** * The persistent ID of the dockable which will be displayed when this dockable is clicked */ private final String persistentID; private final DockingAPI docking; /** * Create a new DockableMenuItem * * @param docking The docking API instance to use for this menu item * @param dockable The dockable to dock when this menu item is selected */ public DockableMenuItem(DockingAPI docking, Dockable dockable) { this(docking, dockable.getPersistentID(), dockable.getTabText()); } /** * * @param docking The docking API instance to use for this menu item * @param persistentID The dockable this menu item refers to * @param text The display text for this menu item */ public DockableMenuItem(DockingAPI docking, String persistentID, String text) { super(text); this.docking = docking; this.persistentIDProvider = null; this.persistentID = persistentID; addActionListener(this); } /** * * @param docking The docking API instance to use for this menu item * @param persistentIDProvider Provides the persistentID that will be displayed * @param text The display text for this menu item */ public DockableMenuItem(DockingAPI docking, Supplier<String> persistentIDProvider, String text) { super(text); this.docking = docking; this.persistentIDProvider = persistentIDProvider; this.persistentID = ""; addActionListener(this); } @Override public void addNotify() { super.addNotify(); // update the menu item, it's about to be displayed DockingInternal internal = DockingInternal.get(docking); String id = persistentIDProvider != null ? persistentIDProvider.get() : persistentID; if (internal.hasDockable(id)) { Dockable dockable = internal.getDockable(id); setSelected(docking.isDocked(dockable)); } else { setVisible(false); logger.log(Level.INFO, "Hiding DockableMenuItem for \"" + getText() + ".\" No dockable with persistentID '" + id + "' registered."); } } @Override public void actionPerformed(ActionEvent e) { DockingInternal internal = DockingInternal.get(docking); String id = persistentIDProvider != null ? persistentIDProvider.get() : persistentID; if (internal.hasDockable(id)) { Dockable dockable = internal.getDockable(id); docking.display(dockable); // set this menu item to the state of the dockable, should be docked at this point setSelected(docking.isDocked(dockable)); } else { logger.log(Level.SEVERE, "DockableMenuItem for \"" + getText() + "\" action failed. No dockable with persistentID '" + id + "' registered."); } } }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/docking-multi-app/src/io/github/andrewauclair/moderndocking/app/RootDockingPanel.java
docking-multi-app/src/io/github/andrewauclair/moderndocking/app/RootDockingPanel.java
/* Copyright (c) 2023 Andrew Auclair Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 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 the Software. 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. */ package io.github.andrewauclair.moderndocking.app; import io.github.andrewauclair.moderndocking.api.DockingAPI; import io.github.andrewauclair.moderndocking.api.RootDockingPanelAPI; import io.github.andrewauclair.moderndocking.ui.ToolbarLocation; import java.awt.Window; import java.util.EnumSet; public class RootDockingPanel extends RootDockingPanelAPI { public RootDockingPanel(DockingAPI docking, Window window) { super(docking, window); } public RootDockingPanel(DockingAPI docking, Window window, EnumSet<ToolbarLocation> supportedToolbars) { super(docking, window, supportedToolbars); } }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/docking-multi-app/src/io/github/andrewauclair/moderndocking/app/DockingState.java
docking-multi-app/src/io/github/andrewauclair/moderndocking/app/DockingState.java
/* Copyright (c) 2023 Andrew Auclair Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 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 the Software. 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. */ package io.github.andrewauclair.moderndocking.app; import io.github.andrewauclair.moderndocking.api.DockingAPI; import io.github.andrewauclair.moderndocking.api.DockingStateAPI; public class DockingState extends DockingStateAPI { public DockingState(DockingAPI docking) { super(docking); } }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/docking-multi-app/src/io/github/andrewauclair/moderndocking/app/Docking.java
docking-multi-app/src/io/github/andrewauclair/moderndocking/app/Docking.java
/* Copyright (c) 2022-2023 Andrew Auclair Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 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 the Software. 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. */ package io.github.andrewauclair.moderndocking.app; import io.github.andrewauclair.moderndocking.api.DockingAPI; import java.awt.Window; /** * Convenience class for apps that only need a single instance of the docking framework. Working with the static functions * is easier than passing an instance of the Docking class all over the app codebase. */ public class Docking extends DockingAPI { public Docking(Window mainWindow) { super(mainWindow); } }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/docking-multi-app/src/io/github/andrewauclair/moderndocking/app/ApplicationLayoutMenuItem.java
docking-multi-app/src/io/github/andrewauclair/moderndocking/app/ApplicationLayoutMenuItem.java
/* Copyright (c) 2023 Andrew Auclair Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 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 the Software. 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. */ package io.github.andrewauclair.moderndocking.app; import io.github.andrewauclair.moderndocking.api.DockingAPI; import io.github.andrewauclair.moderndocking.layouts.ApplicationLayout; import io.github.andrewauclair.moderndocking.layouts.DockingLayouts; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JMenuItem; import javax.swing.JOptionPane; /** * Special JMenuItem which will restore an ApplicationLayout when selected */ public class ApplicationLayoutMenuItem extends JMenuItem implements ActionListener { private final DockingAPI docking; /** * The name of the ApplicationLayout, used to get the layout from DockingLayouts */ private final String layoutName; /** * Create a new ApplicationLayoutMenuItem for the specified layout. The layout name will be used as the display text. * * @param layoutName Name of the ApplicationLayout this ApplicationLayoutMenuItem will restore */ public ApplicationLayoutMenuItem(DockingAPI docking, String layoutName) { super(layoutName); this.docking = docking; this.layoutName = layoutName; addActionListener(this); } /** * Create a new ApplicationLayoutMenuItem for the specified layout * * @param layoutName Name of the ApplicationLayout this ApplicationLayoutMenuItem will restore * @param text Display text of the JMenuItem */ public ApplicationLayoutMenuItem(DockingAPI docking, String layoutName, String text) { super(text); this.docking = docking; this.layoutName = layoutName; addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { ApplicationLayout layout = DockingLayouts.getLayout(layoutName); if (layout == null) { JOptionPane.showMessageDialog(this, "Layout " + layoutName + " does not exist."); } else { docking.getDockingState().restoreApplicationLayout(layout); } } }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/docking-multi-app/src/io/github/andrewauclair/moderndocking/app/LayoutPersistence.java
docking-multi-app/src/io/github/andrewauclair/moderndocking/app/LayoutPersistence.java
/* Copyright (c) 2023 Andrew Auclair Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 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 the Software. 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. */ package io.github.andrewauclair.moderndocking.app; import io.github.andrewauclair.moderndocking.api.DockingAPI; import io.github.andrewauclair.moderndocking.api.LayoutPersistenceAPI; public class LayoutPersistence extends LayoutPersistenceAPI { public LayoutPersistence(DockingAPI docking) { super(docking); } }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/demo-multi-app/src/basic/SimplePanel.java
demo-multi-app/src/basic/SimplePanel.java
/* Copyright (c) 2022 Andrew Auclair Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 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 the Software. 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. */ package basic; import com.formdev.flatlaf.FlatLaf; import io.github.andrewauclair.moderndocking.DockingProperty; import io.github.andrewauclair.moderndocking.api.DockingAPI; import io.github.andrewauclair.moderndocking.ui.DefaultHeaderUI; import io.github.andrewauclair.moderndocking.ui.DockingHeaderUI; import io.github.andrewauclair.moderndocking.ui.HeaderController; import io.github.andrewauclair.moderndocking.ui.HeaderModel; import java.awt.Color; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.util.Objects; import java.util.Random; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JRadioButton; import javax.swing.JTextField; import javax.swing.UIManager; public class SimplePanel extends BasePanel { private String tabText = ""; public boolean limitToWindow = false; private Color backgroundColor = null; private Color foregroundColor = null; @DockingProperty(name = "test", defaultValue = "one") private String test; @DockingProperty(name = "test1", defaultValue = "two") private String test1; @DockingProperty(name = "test2", defaultValue = "three") private String test2; @DockingProperty(name = "test3", defaultValue = "four") private String test3; @DockingProperty(name = "test4", defaultValue = "five") private String test4; @DockingProperty(name = "test5", defaultValue = "six") private String test5; @DockingProperty(name = "test6", defaultValue = "seven") private String test6; @DockingProperty(name = "test7", defaultValue = "eight") private String test7; @DockingProperty(name = "test8", defaultValue = "nine") private String test8; @DockingProperty(name = "test9", defaultValue = "ten") private String test9; @DockingProperty(name = "test10", defaultValue = "eleven") private String test10; @DockingProperty(name = "test11", defaultValue = "twelve") private String test11; @DockingProperty(name = "test_int_1", defaultValue = "5") private int test_int_1; private static final Random rand = new Random(); public SimplePanel(DockingAPI docking, String title, String persistentID) { super(docking, title, persistentID); tabText = title; setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); int numberOfControls = rand.nextInt(15); for (int i = 0; i < numberOfControls; i++) { int randControl = rand.nextInt(4); switch (randControl) { case 0: add(new JLabel("Label Here"), gbc); break; case 1: add(new JTextField(), gbc); break; case 2: add(new JCheckBox(), gbc); break; case 3: add(new JRadioButton(), gbc); break; } if (rand.nextBoolean()) { gbc.gridy++; } else { gbc.gridx++; } } } public void setTitleBackground(Color color) { this.backgroundColor = color; } public void setTitleForeground(Color color) { this.foregroundColor = color; } @Override public DockingHeaderUI createHeaderUI(HeaderController headerController, HeaderModel headerModel) { if (!(UIManager.getLookAndFeel() instanceof FlatLaf)) { return new DefaultHeaderUI(headerController, headerModel) { @Override public void setBackground(Color bg) { if (backgroundColor != null) { super.setBackground(backgroundColor); } else { super.setBackground(bg); } } @Override public void setForeground(Color bg) { if (foregroundColor != null) { super.setForeground(foregroundColor); } else { super.setForeground(bg); } } }; } else { return new DefaultHeaderUI(headerController, headerModel) { @Override public void setBackground(Color bg) { if (backgroundColor != null) { super.setBackground(backgroundColor); } else { super.setBackground(bg); } } @Override public void setForeground(Color bg) { if (foregroundColor != null) { super.setForeground(foregroundColor); } else { super.setForeground(bg); } } }; } } @Override public int getType() { return 1; } @Override public boolean isFloatingAllowed() { return true; } @Override public boolean isClosable() { return true; } @Override public boolean isMinMaxAllowed() { return true; } @Override public boolean isLimitedToWindow() { return limitToWindow; } @Override public String getTabText() { if (tabText == null || tabText.isEmpty()) { return super.getTabText(); } return tabText; } @Override public String getTabTooltip() { return tabText; } public void setTabText(String tabText) { Objects.requireNonNull(tabText); this.tabText = tabText; } @Override public void updateProperties() { System.out.println("Set props for " + getPersistentID()); System.out.println(test); System.out.println(test1); System.out.println(test2); System.out.println(test3); System.out.println(test4); System.out.println(test5); System.out.println(test6); System.out.println(test7); System.out.println(test8); System.out.println(test9); System.out.println(test10); System.out.println(test11); System.out.println(test_int_1); } // @Override // public void setProperties(Map<String, String> properties) { // System.out.println("Set props for " + getPersistentID()); // } }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/demo-multi-app/src/basic/BasePanel.java
demo-multi-app/src/basic/BasePanel.java
/* Copyright (c) 2022 Andrew Auclair Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 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 the Software. 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. */ package basic; import io.github.andrewauclair.moderndocking.Dockable; import io.github.andrewauclair.moderndocking.api.DockingAPI; import java.awt.BorderLayout; import javax.swing.JPanel; public abstract class BasePanel extends JPanel implements Dockable { private final String title; private final String persistentID; public BasePanel(DockingAPI docking, String title, String persistentID) { super(new BorderLayout()); this.title = title; this.persistentID = persistentID; JPanel panel = new JPanel(); add(panel, BorderLayout.CENTER); // the single call to register any docking panel extending this abstract class docking.registerDockable(this); } @Override public String getPersistentID() { return persistentID; } @Override public String getTabText() { return title; } }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/demo-multi-app/src/basic/MainFrame.java
demo-multi-app/src/basic/MainFrame.java
/* Copyright (c) 2022-2023 Andrew Auclair Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 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 the Software. 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. */ package basic; import com.formdev.flatlaf.FlatDarkLaf; import com.formdev.flatlaf.FlatLaf; import com.formdev.flatlaf.FlatLightLaf; import com.formdev.flatlaf.intellijthemes.FlatSolarizedDarkIJTheme; import com.formdev.flatlaf.intellijthemes.materialthemeuilite.FlatMTGitHubDarkIJTheme; import exception.FailOnThreadViolationRepaintManager; import io.github.andrewauclair.moderndocking.Dockable; import io.github.andrewauclair.moderndocking.DockableStyle; import io.github.andrewauclair.moderndocking.DockableTabPreference; import io.github.andrewauclair.moderndocking.DockingRegion; import io.github.andrewauclair.moderndocking.api.DockingAPI; import io.github.andrewauclair.moderndocking.api.RootDockingPanelAPI; import io.github.andrewauclair.moderndocking.app.ApplicationLayoutMenuItem; import io.github.andrewauclair.moderndocking.app.DockableMenuItem; import io.github.andrewauclair.moderndocking.app.Docking; import io.github.andrewauclair.moderndocking.app.LayoutsMenu; import io.github.andrewauclair.moderndocking.app.RootDockingPanel; import io.github.andrewauclair.moderndocking.app.WindowLayoutBuilder; import io.github.andrewauclair.moderndocking.exception.DockingLayoutException; import io.github.andrewauclair.moderndocking.ext.ui.DockingUI; import io.github.andrewauclair.moderndocking.layouts.ApplicationLayout; import io.github.andrewauclair.moderndocking.layouts.DockingLayouts; import io.github.andrewauclair.moderndocking.settings.Settings; import java.awt.Color; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.io.File; import java.util.Objects; import java.util.Optional; import java.util.Random; import java.util.concurrent.Callable; import javax.swing.ImageIcon; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import picocli.CommandLine; public class MainFrame extends JFrame implements Callable<Integer> { private final File layoutFile; @CommandLine.Option(names = "--laf", required = true, description = "look and feel to use. one of: system, light, dark, github-dark or solarized-dark") String lookAndFeel; @CommandLine.Option(names = "--enable-edt-violation-detector", defaultValue = "false", description = "enable the Event Dispatch Thread (EDT) violation checker") boolean edtViolationDetector; @CommandLine.Option(names = "--ui-scale", defaultValue = "1", description = "scale to use for the FlatLaf.uiScale value") int uiScale; @CommandLine.Option(names = "--always-use-tabs", defaultValue = "false", description = "always use tabs, even when there is only 1 dockable in the tab group") boolean alwaysUseTabs; private DockingAPI docking; public MainFrame(File layoutFile) { this.layoutFile = layoutFile; } static Random rng = new Random(); public static String generateString(String characters, int length) { char[] text = new char[length]; for (int i = 0; i < length; i++) { text[i] = characters.charAt(rng.nextInt(characters.length())); } return new String(text); } @Override public void setVisible(boolean visible) { setSize(800, 600); setTitle("Modern Docking Basic Demo (" + layoutFile.getName() + ")"); docking = new Docking(this); if (alwaysUseTabs) { Settings.setDefaultTabPreference(DockableTabPreference.TOP_ALWAYS); } JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenu file = new JMenu("File"); menuBar.add(file); JMenuItem saveLayout = new JMenuItem("Save Layout to File..."); file.add(saveLayout); saveLayout.addActionListener(e -> { JFileChooser chooser = new JFileChooser(); int result = chooser.showSaveDialog(MainFrame.this); if (result == JFileChooser.APPROVE_OPTION) { File selectedFile = chooser.getSelectedFile(); ApplicationLayout layout = docking.getDockingState().getApplicationLayout(); try { docking.getLayoutPersistence().saveLayoutToFile(selectedFile, layout); } catch (DockingLayoutException ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(MainFrame.this, "Failed to save layout"); } } }); JMenuItem loadLayout = new JMenuItem("Load Layout from File..."); file.add(loadLayout); JMenuItem createPanel = new JMenuItem("Create Panel..."); createPanel.addActionListener(e -> { String panelName = JOptionPane.showInputDialog("Panel name"); SimplePanel panel = new SimplePanel(docking, panelName, panelName); docking.dock(panel, MainFrame.this, DockingRegion.EAST); }); file.add(createPanel); loadLayout.addActionListener(e -> { JFileChooser chooser = new JFileChooser(); int result = chooser.showOpenDialog(MainFrame.this); if (result == JFileChooser.APPROVE_OPTION) { File selectedFile = chooser.getSelectedFile(); ApplicationLayout layout = null; try { layout = docking.getLayoutPersistence().loadApplicationLayoutFromFile(selectedFile); } catch (DockingLayoutException ex) { ex.printStackTrace(); } if (layout != null) { docking.getDockingState().restoreApplicationLayout(layout); } } }); JMenu window = new JMenu("Window"); window.add(new LayoutsMenu(docking)); menuBar.add(window); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); SimplePanel one = new SimplePanel(docking, "one", "one"); SimplePanel two = new SimplePanel(docking, "two", "two"); SimplePanel three = new SimplePanel(docking, "three", "three"); SimplePanel four = new SimplePanel(docking, "four", "four"); SimplePanel five = new SimplePanel(docking, "five", "five"); SimplePanel six = new SimplePanel(docking, "six", "six"); SimplePanel seven = new SimplePanel(docking, "seven", "seven"); SimplePanel eight = new SimplePanel(docking, "eight", "eight"); ToolPanel explorer = new ToolPanel(docking, "Explorer", "explorer", DockableStyle.VERTICAL, new ImageIcon(Objects.requireNonNull(getClass().getResource("/icons/light/icons8-vga-16.png")))); ToolPanel output = new OutputPanel(docking, "Output", "output", DockableStyle.HORIZONTAL, new ImageIcon(Objects.requireNonNull(getClass().getResource("/icons/light/icons8-vga-16.png")))); AlwaysDisplayedPanel alwaysDisplayed = new AlwaysDisplayedPanel(docking, "always displayed", "always-displayed"); ThemesPanel themes = new ThemesPanel(docking); one.setTitleBackground(new Color(0xa1f2ff)); two.setTitleBackground(new Color(0xdda1ff)); three.setTitleBackground(new Color(0xffaea1)); four.setTitleBackground(new Color(0xc3ffa1)); one.setTitleForeground(Color.black); two.setTitleForeground(Color.black); three.setTitleForeground(Color.black); four.setTitleForeground(Color.black); JMenuItem changeText = new JMenuItem("Change tab text"); changeText.addActionListener(e -> { String rand = generateString("abcdefg", 4); one.setTabText(rand); docking.updateTabInfo("one"); }); JMenu view = new JMenu("View"); menuBar.add(view); JMenuItem createNewDockable = new JMenuItem(); createNewDockable.addActionListener(e -> { SimplePanel rand = new SimplePanel(docking, generateString("alpha", 6), generateString("abcdefg", 10)); docking.dock(rand, one, DockingRegion.WEST); }); view.add(createNewDockable); view.add(actionListenDock(docking, one)); view.add(actionListenDock(docking, two)); view.add(actionListenDock(docking, three)); view.add(actionListenDock(docking, four)); view.add(actionListenDock(docking, five)); view.add(actionListenDock(docking, six)); view.add(actionListenDock(docking, seven)); view.add(actionListenDock(docking, eight)); view.add(actionListenDock(docking, explorer)); view.add(actionListenDock(docking, output)); view.add(new DockableMenuItem(docking, () -> ((Dockable) alwaysDisplayed).getPersistentID(), ((Dockable) alwaysDisplayed).getTabText())); view.add(changeText); view.add(actionListenDock(docking, themes)); JMenuItem storeCurrentLayout = new JMenuItem("Store Current Layout..."); storeCurrentLayout.addActionListener(e -> { String layoutName = JOptionPane.showInputDialog("Name of Layout"); DockingLayouts.addLayout(layoutName, docking.getDockingState().getApplicationLayout()); }); window.add(storeCurrentLayout); JMenuItem restoreDefaultLayout = new ApplicationLayoutMenuItem(docking, "default", "Restore Default Layout"); window.add(restoreDefaultLayout); setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridy++; gbc.weightx = 1.0; gbc.weighty = 1.0; gbc.fill = GridBagConstraints.BOTH; RootDockingPanelAPI dockingPanel = new RootDockingPanel(docking, this); // dockingPanel.setPinningSupported(false); gbc.insets = new Insets(0, 5, 5, 5); add(dockingPanel, gbc); gbc.gridy++; gbc.weighty = 0; gbc.fill = GridBagConstraints.NONE; ApplicationLayout defaultLayout = new WindowLayoutBuilder(docking, alwaysDisplayed.getPersistentID()) .dock(one.getPersistentID(), alwaysDisplayed.getPersistentID()) .dock(two.getPersistentID(), one.getPersistentID(), DockingRegion.SOUTH) .dockToRoot(three.getPersistentID(), DockingRegion.WEST) .dock(four.getPersistentID(), two.getPersistentID(), DockingRegion.CENTER) .dockToRoot(output.getPersistentID(), DockingRegion.SOUTH) .dockToRoot(themes.getPersistentID(), DockingRegion.EAST) .dock(explorer.getPersistentID(), themes.getPersistentID(), DockingRegion.CENTER) .display(themes.getPersistentID()) .buildApplicationLayout(); DockingLayouts.addLayout("default", defaultLayout); docking.getAppState().setDefaultApplicationLayout(defaultLayout); super.setVisible(visible); } private JMenuItem actionListenDock(DockingAPI docking, Dockable dockable) { return new DockableMenuItem(docking, dockable.getPersistentID(), dockable.getTabText()); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { DockingUI.initialize(); MainFrame one = new MainFrame(new File("multiframe_demo_layout_1.xml")); MainFrame two = new MainFrame(new File("multiframe_demo_layout_2.xml")); new CommandLine(one).execute(args); new CommandLine(two).execute(args); one.setLocation(100, 100); two.setLocation(1000, 100); }); } private void configureLookAndFeel() { try { FlatLaf.registerCustomDefaultsSource( "docking" ); System.setProperty("flatlaf.uiScale", String.valueOf(uiScale)); if (lookAndFeel.equals("light")) { UIManager.setLookAndFeel(new FlatLightLaf()); } else if (lookAndFeel.equals("dark")) { UIManager.setLookAndFeel(new FlatDarkLaf()); } else if (lookAndFeel.equals("github-dark")) { UIManager.setLookAndFeel(new FlatMTGitHubDarkIJTheme()); } else if (lookAndFeel.equals("solarized-dark")) { UIManager.setLookAndFeel(new FlatSolarizedDarkIJTheme()); } else { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { throw new RuntimeException(ex); } } FlatLaf.updateUI(); } catch (Exception e) { e.printStackTrace(); try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { throw new RuntimeException(ex); } } UIManager.getDefaults().put("TabbedPane.contentBorderInsets", new Insets(0,0,0,0)); UIManager.getDefaults().put("TabbedPane.tabsOverlapBorder", true); if (edtViolationDetector) { // this is an app to test the docking framework, we want to make sure we detect EDT violations as soon as possible FailOnThreadViolationRepaintManager.install(); } } @Override public Integer call() throws Exception { SwingUtilities.invokeLater(this::configureLookAndFeel); SwingUtilities.invokeLater(() -> { setVisible(true); // now that the main frame is set up with the defaults, we can restore the layout docking.getAppState().setPersistFile(layoutFile); try { docking.getAppState().restore(); } catch (DockingLayoutException e) { // something happened trying to load the layout file, record it here e.printStackTrace(); } docking.getAppState().setAutoPersist(true); }); return 0; } Optional<Integer> tryParse(String s) { try { return Optional.of(Integer.parseInt(s)); } catch (NumberFormatException ignored) { } return Optional.empty(); } void test() { tryParse("3").ifPresent(integer -> { // use it }); } }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/demo-multi-app/src/basic/ToolPanel.java
demo-multi-app/src/basic/ToolPanel.java
/* Copyright (c) 2022 Andrew Auclair Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 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 the Software. 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. */ package basic; import io.github.andrewauclair.moderndocking.DockableStyle; import io.github.andrewauclair.moderndocking.api.DockingAPI; import javax.swing.Icon; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; public class ToolPanel extends BasePanel { private final DockableStyle style; private final Icon icon; public boolean limitToWindow = false; public ToolPanel(DockingAPI docking, String title, String persistentID, DockableStyle style) { super(docking, title, persistentID); this.style = style; this.icon = null; } public ToolPanel(DockingAPI docking, String title, String persistentID, DockableStyle style, Icon icon) { super(docking, title, persistentID); this.style = style; this.icon = icon; } @Override public int getType() { return 0; } @Override public Icon getIcon() { return icon; } @Override public boolean isFloatingAllowed() { return false; } @Override public boolean isLimitedToWindow() { return limitToWindow; } @Override public DockableStyle getStyle() { return style; } @Override public boolean isClosable() { return true; } @Override public boolean isAutoHideAllowed() { return true; } @Override public boolean isMinMaxAllowed() { return false; } @Override public boolean hasMoreMenuOptions() { return true; } @Override public void addMoreOptions(JPopupMenu menu) { menu.add(new JMenuItem("Something")); menu.add(new JMenuItem("Else")); } }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/demo-multi-app/src/basic/AlwaysDisplayedPanel.java
demo-multi-app/src/basic/AlwaysDisplayedPanel.java
/* Copyright (c) 2022 Andrew Auclair Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 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 the Software. 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. */ package basic; import io.github.andrewauclair.moderndocking.api.DockingAPI; // Docking panel that is always displayed and cannot be closed public class AlwaysDisplayedPanel extends SimplePanel { // create a new basic.AlwaysDisplayedPanel with the given title and persistentID public AlwaysDisplayedPanel(DockingAPI docking, String title, String persistentID) { super(docking, title, persistentID); } @Override public boolean isClosable() { return false; } @Override public boolean isFloatingAllowed() { return false; } @Override public boolean isLimitedToWindow() { return true; } }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/demo-multi-app/src/basic/ThemesPanel.java
demo-multi-app/src/basic/ThemesPanel.java
/* Copyright (c) 2023 Andrew Auclair Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 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 the Software. 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. */ package basic; import com.formdev.flatlaf.FlatDarkLaf; import com.formdev.flatlaf.FlatLaf; import com.formdev.flatlaf.FlatLightLaf; import com.formdev.flatlaf.intellijthemes.FlatSolarizedDarkIJTheme; import com.formdev.flatlaf.intellijthemes.materialthemeuilite.FlatMTGitHubDarkIJTheme; import io.github.andrewauclair.moderndocking.Dockable; import io.github.andrewauclair.moderndocking.api.DockingAPI; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.table.DefaultTableModel; public class ThemesPanel extends BasePanel implements Dockable { public ThemesPanel(DockingAPI docking) { super(docking, "Themes", "themes"); JTable table = new JTable() { @Override public boolean isCellEditable(int row, int column) { return false; } }; table.setTableHeader(null); DefaultTableModel model = new DefaultTableModel(0, 1); model.addRow(new Object[] { "FlatLaf Light"}); model.addRow(new Object[] { "FlatLaf Dark"}); model.addRow(new Object[] { "Github Dark"}); model.addRow(new Object[] { "Solarized Dark"}); table.setModel(model); setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; gbc.weightx = 1; gbc.weighty = 1; gbc.fill = GridBagConstraints.BOTH; add(new JScrollPane(table), gbc); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); table.getSelectionModel().addListSelectionListener(e -> { if (table.getSelectedRow() == -1) { return; } String lookAndFeel = (String) model.getValueAt(table.getSelectedRow(), 0); SwingUtilities.invokeLater(() -> { try { switch (lookAndFeel) { case "FlatLaf Light": UIManager.setLookAndFeel(new FlatLightLaf()); break; case "FlatLaf Dark": UIManager.setLookAndFeel(new FlatDarkLaf()); break; case "Github Dark": UIManager.setLookAndFeel(new FlatMTGitHubDarkIJTheme()); break; case "Solarized Dark": UIManager.setLookAndFeel(new FlatSolarizedDarkIJTheme()); break; } FlatLaf.updateUI(); } catch (UnsupportedLookAndFeelException ex) { throw new RuntimeException(ex); } }); }); } @Override public int getType() { return 1; } @Override public boolean isFloatingAllowed() { return false; } @Override public boolean isClosable() { return false; } @Override public boolean isWrappableInScrollpane() { return false; } }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/demo-multi-app/src/basic/OutputPanel.java
demo-multi-app/src/basic/OutputPanel.java
package basic; import io.github.andrewauclair.moderndocking.DockableStyle; import io.github.andrewauclair.moderndocking.DockingProperty; import io.github.andrewauclair.moderndocking.api.DockingAPI; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import javax.swing.BorderFactory; import javax.swing.Icon; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.event.ChangeEvent; import javax.swing.event.ListSelectionEvent; import javax.swing.event.TableColumnModelEvent; import javax.swing.event.TableColumnModelListener; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumn; public class OutputPanel extends ToolPanel { @DockingProperty(name = "first-column-name", defaultValue = "one") private String firstColumnName; private JTable table = new JTable(new DefaultTableModel(new String[] { "one", "two"}, 0)); private Map<String, String> properties = new HashMap<>(); public OutputPanel(DockingAPI docking, String title, String persistentID, DockableStyle style, Icon icon) { super(docking, title, persistentID, style, icon); table.setBorder(BorderFactory.createEmptyBorder()); JScrollPane comp = new JScrollPane(table); comp.setBorder(BorderFactory.createEmptyBorder()); add(comp); updateColumnsProp(); updateColumnSizesProp(); table.getColumnModel().addColumnModelListener(new TableColumnModelListener() { @Override public void columnAdded(TableColumnModelEvent e) { } @Override public void columnRemoved(TableColumnModelEvent e) { } @Override public void columnMoved(TableColumnModelEvent e) { updateColumnsProp(); docking.getAppState().persist(); } @Override public void columnMarginChanged(ChangeEvent e) { updateColumnSizesProp(); docking.getAppState().persist(); } @Override public void columnSelectionChanged(ListSelectionEvent e) { } }); } private void updateColumnsProp() { Enumeration<TableColumn> columns = table.getColumnModel().getColumns(); String prop = ""; while (columns.hasMoreElements()) { prop += columns.nextElement().getHeaderValue().toString(); prop += ","; } properties.put("columns", prop); } private void updateColumnSizesProp() { Enumeration<TableColumn> columns = table.getColumnModel().getColumns(); String prop = ""; while (columns.hasMoreElements()) { prop += columns.nextElement().getWidth(); prop += ","; } properties.put("column-sizes", prop); } // @Override // public Map<String, String> getProperties() { // return properties; // } // // @Override // public void setProperties(Map<String, String> properties) { // if (properties.get("columns") != null && properties.get("column-sizes") != null) { // String[] columns = properties.get("columns").split(","); // String[] columnSizes = properties.get("column-sizes").split(","); // // // List<TableColumn> tableColumns = Collections.list(table.getColumnModel().getColumns()); // // for (int i = 0; i < columns.length; i++) { // int location = table.getColumnModel().getColumnIndex(columns[i]); // // table.getColumnModel().moveColumn(location, i); // final int index = i; // SwingUtilities.invokeLater(() -> { // table.getColumnModel().getColumn(index).setPreferredWidth(Integer.parseInt(columnSizes[index])); // }); // } // } // } @Override public boolean hasMoreMenuOptions() { return true; } @Override public void addMoreOptions(JPopupMenu menu) { JMenuItem rename = new JMenuItem(); rename.addActionListener(e -> { firstColumnName = "changed"; table.getColumnModel().getColumn(0).setHeaderValue(firstColumnName); }); menu.add(rename); } @Override public void updateProperties() { // properties have now been loaded, use them table.getColumnModel().getColumn(0).setHeaderValue(firstColumnName); } @Override public boolean isWrappableInScrollpane() { return false; } }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/demo-multi-app/src/basic/MultipleInstances.java
demo-multi-app/src/basic/MultipleInstances.java
/* Copyright (c) 2023 Andrew Auclair Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 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 the Software. 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. */ package basic; public class MultipleInstances { }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/demo-multi-app/src/exception/CheckThreadViolationRepaintManager.java
demo-multi-app/src/exception/CheckThreadViolationRepaintManager.java
/* * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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> * Copyright 2012-2015 the original author or authors. */ package exception; import java.lang.ref.WeakReference; import java.util.Objects; import javax.swing.JComponent; import javax.swing.RepaintManager; import static javax.swing.SwingUtilities.isEventDispatchThread; /** * <p> * This class is used to detect Event Dispatch Thread rule violations<br> * See <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html">How to Use Threads</a> for more info * </p> * * <p> * This is a modification of original idea of Scott Delap.<br> * </p> * * @author Scott Delap * @author Alexander Potochkin * <p> * <a href="https://swinghelper.dev.java.net/">...</a> */ abstract class CheckThreadViolationRepaintManager extends RepaintManager { private final boolean completeCheck; private WeakReference<JComponent> lastComponent; CheckThreadViolationRepaintManager() { // it is recommended to pass the complete check this(true); } CheckThreadViolationRepaintManager(boolean completeCheck) { this.completeCheck = completeCheck; } @Override public synchronized void addInvalidComponent(JComponent component) { checkThreadViolations(Objects.requireNonNull(component)); super.addInvalidComponent(component); } @Override public void addDirtyRegion(JComponent component, int x, int y, int w, int h) { checkThreadViolations(Objects.requireNonNull(component)); super.addDirtyRegion(component, x, y, w, h); } private void checkThreadViolations(JComponent c) { if (!isEventDispatchThread() && (completeCheck || c.isShowing())) { boolean imageUpdate = false; boolean repaint = false; boolean fromSwing = false; StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); for (StackTraceElement st : stackTrace) { if (repaint && st.getClassName().startsWith("javax.swing.")) { fromSwing = true; } if (repaint && "imageUpdate".equals(st.getMethodName())) { imageUpdate = true; } if ("repaint".equals(st.getMethodName())) { repaint = true; fromSwing = false; } } if (imageUpdate) { // assuming it is java.awt.image.ImageObserver.imageUpdate(...) // image was asynchronously updated, that's ok return; } if (repaint && !fromSwing) { // no problems here, since repaint() is thread safe return; } // ignore the last processed component if (lastComponent != null && c == lastComponent.get()) { return; } lastComponent = new WeakReference<>(c); violationFound(c, stackTrace); } } abstract void violationFound(JComponent c, StackTraceElement[] stackTrace); }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/demo-multi-app/src/exception/EdtViolationException.java
demo-multi-app/src/exception/EdtViolationException.java
/* 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. Copyright 2012-2015 the original author or authors. */ package exception; /** * Error thrown when an EDT violation is detected. For more details, please read the <a * href="http://java.sun.com/javase/6/docs/api/javax/swing/package-summary.html#threading" target="_blank">Swing's * Threading Policy</a>. * * @author Alex Ruiz */ public class EdtViolationException extends RuntimeException { /** * Creates a new {@link EdtViolationException}. * * @param message the detail message. */ public EdtViolationException(String message) { super(message); } }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/demo-multi-app/src/exception/FailOnThreadViolationRepaintManager.java
demo-multi-app/src/exception/FailOnThreadViolationRepaintManager.java
/* 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. Copyright 2012-2015 the original author or authors. */ package exception; import javax.swing.JComponent; import javax.swing.RepaintManager; /** * <p> * Fails a test when a Event Dispatch Thread rule violation is detected. See <a * href="http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html">How to Use Threads</a> for more information. * </p> * * @author Alex Ruiz */ public class FailOnThreadViolationRepaintManager extends CheckThreadViolationRepaintManager { /** * the {@link RepaintManager} that was installed before {@link #install()} has been called. */ private static RepaintManager previousRepaintManager; /** * <p> * Creates a new {@link FailOnThreadViolationRepaintManager} and sets it as the current repaint manager. * </p> * * <p> * On Sun JVMs, this method will install the new repaint manager the first time only. Once installed, subsequent calls * to this method will not install new repaint managers. This optimization may not work on non-Sun JVMs, since we use * reflection to check if a {@code CheckThreadViolationRepaintManager.java} is already installed. * </p> * * @return the created (and installed) repaint manager. * @see #uninstall() * @see RepaintManager#setCurrentManager(RepaintManager) */ public static FailOnThreadViolationRepaintManager install() { Object m = currentRepaintManager(); if (m instanceof FailOnThreadViolationRepaintManager) { return (FailOnThreadViolationRepaintManager) m; } return installNew(); } /** * <p> * Tries to restore the repaint manager before installing the {@link FailOnThreadViolationRepaintManager} via * {@link #install()}. * </p> * * @return the restored (and installed) repaint manager. * @see #install() * @see RepaintManager#setCurrentManager(RepaintManager) */ public static RepaintManager uninstall() { RepaintManager restored = previousRepaintManager; setCurrentManager(restored); previousRepaintManager = null; return restored; } private static RepaintManager currentRepaintManager() { try { RepaintManager repaintManager = RepaintManager.currentManager(null); if (repaintManager != null) { return repaintManager; } } catch (RuntimeException e) { return null; } return null; } private static FailOnThreadViolationRepaintManager installNew() { FailOnThreadViolationRepaintManager m = new FailOnThreadViolationRepaintManager(); previousRepaintManager = currentRepaintManager(); setCurrentManager(m); return m; } public FailOnThreadViolationRepaintManager() { } public FailOnThreadViolationRepaintManager(boolean completeCheck) { super(completeCheck); } /** * Throws a {@link EdtViolationException} when an EDT access violation is found. * * @param c the component involved in the EDT violation. * @param stackTraceElements stack trace elements to be set to the thrown exception. * @throws EdtViolationException when an EDT access violation is found. */ @Override void violationFound(JComponent c, StackTraceElement[] stackTraceElements) { EdtViolationException e = new EdtViolationException("EDT violation detected"); e.setStackTrace(stackTraceElements); throw e; } }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/demo-multi-app/src/examples/Display.java
demo-multi-app/src/examples/Display.java
package examples; public class Display { }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/demo-multi-app/src/examples/BringToFront.java
demo-multi-app/src/examples/BringToFront.java
package examples; public class BringToFront { }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/demo-multi-app/src/examples/Maximize.java
demo-multi-app/src/examples/Maximize.java
package examples; public class Maximize { }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/docking-api/src/module-info.java
docking-api/src/module-info.java
/** * Module for the Modern Docking framework */ module modern_docking.api { requires java.desktop; requires java.logging; exports io.github.andrewauclair.moderndocking; exports io.github.andrewauclair.moderndocking.event; exports io.github.andrewauclair.moderndocking.exception; exports io.github.andrewauclair.moderndocking.layouts; exports io.github.andrewauclair.moderndocking.settings; exports io.github.andrewauclair.moderndocking.ui; exports io.github.andrewauclair.moderndocking.api; // export our internal package only to our other extension modules exports io.github.andrewauclair.moderndocking.internal to modern_docking.ui_ext, modern_docking.single_app, modern_docking.multi_app; }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/docking-api/src/io/github/andrewauclair/moderndocking/Property.java
docking-api/src/io/github/andrewauclair/moderndocking/Property.java
package io.github.andrewauclair.moderndocking; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Base64; /** * Base class for all Property classes */ public abstract class Property { private final String name; /** * Create a new instance with name * * @param name The name of the property */ public Property(String name) { this.name = name; } /** * Get the actual type of the property * * @return The type of the property */ public abstract Class<?> getType(); /** * Check if the property is a null value * * @return Is the property null? */ public abstract boolean isNull(); /** * Get the name of the property * * @return Name of the property */ public String getName() { return name; } /** * Property class that provides access to a byte */ public static class ByteProperty extends Property { private final byte value; /** * Create a new instance * * @param name The name of the property * @param value The value of the property */ public ByteProperty(String name, byte value) { super(name); this.value = value; } @Override public Class<?> getType() { return byte.class; } @Override public boolean isNull() { return false; } @Override public String toString() { return Byte.toString(value); } /** * Get the value of this property * * @return Current value */ public byte getValue() { return value; } } /** * Property class that provides access to a short */ public static class ShortProperty extends Property { private final short value; /** * Create a new instance * * @param name The name of the property * @param value The value of the property */ public ShortProperty(String name, short value) { super(name); this.value = value; } @Override public Class<?> getType() { return short.class; } @Override public boolean isNull() { return false; } @Override public String toString() { return Short.toString(value); } /** * Get the value of this property * * @return Current value */ public short getValue() { return value; } } /** * Property class that provides access to a int */ public static class IntProperty extends Property { private final int value; /** * Create a new instance * * @param name The name of the property * @param value The value of the property */ public IntProperty(String name, int value) { super(name); this.value = value; } @Override public Class<?> getType() { return int.class; } @Override public boolean isNull() { return false; } @Override public String toString() { return Integer.toString(value); } /** * Get the value of this property * * @return Current value */ public int getValue() { return value; } } /** * Property class that provides access to a long */ public static class LongProperty extends Property { private final long value; /** * Create a new instance * * @param name The name of the property * @param value The value of the property */ public LongProperty(String name, long value) { super(name); this.value = value; } @Override public Class<?> getType() { return long.class; } @Override public boolean isNull() { return false; } @Override public String toString() { return Long.toString(value); } /** * Get the value of this property * * @return Current value */ public long getValue() { return value; } } /** * Property class that provides access to a float */ public static class FloatProperty extends Property { private final float value; /** * Create a new instance * * @param name The name of the property * @param value The value of the property */ public FloatProperty(String name, float value) { super(name); this.value = value; } @Override public Class<?> getType() { return float.class; } @Override public boolean isNull() { return false; } @Override public String toString() { return Float.toString(value); } /** * Get the value of this property * * @return Current value */ public float getValue() { return value; } } /** * Property class that provides access to a double */ public static class DoubleProperty extends Property { private final double value; /** * Create a new instance * * @param name The name of the property * @param value The value of the property */ public DoubleProperty(String name, double value) { super(name); this.value = value; } @Override public Class<?> getType() { return double.class; } @Override public boolean isNull() { return false; } @Override public String toString() { return Double.toString(value); } /** * Get the value of this property * * @return Current value */ public double getValue() { return value; } } /** * Property class that provides access to a char */ public static class CharacterProperty extends Property { private final char value; /** * Create a new instance * * @param name The name of the property * @param value The value of the property */ public CharacterProperty(String name, char value) { super(name); this.value = value; } @Override public Class<?> getType() { return char.class; } @Override public boolean isNull() { return false; } @Override public String toString() { return Character.toString(value); } /** * Get the value of this property * * @return Current value */ public char getValue() { return value; } } /** * Property class that provides access to a boolean */ public static class BooleanProperty extends Property { private final boolean value; /** * Create a new instance * * @param name The name of the property * @param value The value of the property */ public BooleanProperty(String name, boolean value) { super(name); this.value = value; } @Override public Class<?> getType() { return boolean.class; } @Override public boolean isNull() { return false; } @Override public String toString() { return Boolean.toString(value); } /** * Get the value of this property * * @return Current value */ public boolean getValue() { return value; } } /** * Property class that provides access to a String */ public static class StringProperty extends Property { private final String value; /** * Create a new instance * * @param name The name of the property * @param value The value of the property */ public StringProperty(String name, String value) { super(name); this.value = value; } @Override public Class<?> getType() { return String.class; } @Override public boolean isNull() { return value == null; } @Override public String toString() { return value; } /** * Get the value of this property * * @return Current value */ public String getValue() { return value; } } /** * Property class that provides access to a String */ public static class SerializableProperty extends Property { private final Serializable value; /** * Create a new instance * * @param name The name of the property * @param value The value of the property */ public SerializableProperty(String name, Serializable value) { super(name); this.value = value; } @Override public Class<?> getType() { return Serializable.class; } @Override public boolean isNull() { return value == null; } @Override public String toString() { try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { ObjectOutputStream os = new ObjectOutputStream(bos); os.writeObject(value); return Base64.getEncoder().encodeToString(bos.toByteArray()); } catch (IOException e) { throw new RuntimeException(e); } } /** * Get the value of this property * * @return Current value */ public Serializable getValue() { return value; } } }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/docking-api/src/io/github/andrewauclair/moderndocking/DockableTabPreference.java
docking-api/src/io/github/andrewauclair/moderndocking/DockableTabPreference.java
/* Copyright (c) 2024 Andrew Auclair Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 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 the Software. 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. */ package io.github.andrewauclair.moderndocking; /** * Specify the tab preference of dockables and applications */ public enum DockableTabPreference { /** * Dockable has no tab preference */ NONE, /** * Dockable prefers tabs on the bottom */ BOTTOM, /** * Dockable prefers tabs on the top */ TOP, // use these options with Settings.setDefaultTabPreference to force tabs to always display, even with a single dockable /** * Application wants tabs always on the top */ BOTTOM_ALWAYS, /** * Application wants tabs always on the bottom */ TOP_ALWAYS }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/docking-api/src/io/github/andrewauclair/moderndocking/DockableStyle.java
docking-api/src/io/github/andrewauclair/moderndocking/DockableStyle.java
/* Copyright (c) 2022 Andrew Auclair Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 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 the Software. 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. */ package io.github.andrewauclair.moderndocking; /** * The style used by a dockable. Used to lock dockables into specific orientations */ public enum DockableStyle { /** * Dockable is only allowed to be docked horizontally */ HORIZONTAL, /** * Dockable is only allowed to be docked vertically */ VERTICAL, /** * Dockable is allowed to be docked horizontally or vertically */ BOTH, /** * Dockable is only allowed to be docked to the center of other dockables */ CENTER_ONLY }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/docking-api/src/io/github/andrewauclair/moderndocking/DynamicDockableParameters.java
docking-api/src/io/github/andrewauclair/moderndocking/DynamicDockableParameters.java
/* Copyright (c) 2025 Andrew Auclair Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 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 the Software. 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. */ package io.github.andrewauclair.moderndocking; /** * Parameters passed to the constructor of a dynamic dockable */ public class DynamicDockableParameters { private final String persistentID; private final String tabText; private final String titleText; /** * Create a new instance * * @param persistentID Persistent ID of the dynamic dockable * @param tabText Tab text of the dynamic dockable * @param titleText Title text of the dynamic dockable */ public DynamicDockableParameters(String persistentID, String tabText, String titleText) { this.persistentID = persistentID; this.tabText = tabText; this.titleText = titleText; } /** * The persistent ID of the dynamic dockable under construction * * @return Persistent ID */ public String getPersistentID() { return persistentID; } /** * Get the tab text of the dynamic dockable under construction * * @return Tab text */ public String getTabText() { return tabText; } /** * Get the title text of the dynamic dockable under construction * * @return Title text */ public String getTitleText() { return titleText; } }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/docking-api/src/io/github/andrewauclair/moderndocking/DockingRegion.java
docking-api/src/io/github/andrewauclair/moderndocking/DockingRegion.java
/* Copyright (c) 2022 Andrew Auclair Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 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 the Software. 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. */ package io.github.andrewauclair.moderndocking; /** * Enum used to determine docking regions throughout the framework */ public enum DockingRegion { /** * Used to dock to the center of components */ CENTER, /** * North or top of windows */ NORTH, /** * East or right of windows */ EAST, /** * South or bottom of windows */ SOUTH, /** * West or left of windows */ WEST }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/docking-api/src/io/github/andrewauclair/moderndocking/DockingProperty.java
docking-api/src/io/github/andrewauclair/moderndocking/DockingProperty.java
/* Copyright (c) 2023 Andrew Auclair Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 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 the Software. 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. */ package io.github.andrewauclair.moderndocking; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Java annotation used to indicate a field is a docking property and should be saved and restored when saving and loading layout files */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD}) public @interface DockingProperty { /** * The name of the property. Used for saving to layout files * * @return Name of the property */ String name(); /** * Indicate that this property is required to properly initialize a dockable * * NOTE: Currently unused * * @return Is this property required when initializing dockables */ boolean required() default false; /** * The default value of the property * * @return Default value */ String defaultValue() default "__no_default_value__"; }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/docking-api/src/io/github/andrewauclair/moderndocking/Dockable.java
docking-api/src/io/github/andrewauclair/moderndocking/Dockable.java
/* Copyright (c) 2022 Andrew Auclair Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 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 the Software. 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. */ package io.github.andrewauclair.moderndocking; import io.github.andrewauclair.moderndocking.internal.DockingInternal; import io.github.andrewauclair.moderndocking.ui.DockingHeaderUI; import io.github.andrewauclair.moderndocking.ui.HeaderController; import io.github.andrewauclair.moderndocking.ui.HeaderModel; import javax.swing.Icon; import javax.swing.JPopupMenu; /** * this is the main interface for a Dockable. Any panel that an application wishes to be dockable must implement * this interface and provide the appropriate values. * <p> * along with implementing this interface, the application will need to call Docking.registerDockable and Docking.dock * to use the dockable. */ public interface Dockable { /** * provide the persistent ID to the docking framework * this should be unique in the application (will be verified when adding dockable) * * @return Persistent ID of the dockable */ String getPersistentID(); /** * Provides the type of this dockable. Uses an int so that the user code can decide if they're just ints * or an enum (using the ordinal values) * * @return Type as an int, user defined */ default int getType() { return 0; } /** * provide the tab text to the docking framework * the tab text to be displayed when Dockable is in a tabbed pane. Does not need to be unique * <p> * NOTE: If this text changes, you will need to call Dockable.updateTabInfo() * * @return Tab text of the dockable */ String getTabText(); /** * provide the title text to the docking frame * the title text to be displayed when Dockable displays a header with a title bar * by default, this will be the same as the tab text * <p> * NOTE: If this text changes, you will need to call Dockable.updateTabInfo() * * @return Title text of the dockable */ default String getTitleText() { return getTabText(); } /** * provide the tab tooltip to the docking framework * <p> * NOTE: If this text changes, you will need to call Dockable.updateTabInfo() * * @return The text to display on a tooltip when hovering over the tab in a JTabbedPane */ default String getTabTooltip() { return null; } /** * provide the dockable icon to the docking framework * used in the default header UI, when displayed on in a JTabbedPane and when unpinned * * @return Icon of the dockable */ default Icon getIcon() { return null; } /** * indicates that this dockable is allowed to be floated as its own new window. * if floating is not allowed and an attempt is made to float the dockable, it will be returned to where it was undocked. * <p> * Note that this is independent of limitToRoot(). Returning false for floatingAllowed() and false for limitToRoot() will still * allow the dockable to be moved between roots, but it can't be used to start a new floating root. * * @return True, if floating is allowed */ default boolean isFloatingAllowed() { return true; } /** * force the dockable to remain in the window it started in. * this is useful for having a new floating window with many dockables that are only allowed in that one window. * <p> * NOTE: Dockables that return false for isClosable() will function as if isLimitedToWindow returns false, regardless of the return value. * * @return Should this dockable be limited to the window it starts in? */ default boolean isLimitedToWindow() { return false; } /** * style of the dockable. vertical will disallow the east and west regions. horizontal will disallow the north and south regions. * both will allow all 4 regions * * @return The style of this dockable */ default DockableStyle getStyle() { return DockableStyle.BOTH; } /** * auto hide style of the dockable. separate from getStyle, which is used for docking. this option allows the dockable to have different * preferences on auto hide than it does on docking. * * @return The auto hide style of this dockable */ default DockableStyle getAutoHideStyle() { return DockableStyle.BOTH; } /** * helper function to determine if the header close option should be enabled * * @return Can this dockable be closed? */ default boolean isClosable() { return true; } /** * callback function to all the application to override the closing of a dockable. * For example: an application might want to ask the user if they wish to continue. * * @return Should Modern Docking continue to close this dockable? */ default boolean requestClose() { return true; } /** * helper function to determine if the header auto hide option should be enabled * NOTE: this is a suggestion. If the parent frame of the dockable does not support auto hiding then the button will be hidden regardless. * auto hide is supported on all Modern Docking FloatingFrames and can be enabled for other frames with configureAutoHide in Docking * * @return True if auto hide is allowed */ default boolean isAutoHideAllowed() { return false; } /** * helper function to determine if the header min/max option should be enabled * * @return Is min/max allowed for this dockable */ default boolean isMinMaxAllowed() { return false; } /** * Dockables can be displayed with less room than they need. By default, this interface will tell the docking framework * to wrap the Dockable in a JScrollPane. To disable this functionality, override this method and return false. * * @return True if this dockable should be wrapped in a JScrollPane internally in the docking framework when displayed */ default boolean isWrappableInScrollpane() { return true; } /** * helper function to determine if the header 'more' option should be enabled * NOTE: isAutoHideAllowed() = true results in more options regardless of this return value * * @return True if there are more options to display on the context menu */ default boolean hasMoreMenuOptions() { return false; } /** * The tab preference of the dockable, either TOP, BOTTOM or NONE * * @return Tab preference */ default DockableTabPreference getTabPreference() { return DockableTabPreference.NONE; } /** * add the more options to the popup menu. defaults to an empty block to handle the case of hasMoreOptions() = false * * @param menu The JPopupMenu to add options to */ default void addMoreOptions(JPopupMenu menu) { } /** * create the header for the panel. By default, the framework will create a DefaultHeaderUI for non-flatlaf * * @param headerController Header controller for this dockable * @param headerModel Header model for this dockable * @return A new header UI that uses the provided controller and model */ default DockingHeaderUI createHeaderUI(HeaderController headerController, HeaderModel headerModel) { return DockingInternal.createDefaultHeaderUI(headerController, headerModel); } /** * The member variables with the DockingProperty annotation have been updated from the layout file */ default void updateProperties() { } }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/docking-api/src/io/github/andrewauclair/moderndocking/settings/Settings.java
docking-api/src/io/github/andrewauclair/moderndocking/settings/Settings.java
/* Copyright (c) 2023 Andrew Auclair Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 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 the Software. 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. */ package io.github.andrewauclair.moderndocking.settings; import io.github.andrewauclair.moderndocking.DockableTabPreference; import javax.swing.JTabbedPane; /** * General settings for Modern Docking */ public class Settings { private static DockableTabPreference defaultTabPreference = DockableTabPreference.BOTTOM; private static int tabLayoutPolicy = JTabbedPane.SCROLL_TAB_LAYOUT; private static boolean enableActiveHighlighter = true; private static int dragThreshold = 20; private static boolean useExistingDragThreshold = false; /** * Unused. All methods are static */ private Settings() { } /** * Checks if we're forcing tabs to always be on top or bottom * * @return Are we using a default tab preference of TOP_ALWAYS or BOTTOM_ALWAYS? */ public static boolean alwaysDisplayTabsMode() { return defaultTabPreference == DockableTabPreference.TOP_ALWAYS || defaultTabPreference == DockableTabPreference.BOTTOM_ALWAYS; } /** * Get the current default tab preferenced used by Modern Docking in JTabbedPanes * * @return Default tab preference */ public static DockableTabPreference defaultTabPreference() { return defaultTabPreference; } /** * Set the applications preference for default tab location when adding dockables to tab groups. * * @param tabPreference The new default tab location preference */ public static void setDefaultTabPreference(DockableTabPreference tabPreference) { defaultTabPreference = tabPreference; } /** * Get the current tab layout policy used by Modern Docking for JTabbedPanes * * @return Current tab layout policy */ public static int getTabLayoutPolicy() { return tabLayoutPolicy; } /** * Set the tab layout policy Modern Docking should use for JTabbedPanes * * @param tabLayoutPolicy New tab layout policy */ public static void setTabLayoutPolicy(int tabLayoutPolicy) { if (tabLayoutPolicy != JTabbedPane.WRAP_TAB_LAYOUT && tabLayoutPolicy != JTabbedPane.SCROLL_TAB_LAYOUT) { throw new IllegalArgumentException("illegal tab layout policy: must be WRAP_TAB_LAYOUT or SCROLL_TAB_LAYOUT"); } Settings.tabLayoutPolicy = tabLayoutPolicy; } /** * Check if the active dockable highlighter is enabled * * @return Is the ActiveDockableHighlighter enabled? */ public static boolean isActiveHighlighterEnabled() { return enableActiveHighlighter; } /** * Enable or disable the ActiveDockableHighlighter * * @param enabled New flag state */ public static void setActiveHighlighterEnabled(boolean enabled) { enableActiveHighlighter = enabled; } /** * The drag threshold Modern Docking should use */ public static int getDragThreshold() { return dragThreshold; } /** * Is Modern Docking using an existing drag threhsold? */ public static boolean isUseExistingDragThreshold() { return useExistingDragThreshold; } /** * Set the drag threshold. Modern Docking will use 20 by default * <p> * This setting will only take effect if called before the first instance of DockingAPI is created */ public static void setDragThreshold(int threshold) { dragThreshold = threshold; } /** * Use the existing drag threshold instead of setting the AWT property * <p> * This setting will only take effect if called before the first instance of DockingAPI is created */ public static void useExistingDragThreshold(boolean useExisting) { useExistingDragThreshold = useExisting; } }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/docking-api/src/io/github/andrewauclair/moderndocking/exception/DockableRegistrationFailureException.java
docking-api/src/io/github/andrewauclair/moderndocking/exception/DockableRegistrationFailureException.java
/* Copyright (c) 2022-2024 Andrew Auclair Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 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 the Software. 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. */ package io.github.andrewauclair.moderndocking.exception; /** * This exception is thrown when the docking framework fails to register a dockable because one with the same persistentID already exists */ public class DockableRegistrationFailureException extends RuntimeException { /** * The persistent ID of the dockable that we failed to register */ private final String persistentID; /** * Create a new instance of this exception * * @param persistentID The persistentID of dockable that failed to register */ public DockableRegistrationFailureException(String persistentID) { super("Dockable with Persistent ID " + persistentID + " has not been registered."); this.persistentID = persistentID; } /** * Retrieve the persistent ID that already exists * * @return Persistent ID */ public String getPersistentID() { return persistentID; } }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/docking-api/src/io/github/andrewauclair/moderndocking/exception/DockableNotFoundException.java
docking-api/src/io/github/andrewauclair/moderndocking/exception/DockableNotFoundException.java
/* Copyright (c) 2022-2024 Andrew Auclair Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 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 the Software. 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. */ package io.github.andrewauclair.moderndocking.exception; /** * This exception is thrown when the docking framework tries to lookup a dockable and fails */ public class DockableNotFoundException extends RuntimeException { /** * The persistent ID that we were unable to find a dockable registered with */ private final String persistentID; /** * Create a new DockableNotFoundException * * @param persistentID The persistentID of the non-existent dockable */ public DockableNotFoundException(String persistentID) { super("Dockable with persistent ID '" + persistentID + "' not found."); this.persistentID = persistentID; } /** * Retrieve the persistentID of the dockable that was not found * @return The persistentID of the non-existent dockable */ public String getPersistentID() { return persistentID; } }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/docking-api/src/io/github/andrewauclair/moderndocking/exception/NotDockedException.java
docking-api/src/io/github/andrewauclair/moderndocking/exception/NotDockedException.java
/* Copyright (c) 2022-2024 Andrew Auclair Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 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 the Software. 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. */ package io.github.andrewauclair.moderndocking.exception; import io.github.andrewauclair.moderndocking.Dockable; /** * Exception that is thrown when a dockable is not already docked */ public class NotDockedException extends RuntimeException { /** * The dockable that was not docked while attempting a docking operation */ private final Dockable dockable; /** * Create a new exception with the given dockable * * @param message Extra message information to display more detail about the problem * @param dockable Dockable that is not docked */ public NotDockedException(String message, Dockable dockable) { super(message + " because dockable with persistent ID '" + dockable.getPersistentID() + "' is not docked."); this.dockable = dockable; } /** * Retrieve the dockable * * @return The dockable that is not docked */ public Dockable getDockable() { return dockable; } }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/docking-api/src/io/github/andrewauclair/moderndocking/exception/RootDockingPanelNotFoundException.java
docking-api/src/io/github/andrewauclair/moderndocking/exception/RootDockingPanelNotFoundException.java
/* Copyright (c) 2024 Andrew Auclair Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 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 the Software. 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. */ package io.github.andrewauclair.moderndocking.exception; import java.awt.Window; /** * Exception thrown when a RootDockingPanel is not found for the given window */ public class RootDockingPanelNotFoundException extends RuntimeException { /** * The window that we wouldn't find a registered root docking panel for */ private final Window window; /** * Create a new instance of this exception * * @param window The window we didn't find a root for */ public RootDockingPanelNotFoundException(Window window) { super("No root panel for window has been registered."); this.window = window; } /** * Retrieve the window we didn't find a root for * * @return A Window, either a JFrame or JDialog */ public Window getWindow() { return window; } }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/docking-api/src/io/github/andrewauclair/moderndocking/exception/DockingLayoutException.java
docking-api/src/io/github/andrewauclair/moderndocking/exception/DockingLayoutException.java
/* Copyright (c) 2023-2024 Andrew Auclair Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 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 the Software. 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. */ package io.github.andrewauclair.moderndocking.exception; import java.io.File; /** * Exception wrapper for exceptions encountered while dealing loading or saving docking layouts */ public class DockingLayoutException extends Exception { /** * The type of failure for the exception */ public enum FailureType { /** * A docking layout has failed to load from a file */ LOAD, /** * A docking layout has failed to save to a file */ SAVE } /** * The file that we attempted to load or save */ private final File file; /** * The type of failure. load or save */ private final FailureType failureType; /** * Create a new instance * * @param file The layout file that was being saved or loaded * @param failureType The state we failed in, loading or saving * @param cause The root cause of the exception */ public DockingLayoutException(File file, FailureType failureType, Exception cause) { initCause(cause); this.file = file; this.failureType = failureType; } /** * Retrieve the file being loaded or saved * * @return File the framework attempted to load or save */ public File getFile() { return file; } /** * Retrieve the failure type * * @return Returns the failure type of this exception */ public FailureType getFailureType() { return failureType; } }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/docking-api/src/io/github/andrewauclair/moderndocking/exception/RootDockingPanelRegistrationFailureException.java
docking-api/src/io/github/andrewauclair/moderndocking/exception/RootDockingPanelRegistrationFailureException.java
/* Copyright (c) 2024 Andrew Auclair Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 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 the Software. 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. */ package io.github.andrewauclair.moderndocking.exception; import io.github.andrewauclair.moderndocking.api.RootDockingPanelAPI; import java.awt.Window; /** * This exception is thrown when the docking framework fails to register a RootDockingPanel because one already exists for the window */ public class RootDockingPanelRegistrationFailureException extends RuntimeException { /** * The root docking panel that the application attempted to register */ private final RootDockingPanelAPI panel; /** * The window that already has a root docking panel registered for it */ private final Window window; /** * Create a new instance of this exception * * @param panel The RootDockingPanel being registered * @param window The window the root is being registered for */ public RootDockingPanelRegistrationFailureException(RootDockingPanelAPI panel, Window window) { super("RootDockingPanel already registered for frame: " + window); this.panel = panel; this.window = window; } /** * Retrieve the panel that failed to register * * @return The RootDockingPanel being registered */ public RootDockingPanelAPI getPanel() { return panel; } /** * Retrieve the window the root was being registered for * * @return The window the root is being registered for */ public Window getWindow() { return window; } }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/docking-api/src/io/github/andrewauclair/moderndocking/api/DockingAPI.java
docking-api/src/io/github/andrewauclair/moderndocking/api/DockingAPI.java
/* Copyright (c) 2023-2024 Andrew Auclair Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 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 the Software. 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. */ package io.github.andrewauclair.moderndocking.api; import io.github.andrewauclair.moderndocking.Dockable; import io.github.andrewauclair.moderndocking.DockableStyle; import io.github.andrewauclair.moderndocking.DockingRegion; import io.github.andrewauclair.moderndocking.event.DockingListener; import io.github.andrewauclair.moderndocking.event.MaximizeListener; import io.github.andrewauclair.moderndocking.event.NewFloatingFrameListener; import io.github.andrewauclair.moderndocking.exception.NotDockedException; import io.github.andrewauclair.moderndocking.exception.RootDockingPanelNotFoundException; import io.github.andrewauclair.moderndocking.internal.floating.Floating; import io.github.andrewauclair.moderndocking.internal.ActiveDockableHighlighter; import io.github.andrewauclair.moderndocking.internal.DisplayPanel; import io.github.andrewauclair.moderndocking.internal.DockableWrapper; import io.github.andrewauclair.moderndocking.internal.DockedTabbedPanel; import io.github.andrewauclair.moderndocking.internal.DockingComponentUtils; import io.github.andrewauclair.moderndocking.internal.DockingInternal; import io.github.andrewauclair.moderndocking.internal.DockingListeners; import io.github.andrewauclair.moderndocking.internal.DockingPanel; import io.github.andrewauclair.moderndocking.internal.FloatingFrame; import io.github.andrewauclair.moderndocking.internal.InternalRootDockingPanel; import io.github.andrewauclair.moderndocking.layouts.DynamicDockableCreationListener; import io.github.andrewauclair.moderndocking.layouts.WindowLayout; import io.github.andrewauclair.moderndocking.settings.Settings; import io.github.andrewauclair.moderndocking.ui.ToolbarLocation; import java.awt.*; import java.beans.PropertyChangeListener; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.SwingUtilities; import javax.swing.UIManager; /** * Single instance of the docking framework. Useful when a single JVM is to host multiple instances of an application * and docking should be handled separately for each of them */ public class DockingAPI { private final DockingInternal internals = new DockingInternal(this); // the applications main frame private Window mainWindow; // this may look unused, but we need to create an instance of it to make it work private final ActiveDockableHighlighter activeDockableHighlighter = new ActiveDockableHighlighter(this); // map of all the root panels in the application // private final Map<Window, InternalRootDockingPanel> rootPanels = new HashMap<>(); private final AppStateAPI appState = new AppStateAPI(this); private final DockingStateAPI dockingState = new DockingStateAPI(this); private final LayoutPersistenceAPI layoutPersistence = new LayoutPersistenceAPI(this); // listen for L&F changes so that we can update dockable panels properly when not displayed private final PropertyChangeListener propertyChangeListener = e -> { if ("lookAndFeel".equals(e.getPropertyName())) { SwingUtilities.invokeLater(internals::updateLAF); } }; public AppStateAPI getAppState() { return appState; } public DockingStateAPI getDockingState() { return dockingState; } public LayoutPersistenceAPI getLayoutPersistence() { return layoutPersistence; } /** * Create a new instance of the DockingAPI. Applications will use the single-app or multi-app Docking class * * @param mainWindow The main window for this docking instance */ protected DockingAPI(Window mainWindow) { this.mainWindow = mainWindow; UIManager.addPropertyChangeListener(propertyChangeListener); if (!Settings.isUseExistingDragThreshold()) { System.setProperty("awt.dnd.drag.threshold", String.valueOf(Settings.getDragThreshold())); } } /** * Uninitialize the docking framework so that it can be initialized again with a new window */ public void uninitialize() { // deregister all dockables and panels deregisterAllDockables(); deregisterAllDockingPanels(); // remove reference to window so it can be cleaned up mainWindow = null; activeDockableHighlighter.removeListeners(); UIManager.removePropertyChangeListener(propertyChangeListener); DockingInternal.remove(this); } /** * Get a map of RootDockingPanels to their Windows * * @return map of root panels */ public Map<Window, RootDockingPanelAPI> getRootPanels() { Map<Window, RootDockingPanelAPI> panels = new HashMap<>(); internals.getRootPanels().forEach((window, internalRootDockingPanel) -> panels.put(window, internalRootDockingPanel.getRootPanel())); return panels; } /** * Get the main window instance * * @return main window */ public Window getMainWindow() { return mainWindow; } /** * register a dockable with the framework * * @param dockable Dockable to register */ public void registerDockable(Dockable dockable) { internals.registerDockable(dockable); } /** * Check if a dockable has already been registered * * @param persistentID The persistent ID to look for * @return Has the dockable been registered? */ public boolean isDockableRegistered(String persistentID) { return getDockables().stream().anyMatch(dockable -> Objects.equals(persistentID, dockable.getPersistentID())); } /** * Dockables must be deregistered so it can be properly disposed * * @param dockable Dockable to deregister */ public void deregisterDockable(Dockable dockable) { internals.setDeregistering(this, true); try { // make sure we undock the dockable from the UI before deregistering undock(dockable); internals.deregisterDockable(dockable); } finally { internals.setDeregistering(this, false); } } /** * Deregister all dockables that have been registered. This action will also undock all dockables. */ public void deregisterAllDockables() { internals.setDeregistering(this, true); try { Set<Window> windows = new HashSet<>(getRootPanels().keySet()); for (Window window : windows) { DockingComponentUtils.undockComponents(this, window); // only dispose this window if we created it if (window instanceof FloatingFrame) { window.dispose(); } } for (Dockable dockable : internals.getDockables()) { deregisterDockable(dockable); } } finally { internals.setDeregistering(this, false); } } public List<Dockable> getDockables() { return internals.getDockables(); } /** * registration function for DockingPanel * * @param panel Panel to register * @param parent The parent frame of the panel */ public void registerDockingPanel(RootDockingPanelAPI panel, JFrame parent) { internals.registerDockingPanel(panel, parent); } /** * Register a RootDockingPanel * * @param panel RootDockingPanel to register * @param parent The parent JDialog of the panel */ public void registerDockingPanel(RootDockingPanelAPI panel, JDialog parent) { internals.registerDockingPanel(panel, parent); } /** * Deregister a docking root panel * * @param parent The parent of the panel that we're deregistering */ public void deregisterDockingPanel(Window parent) { internals.deregisterDockingPanel(parent); } /** * Deregister all registered panels. Additionally, dispose any windows created by Modern Docking. */ public void deregisterAllDockingPanels() { Set<Window> windows = new HashSet<>(getRootPanels().keySet()); for (Window window : windows) { deregisterDockingPanel(window); // only dispose this window if we created it if (window instanceof FloatingFrame) { window.dispose(); } } } public void registerDockingAnchor(Dockable anchor) { internals.registerDockingAnchor(anchor); } public void deregisterDockingAnchor(Dockable anchor) { internals.deregisterDockingAnchor(anchor); } /** * allows the user to configure auto hide per window. by default auto hide is only enabled on the frames the docking framework creates * * @param window The window to configure auto hide on * @param layer The layout to use for auto hide in the JLayeredPane * @param allow Whether auto hide is allowed on this Window */ public void configureAutoHide(Window window, int layer, boolean allow) { if (!internals.getRootPanels().containsKey(window)) { throw new RootDockingPanelNotFoundException(window); } InternalRootDockingPanel root = DockingComponentUtils.rootForWindow(this, window); root.getRootPanel().setAutoHideSupported(allow); root.getRootPanel().setAutoHideLayer(layer); } /** * Check if auto hide is allowed for a dockable * * @param dockable Dockable to check * @return Whether the dockable can be auto hide */ public boolean autoHideAllowed(Dockable dockable) { InternalRootDockingPanel root = DockingComponentUtils.rootForWindow(this, DockingComponentUtils.findWindowForDockable(this, dockable)); return dockable.isAutoHideAllowed() && root.getRootPanel().isAutoHideSupported(); } /** * Check if auto hide is allowed for a dockable * * @param dockable Dockable to check * @return Whether the dockable can be hidden */ public boolean isAutoHideAllowed(Dockable dockable) { InternalRootDockingPanel root = DockingComponentUtils.rootForWindow(this, DockingComponentUtils.findWindowForDockable(this, dockable)); return dockable.isAutoHideAllowed() && root.getRootPanel().isAutoHideSupported(); } /** * docks a dockable to the center of the given window * <p> * NOTE: This will only work if the window root docking node is empty. Otherwise, this does nothing. * * @param persistentID The persistentID of the dockable to dock * @param window The window to dock into */ public void dock(String persistentID, Window window) { dock(internals.getDockable(persistentID), window, DockingRegion.CENTER); } /** * docks a dockable to the center of the given window * <p> * NOTE: This will only work if the window root docking node is empty. Otherwise, this does nothing. * * @param dockable The dockable to dock * @param window The window to dock into */ public void dock(Dockable dockable, Window window) { dock(dockable, window, DockingRegion.CENTER); } /** * docks a dockable into the specified region of the root of the window with 25% divider proportion * * @param persistentID The persistentID of the dockable to dock * @param window The window to dock into * @param region The region to dock into */ public void dock(String persistentID, Window window, DockingRegion region) { dock(internals.getDockable(persistentID), window, region, 0.25); } /** * docks a dockable into the specified region of the root of the window with 25% divider proportion * <p> * NOTE: Nothing will be done if docking to the CENTER of the window and the window root panel is not empty * * @param dockable The dockable to dock * @param window The window to dock into * @param region The region to dock into */ public void dock(Dockable dockable, Window window, DockingRegion region) { InternalRootDockingPanel root = internals.getRootPanels().get(window); if (root == null) { throw new RootDockingPanelNotFoundException(window); } if (!root.isEmpty() && region == DockingRegion.CENTER) { // can't dock here, so stop return; } dock(dockable, window, region, 0.25); } /** * docks a dockable into the specified region of the window with the specified divider proportion * * @param persistentID The persistentID of the dockable to dock * @param window The window to dock into * @param region The region to dock into * @param dividerProportion The proportion to use if docking in a split pane */ public void dock(String persistentID, Window window, DockingRegion region, double dividerProportion) { dock(internals.getDockable(persistentID), window, region, dividerProportion); } /** * docks a dockable into the specified region of the window with the specified divider proportion * * @param dockable The dockable to dock * @param window The window to dock into * @param region The region to dock into * @param dividerProportion The proportion to use if docking in a split pane */ public void dock(Dockable dockable, Window window, DockingRegion region, double dividerProportion) { InternalRootDockingPanel root = internals.getRootPanels().get(window); if (root == null) { throw new RootDockingPanelNotFoundException(window); } // if the source is already docked we need to undock it before docking it again, otherwise we might steal it from its UI parent if (isDocked(dockable)) { DockableWrapper wrapper = internals.getWrapper(dockable); wrapper.getParent().undock(dockable); DockingComponentUtils.removeIllegalFloats(this, wrapper.getWindow()); // dispose the window if we need to if (canDisposeWindow(wrapper.getWindow()) && internals.getRootPanels().get(wrapper.getWindow()).isEmpty() && !Floating.isFloating()) { deregisterDockingPanel(wrapper.getWindow()); wrapper.getWindow().dispose(); } // fire an undock event if the dockable is changing windows if (wrapper.getWindow() != window) { DockingListeners.fireUndockedEvent(dockable, false); } } root.dock(dockable, region, dividerProportion); internals.getWrapper(dockable).setWindow(window); // fire a docked event when the component is actually added DockingListeners.fireDockedEvent(dockable); appState.persist(); } /** * docks the target to the source in the specified region with 50% divider proportion * * @param sourcePersistentID The persistentID of the source dockable to dock the target dockable to * @param targetPersistentID The persistentID of the target dockable * @param region The region on the source dockable to dock into */ public void dock(String sourcePersistentID, String targetPersistentID, DockingRegion region) { dock(internals.getDockable(sourcePersistentID), internals.getDockable(targetPersistentID), region, 0.5); } /** * docks the target to the source in the specified region with 50% divider proportion * * @param sourcePersistentID The persistentID of the source dockable to dock the target dockable to * @param target The target dockable * @param region The region on the source dockable to dock into */ public void dock(String sourcePersistentID, Dockable target, DockingRegion region) { dock(internals.getDockable(sourcePersistentID), target, region, 0.5); } /** * docks the target to the source in the specified region with 50% divider proportion * * @param source The source dockable to dock the target dockable to * @param targetPersistentID The persistentID of the target dockable * @param region The region on the source dockable to dock into */ public void dock(Dockable source, String targetPersistentID, DockingRegion region) { dock(source, internals.getDockable(targetPersistentID), region, 0.5); } /** * docks the target to the source in the specified region with 50% divider proportion * * @param source The source dockable to dock the target dockable to * @param target The target dockable * @param region The region on the source dockable to dock into */ public void dock(Dockable source, Dockable target, DockingRegion region) { dock(source, target, region, 0.5); } /** * docks the target to the source in the specified region with the specified divider proportion * * @param sourcePersistentID The persistentID of the source dockable to dock the target dockable to * @param targetPersistentID The persistentID of the target dockable * @param region The region on the source dockable to dock into * @param dividerProportion The proportion to use if docking in a split pane */ public void dock(String sourcePersistentID, String targetPersistentID, DockingRegion region, double dividerProportion) { dock(internals.getDockable(sourcePersistentID), internals.getDockable(targetPersistentID), region, dividerProportion); } /** * docks the target to the source in the specified region with the specified divider proportion * * @param source The source dockable to dock the target dockable to * @param target The target dockable * @param region The region on the source dockable to dock into * @param dividerProportion The proportion to use if docking in a split pane */ public void dock(Dockable source, Dockable target, DockingRegion region, double dividerProportion) { if (!isDocked(target)) { throw new NotDockedException("Unable to dock dockable with persistent ID '" + source.getPersistentID() + "'", target); } // if the source is already docked we need to undock it before docking it again, otherwise we might steal it from its UI parent if (isDocked(source)) { DockableWrapper wrapper = internals.getWrapper(source); wrapper.getParent().undock(source); DockingComponentUtils.removeIllegalFloats(this, wrapper.getWindow()); // dispose the window if we need to if (canDisposeWindow(wrapper.getWindow()) && internals.getRootPanels().get(wrapper.getWindow()).isEmpty() && !Floating.isFloating()) { deregisterDockingPanel(wrapper.getWindow()); wrapper.getWindow().dispose(); } // fire an undock event if the dockable is changing windows if (wrapper.getWindow() != internals.getWrapper(source).getWindow()) { DockingListeners.fireUndockedEvent(source, false); } } DockableWrapper wrapper = internals.getWrapper(target); wrapper.getParent().dock(source, region, dividerProportion); internals.getWrapper(source).setWindow(wrapper.getWindow()); internals.getWrapper(source).setRoot(internals.getRootPanels().get(wrapper.getWindow())); DockingListeners.fireDockedEvent(source); appState.persist(); } /** * create a new FloatingFrame window for the given dockable, undock it from its current frame (if there is one) and dock it into the new frame * * @param persistentID The persistent ID of the dockable to float in a new window */ public void newWindow(String persistentID) { newWindow(internals.getDockable(persistentID)); } /** * create a new FloatingFrame window for the given dockable, undock it from its current frame (if there is one) and dock it into the new frame * * @param dockable The dockable to float in a new window */ public void newWindow(Dockable dockable) { DisplayPanel displayPanel = internals.getWrapper(dockable).getDisplayPanel(); if (isDocked(dockable)) { Point location = displayPanel.getLocationOnScreen(); Dimension size = displayPanel.getSize(); newWindow(dockable, location, size); } else { FloatingFrame frame = new FloatingFrame(this); dock(dockable, frame); frame.pack(); frame.setLocationRelativeTo(getMainWindow()); SwingUtilities.invokeLater(() -> { bringToFront(dockable); DockingListeners.fireNewFloatingFrameEvent(frame, frame.getRoot(), dockable); }); } } /** * Create a new FloatingFrame window for the given dockable, undock it from its current frame (if there is one) and dock it into the new frame * * @param persistentID The persistent ID of the dockable to float in a new window * @param location The screen location to display the new frame at * @param size The size of the new frame */ public void newWindow(String persistentID, Point location, Dimension size) { newWindow(internals.getDockable(persistentID), location, size); } /** * Create a new FloatingFrame window for the given dockable, undock it from its current frame (if there is one) and dock it into the new frame * * @param dockable The dockable to float in a new window * @param location The screen location to display the new frame at * @param size The size of the new frame */ public void newWindow(Dockable dockable, Point location, Dimension size) { FloatingFrame frame = new FloatingFrame(this, dockable, location, size, JFrame.NORMAL); undock(dockable); dock(dockable, frame); SwingUtilities.invokeLater(() -> { bringToFront(dockable); DockingListeners.fireNewFloatingFrameEvent(frame, frame.getRoot(), dockable); }); } /** * bring the specified dockable to the front if it is in a tabbed panel * * @param persistentID The persistent ID of the dockable */ public void bringToFront(String persistentID) { bringToFront(internals.getDockable(persistentID)); } /** * bring the specified dockable to the front if it is in a tabbed panel * * @param dockable Dockable to bring to the front */ public void bringToFront(Dockable dockable) { if (!isDocked(dockable)) { throw new NotDockedException("Unable to bring dockable to the front ", dockable); } Window window = DockingComponentUtils.findWindowForDockable(this, dockable); if (window instanceof JFrame && ((JFrame) window).getState() == JFrame.ICONIFIED) { ((JFrame)window).setState(JFrame.NORMAL); window.setAlwaysOnTop(true); window.setAlwaysOnTop(false); } if (internals.getWrapper(dockable).getParent() instanceof DockedTabbedPanel) { DockedTabbedPanel tabbedPanel = (DockedTabbedPanel) internals.getWrapper(dockable).getParent(); tabbedPanel.bringToFront(dockable); } } /** * undock a dockable * * @param persistentID The persistentID of the dockable to undock */ public void undock(String persistentID) { undock(internals.getDockable(persistentID)); } /** * undock a dockable * * @param dockable The dockable to undock */ public void undock(Dockable dockable) { internals.undock(dockable, false); } /** * check if a dockable is currently docked * * @param persistentID The persistentID of the dockable to check * @return Whether the dockable is docked */ public boolean isDocked(String persistentID) { return isDocked(internals.getDockable(persistentID)); } /** * check if a dockable is currently docked * * @param dockable The dockable to check * @return Whether the dockable is docked */ public boolean isDocked(Dockable dockable) { return internals.getWrapper(dockable).getParent() != null; } /** * check if a dockable is currently in the unpinned state * * @param persistentID The persistentID of the dockable to check * @return Whether the dockable is unpinned */ public boolean isHidden(String persistentID) { return isHidden(internals.getDockable(persistentID)); } /** * check if a dockable is currently in the unpinned state * * @param dockable The dockable to check * @return Whether the dockable is unpinned */ public boolean isHidden(Dockable dockable) { return internals.getWrapper(dockable).isHidden(); } /** * check if the window can be disposed. Windows can be disposed if they are not the main window and are not maximized * * @param window Window to check * @return Boolean indicating if the specified Window can be disposed */ public boolean canDisposeWindow(Window window) { // don't dispose of any docking windows that are JDialogs if (window instanceof JDialog) { return false; } if (dockingState.maximizeRestoreLayout.containsKey(window)) { return false; } // only dispose this window if we created it return window instanceof FloatingFrame; } /** * checks if a dockable is currently maximized * * @param dockable The dockable to check * @return Whether the dockable is maximized */ public boolean isMaximized(Dockable dockable) { return internals.getWrapper(dockable).isMaximized(); } /** * maximizes a dockable * * @param dockable Dockable to maximize */ public void maximize(Dockable dockable) { Window window = DockingComponentUtils.findWindowForDockable(this, dockable); InternalRootDockingPanel root = DockingComponentUtils.rootForWindow(this, window); // can only maximize one panel per root if (!dockingState.maximizeRestoreLayout.containsKey(window) && root != null) { internals.getWrapper(dockable).setMaximized(true); DockingListeners.fireMaximizeEvent(dockable, true); WindowLayout layout = dockingState.getWindowLayout(window); layout.setMaximizedDockable(dockable.getPersistentID()); dockingState.maximizeRestoreLayout.put(window, layout); DockingComponentUtils.undockComponents(this, root); dock(dockable, window); } } /** * minimize a dockable if it is currently maximized * * @param dockable Dockable to minimize */ public void minimize(Dockable dockable) { Window window = DockingComponentUtils.findWindowForDockable(this, dockable); // can only minimize if already maximized if (dockingState.maximizeRestoreLayout.containsKey(window)) { internals.getWrapper(dockable).setMaximized(false); DockingListeners.fireMaximizeEvent(dockable, false); dockingState.restoreWindowLayout(window, dockingState.maximizeRestoreLayout.get(window)); dockingState.maximizeRestoreLayout.remove(window); internals.fireDockedEventForFrame(window); } } public void autoShowDockable(Dockable dockable) { Window window = DockingComponentUtils.findWindowForDockable(this, dockable); InternalRootDockingPanel root = DockingComponentUtils.rootForWindow(this, window); if (internals.getWrapper(dockable).isHidden()) { root.setDockableShown(dockable); internals.getWrapper(dockable).setHidden(false); DockingListeners.fireAutoShownEvent(dockable); } } public void autoShowDockable(String persistentID) { autoShowDockable(internals.getDockable(persistentID)); } public void autoHideDockable(Dockable dockable) { if (isHidden(dockable)) { return; } Window window = DockingComponentUtils.findWindowForDockable(this, dockable); InternalRootDockingPanel root = DockingComponentUtils.rootForWindow(this, window); Component component = (Component) dockable; Point posInFrame = component.getLocation(); SwingUtilities.convertPointToScreen(posInFrame, component.getParent()); SwingUtilities.convertPointFromScreen(posInFrame, root); posInFrame.x += component.getWidth() / 2; posInFrame.y += component.getHeight() / 2; DockableStyle autoHideStyle = dockable.getAutoHideStyle(); RootDockingPanelAPI rootPanel = root.getRootPanel(); // location availability Map<ToolbarLocation, Boolean> sideMap = Map.of( ToolbarLocation.WEST, rootPanel.isLocationSupported(ToolbarLocation.WEST), ToolbarLocation.EAST, rootPanel.isLocationSupported(ToolbarLocation.EAST), ToolbarLocation.SOUTH, rootPanel.isLocationSupported(ToolbarLocation.SOUTH) && (autoHideStyle == DockableStyle.BOTH || autoHideStyle == DockableStyle.HORIZONTAL) ); // distances from each side Map<ToolbarLocation, Integer> distanceMap = Map.of( ToolbarLocation.WEST, posInFrame.x, ToolbarLocation.EAST, window.getWidth() - posInFrame.x, ToolbarLocation.SOUTH, window.getHeight() - posInFrame.y ); var minSideOpt = distanceMap.entrySet() .stream() .filter(e -> sideMap.get(e.getKey())) // keep the supported ones .min(Map.Entry.comparingByValue()); // choose the shortest distance if (minSideOpt.isPresent()) { ToolbarLocation location = minSideOpt.get().getKey(); autoHideDockable(dockable, location); } } public void autoHideDockable(String persistentID) { autoHideDockable(internals.getDockable(persistentID)); } public void autoHideDockable(Dockable dockable, ToolbarLocation location) { Window window = DockingComponentUtils.findWindowForDockable(this, dockable); autoHideDockable(dockable, location, window); } public void autoHideDockable(String persistentID, ToolbarLocation location) { autoHideDockable(internals.getDockable(persistentID), location); } public void autoHideDockable(Dockable dockable, ToolbarLocation location, Window window) { InternalRootDockingPanel root = internals.getRootPanels().get(window); RootDockingPanelAPI root1 = root.getRootPanel(); if (isHidden(dockable)) { return; } InternalRootDockingPanel internalRoot = internals.getRootPanels().get(window); Component component = (Component) dockable; Point posInFrame = component.getLocation(); SwingUtilities.convertPointToScreen(posInFrame, component.getParent()); SwingUtilities.convertPointFromScreen(posInFrame, internalRoot); posInFrame.x += component.getWidth() / 2; posInFrame.y += component.getHeight() / 2; if (!root1.isAutoHideSupported()) { return; }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
true
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/docking-api/src/io/github/andrewauclair/moderndocking/api/WindowLayoutBuilderAPI.java
docking-api/src/io/github/andrewauclair/moderndocking/api/WindowLayoutBuilderAPI.java
/* Copyright (c) 2022 Andrew Auclair Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 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 the Software. 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. */ package io.github.andrewauclair.moderndocking.api; import io.github.andrewauclair.moderndocking.DockingRegion; import io.github.andrewauclair.moderndocking.Property; import io.github.andrewauclair.moderndocking.layouts.ApplicationLayout; import io.github.andrewauclair.moderndocking.layouts.DockingLayoutNode; import io.github.andrewauclair.moderndocking.layouts.DockingLayoutRootNode; import io.github.andrewauclair.moderndocking.layouts.DockingSimplePanelNode; import io.github.andrewauclair.moderndocking.layouts.DockingTabPanelNode; import io.github.andrewauclair.moderndocking.layouts.WindowLayout; import java.util.HashMap; import java.util.Map; /** * Utility to help create layouts without directly applying them to the actual app */ public class WindowLayoutBuilderAPI { private final DockingLayoutRootNode rootNode; private final Map<String, Map<String, Property>> properties = new HashMap<>(); /** * Start building a new layout * * @param docking The docking instance we're building a layout for * @param firstID First dockable ID in the layout */ protected WindowLayoutBuilderAPI(DockingAPI docking, String firstID) { rootNode = new DockingLayoutRootNode(docking); rootNode.dock(firstID, DockingRegion.CENTER, 0.0); } /** * Dock a new dockable into this layout * * @param sourceID The new dockable * @param targetID The dockable to dock to the center of * @return This builder in order to chain calls */ public WindowLayoutBuilderAPI dock(String sourceID, String targetID) { return dock(sourceID, targetID, DockingRegion.CENTER); } /** * Dock a new dockable into this layout * * @param sourceID The new dockable * @param targetID The dockable to dock to * @param region The region on the dockable to dock to * @return This builder in order to chain calls */ public WindowLayoutBuilderAPI dock(String sourceID, String targetID, DockingRegion region) { return dock(sourceID, targetID, region, 0.5); } /** * Dock a new dockable into this layout * * @param sourceID The new dockable * @param targetID The dockable to dock to * @param region The region on the dockable to dock to * @param dividerProportion The divider proportion to use if creating a split pane * @return This builder in order to chain calls */ public WindowLayoutBuilderAPI dock(String sourceID, String targetID, DockingRegion region, double dividerProportion) { DockingLayoutNode node = findNode(targetID); if (exists(sourceID)) { throw new RuntimeException("Dockable already in layout: " + sourceID); } node.dock(sourceID, region, dividerProportion); return this; } /** * Dock a dockable to the root in this layout builder * * @param persistentID Persistent ID of the dockable * @param region The region to dock into * * @return This WindowLayoutBuilderAPI instance */ public WindowLayoutBuilderAPI dockToRoot(String persistentID, DockingRegion region) { return dockToRoot(persistentID, region, 0.25); } /** * Dock a dockable to the root in this layout builder * @param persistentID Persistent ID of the dockable * @param region The region to dock into * @param dividerProportion The divider proportion to use * * @return This WindowLayoutBuilderAPI instance */ public WindowLayoutBuilderAPI dockToRoot(String persistentID, DockingRegion region, double dividerProportion) { if (exists(persistentID)) { throw new RuntimeException("Dockable already in layout: " + persistentID); } rootNode.dock(persistentID, region, dividerProportion); return this; } /** * Bring a dockable to the front in this builder * * @param persistentID The dockable to bring to front * * @return This WindowLayoutBuilderAPI instance */ public WindowLayoutBuilderAPI display(String persistentID) { DockingLayoutNode node = findNode(persistentID); if (node.getParent() != null && node.getParent() instanceof DockingTabPanelNode) { ((DockingTabPanelNode) node.getParent()).bringToFront(node); } return this; } /** * Set the value of a dockable property * * @param persistentID The persistent ID of the dockable we're setting a property for * @param property The name of the property we're configuring * @param value The value of the property * * @return This WindowLayoutBuilderAPI instance */ public WindowLayoutBuilderAPI setProperty(String persistentID, String property, byte value) { Map<String, Property> props = properties.getOrDefault(persistentID, new HashMap<>()); props.put(property, new Property.ByteProperty(property, value)); properties.put(persistentID, props); return this; } /** * Set the value of a dockable property * * @param persistentID The persistent ID of the dockable we're setting a property for * @param property The name of the property we're configuring * @param value The value of the property * * @return This WindowLayoutBuilderAPI instance */ public WindowLayoutBuilderAPI setProperty(String persistentID, String property, short value) { Map<String, Property> props = properties.getOrDefault(persistentID, new HashMap<>()); props.put(property, new Property.ShortProperty(property, value)); properties.put(persistentID, props); return this; } /** * Set the value of a dockable property * * @param persistentID The persistent ID of the dockable we're setting a property for * @param property The name of the property we're configuring * @param value The value of the property * * @return This WindowLayoutBuilderAPI instance */ public WindowLayoutBuilderAPI setProperty(String persistentID, String property, int value) { Map<String, Property> props = properties.getOrDefault(persistentID, new HashMap<>()); props.put(property, new Property.IntProperty(property, value)); properties.put(persistentID, props); return this; } /** * Set the value of a dockable property * * @param persistentID The persistent ID of the dockable we're setting a property for * @param property The name of the property we're configuring * @param value The value of the property * * @return This WindowLayoutBuilderAPI instance */ public WindowLayoutBuilderAPI setProperty(String persistentID, String property, long value) { Map<String, Property> props = properties.getOrDefault(persistentID, new HashMap<>()); props.put(property, new Property.LongProperty(property, value)); properties.put(persistentID, props); return this; } /** * Set the value of a dockable property * * @param persistentID The persistent ID of the dockable we're setting a property for * @param property The name of the property we're configuring * @param value The value of the property * * @return This WindowLayoutBuilderAPI instance */ public WindowLayoutBuilderAPI setProperty(String persistentID, String property, float value) { Map<String, Property> props = properties.getOrDefault(persistentID, new HashMap<>()); props.put(property, new Property.FloatProperty(property, value)); properties.put(persistentID, props); return this; } /** * Set the value of a dockable property * * @param persistentID The persistent ID of the dockable we're setting a property for * @param property The name of the property we're configuring * @param value The value of the property * * @return This WindowLayoutBuilderAPI instance */ public WindowLayoutBuilderAPI setProperty(String persistentID, String property, double value) { Map<String, Property> props = properties.getOrDefault(persistentID, new HashMap<>()); props.put(property, new Property.DoubleProperty(property, value)); properties.put(persistentID, props); return this; } /** * Set the value of a dockable property * * @param persistentID The persistent ID of the dockable we're setting a property for * @param property The name of the property we're configuring * @param value The value of the property * * @return This WindowLayoutBuilderAPI instance */ public WindowLayoutBuilderAPI setProperty(String persistentID, String property, char value) { Map<String, Property> props = properties.getOrDefault(persistentID, new HashMap<>()); props.put(property, new Property.CharacterProperty(property, value)); properties.put(persistentID, props); return this; } /** * Set a property for the dockable * * @param persistentID The dockable persistent ID * @param property The name of the property to set * @param value The value of the property * * @return This WindowLayoutBuilderAPI instance */ public WindowLayoutBuilderAPI setProperty(String persistentID, String property, boolean value) { Map<String, Property> props = properties.getOrDefault(persistentID, new HashMap<>()); props.put(property, new Property.BooleanProperty(property, value)); properties.put(persistentID, props); return this; } /** * Set the value of a dockable property * * @param persistentID The persistent ID of the dockable we're setting a property for * @param property The name of the property we're configuring * @param value The value of the property * * @return This WindowLayoutBuilderAPI instance */ public WindowLayoutBuilderAPI setProperty(String persistentID, String property, String value) { Map<String, Property> props = properties.getOrDefault(persistentID, new HashMap<>()); props.put(property, new Property.StringProperty(property, value)); properties.put(persistentID, props); return this; } /** * Set the value of a custom dockable property * * @param persistentID The persistent ID of the dockable we're setting a property for * @param property The name of the property we're configuring * @param value The value of the property * * @return This WindowLayoutBuilderAPI instance */ public WindowLayoutBuilderAPI setProperty(String persistentID, String property, Property value) { Map<String, Property> props = properties.getOrDefault(persistentID, new HashMap<>()); props.put(property, value); properties.put(persistentID, props); return this; } /** * build a WindowLayout using the rootNode * * @return The built window layout */ public WindowLayout build() { properties.forEach((persistentID, stringPropertyMap) -> { DockingLayoutNode node = findNode(persistentID); if (node instanceof DockingSimplePanelNode) { ((DockingSimplePanelNode) node).setProperties(stringPropertyMap); } }); return new WindowLayout(rootNode.getNode()); } /** * Shortcut for building an ApplicationLayout from this builder's WindowLayout * * @return Application layout */ public ApplicationLayout buildApplicationLayout() { return new ApplicationLayout(build()); } /** * Find the node for a dockable * * @param persistentID Persistent ID of the dockabe to find * * @return Dockable layout node or null if not found */ public DockingLayoutNode findNode(String persistentID) { DockingLayoutNode node = rootNode.findNode(persistentID); if (node == null) { throw new RuntimeException("No node for dockable ID found: " + persistentID); } return node; } private boolean exists(String persistentID) { DockingLayoutNode node = rootNode.findNode(persistentID); return node != null; } }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/docking-api/src/io/github/andrewauclair/moderndocking/api/LayoutPersistenceAPI.java
docking-api/src/io/github/andrewauclair/moderndocking/api/LayoutPersistenceAPI.java
/* Copyright (c) 2023-2024 Andrew Auclair Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 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 the Software. 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. */ package io.github.andrewauclair.moderndocking.api; import io.github.andrewauclair.moderndocking.Dockable; import io.github.andrewauclair.moderndocking.Property; import io.github.andrewauclair.moderndocking.exception.DockableNotFoundException; import io.github.andrewauclair.moderndocking.exception.DockableRegistrationFailureException; import io.github.andrewauclair.moderndocking.exception.DockingLayoutException; import io.github.andrewauclair.moderndocking.internal.DockableProperties; import io.github.andrewauclair.moderndocking.internal.DockableWrapper; import io.github.andrewauclair.moderndocking.internal.DockingInternal; import io.github.andrewauclair.moderndocking.layouts.ApplicationLayout; import io.github.andrewauclair.moderndocking.layouts.DockingAnchorPanelNode; import io.github.andrewauclair.moderndocking.layouts.DockingLayoutNode; import io.github.andrewauclair.moderndocking.layouts.DockingSimplePanelNode; import io.github.andrewauclair.moderndocking.layouts.DockingSplitPanelNode; import io.github.andrewauclair.moderndocking.layouts.DockingTabPanelNode; import io.github.andrewauclair.moderndocking.layouts.WindowLayout; import java.awt.Dimension; import java.awt.Point; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; /** * Save and load layouts to/from files and streams */ public class LayoutPersistenceAPI { private static final Logger logger = Logger.getLogger(LayoutPersistenceAPI.class.getPackageName()); private static final String NL = "\n"; private final DockingAPI docking; private final XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); private final XMLInputFactory inputFactory = XMLInputFactory.newInstance(); private class ToolbarDockable { String id; double slidePosition; }; /** * Create a new instance of the layout persistence API * * @param docking The docking instance this belongs to */ protected LayoutPersistenceAPI(DockingAPI docking) { this.docking = docking; } /** * saves a docking layout to the given file * * @param file File to save the docking layout into * @param layout The layout to save * @throws DockingLayoutException Thrown if we failed to save the layout to the file */ public void saveLayoutToFile(File file, ApplicationLayout layout) throws DockingLayoutException { // create the file if it doens't exist try { // make sure all the required directories exist if (file.getParentFile() != null) { //noinspection ResultOfMethodCallIgnored file.getParentFile().mkdirs(); } //noinspection ResultOfMethodCallIgnored file.createNewFile(); } catch (IOException e) { throw new DockingLayoutException(file, DockingLayoutException.FailureType.SAVE, e); } try (OutputStream out = Files.newOutputStream(file.toPath())) { saveLayoutToOutputStream(out, layout); } catch (Exception e) { throw new DockingLayoutException(file, DockingLayoutException.FailureType.SAVE, e); } } /** * Save the application layout to an output stream * * @param out The output stream to write the layout to * @param layout The layout to save * @throws XMLStreamException Thrown if there are any XML issues while saving */ public void saveLayoutToOutputStream(final OutputStream out, final ApplicationLayout layout) throws XMLStreamException { XMLStreamWriter writer = outputFactory.createXMLStreamWriter(out); writer.writeStartDocument(); writer.writeCharacters(NL); writer.writeStartElement("app-layout"); saveLayoutToFile(writer, layout.getMainFrameLayout(), true); for (WindowLayout frameLayout : layout.getFloatingFrameLayouts()) { saveLayoutToFile(writer, frameLayout, false); } writer.writeStartElement("undocked"); writer.writeCharacters(NL); for (Dockable dockable : DockingInternal.get(docking).getDockables()) { if (!docking.isDocked(dockable)) { DockableWrapper wrapper = DockingInternal.get(docking).getWrapper(dockable); if (wrapper.getRoot() != null) { int slidePosition = wrapper.getRoot().getSlidePosition(dockable); // layout.getMainFrameLayout().siz System.out.println("slidePosition = " + slidePosition); } writeSimpleNodeToFile(writer, new DockingSimplePanelNode(docking, dockable.getPersistentID(), dockable.getClass().getTypeName(), "", dockable.getTitleText(), dockable.getTabText(), DockableProperties.saveProperties(wrapper))); } } writer.writeEndElement(); writer.writeCharacters(NL); writer.writeEndElement(); writer.writeEndDocument(); writer.close(); } /** * Load an ApplicationLayout from the specified file * * @param file File to load the ApplicationLayout from * @return ApplicationLayout loaded from the file * @throws DockingLayoutException Thrown if we failed to read from the file or something went wrong with loading the layout */ public ApplicationLayout loadApplicationLayoutFromFile(File file) throws DockingLayoutException { try (InputStream in = Files.newInputStream(file.toPath())) { return loadApplicationLayoutFromInputStream(in); } catch (Exception e) { throw new DockingLayoutException(file, DockingLayoutException.FailureType.LOAD, e); } } /** * Load an application layout from an input stream * * @param in The input stream to read from * @return The new application layout * @throws XMLStreamException Thrown if the XML is not properly formatted */ public ApplicationLayout loadApplicationLayoutFromInputStream(final InputStream in) throws XMLStreamException { XMLStreamReader reader = inputFactory.createXMLStreamReader(in); try { ApplicationLayout layout = new ApplicationLayout(); while (reader.hasNext()) { int next = reader.nextTag(); if (next == XMLStreamConstants.START_ELEMENT && reader.getLocalName().equals("layout")) { layout.addFrame(readLayoutFromReader(reader)); } else if (next == XMLStreamConstants.START_ELEMENT && reader.getLocalName().equals("undocked")) { readUndocked(reader); } else if (next == XMLStreamConstants.END_ELEMENT && reader.getLocalName().equals("app-layout")) { break; } } return layout; } finally { reader.close(); } } // read undocked dockables from the file and configure their properties on the actual dockable already loaded in memory // if the dockable does not exist, we simply ignore it and the properties disappear. private void readUndocked(XMLStreamReader reader) throws XMLStreamException { while (reader.hasNext()) { int next = reader.nextTag(); if (next == XMLStreamConstants.START_ELEMENT) { if (reader.getLocalName().equals("simple")) { DockingSimplePanelNode node = readSimpleNodeFromFile(reader); try { DockableWrapper wrapper = DockingInternal.get(docking).getWrapper(DockingInternal.get(docking).getDockable(node.getPersistentID())); DockableProperties.configureProperties(wrapper, node.getProperties()); } catch (DockableRegistrationFailureException | DockableNotFoundException ignored) { } } } else if (next == XMLStreamConstants.END_ELEMENT && reader.getLocalName().equals("undocked")) { break; } } } /** * Save a window layout to a file * * @param file The file to save to * @param layout The layout to save * * @return True if the file was successfully saved, false otherwise */ public boolean saveWindowLayoutToFile(File file, WindowLayout layout) { //noinspection ResultOfMethodCallIgnored file.getParentFile().mkdirs(); XMLOutputFactory factory = XMLOutputFactory.newInstance(); XMLStreamWriter writer; try { writer = factory.createXMLStreamWriter(Files.newOutputStream(file.toPath())); } catch (Exception e) { logger.log(Level.INFO, e.getMessage(), e); return false; } try { writer.writeStartDocument(); saveLayoutToFile(writer, layout, false); writer.writeEndDocument(); } catch (XMLStreamException e) { logger.log(Level.INFO, e.getMessage(), e); return false; } finally { try { writer.close(); } catch (XMLStreamException e) { logger.log(Level.INFO, e.getMessage(), e); } } return true; } private void saveLayoutToFile(XMLStreamWriter writer, WindowLayout layout, boolean isMainFrame) throws XMLStreamException { writer.writeCharacters(NL); writer.writeStartElement("layout"); writer.writeAttribute("main-frame", String.valueOf(isMainFrame)); writer.writeAttribute("location", layout.getLocation().x + "," + layout.getLocation().y); writer.writeAttribute("size", layout.getSize().width + "," + layout.getSize().height); writer.writeAttribute("state", String.valueOf(layout.getState())); if (layout.getMaximizedDockable() != null) { writer.writeAttribute("max-dockable", layout.getMaximizedDockable()); } writer.writeCharacters(NL); writer.writeStartElement("westToolbar"); writer.writeCharacters(NL); for (String id : layout.getWestAutoHideToolbarIDs()) { writer.writeStartElement("dockable"); writer.writeAttribute("id", id); writer.writeEndElement(); writer.writeCharacters(NL); } writer.writeEndElement(); writer.writeCharacters(NL); writer.writeStartElement("eastToolbar"); writer.writeCharacters(NL); for (String id : layout.getEastAutoHideToolbarIDs()) { writer.writeStartElement("dockable"); writer.writeAttribute("id", id); writer.writeEndElement(); writer.writeCharacters(NL); } writer.writeEndElement(); writer.writeCharacters(NL); writer.writeStartElement("southToolbar"); writer.writeCharacters(NL); for (String id : layout.getSouthAutoHideToolbarIDs()) { writer.writeStartElement("dockable"); writer.writeAttribute("id", id); writer.writeAttribute("slidePosition", String.valueOf(layout.slidePosition(id))); writer.writeEndElement(); writer.writeCharacters(NL); } writer.writeEndElement(); writer.writeCharacters(NL); writeNodeToFile(writer, layout.getRootNode()); writer.writeEndElement(); writer.writeCharacters(NL); } private void writeNodeToFile(XMLStreamWriter writer, DockingLayoutNode node) throws XMLStreamException { if (node instanceof DockingSimplePanelNode) { writeSimpleNodeToFile(writer, (DockingSimplePanelNode) node); } else if (node instanceof DockingSplitPanelNode) { writeSplitNodeToFile(writer, (DockingSplitPanelNode) node); } else if (node instanceof DockingTabPanelNode) { writeTabbedNodeToFile(writer, (DockingTabPanelNode) node); } else if (node instanceof DockingAnchorPanelNode) { writeAnchorNodeToFile(writer, (DockingAnchorPanelNode) node); } } private void writeSimpleNodeToFile(XMLStreamWriter writer, DockingSimplePanelNode node) throws XMLStreamException { writer.writeStartElement("simple"); writer.writeAttribute("persistentID", node.getPersistentID()); writer.writeAttribute("class-name", DockingInternal.get(docking).getDockable(node.getPersistentID()).getClass().getTypeName()); if (node.getAnchor() != null) { writer.writeAttribute("anchor", node.getAnchor()); } writer.writeAttribute("title-text", node.getTitleText()); writer.writeAttribute("tab-text", node.getTabText()); writer.writeCharacters(NL); writer.writeStartElement("properties"); Map<String, Property> properties = node.getProperties(); for (String key : properties.keySet()) { Property value = properties.get(key); if (value != null && !value.isNull()) { writer.writeStartElement("property"); writer.writeAttribute("name", value.getName()); writer.writeAttribute("type", value.getType().getSimpleName()); writer.writeAttribute("value", value.toString()); writer.writeEndElement(); } } writer.writeEndElement(); writer.writeCharacters(NL); writer.writeEndElement(); writer.writeCharacters(NL); } private void writeSplitNodeToFile(XMLStreamWriter writer, DockingSplitPanelNode node) throws XMLStreamException { writer.writeStartElement("split"); writer.writeAttribute("orientation", String.valueOf(node.getOrientation())); writer.writeAttribute("divider-proportion", String.valueOf(node.getDividerProportion())); writer.writeCharacters(NL); writer.writeStartElement("left"); writer.writeCharacters(NL); writeNodeToFile(writer, node.getLeft()); writer.writeEndElement(); writer.writeCharacters(NL); writer.writeStartElement("right"); writer.writeCharacters(NL); writeNodeToFile(writer, node.getRight()); writer.writeEndElement(); writer.writeCharacters(NL); writer.writeEndElement(); writer.writeCharacters(NL); } private void writeTabbedNodeToFile(XMLStreamWriter writer, DockingTabPanelNode node) throws XMLStreamException { writer.writeStartElement("tabbed"); writer.writeCharacters(NL); writer.writeStartElement("selectedTab"); Dockable selectedTab = DockingInternal.get(docking).getDockable(node.getSelectedTabID()); writer.writeAttribute("class-name", selectedTab.getClass().getTypeName()); writer.writeAttribute("persistentID", node.getSelectedTabID()); writer.writeAttribute("anchor", node.getAnchor()); writer.writeAttribute("title-text", selectedTab.getTitleText()); writer.writeAttribute("tab-text", selectedTab.getTabText()); writer.writeCharacters(NL); writer.writeEndElement(); writer.writeCharacters(NL); for (DockingSimplePanelNode simpleNode : node.getPersistentIDs()) { writer.writeStartElement("tab"); writer.writeAttribute("persistentID", simpleNode.getPersistentID()); writer.writeAttribute("class-name", DockingInternal.get(docking).getDockable(simpleNode.getPersistentID()).getClass().getTypeName()); writer.writeAttribute("anchor", simpleNode.getAnchor()); writer.writeAttribute("title-text", simpleNode.getTitleText()); writer.writeAttribute("tab-text", simpleNode.getTabText()); writer.writeCharacters(NL); writer.writeStartElement("properties"); Map<String, Property> properties = simpleNode.getProperties(); for (String key : properties.keySet()) { Property value = properties.get(key); if (value != null) { writer.writeStartElement("property"); writer.writeAttribute("name", value.getName()); writer.writeAttribute("type", value.getType().getSimpleName()); if (value.toString() == null) { writer.writeAttribute("value", ""); } else { writer.writeAttribute("value", value.toString()); } writer.writeEndElement(); } } writer.writeEndElement(); writer.writeCharacters(NL); writer.writeEndElement(); writer.writeCharacters(NL); } writer.writeEndElement(); writer.writeCharacters(NL); } private void writeAnchorNodeToFile(XMLStreamWriter writer, DockingAnchorPanelNode node) throws XMLStreamException { writer.writeStartElement("anchor"); writer.writeAttribute("persistentID", node.getPersistentID()); writer.writeAttribute("class-name", DockingInternal.get(docking).getDockable(node.getPersistentID()).getClass().getTypeName()); writer.writeCharacters(NL); writer.writeEndElement(); writer.writeCharacters(NL); } /** * Load a WindowLayout from an XML file * * @param file File to load WindowLayout from * @return The loaded WindowLayout */ public WindowLayout loadWindowLayoutFromFile(File file) { XMLInputFactory factory = XMLInputFactory.newInstance(); XMLStreamReader reader; try { reader = factory.createXMLStreamReader(Files.newInputStream(file.toPath())); } catch (Exception e) { logger.log(Level.INFO, e.getMessage(), e); return null; } WindowLayout layout = null; try { while (reader.hasNext()) { int next = reader.nextTag(); if (next == XMLStreamConstants.START_ELEMENT && reader.getLocalName().equals("layout")) { layout = readLayoutFromReader(reader); break; } } } catch (XMLStreamException e) { logger.log(Level.INFO, e.getMessage(), e); } finally { try { reader.close(); } catch (XMLStreamException e) { logger.log(Level.INFO, e.getMessage(), e); } } return layout; } private WindowLayout readLayoutFromReader(XMLStreamReader reader) throws XMLStreamException { boolean isMainFrame = Boolean.parseBoolean(reader.getAttributeValue(null, "main-frame")); String locStr = reader.getAttributeValue(null, "location"); String sizeStr = reader.getAttributeValue(null, "size"); int state = Integer.parseInt(reader.getAttributeValue(null, "state")); String maximizedDockable = reader.getAttributeValue(null, "max-dockable"); Point location = new Point(Integer.parseInt(locStr.substring(0, locStr.indexOf(","))), Integer.parseInt(locStr.substring(locStr.indexOf(",") + 1))); Dimension size = new Dimension(Integer.parseInt(sizeStr.substring(0, sizeStr.indexOf(","))), Integer.parseInt(sizeStr.substring(sizeStr.indexOf(",") + 1))); java.util.List<ToolbarDockable> westToolbar = readToolbarFromFile(reader, "westToolbar"); java.util.List<ToolbarDockable> eastToolbar = readToolbarFromFile(reader, "eastToolbar"); java.util.List<ToolbarDockable> southToolbar = readToolbarFromFile(reader, "southToolbar"); WindowLayout layout = new WindowLayout(isMainFrame, location, size, state, readNodeFromFile(reader, "layout")); layout.setWestAutoHideToolbarIDs(westToolbar.stream().map(toolbarDockable -> toolbarDockable.id).collect(Collectors.toList())); layout.setEastAutoHideToolbarIDs(eastToolbar.stream().map(toolbarDockable -> toolbarDockable.id).collect(Collectors.toList())); layout.setSouthAutoHideToolbarIDs(southToolbar.stream().map(toolbarDockable -> toolbarDockable.id).collect(Collectors.toList())); for (ToolbarDockable dockable : westToolbar) { layout.setSlidePosition(dockable.id, dockable.slidePosition); } for (ToolbarDockable dockable : eastToolbar) { layout.setSlidePosition(dockable.id, dockable.slidePosition); } for (ToolbarDockable dockable : southToolbar) { layout.setSlidePosition(dockable.id, dockable.slidePosition); } layout.setMaximizedDockable(maximizedDockable); return layout; } private java.util.List<ToolbarDockable> readToolbarFromFile(XMLStreamReader reader, String name) throws XMLStreamException { List<ToolbarDockable> dockables = new ArrayList<>(); while (reader.hasNext()) { int next = reader.nextTag(); if (next == XMLStreamConstants.START_ELEMENT) { if (reader.getLocalName().equals("dockable")) { ToolbarDockable dockable = new ToolbarDockable(); dockable.id = reader.getAttributeValue(null, "id"); String slidePosition = reader.getAttributeValue(null, "slidePosition"); if (slidePosition != null) { dockable.slidePosition = Double.parseDouble(slidePosition); } dockables.add(dockable); } } else if (next == XMLStreamConstants.END_ELEMENT && reader.getLocalName().equals(name)) { break; } } return dockables; } private DockingLayoutNode readNodeFromFile(XMLStreamReader reader, String name) throws XMLStreamException { DockingLayoutNode node = null; while (reader.hasNext()) { int next = reader.nextTag(); if (next == XMLStreamConstants.START_ELEMENT) { if (reader.getLocalName().equals("simple")) { node = readSimpleNodeFromFile(reader); } else if (reader.getLocalName().equals("split")) { node = readSplitNodeFromFile(reader); } else if (reader.getLocalName().equals("tabbed")) { node = readTabNodeFromFile(reader); } else if (reader.getLocalName().equals("anchor")) { node = readAnchorNodeFromFile(reader); } } else if (next == XMLStreamConstants.END_ELEMENT && reader.getLocalName().equals(name)) { break; } } return node; } private DockingSimplePanelNode readSimpleNodeFromFile(XMLStreamReader reader) throws XMLStreamException { String persistentID = reader.getAttributeValue(null, "persistentID"); String className = reader.getAttributeValue(null, "class-name"); String anchor = reader.getAttributeValue(null, "anchor"); String titleText = reader.getAttributeValue(null, "title-text"); String tabText = reader.getAttributeValue(null, "tab-text"); // class name didn't always exist, set it to an empty string if it's null if (className == null) { className = ""; } // anchor didn't always exist, set it to an empty string if it's null if (anchor == null) { anchor = ""; } if (titleText == null) { titleText = ""; } if (tabText == null) { tabText = ""; } return new DockingSimplePanelNode(docking, persistentID, className, anchor, titleText, tabText, readProperties(reader)); } // expects that we haven't already read the starting element for <properties> private Map<String, Property> readProperties(XMLStreamReader reader) throws XMLStreamException { Map<String, Property> properties = new HashMap<>(); while (reader.hasNext()) { int next = reader.nextTag(); if (next == XMLStreamConstants.START_ELEMENT) { if (reader.getLocalName().equals("properties")) { // old style of properties from before 0.12.0 if (reader.getAttributeCount() != 0) { DockableProperties.setLoadingLegacyFile(true); for (int i = 0; i < reader.getAttributeCount(); i++) { Property prop = DockableProperties.parseProperty(reader.getAttributeLocalName(i), "String", reader.getAttributeValue(i)); properties.put(String.valueOf(reader.getAttributeName(i)), prop); } } else { DockableProperties.setLoadingLegacyFile(false); while (reader.hasNext()) { next = reader.nextTag(); if (next == XMLStreamConstants.START_ELEMENT && reader.getLocalName().equals("property")) { String property = null; String type = null; String value = null; for (int i = 0; i < reader.getAttributeCount(); i++) { String attributeLocalName = reader.getAttributeLocalName(i); switch (attributeLocalName) { case "name": property = reader.getAttributeValue(i); break; case "type": type = reader.getAttributeValue(i); break; case "value": value = reader.getAttributeValue(i); break; } } if (property != null && type != null && value != null) { Property parsedProperty = DockableProperties.parseProperty(property, type, value); properties.put(parsedProperty.getName(), parsedProperty); } } else if (next == XMLStreamConstants.END_ELEMENT && reader.getLocalName().equals("properties")) { break; } } } } } if (next == XMLStreamConstants.END_ELEMENT && reader.getLocalName().equals("properties")) { break; } } return properties; } private DockingSplitPanelNode readSplitNodeFromFile(XMLStreamReader reader) throws XMLStreamException { DockingLayoutNode left = null; DockingLayoutNode right = null; int orientation = Integer.parseInt(reader.getAttributeValue(null, "orientation")); double dividerProportion = Double.parseDouble(reader.getAttributeValue(null, "divider-proportion")); String anchor = reader.getAttributeValue(null, "anchor"); // anchor didn't always exist, set it to an empty string if it's null if (anchor == null) { anchor = ""; } if (dividerProportion < 0.0) { dividerProportion = 0.0; } else if (dividerProportion > 1.0) { dividerProportion = 1.0; } while (reader.hasNext()) { int next = reader.nextTag(); if (next == XMLStreamConstants.START_ELEMENT) { if (reader.getLocalName().equals("left")) { left = readNodeFromFile(reader, "left"); } else if (reader.getLocalName().equals("right")) { right = readNodeFromFile(reader, "right"); } } else if (next == XMLStreamConstants.END_ELEMENT && reader.getLocalName().equals("split")) { break; } } return new DockingSplitPanelNode(docking, left, right, orientation, dividerProportion, anchor); } private DockingTabPanelNode readTabNodeFromFile(XMLStreamReader reader) throws XMLStreamException { DockingTabPanelNode node = null; String currentPersistentID = ""; String anchor = ""; while (reader.hasNext()) { int next = reader.nextTag(); if (next == XMLStreamConstants.START_ELEMENT && reader.getLocalName().equals("selectedTab")) { String persistentID = reader.getAttributeValue(null, "persistentID"); String className = reader.getAttributeValue(null, "class-name"); anchor = reader.getAttributeValue(null, "anchor"); String titleText = reader.getAttributeValue(null, "title-text"); String tabText = reader.getAttributeValue(null, "tab-text"); // class name didn't always exist, set it to an empty string if it's null if (className == null) { className = ""; } if (anchor == null) { anchor = ""; } if (titleText == null) { titleText = ""; } if (tabText == null) { tabText = ""; } node = new DockingTabPanelNode(docking, persistentID, className, anchor, titleText, tabText); } else if (next == XMLStreamConstants.START_ELEMENT && reader.getLocalName().equals("tab")) { currentPersistentID = reader.getAttributeValue(null, "persistentID"); String className = reader.getAttributeValue(null, "class-name"); anchor = reader.getAttributeValue(null, "anchor"); String titleText = reader.getAttributeValue(null, "title-text"); String tabText = reader.getAttributeValue(null, "tab-text"); // class name didn't always exist, set it to an empty string if it's null if (className == null) { className = ""; } // anchor didn't always exist, set it to an empty string if it's null if (anchor == null) { anchor = ""; } if (titleText == null) { titleText = ""; } if (tabText == null) { tabText = ""; } if (node != null) {
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
true
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/docking-api/src/io/github/andrewauclair/moderndocking/api/RootDockingPanelAPI.java
docking-api/src/io/github/andrewauclair/moderndocking/api/RootDockingPanelAPI.java
/* Copyright (c) 2022 Andrew Auclair Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 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 the Software. 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. */ package io.github.andrewauclair.moderndocking.api; import io.github.andrewauclair.moderndocking.ui.ToolbarLocation; import java.awt.GridBagLayout; import java.awt.Window; import java.util.EnumSet; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLayeredPane; import javax.swing.JPanel; /** * Panel that should be added to each frame that should support docking */ public class RootDockingPanelAPI extends JPanel { /** * The docking instance this root docking panel belongs to */ private DockingAPI docking = null; /** * The window this root docking panel is contained in */ private Window window = null; /** * A panel to display when there are no dockables in the root docking panel */ private JPanel emptyPanel = new JPanel(); /** * The layer to display auto-hide dockables in when showing. This is used because the dockable panel needs * to be displayed above the rest of the panels */ private int autoHideLayer = JLayeredPane.MODAL_LAYER; /** * The toolbars that are supported on this root docking panel. The application can turn some off */ private EnumSet<ToolbarLocation> supportedToolbars = EnumSet.noneOf(ToolbarLocation.class); /** * Does this root docking panel support the toolbars and display of auto-hide dockables? */ private boolean autoHideSupported = false; /** * Create a new default panel with a GridBagLayout */ protected RootDockingPanelAPI() { setLayout(new GridBagLayout()); } /** * Create a new RootDockingPanel for the given window with a specific docking instance * * @param window Window this root panel is attached to * @param docking Instance of the docking framework to use, if multiple are in use */ protected RootDockingPanelAPI(DockingAPI docking, Window window) { setLayout(new GridBagLayout()); this.docking = docking; this.window = window; supportedToolbars = EnumSet.allOf(ToolbarLocation.class); autoHideSupported = !supportedToolbars.isEmpty(); setWindow(window); } /** * Set the parent window of this root * * @param window Parent window of root */ private void setWindow(Window window) { if (this.window != null) { docking.deregisterDockingPanel(this.window); } this.window = window; if (window instanceof JFrame) { docking.registerDockingPanel(this, (JFrame) window); } else { docking.registerDockingPanel(this, (JDialog) window); } supportedToolbars = EnumSet.allOf(ToolbarLocation.class); autoHideSupported = !supportedToolbars.isEmpty(); } /** * Create a new RootDockingPanel for the given window and set of supported toolbars * * @param docking The docking instance for this root * @param window Window this root panel is attached to * @param supportedToolbars Supported toolbars */ protected RootDockingPanelAPI(DockingAPI docking, Window window, EnumSet<ToolbarLocation> supportedToolbars) { this(docking, window); this.supportedToolbars = supportedToolbars; autoHideSupported = !supportedToolbars.isEmpty(); } /** * Get the window that contains this RootDockingPanel * * @return Parent window */ public Window getWindow() { return window; } /** * Get the empty panel * * @return Current empty panel */ public JPanel getEmptyPanel() { return emptyPanel; } /** * Set the panel that should be displayed when the root is empty * * @param panel New empty panel */ public void setEmptyPanel(JPanel panel) { this.emptyPanel = panel; } /** * Check if auto hide is supported on this root * * @return True if auto hide is supported */ public boolean isAutoHideSupported() { if (supportedToolbars.isEmpty()) { // if there are no auto hide tool bars then we can't support auto hide return false; } return autoHideSupported; } /** * Set auto hide supported flag * * @param supported Is auto hide supported? */ public void setAutoHideSupported(boolean supported) { autoHideSupported = supported; } /** * Get the layer that is being used for auto hide * * @return Auto hide layer */ public int getAutoHideLayer() { return autoHideLayer; } /** * Set the auto hide layer used for auto hide dockable toolbars * * @param layer Auto hide layer */ public void setAutoHideLayer(int layer) { autoHideLayer = layer; } /** * Check if an auto-hide toolbar location is supported * @param location Location to check * * @return Is the location supported? */ public boolean isLocationSupported(ToolbarLocation location) { return supportedToolbars.contains(location); } }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/docking-api/src/io/github/andrewauclair/moderndocking/api/DockingStateAPI.java
docking-api/src/io/github/andrewauclair/moderndocking/api/DockingStateAPI.java
/* Copyright (c) 2022 Andrew Auclair Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 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 the Software. 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. */ package io.github.andrewauclair.moderndocking.api; import io.github.andrewauclair.moderndocking.Dockable; import io.github.andrewauclair.moderndocking.DockableTabPreference; import io.github.andrewauclair.moderndocking.DynamicDockableParameters; import io.github.andrewauclair.moderndocking.Property; import io.github.andrewauclair.moderndocking.exception.DockableNotFoundException; import io.github.andrewauclair.moderndocking.exception.RootDockingPanelNotFoundException; import io.github.andrewauclair.moderndocking.internal.DockableProperties; import io.github.andrewauclair.moderndocking.internal.DockableWrapper; import io.github.andrewauclair.moderndocking.internal.DockedAnchorPanel; import io.github.andrewauclair.moderndocking.internal.DockedSimplePanel; import io.github.andrewauclair.moderndocking.internal.DockedSplitPanel; import io.github.andrewauclair.moderndocking.internal.DockedTabbedPanel; import io.github.andrewauclair.moderndocking.internal.DockingComponentUtils; import io.github.andrewauclair.moderndocking.internal.DockingInternal; import io.github.andrewauclair.moderndocking.internal.DockingListeners; import io.github.andrewauclair.moderndocking.internal.DockingPanel; import io.github.andrewauclair.moderndocking.internal.FailedDockable; import io.github.andrewauclair.moderndocking.internal.FloatingFrame; import io.github.andrewauclair.moderndocking.internal.InternalRootDockingPanel; import io.github.andrewauclair.moderndocking.layouts.ApplicationLayout; import io.github.andrewauclair.moderndocking.layouts.DefaultDynamicDockableCreationListener; import io.github.andrewauclair.moderndocking.layouts.DockingAnchorPanelNode; import io.github.andrewauclair.moderndocking.layouts.DockingLayoutNode; import io.github.andrewauclair.moderndocking.layouts.DockingLayouts; import io.github.andrewauclair.moderndocking.layouts.DockingSimplePanelNode; import io.github.andrewauclair.moderndocking.layouts.DockingSplitPanelNode; import io.github.andrewauclair.moderndocking.layouts.DockingTabPanelNode; import io.github.andrewauclair.moderndocking.layouts.DynamicDockableCreationListener; import io.github.andrewauclair.moderndocking.layouts.WindowLayout; import io.github.andrewauclair.moderndocking.settings.Settings; import io.github.andrewauclair.moderndocking.ui.ToolbarLocation; import java.awt.*; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.HierarchyEvent; import java.awt.event.HierarchyListener; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFrame; import javax.swing.JSplitPane; import javax.swing.SwingUtilities; /** * Utility class to get layouts from existing windows and to restore layouts onto existing windows */ public class DockingStateAPI { private static final Logger logger = Logger.getLogger(DockingStateAPI.class.getPackageName()); /** * cached layout for when a maximized dockable is minimized */ public final Map<Window, WindowLayout> maximizeRestoreLayout = new HashMap<>(); private final DockingAPI docking; private final DynamicDockableCreationListener defaultDynamicDockableCreation; private DynamicDockableCreationListener userDynamicDockableCreation = null; /** * Create a new instance for the given docking instance * * @param docking Docking instance this docking state belongs to */ protected DockingStateAPI(DockingAPI docking) { this.docking = docking; defaultDynamicDockableCreation = new DefaultDynamicDockableCreationListener(docking); } /** * Get the current window layout of a window * * @param window The window to get a layout for * * @return The window layout */ public WindowLayout getWindowLayout(Window window) { InternalRootDockingPanel root = DockingComponentUtils.rootForWindow(docking, window); if (root == null) { throw new RootDockingPanelNotFoundException(window); } WindowLayout maxLayout = maximizeRestoreLayout.get(window); if (maxLayout != null) { return maxLayout; } return DockingLayouts.layoutFromRoot(docking, root.getRootPanel()); } /** * Get the current application layout of the application * * @return Layout of the application */ public ApplicationLayout getApplicationLayout() { ApplicationLayout layout = new ApplicationLayout(); layout.setMainFrame(getWindowLayout(docking.getMainWindow())); for (Window frame : docking.getRootPanels().keySet()) { if (frame != docking.getMainWindow()) { layout.addFrame(getWindowLayout(frame)); } } return layout; } /** * Restore the application layout, creating any necessary windows * * @param layout Application layout to restore */ public void restoreApplicationLayout(ApplicationLayout layout) { // get rid of all existing windows and undock all dockables Set<Window> windows = new HashSet<>(docking.getRootPanels().keySet()); for (Window window : windows) { DockingComponentUtils.clearAnchors(window); DockingComponentUtils.undockComponents(docking, window); // only dispose this window if we created it if (window instanceof FloatingFrame) { window.dispose(); } } docking.getAppState().setPaused(true); // setup main frame restoreWindowLayout(docking.getMainWindow(), layout.getMainFrameLayout()); // setup rest of floating windows from layout for (WindowLayout frameLayout : layout.getFloatingFrameLayouts()) { FloatingFrame frame = new FloatingFrame(docking, frameLayout.getLocation(), frameLayout.getSize(), frameLayout.getState()); restoreWindowLayout(frame, frameLayout); SwingUtilities.invokeLater(() -> { DockingListeners.fireNewFloatingFrameEvent(frame, frame.getRoot()); }); } docking.getAppState().setPaused(false); docking.getAppState().persist(); DockingInternal.fireDockedEventForAll(docking); DockingLayouts.layoutRestored(layout); } /** * Restore the layout of a single window * * @param window Window to restore the layout onto * @param layout The layout to restore */ public void restoreWindowLayout(Window window, WindowLayout layout) { InternalRootDockingPanel root = DockingComponentUtils.rootForWindow(docking, window); if (root == null) { throw new RootDockingPanelNotFoundException(window); } if (layout.hasSizeAndLocationInformation()) { if (layout.getState() != Frame.MAXIMIZED_BOTH) { GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice[] devices = env.getScreenDevices(); boolean locationOnScreen = false; for (GraphicsDevice device : devices) { if (device.getDefaultConfiguration().getBounds().contains(layout.getLocation())) { locationOnScreen = true; } } if (!locationOnScreen && devices.length > 0) { layout.setLocation(devices[0].getDefaultConfiguration().getBounds().getLocation()); } } window.setLocation(layout.getLocation()); window.setSize(layout.getSize()); if (window instanceof JFrame) { ((JFrame) window).setExtendedState(layout.getState()); } } DockingComponentUtils.clearAnchors(root); DockingComponentUtils.undockComponents(docking, root); root.setPanel(restoreLayout(docking, layout.getRootNode(), window)); // undock and destroy any failed dockables undockFailedComponents(docking, root); restoreProperSplitLocations(root.getRootPanel()); for (String id : layout.getWestAutoHideToolbarIDs()) { Dockable dockable = getDockable(docking, id); root.setDockableHidden(dockable, ToolbarLocation.WEST); root.hideHiddenPanels(); getWrapper(dockable).setHidden(true); root.setSlidePosition(dockable, (int) (layout.slidePosition(id) * window.getWidth())); } for (String id : layout.getEastAutoHideToolbarIDs()) { Dockable dockable = getDockable(docking, id); root.setDockableHidden(dockable, ToolbarLocation.EAST); root.hideHiddenPanels(); getWrapper(dockable).setHidden(true); root.setSlidePosition(dockable, (int) (layout.slidePosition(id) * window.getHeight())); } for (String id : layout.getSouthAutoHideToolbarIDs()) { Dockable dockable = getDockable(docking, id); root.setDockableHidden(dockable, ToolbarLocation.SOUTH); root.hideHiddenPanels(); getWrapper(dockable).setHidden(true); root.setSlidePosition(dockable, (int) (layout.slidePosition(id) * window.getHeight())); } if (layout.getMaximizedDockable() != null) { docking.maximize(getDockable(docking, layout.getMaximizedDockable())); } } private void findSplitPanels(Container container, List<DockedSplitPanel> panels) { for (Component component : container.getComponents()) { if (component instanceof DockedSplitPanel) { panels.add((DockedSplitPanel) component); } if (component instanceof Container) { findSplitPanels((Container) component, panels); } } } /** * Restore the layout of a single window, preserving the current size and position of the window * * @param window Window to restore the layout onto * @param layout The layout to restore */ public void restoreWindowLayout_PreserveSizeAndPos(Window window, WindowLayout layout) { Point location = window.getLocation(); Dimension size = window.getSize(); restoreWindowLayout(window, layout); window.setLocation(location); window.setSize(size); } private DockingPanel restoreLayout(DockingAPI docking, DockingLayoutNode node, Window window) { if (node instanceof DockingSimplePanelNode) { return restoreSimple(docking, (DockingSimplePanelNode) node, window); } else if (node instanceof DockingSplitPanelNode) { return restoreSplit(docking, (DockingSplitPanelNode) node, window); } else if (node instanceof DockingTabPanelNode) { return restoreTabbed(docking, (DockingTabPanelNode) node, window); } else if (node instanceof DockingAnchorPanelNode) { return restoreAnchor(docking, (DockingAnchorPanelNode) node, window); } else if (node == null) { // the main window root can contain a null panel if nothing is docked return null; } else { throw new RuntimeException("Unknown state type"); } } private DockedSplitPanel restoreSplit(DockingAPI docking, DockingSplitPanelNode node, Window window) { DockedSplitPanel panel = new DockedSplitPanel(docking, window, ""); panel.setLeft(restoreLayout(docking, node.getLeft(), window)); panel.setRight(restoreLayout(docking, node.getRight(), window)); panel.setOrientation(node.getOrientation()); panel.setDividerLocation(node.getDividerProportion()); return panel; } private DockingPanel restoreTabbed(DockingAPI docking, DockingTabPanelNode node, Window window) { DockedTabbedPanel panel = null; for (DockingSimplePanelNode simpleNode : node.getPersistentIDs()) { Dockable dockable = getDockable(docking, simpleNode.getPersistentID()); if (dockable instanceof FailedDockable) { dockable = createDynamicDockable(dockable, simpleNode.getPersistentID(), simpleNode.getClassName(), simpleNode.getTitleText(), simpleNode.getTabText(), simpleNode.getProperties()); } if (dockable == null) { throw new DockableNotFoundException(simpleNode.getPersistentID()); } DockableWrapper wrapper = DockingInternal.get(docking).getWrapper(dockable); DockableProperties.configureProperties(wrapper, simpleNode.getProperties()); docking.undock(dockable); wrapper.setWindow(window); if (panel == null) { panel = new DockedTabbedPanel(docking, wrapper, node.getAnchor()); } else { panel.addPanel(wrapper); } } if (panel == null) { throw new RuntimeException("DockedTabbedPanel has no tabs"); } if (!node.getSelectedTabID().isEmpty()) { panel.bringToFront(getDockable(docking, node.getSelectedTabID())); } return panel; } private DockingPanel restoreAnchor(DockingAPI docking, DockingAnchorPanelNode node, Window window) { Dockable dockable = getDockable(docking, node.getPersistentID()); if (dockable instanceof FailedDockable) { dockable = createDynamicDockable(dockable, node.getPersistentID(), node.getClassName(), "", "", Collections.emptyMap()); } if (dockable == null) { throw new DockableNotFoundException(node.getPersistentID()); } DockableWrapper wrapper = DockingInternal.get(docking).getWrapper(dockable); // undock the dockable in case it is currently docked somewhere else docking.undock(dockable); wrapper.setWindow(window); return new DockedAnchorPanel(docking, wrapper); } private DockingPanel restoreSimple(DockingAPI docking, DockingSimplePanelNode node, Window window) { Dockable dockable = getDockable(docking, node.getPersistentID()); if (dockable instanceof FailedDockable) { dockable = createDynamicDockable(dockable, node.getPersistentID(), node.getClassName(), node.getTitleText(), node.getTabText(), node.getProperties()); } if (dockable == null) { throw new DockableNotFoundException(node.getPersistentID()); } DockableWrapper wrapper = DockingInternal.get(docking).getWrapper(dockable); DockableProperties.configureProperties(wrapper, node.getProperties()); // undock the dockable in case it is currently docked somewhere else docking.undock(dockable); wrapper.setWindow(window); if (wrapper.isAnchor()) { return new DockedAnchorPanel(docking, wrapper); } if (Settings.alwaysDisplayTabsMode() || dockable.getTabPreference() == DockableTabPreference.TOP) { return new DockedTabbedPanel(docking, wrapper, node.getAnchor()); } return new DockedSimplePanel(docking, wrapper, node.getAnchor()); } private Dockable createDynamicDockable(Dockable dockable, String persistentID, String className, String titleText, String tabText, Map<String, Property> properties) { // the failed dockable is registered with the persistentID we want to use docking.deregisterDockable(dockable); dockable = null; if (userDynamicDockableCreation != null) { dockable = userDynamicDockableCreation.createDockable(persistentID, className, titleText, tabText, properties); } if (dockable == null) { dockable = defaultDynamicDockableCreation.createDockable(persistentID, className, titleText, tabText, properties); } return dockable; // boolean foundNewConstructor = false; // // try { // Class<?> aClass = Class.forName(className); // Constructor<?> constructor = aClass.getConstructor(DynamicDockableParameters.class); // // // the failed dockable is registered with the persistentID we want to use // docking.deregisterDockable(dockable); // // constructor.newInstance(new DynamicDockableParameters(persistentID, tabText, titleText)); // // foundNewConstructor = true; // } // catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | // InvocationTargetException e) { // logger.log(Level.INFO, "Failed to create instance of dynamic dockable with DynamicDockableParameters constructor. Falling back on (String, String)"); // logger.log(Level.INFO, e.getMessage(), e); // } // // if (!foundNewConstructor) { // try { // Class<?> aClass = Class.forName(className); // Constructor<?> constructor = aClass.getConstructor(String.class, String.class); // // // the failed dockable is registered with the persistentID we want to use // docking.deregisterDockable(dockable); // // // create the instance, this should register the dockable and let us look it up // constructor.newInstance(persistentID, persistentID); // } // catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | // InvocationTargetException e) { // logger.log(Level.INFO, e.getMessage(), e); // return null; // } // } // // dockable = getDockable(docking, persistentID); // // if (dockable instanceof FailedDockable) { // return null; // } // return dockable; } private Dockable getDockable(DockingAPI docking, String persistentID) { try { return DockingInternal.get(docking).getDockable(persistentID); } catch (DockableNotFoundException ignore) { } return new FailedDockable(docking, persistentID); } private DockableWrapper getWrapper(Dockable dockable) { return DockingInternal.get(docking).getWrapper(dockable); } private void undockFailedComponents(DockingAPI docking, Container container) { for (Component component : container.getComponents()) { if (component instanceof FailedDockable) { FailedDockable dockable = (FailedDockable) component; docking.undock(getDockable(docking, dockable.getPersistentID())); dockable.destroy(); } else if (component instanceof Container) { undockFailedComponents(docking, (Container) component); } } } private void restoreProperSplitLocations(RootDockingPanelAPI root) { SwingUtilities.invokeLater(() -> { // find all the splits and restore their divider locations from the bottom up List<DockedSplitPanel> splitPanels = new ArrayList<>(); // find all the splits recursively. Pushing new splits onto the front of the deque. this forces the deepest // splits to be adjusted last, keeping their position proper. findSplitPanels(root, splitPanels); List<JSplitPane> splits = new ArrayList<>(); List<Double> proportions = new ArrayList<>(); // loop through and restore split proportions, bottom up for (DockedSplitPanel splitPanel : splitPanels) { splits.add(splitPanel.getSplitPane()); proportions.add(splitPanel.getLastRequestedDividerProportion()); } restoreSplits(splits, proportions); }); } private void restoreSplits(List<JSplitPane> splits, List<Double> proportions) { if (splits.size() != proportions.size()) { return; } if (splits.isEmpty()) { return; } JSplitPane splitPane = splits.get(0); double proportion = proportions.get(0); splits.remove(0); proportions.remove(0); restoreSplit(splitPane, proportion, splits, proportions); } /** * Restore all splits in the window, starting with the outer most splits and working our way in. Only moving to the next when the previous * has been completely set. * * @param splitPane The current splitpane we're setting * @param proportion The proportion of the splitpane * @param splits The list of splitpanes left * @param proportions The list of proportions for the remaining splitpanes */ private void restoreSplit(JSplitPane splitPane, double proportion, List<JSplitPane> splits, List<Double> proportions) { // calling setDividerLocation on a JSplitPane that isn't visible does nothing, so we need to check if it is showing first if (splitPane.isShowing()) { if (splitPane.getWidth() > 0 && splitPane.getHeight() > 0) { splitPane.setDividerLocation(proportion); if (!splits.isEmpty()) { SwingUtilities.invokeLater(() -> { JSplitPane nextSplit = splits.get(0); double nextProportion = proportions.get(0); splits.remove(0); proportions.remove(0); restoreSplit(nextSplit, nextProportion, splits, proportions); }); } } else { // split hasn't been completely calculated yet, wait until componentResize splitPane.addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { // remove this listener, it's a one off splitPane.removeComponentListener(this); // call the function again, this time it should actually set the divider location restoreSplit(splitPane, proportion, splits, proportions); } }); } } else { // split hasn't been shown yet, wait until it's showing splitPane.addHierarchyListener(new HierarchyListener() { @Override public void hierarchyChanged(HierarchyEvent e) { boolean isShowingChangeEvent = (e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0; if (isShowingChangeEvent && splitPane.isShowing()) { // remove this listener, it's a one off splitPane.removeHierarchyListener(this); // call the function again, this time it might set the size or wait for componentResize restoreSplit(splitPane, proportion, splits, proportions); } } }); } } public void setUserDynamicDockableCreationListener(DynamicDockableCreationListener userDynamicDockableCreation) { this.userDynamicDockableCreation = userDynamicDockableCreation; } }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/docking-api/src/io/github/andrewauclair/moderndocking/api/AppStateAPI.java
docking-api/src/io/github/andrewauclair/moderndocking/api/AppStateAPI.java
/* Copyright (c) 2022-2024 Andrew Auclair Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 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 the Software. 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. */ package io.github.andrewauclair.moderndocking.api; import io.github.andrewauclair.moderndocking.Dockable; import io.github.andrewauclair.moderndocking.Property; import io.github.andrewauclair.moderndocking.exception.DockingLayoutException; import io.github.andrewauclair.moderndocking.internal.DockableWrapper; import io.github.andrewauclair.moderndocking.internal.DockingInternal; import io.github.andrewauclair.moderndocking.layouts.ApplicationLayout; import io.github.andrewauclair.moderndocking.layouts.DockingLayouts; import io.github.andrewauclair.moderndocking.layouts.WindowLayout; import java.awt.Frame; import java.awt.event.ActionEvent; import java.io.File; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.Timer; /** * This class is used for auto persisting the application layout to a file when there are changes to the layout */ public class AppStateAPI { private static final Logger logger = Logger.getLogger(AppStateAPI.class.getPackageName()); private static final int PERSIST_TIMER_DELAY_MS = 500; private static boolean autoPersist = false; private static final Map<DockingAPI, File> autoPersistFiles = new HashMap<>(); private static ApplicationLayout defaultAppLayout = null; private static ApplicationLayout lastPersistedLayout = null; private static boolean paused = false; private static Timer persistTimer = null; private final DockingAPI docking; /** * Create a new App State instance for the docking instance * * @param docking Docking instance */ protected AppStateAPI(DockingAPI docking) { this.docking = docking; } /** * Set whether the framework should auto persist the application layout to a file when * docking changes, windows resize, etc. * * @param autoPersist Should the framework auto persist the application layout to a file? */ public void setAutoPersist(boolean autoPersist) { AppStateAPI.autoPersist = autoPersist; } /** * Are we currently auto persisting to a file? * * @return True - we are auto persisting, False - we are not auto persisting */ public boolean isAutoPersist() { return autoPersist; } /** * Set the file that should be used for auto persistence. This will be written as an XML file. * * @param file File to persist layout to */ public void setPersistFile(File file) { autoPersistFiles.put(docking, file); } /** * Retrieve the file that we are persisting the application layout into * * @return The file we are currently persisting to */ public File getPersistFile() { return autoPersistFiles.get(docking); } /** * Sets the pause state of the auto persistence * * @param paused Whether auto persistence should be enabled */ public void setPaused(boolean paused) { AppStateAPI.paused = paused; } /** * Gets the pause state of the auto persistence * * @return Whether auto persistence is enabled */ public boolean isPaused() { return paused; } /** * Used to persist the current app layout to the layout file. * This is a no-op if auto persistence is turned off, it's paused or there is no file */ public void persist() { if (!autoPersist || paused) { return; } // we don't want to persist immediately in case this function is getting called a lot. // start a timer that will be restarted every time persist() is called, until finally the timer will go off and persist the file. if (persistTimer == null) { persistTimer = new Timer(PERSIST_TIMER_DELAY_MS, new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { // we might have gotten to the timer and then paused persistence if (!paused && docking.getRootPanels().containsKey(docking.getMainWindow())) { ApplicationLayout layout = docking.getDockingState().getApplicationLayout(); /* Remember the size of all windows before they were minimized or maximized This allows us to return to the normal state after restoring a layout and have the proper size Without this change the window would remain nearly full screen, but in the NORMAL state */ if (lastPersistedLayout != null) { if (layout.getMainFrameLayout().getState() != Frame.NORMAL) { // set position and size of all frames into the new layout layout.getMainFrameLayout().setLocation(lastPersistedLayout.getMainFrameLayout().getLocation()); layout.getMainFrameLayout().setSize(lastPersistedLayout.getMainFrameLayout().getSize()); } List<WindowLayout> oldFrames = lastPersistedLayout.getFloatingFrameLayouts(); List<WindowLayout> newFrames = layout.getFloatingFrameLayouts(); for (WindowLayout newFrame : newFrames) { if (newFrame.getState() == Frame.NORMAL) { continue; } Optional<WindowLayout> oldFrame = oldFrames.stream() .filter(windowLayout -> windowLayout.getWindowHashCode() == newFrame.getWindowHashCode()) .findFirst(); if (oldFrame.isPresent()) { newFrame.setLocation(oldFrame.get().getLocation()); newFrame.setSize(oldFrame.get().getSize()); } } } lastPersistedLayout = layout; try { docking.getLayoutPersistence().saveLayoutToFile(autoPersistFiles.get(docking), layout); DockingLayouts.layoutPersisted(layout); logger.log(Level.FINE, "ModernDocking: Persisted Layout Successfully"); } catch (DockingLayoutException ex) { logger.log(Level.WARNING, ex.getMessage(), ex); } } // we're done with the timer for now. null it out persistTimer = null; } }); persistTimer.setRepeats(false); persistTimer.setCoalesce(false); persistTimer.start(); } else { persistTimer.restart(); } } /** * Restore the application layout from the auto persist file. * * @return true if and only if a layout is restored from a file. Restoring from the default layout will return false. * @throws DockingLayoutException Thrown for any issues with the layout file. */ public boolean restore() throws DockingLayoutException { // don't restore if auto persist is disabled File file = autoPersistFiles.get(docking); if (!autoPersistFiles.containsKey(docking) || !file.exists()) { // restore the default layout if we have one if (defaultAppLayout != null) { docking.getDockingState().restoreApplicationLayout(defaultAppLayout); } return false; } try { setPaused(true); ApplicationLayout layout = docking.getLayoutPersistence().loadApplicationLayoutFromFile(file); docking.getDockingState().restoreApplicationLayout(layout); return true; } catch (Exception e) { if (defaultAppLayout != null) { docking.getDockingState().restoreApplicationLayout(defaultAppLayout); } if (e instanceof DockingLayoutException) { throw e; } throw new DockingLayoutException(file, DockingLayoutException.FailureType.LOAD, e); } finally { // make sure that we turn persistence back on setPaused(false); } } /** * Set the default layout used by the application. This layout is restored after the application has loaded * and there is no persisted layout or the persisted layout fails to load. * * @param layout Default layout */ public void setDefaultApplicationLayout(ApplicationLayout layout) { defaultAppLayout = layout; } /** * Get the property for a dockable by name * * @param dockable The dockable to get a property for * @param propertyName The property to search for * * @return The property instance of the dockable, or null if not found */ public Property getProperty(Dockable dockable, String propertyName) { DockableWrapper wrapper = DockingInternal.get(docking).getWrapper(dockable); return wrapper.getProperty(propertyName); } /** * Set the value of a property on the dockable. If the property does not exist, it will be created * * @param dockable The dockable to set a property for * @param propertyName The name of the property we're setting * @param value The value of the property */ public void setProperty(Dockable dockable, String propertyName, Property value) { DockableWrapper wrapper = DockingInternal.get(docking).getWrapper(dockable); wrapper.setProperty(propertyName, value); } /** * Remove the property from the dockable * * @param dockable The dockable to remove the property from * @param propertyName The property to remove */ public void removeProperty(Dockable dockable, String propertyName) { DockableWrapper wrapper = DockingInternal.get(docking).getWrapper(dockable); wrapper.removeProperty(propertyName); } }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/docking-api/src/io/github/andrewauclair/moderndocking/layouts/DefaultDynamicDockableCreationListener.java
docking-api/src/io/github/andrewauclair/moderndocking/layouts/DefaultDynamicDockableCreationListener.java
package io.github.andrewauclair.moderndocking.layouts; import io.github.andrewauclair.moderndocking.Dockable; import io.github.andrewauclair.moderndocking.DynamicDockableParameters; import io.github.andrewauclair.moderndocking.Property; import io.github.andrewauclair.moderndocking.api.DockingAPI; import io.github.andrewauclair.moderndocking.exception.DockableNotFoundException; import io.github.andrewauclair.moderndocking.internal.DockingInternal; import io.github.andrewauclair.moderndocking.internal.FailedDockable; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; public class DefaultDynamicDockableCreationListener implements DynamicDockableCreationListener { private static final Logger logger = Logger.getLogger(DefaultDynamicDockableCreationListener.class.getPackageName()); private final DockingAPI docking; public DefaultDynamicDockableCreationListener(DockingAPI docking) { this.docking = docking; } @Override public Dockable createDockable(String persistentID, String className, String titleText, String tabText, Map<String, Property> properties) { boolean foundNewConstructor = false; try { Class<?> aClass = Class.forName(className); Constructor<?> constructor = aClass.getConstructor(DynamicDockableParameters.class); constructor.newInstance(new DynamicDockableParameters(persistentID, tabText, titleText)); foundNewConstructor = true; } catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) { logger.log(Level.INFO, "Failed to create instance of dynamic dockable with DynamicDockableParameters constructor. Falling back on (String, String)"); logger.log(Level.INFO, e.getMessage(), e); } if (!foundNewConstructor) { try { Class<?> aClass = Class.forName(className); Constructor<?> constructor = aClass.getConstructor(String.class, String.class); // create the instance, this should register the dockable and let us look it up constructor.newInstance(persistentID, persistentID); } catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) { logger.log(Level.INFO, e.getMessage(), e); return null; } } Dockable dockable = getDockable(docking, persistentID); if (dockable instanceof FailedDockable) { return null; } return dockable; } private Dockable getDockable(DockingAPI docking, String persistentID) { try { return DockingInternal.get(docking).getDockable(persistentID); } catch (DockableNotFoundException ignore) { } return new FailedDockable(docking, persistentID); } }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/docking-api/src/io/github/andrewauclair/moderndocking/layouts/DockingSplitPanelNode.java
docking-api/src/io/github/andrewauclair/moderndocking/layouts/DockingSplitPanelNode.java
/* Copyright (c) 2022-2023 Andrew Auclair Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 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 the Software. 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. */ package io.github.andrewauclair.moderndocking.layouts; import io.github.andrewauclair.moderndocking.Dockable; import io.github.andrewauclair.moderndocking.DockingRegion; import io.github.andrewauclair.moderndocking.api.DockingAPI; import io.github.andrewauclair.moderndocking.internal.DockingInternal; import io.github.andrewauclair.moderndocking.settings.Settings; import javax.swing.JSplitPane; /** * Layout node that represents a splitpane */ public class DockingSplitPanelNode implements DockingLayoutNode { private final DockingAPI docking; private DockingLayoutNode left; private DockingLayoutNode right; private final int orientation; private final double dividerProportion; private String anchor; private DockingLayoutNode parent; /** * Create a new DockingSplitPanelNode for a layout * * @param docking The docking instance this node belongs to * @param left The left component of the split * @param right The right component of the split * @param orientation The orientation of the split * @param dividerProportion The divider proportion of the split * @param anchor The anchor associated with this node */ public DockingSplitPanelNode(DockingAPI docking, DockingLayoutNode left, DockingLayoutNode right, int orientation, double dividerProportion, String anchor) { this.docking = docking; this.left = left; this.right = right; this.orientation = orientation; this.dividerProportion = dividerProportion; this.anchor = anchor; if (this.left != null) { this.left.setParent(this); } if (this.right != null) { this.right.setParent(this); } } @Override public DockingLayoutNode getParent() { return parent; } @Override public void setParent(DockingLayoutNode parent) { this.parent = parent; } @Override public DockingLayoutNode findNode(String persistentID) { if (this.left != null) { DockingLayoutNode left = this.left.findNode(persistentID); if (left != null) { return left; } } if (this.right == null) { return null; } return this.right.findNode(persistentID); } @Override public void dock(String persistentID, DockingRegion region, double dividerProportion) { if (region != DockingRegion.CENTER) { int orientation = region == DockingRegion.EAST || region == DockingRegion.WEST ? JSplitPane.HORIZONTAL_SPLIT : JSplitPane.VERTICAL_SPLIT; DockingLayoutNode left; DockingLayoutNode right; Dockable dockable = DockingInternal.get(docking).getDockable(persistentID); String className = dockable.getClass().getTypeName(); if (Settings.alwaysDisplayTabsMode()) { left = region == DockingRegion.NORTH || region == DockingRegion.WEST ? new DockingTabPanelNode(docking, persistentID, className, anchor, dockable.getTitleText(), dockable.getTabText()) : this; right = region == DockingRegion.NORTH || region == DockingRegion.WEST ? this : new DockingTabPanelNode(docking, persistentID, className, anchor, dockable.getTitleText(), dockable.getTabText()); } else { left = region == DockingRegion.NORTH || region == DockingRegion.WEST ? new DockingSimplePanelNode(docking, persistentID, className, anchor, dockable.getTitleText(), dockable.getTabText()) : this; right = region == DockingRegion.NORTH || region == DockingRegion.WEST ? this : new DockingSimplePanelNode(docking, persistentID, className, anchor, dockable.getTitleText(), dockable.getTabText()); } if (region == DockingRegion.EAST || region == DockingRegion.SOUTH) { dividerProportion = 1.0 - dividerProportion; } DockingLayoutNode oldParent = parent; DockingSplitPanelNode split = new DockingSplitPanelNode(docking, left, right, orientation, dividerProportion, anchor); oldParent.replaceChild(this, split); } } @Override public void replaceChild(DockingLayoutNode child, DockingLayoutNode newChild) { if (left == child) { left = newChild; left.setParent(this); } else if (right == child) { right = newChild; right.setParent(this); } } /** * Get the left component of the split * * @return Left component */ public DockingLayoutNode getLeft() { return left; } /** * Get the right component of the split * * @return Right component */ public DockingLayoutNode getRight() { return right; } /** * Get the orientation * * @return The orientation of the JSplitPane */ public int getOrientation() { return orientation; } /** * Get the divider proportion * * @return Proportion of the JSPlitPane Divider */ public double getDividerProportion() { return dividerProportion; } }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/docking-api/src/io/github/andrewauclair/moderndocking/layouts/WindowLayout.java
docking-api/src/io/github/andrewauclair/moderndocking/layouts/WindowLayout.java
/* Copyright (c) 2022 Andrew Auclair Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 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 the Software. 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. */ package io.github.andrewauclair.moderndocking.layouts; import java.awt.Dialog.ModalityType; import java.awt.Dimension; import java.awt.Frame; import java.awt.Point; import java.awt.Window; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.JDialog; import javax.swing.JFrame; /** * layout of a single frame */ public class WindowLayout { private boolean isMainFrame; private Point location; private final boolean hasSizeAndLocationInformation; private Dimension size; private final int state; private final ModalityType modalityType; private final DockingLayoutNode rootNode; private String maximizedDockable = null; private final int windowHashCode; private final List<String> westAutoHideToolbarIDs = new ArrayList<>(); private final List<String> eastAutoHideToolbarIDs = new ArrayList<>(); private final List<String> southAutoHideToolbarIDs = new ArrayList<>(); private final Map<String, Double> toolbarSlidePositions = new HashMap<>(); /** * Create a new WindowLayout from an existing root node * * @param isMainFrame Flag indicating if this is the main frame of the application * @param location The location of the window on screen * @param size The width and height of the window * @param state State of the window (maximized, minimized) * @param rootNode Root of the window */ public WindowLayout(boolean isMainFrame, Point location, Dimension size, int state, DockingLayoutNode rootNode) { this.isMainFrame = isMainFrame; this.location = location; this.size = size; this.state = state; this.rootNode = rootNode; this.modalityType = ModalityType.MODELESS; this.windowHashCode = 0; hasSizeAndLocationInformation = true; } /** * Create a WindowLayout from a root node. All other info is defaulted * * @param rootNode Root of window */ public WindowLayout(DockingLayoutNode rootNode) { this.rootNode = rootNode; this.state = Frame.NORMAL; this.windowHashCode = 0; hasSizeAndLocationInformation = false; location = new Point(); size = new Dimension(); modalityType = ModalityType.MODELESS; } /** * Create a new WindowLayout for the given window and its root. Assumed to not be the main frame * * @param window The window for this layout * @param rootNode The root for the window */ public WindowLayout(Window window, DockingLayoutNode rootNode) { this.rootNode = rootNode; this.location = window.getLocation(); this.size = window.getSize(); this.windowHashCode = window.hashCode(); if (window instanceof JFrame) { this.state = ((JFrame) window).getExtendedState(); this.modalityType = ModalityType.MODELESS; } else { this.state = Frame.NORMAL; this.modalityType = ((JDialog) window).getModalityType(); } hasSizeAndLocationInformation = true; } /** * Check if the contained window is the applications main frame * * @return True if contained window is the main frame of the application */ public boolean isMainFrame() { return isMainFrame; } /** * Get the location on screen of this window * * @return Screen location */ public Point getLocation() { return location; } /** * Set the location of the window * * @param location New location of the window */ public void setLocation(Point location) { this.location = location; } /** * Get the size of this window * * @return Size (width and height) of the contained window */ public Dimension getSize() { return size; } /** * Set the size of the window * * @param size New size for window */ public void setSize(Dimension size) { this.size = size; } /** * Get state of window (ICONIFIED, MAXIMIZED, NORMAL) * * @return State of window */ public int getState() { return state; } /** * Current modality type of the window * * @return Modality type */ public ModalityType getModalityType() { return modalityType; } /** * Get the root layout node of the window * * @return Root layout node */ public DockingLayoutNode getRootNode() { return rootNode; } /** * Set the dockable that is maximized * * @param persistentID Persistent ID of maximized dockable or null */ public void setMaximizedDockable(String persistentID) { maximizedDockable = persistentID; } /** * Get the persistent ID of the dockable which is currently maximized * * @return Name of maximized dockable. Empty string if none. */ public String getMaximizedDockable() { return maximizedDockable; } /** * Set a list of all the dockables on the west toolbar * * @param ids List of unpinned dockable IDs on the west toolbar */ public void setWestAutoHideToolbarIDs(List<String> ids) { westAutoHideToolbarIDs.clear(); westAutoHideToolbarIDs.addAll(ids); } /** * Get a list of all the dockables on the west toolbar * * @return List of unpinned dockable IDs on the west toolbar */ public List<String> getWestAutoHideToolbarIDs() { return westAutoHideToolbarIDs; } /** * Set a list of all the dockables on the east toolbar * * @param ids List of unpinned dockable IDs on the east toolbar */ public void setEastAutoHideToolbarIDs(List<String> ids) { eastAutoHideToolbarIDs.clear(); eastAutoHideToolbarIDs.addAll(ids); } /** * Get a list of all the dockables on the east toolbar * * @return List of unpinned dockable IDs on the east toolbar */ public List<String> getEastAutoHideToolbarIDs() { return eastAutoHideToolbarIDs; } /** * Set a list of all the dockables on the south toolbar * * @param ids List of unpinned dockable IDs on the south toolbar */ public void setSouthAutoHideToolbarIDs(List<String> ids) { southAutoHideToolbarIDs.clear(); southAutoHideToolbarIDs.addAll(ids); } /** * Get a list of all the dockables on the south toolbar * * @return List of unpinned dockable IDs on the south toolbar */ public List<String> getSouthAutoHideToolbarIDs() { return southAutoHideToolbarIDs; } public void setSlidePosition(String id, double slidePosition) { toolbarSlidePositions.put(id, slidePosition); } public double slidePosition(String id) { return toolbarSlidePositions.getOrDefault(id, 0.0); } /** * Check if this window layout has information about the size and location of the window * * @return Does the layout have size and location? */ public boolean hasSizeAndLocationInformation() { return hasSizeAndLocationInformation; } /** * Get the hash code of the window * * @return Window hash code */ public int getWindowHashCode() { return windowHashCode; } }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/docking-api/src/io/github/andrewauclair/moderndocking/layouts/DockingLayoutRootNode.java
docking-api/src/io/github/andrewauclair/moderndocking/layouts/DockingLayoutRootNode.java
/* Copyright (c) 2023 Andrew Auclair Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 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 the Software. 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. */ package io.github.andrewauclair.moderndocking.layouts; import io.github.andrewauclair.moderndocking.Dockable; import io.github.andrewauclair.moderndocking.DockingRegion; import io.github.andrewauclair.moderndocking.api.DockingAPI; import io.github.andrewauclair.moderndocking.internal.DockingInternal; import io.github.andrewauclair.moderndocking.settings.Settings; /** * The root node of a docking layout */ public class DockingLayoutRootNode implements DockingLayoutNode { private final DockingAPI docking; private DockingLayoutNode node; /** * Create a new instance for the docking instance * * @param docking Docking instance this root node is tied to */ public DockingLayoutRootNode(DockingAPI docking) { this.docking = docking; } @Override public DockingLayoutNode findNode(String persistentID) { return node.findNode(persistentID); } @Override public void dock(String persistentID, DockingRegion region, double dividerProportion) { if (node != null) { node.dock(persistentID, region, dividerProportion); } else if (DockingInternal.get(docking).hasAnchor(persistentID)) { String className = DockingInternal.get(docking).getDockable(persistentID).getClass().getTypeName(); node = new DockingAnchorPanelNode(docking, persistentID, className); } else if (Settings.alwaysDisplayTabsMode()) { node = new DockingTabPanelNode(docking, persistentID, "", "", "", ""); node.setParent(this); } else { Dockable dockable = DockingInternal.get(docking).getDockable(persistentID); String className = dockable.getClass().getTypeName(); node = new DockingSimplePanelNode(docking, persistentID, className, "", dockable.getTitleText(), dockable.getTabText()); node.setParent(this); } } @Override public void replaceChild(DockingLayoutNode child, DockingLayoutNode newChild) { if (node == child) { node = newChild; node.setParent(this); } } @Override public DockingLayoutNode getParent() { return null; } @Override public void setParent(DockingLayoutNode parent) { } /** * Get the first node in the hierarchy * @return The primary node. This will be null if the root is empty */ public DockingLayoutNode getNode() { return node; } }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false
andrewauclair/ModernDocking
https://github.com/andrewauclair/ModernDocking/blob/cb69cbcf9bad74d73b1e32de5f813e86872d20e6/docking-api/src/io/github/andrewauclair/moderndocking/layouts/DynamicDockableCreationListener.java
docking-api/src/io/github/andrewauclair/moderndocking/layouts/DynamicDockableCreationListener.java
package io.github.andrewauclair.moderndocking.layouts; import io.github.andrewauclair.moderndocking.Dockable; import io.github.andrewauclair.moderndocking.Property; import java.util.Map; public interface DynamicDockableCreationListener { Dockable createDockable(String persistentID, String className, String titleText, String tabText, Map<String, Property> properties); }
java
MIT
cb69cbcf9bad74d73b1e32de5f813e86872d20e6
2026-01-05T02:41:37.174237Z
false