file_path
stringlengths
3
280
file_language
stringclasses
66 values
content
stringlengths
1
1.04M
repo_name
stringlengths
5
92
repo_stars
int64
0
154k
repo_description
stringlengths
0
402
repo_primary_language
stringclasses
108 values
developer_username
stringlengths
1
25
developer_name
stringlengths
0
30
developer_company
stringlengths
0
82
tools/scripts/dist_train.sh
Shell
#!/usr/bin/env bash set -x NGPUS=$1 PY_ARGS="${@:2}" torchrun --nproc_per_node=${NGPUS} train.py --launcher pytorch ${PY_ARGS}
yxlao/lit
24
(NeurIPS 2024) LiT: Unifying LiDAR "Languages" with LiDAR Translator
Python
yxlao
Yixing Lao
HKU-CS
tools/scripts/dist_train_on_port.sh
Shell
#!/usr/bin/env bash set -x NGPUS=$1 PORT=$2 PY_ARGS="${@:3}" torchrun --nproc_per_node=${NGPUS} --master_port=${PORT} train.py --launcher pytorch ${PY_ARGS}
yxlao/lit
24
(NeurIPS 2024) LiT: Unifying LiDAR "Languages" with LiDAR Translator
Python
yxlao
Yixing Lao
HKU-CS
tools/test.py
Python
import argparse import datetime import glob import os import re import time from pathlib import Path import numpy as np import torch import torch.distributed as dist from eval_utils import eval_utils from tensorboardX import SummaryWriter from lit.path_utils import LitPaths from pcdet.config import cfg, cfg_from_list, cfg_from_yaml_file, log_config_to_file from pcdet.datasets import build_dataloader from pcdet.models import build_network from pcdet.models.model_utils.dsnorm import DSNorm from pcdet.utils import common_utils def parse_config(): parser = argparse.ArgumentParser(description="arg parser") parser.add_argument( "--cfg_file", type=str, default=None, help="specify the config for training" ) parser.add_argument( "--batch_size", type=int, default=16, required=False, help="batch size for training", ) parser.add_argument( "--epochs", type=int, default=80, required=False, help="Number of epochs to train for", ) parser.add_argument( "--workers", type=int, default=4, help="number of workers for dataloader" ) parser.add_argument( "--extra_tag", type=str, default="default", help="extra tag for this experiment" ) parser.add_argument( "--ckpt", type=str, default=None, help="checkpoint to start from" ) parser.add_argument( "--launcher", choices=["none", "pytorch", "slurm"], default="none" ) parser.add_argument( "--tcp_port", type=int, default=18888, help="tcp port for distrbuted training" ) parser.add_argument( "--local_rank", type=int, default=0, help="local rank for distributed training" ) parser.add_argument( "--set", dest="set_cfgs", default=None, nargs=argparse.REMAINDER, help="set extra config keys if needed", ) parser.add_argument( "--max_waiting_mins", type=int, default=30, help="max waiting minutes" ) parser.add_argument("--start_epoch", type=int, default=0, help="") parser.add_argument( "--eval_tag", type=str, default="default", help="eval tag for this experiment" ) parser.add_argument( "--eval_all", action="store_true", default=False, help="whether to evaluate all checkpoints", ) parser.add_argument( "--ckpt_dir", type=str, default=None, help="specify a ckpt directory to be evaluated if needed", ) parser.add_argument("--save_to_file", action="store_true", default=False, help="") args = parser.parse_args() cfg_from_yaml_file(args.cfg_file, cfg) cfg.TAG = Path(args.cfg_file).stem cfg.EXP_GROUP_PATH = "/".join( args.cfg_file.split("/")[1:-1] ) # remove 'cfgs' and 'xxxx.yaml' np.random.seed(1024) if args.set_cfgs is not None: cfg_from_list(args.set_cfgs, cfg) return args, cfg def eval_single_ckpt( model, test_loader, args, eval_output_dir, logger, epoch_id, dist_test=False ): # Load checkpoint model.load_params_from_file(filename=args.ckpt, logger=logger, to_cpu=dist_test) model.cuda() # Get metric path ckpt_path = Path(args.ckpt) ckpt_dir = ckpt_path.parent if dist_test: metric_dir = ckpt_dir.parent / "metric_dist_test" else: metric_dir = ckpt_dir.parent / "metric_test" metric_path = metric_dir / f"{ckpt_path.stem}.txt" if metric_path.is_file() and metric_path.stat().st_size > 0: print(f"Skip evaluation because {metric_path} exists and is not empty") return # Start evaluation ret_dict, result_str = eval_utils.eval_one_epoch( cfg, model, test_loader, epoch_id, logger, dist_test=dist_test, result_dir=eval_output_dir, save_to_file=args.save_to_file, args=args, ) # Save result_str to metric_path metric_path.parent.mkdir(parents=True, exist_ok=True) with open(metric_path, "w") as f: f.write(result_str) def get_no_evaluated_ckpt(ckpt_dir, ckpt_record_file, args): ckpt_list = glob.glob(os.path.join(ckpt_dir, "*checkpoint_epoch_*.pth")) ckpt_list.sort(key=os.path.getmtime) evaluated_ckpt_list = [ float(x.strip()) for x in open(ckpt_record_file, "r").readlines() ] for cur_ckpt in ckpt_list: num_list = re.findall("checkpoint_epoch_(.*).pth", cur_ckpt) if num_list.__len__() == 0: continue epoch_id = num_list[-1] if "optim" in epoch_id: continue if ( float(epoch_id) not in evaluated_ckpt_list and int(float(epoch_id)) >= args.start_epoch ): return epoch_id, cur_ckpt return -1, None def repeat_eval_ckpt( model, test_loader, args, eval_output_dir, logger, ckpt_dir, dist_test=False ): # Tensorboard log if cfg.LOCAL_RANK == 0: tb_log = SummaryWriter( log_dir=str( eval_output_dir / ("tensorboard_%s" % cfg.DATA_CONFIG.DATA_SPLIT["test"]) ) ) # Get a list of non-evaluated checkpoints. If metric_path exists and the # file is not empty, the checkpoint is regarded as evaluated. # # Example: # - ckpt_path : {ckpt_dir}/checkpoint_epoch_1.pth # - metric_path: {ckpt_dir}/../"metric"/checkpoint_epoch_1.txt ckpt_paths = glob.glob(os.path.join(ckpt_dir, "*checkpoint_epoch_*.pth")) ckpt_paths.sort(key=os.path.getmtime) ckpt_paths = [Path(p) for p in ckpt_paths] if dist_test: metric_dir = ckpt_dir.parent / "metric_dist_test" else: metric_dir = ckpt_dir.parent / "metric_test" print(f"Found {len(ckpt_paths)} checkpoints =====================") to_evaluate_ckpt_paths = [] for ckpt_path in ckpt_paths: metric_path = metric_dir / f"{ckpt_path.stem}.txt" if metric_path.is_file() and metric_path.stat().st_size > 0: print(f"- Evaluated : {ckpt_path}") else: to_evaluate_ckpt_paths.append(ckpt_path) print(f"- To evaluate: {ckpt_path}") print("===========================================================") # Evaluate non-evaluated checkpoints for ckpt_path in to_evaluate_ckpt_paths: # Get epoch_id epoch_id = int(ckpt_path.stem.split("_")[-1]) # Load checkpoint model.load_params_from_file(filename=ckpt_path, logger=logger, to_cpu=dist_test) model.cuda() # Start evaluation result_dir = ( eval_output_dir / ("epoch_%s" % epoch_id) / cfg.DATA_CONFIG.DATA_SPLIT["test"] ) ret_dict, result_str = eval_utils.eval_one_epoch( cfg, model, test_loader, epoch_id, logger, dist_test=dist_test, result_dir=result_dir, save_to_file=args.save_to_file, args=args, ) if cfg.LOCAL_RANK == 0: for key, val in ret_dict.items(): tb_log.add_scalar(key, val, epoch_id) # Save result_str to metric_path if cfg.LOCAL_RANK == 0: metric_path = metric_dir / f"{ckpt_path.stem}.txt" metric_path.parent.mkdir(parents=True, exist_ok=True) with open(metric_path, "w") as f: f.write(result_str) if cfg.LOCAL_RANK == 0: tb_log.flush() def main(): args, cfg = parse_config() if args.launcher == "none": dist_test = False total_gpus = 1 else: total_gpus, cfg.LOCAL_RANK = getattr( common_utils, "init_dist_%s" % args.launcher )(args.tcp_port, args.local_rank, backend="nccl") dist_test = True if args.batch_size is None: args.batch_size = cfg.OPTIMIZATION.BATCH_SIZE_PER_GPU else: assert ( args.batch_size % total_gpus == 0 ), "Batch size should match the number of gpus" args.batch_size = args.batch_size // total_gpus output_dir = cfg.ROOT_DIR / "output" / cfg.EXP_GROUP_PATH / cfg.TAG / args.extra_tag output_dir.mkdir(parents=True, exist_ok=True) eval_output_dir = output_dir / "eval" if not args.eval_all: num_list = re.findall(r"\d+", args.ckpt) if args.ckpt is not None else [] epoch_id = num_list[-1] if num_list.__len__() > 0 else "no_number" eval_output_dir = ( eval_output_dir / ("epoch_%s" % epoch_id) / cfg.DATA_CONFIG.DATA_SPLIT["test"] ) else: eval_output_dir = eval_output_dir / "eval_all_default" if args.eval_tag is not None: eval_output_dir = eval_output_dir / args.eval_tag eval_output_dir.mkdir(parents=True, exist_ok=True) log_file = eval_output_dir / ( "log_eval_%s.txt" % datetime.datetime.now().strftime("%Y%m%d-%H%M%S") ) logger = common_utils.create_logger(log_file, rank=cfg.LOCAL_RANK) # log to file logger.info("**********************Start logging**********************") gpu_list = ( os.environ["CUDA_VISIBLE_DEVICES"] if "CUDA_VISIBLE_DEVICES" in os.environ.keys() else "ALL" ) logger.info("CUDA_VISIBLE_DEVICES=%s" % gpu_list) if dist_test: logger.info("total_batch_size: %d" % (total_gpus * args.batch_size)) for key, val in vars(args).items(): logger.info("{:16} {}".format(key, val)) log_config_to_file(cfg, logger=logger) ckpt_dir = args.ckpt_dir if args.ckpt_dir is not None else output_dir / "ckpt" if cfg.get("DATA_CONFIG_TAR", None): test_set, test_loader, sampler = build_dataloader( dataset_cfg=cfg.DATA_CONFIG_TAR, class_names=cfg.DATA_CONFIG_TAR.CLASS_NAMES, batch_size=args.batch_size, dist=dist_test, workers=args.workers, logger=logger, training=False, ) else: test_set, test_loader, sampler = build_dataloader( dataset_cfg=cfg.DATA_CONFIG, class_names=cfg.CLASS_NAMES, batch_size=args.batch_size, dist=dist_test, workers=args.workers, logger=logger, training=False, ) model = build_network( model_cfg=cfg.MODEL, num_class=len(cfg.CLASS_NAMES), dataset=test_set ) if cfg.get("SELF_TRAIN", None) and cfg.SELF_TRAIN.get("DSNORM", None): model = DSNorm.convert_dsnorm(model) state_name = "model_state" with torch.no_grad(): if args.eval_all: repeat_eval_ckpt( model, test_loader, args, eval_output_dir, logger, ckpt_dir, dist_test=dist_test, ) else: eval_single_ckpt( model, test_loader, args, eval_output_dir, logger, epoch_id, dist_test=dist_test, ) if __name__ == "__main__": main()
yxlao/lit
24
(NeurIPS 2024) LiT: Unifying LiDAR "Languages" with LiDAR Translator
Python
yxlao
Yixing Lao
HKU-CS
tools/train.py
Python
import argparse import datetime import glob import os import sys from pathlib import Path import torch import torch.distributed as dist import torch.nn as nn from tensorboardX import SummaryWriter from train_utils.optimization import build_optimizer, build_scheduler from train_utils.train_st_utils import train_model_st from train_utils.train_utils import train_model from lit.path_utils import LitPaths from pcdet.config import cfg, cfg_from_list, cfg_from_yaml_file, log_config_to_file from pcdet.datasets import build_dataloader, build_wayscenes_dataloader from pcdet.models import build_network, model_fn_decorator from pcdet.models.model_utils.dsnorm import DSNorm from pcdet.utils import common_utils def parse_config(): parser = argparse.ArgumentParser(description="arg parser") parser.add_argument( "--cfg_file", type=str, default=None, help="specify the config for training" ) parser.add_argument( "--batch_size", type=int, default=16, required=False, help="batch size for training", ) parser.add_argument( "--epochs", type=int, default=None, required=False, help="number of epochs to train for", ) parser.add_argument( "--workers", type=int, default=4, help="number of workers for dataloader" ) parser.add_argument( "--extra_tag", type=str, default="default", help="extra tag for this experiment" ) parser.add_argument( "--ckpt", type=str, default=None, help="checkpoint to start from" ) parser.add_argument( "--pretrained_model", type=str, default=None, help="pretrained_model" ) parser.add_argument( "--launcher", choices=["none", "pytorch", "slurm"], default="none" ) parser.add_argument( "--tcp_port", type=int, default=18888, help="tcp port for distrbuted training" ) parser.add_argument( "--sync_bn", action="store_true", default=False, help="whether to use sync bn" ) parser.add_argument( "--fix_random_seed", action="store_true", default=False, help="" ) parser.add_argument( "--ckpt_save_interval", type=int, default=1, help="number of training epochs" ) parser.add_argument( "--local_rank", type=int, default=0, help="local rank for distributed training" ) parser.add_argument( "--max_ckpt_save_num", type=int, default=30, help="max number of saved checkpoint", ) parser.add_argument( "--merge_all_iters_to_one_epoch", action="store_true", default=False, help="" ) parser.add_argument( "--set", dest="set_cfgs", default=None, nargs=argparse.REMAINDER, help="set extra config keys if needed", ) parser.add_argument( "--max_waiting_mins", type=int, default=0, help="max waiting minutes" ) parser.add_argument("--start_epoch", type=int, default=0, help="") parser.add_argument("--save_to_file", action="store_true", default=False, help="") parser.add_argument("--lr", type=float, default=None, help="Learning rate") parser.add_argument( "--skip_test", action="store_true", default=False, help="Skip per-epoch test after saving a checkpoint", ) parser.add_argument( "--debug_on_error", action="store_true", default=False, help="Set break point with ipdb when error occurs", ) args = parser.parse_args() cfg_from_yaml_file(args.cfg_file, cfg) cfg.TAG = Path(args.cfg_file).stem cfg.EXP_GROUP_PATH = "/".join( args.cfg_file.split("/")[1:-1] ) # remove 'cfgs' and 'xxxx.yaml' if args.set_cfgs is not None: cfg_from_list(args.set_cfgs, cfg) return args, cfg def main(): args, cfg = parse_config() if args.debug_on_error: sys.excepthook = lambda et, ev, tb: ( None if issubclass(et, (KeyboardInterrupt, SystemExit)) else ( print(f"Unhandled exception: {ev}"), __import__("ipdb").post_mortem(tb), ) ) if args.launcher == "none": dist_train = False total_gpus = 1 else: total_gpus, cfg.LOCAL_RANK = getattr( common_utils, "init_dist_%s" % args.launcher )(args.tcp_port, args.local_rank, backend="nccl") dist_train = True if args.batch_size is None: args.batch_size = cfg.OPTIMIZATION.BATCH_SIZE_PER_GPU else: assert ( args.batch_size % total_gpus == 0 ), "Batch size should match the number of gpus" args.batch_size = args.batch_size // total_gpus args.epochs = cfg.OPTIMIZATION.NUM_EPOCHS if args.epochs is None else args.epochs if args.fix_random_seed: common_utils.set_random_seed(666) if args.lr is not None: print(f"Overwrite LR to {args.lr}") cfg.OPTIMIZATION.LR = args.lr output_dir = cfg.ROOT_DIR / "output" / cfg.EXP_GROUP_PATH / cfg.TAG / args.extra_tag ckpt_dir = output_dir / "ckpt" ps_label_dir = output_dir / "ps_label" ps_label_dir.mkdir(parents=True, exist_ok=True) output_dir.mkdir(parents=True, exist_ok=True) ckpt_dir.mkdir(parents=True, exist_ok=True) log_file = output_dir / ( "log_train_%s.txt" % datetime.datetime.now().strftime("%Y%m%d-%H%M%S") ) logger = common_utils.create_logger(log_file, rank=cfg.LOCAL_RANK) # log to file logger.info("**********************Start logging**********************") gpu_list = ( os.environ["CUDA_VISIBLE_DEVICES"] if "CUDA_VISIBLE_DEVICES" in os.environ.keys() else "ALL" ) logger.info("CUDA_VISIBLE_DEVICES=%s" % gpu_list) if dist_train: logger.info( "total_batch_size: %d, num_gpus: %d, batch_size_per_gpu: %d" % (total_gpus * args.batch_size, total_gpus, args.batch_size) ) print( f"total_batch_size: {total_gpus * args.batch_size}, " f"num_gpus: {total_gpus}, batch_size_per_gpu: {args.batch_size}" ) for key, val in vars(args).items(): logger.info("{:16} {}".format(key, val)) log_config_to_file(cfg, logger=logger) if cfg.LOCAL_RANK == 0: os.system("cp %s %s" % (args.cfg_file, output_dir)) tb_log = ( SummaryWriter(log_dir=str(output_dir / "tensorboard")) if cfg.LOCAL_RANK == 0 else None ) # -----------------------create dataloader & network & optimizer--------------------------- # Source loader if "DATA_CONFIG_SRC_WAYMO" in cfg and "DATA_CONFIG_SRC_NUSCENES" in cfg: source_set, source_loader, source_sampler = build_wayscenes_dataloader( waymo_cfg=cfg.DATA_CONFIG_SRC_WAYMO, nuscenes_cfg=cfg.DATA_CONFIG_SRC_NUSCENES, batch_size=args.batch_size, dist=dist_train, workers=args.workers, logger=logger, training=True, merge_all_iters_to_one_epoch=args.merge_all_iters_to_one_epoch, total_epochs=args.epochs, ) else: source_set, source_loader, source_sampler = build_dataloader( dataset_cfg=cfg.DATA_CONFIG, class_names=cfg.CLASS_NAMES, batch_size=args.batch_size, dist=dist_train, workers=args.workers, logger=logger, training=True, merge_all_iters_to_one_epoch=args.merge_all_iters_to_one_epoch, total_epochs=args.epochs, ) # Target loader if cfg.get("SELF_TRAIN", None): target_set, target_loader, target_sampler = build_dataloader( cfg.DATA_CONFIG_TAR, cfg.DATA_CONFIG_TAR.CLASS_NAMES, args.batch_size, dist_train, workers=args.workers, logger=logger, training=True, ) else: target_set = target_loader = target_sampler = None # Test loader if args.skip_test: test_loader = None else: if cfg.get("DATA_CONFIG_TAR", None): # For simplicity, test data loader and eval are always single GPU # If the test dataset is KITTI, set DATA_CONFIG_TAR.FOV_POINTS_ONLY True if cfg.DATA_CONFIG_TAR.DATASET == "KittiDataset": cfg.DATA_CONFIG_TAR.FOV_POINTS_ONLY = True print("Set FOV_POINTS_ONLY to True for KITTI test dataset") test_set, test_loader, sampler = build_dataloader( dataset_cfg=cfg.DATA_CONFIG_TAR, class_names=cfg.DATA_CONFIG_TAR.CLASS_NAMES, batch_size=args.batch_size, dist=False, workers=args.workers, logger=logger, training=False, ) else: raise NotImplementedError("No test dataset is provided in config.") model = build_network( model_cfg=cfg.MODEL, num_class=len(cfg.CLASS_NAMES), dataset=source_set ) if args.sync_bn: model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model) elif cfg.get("SELF_TRAIN", None) and cfg.SELF_TRAIN.get("DSNORM", None): model = DSNorm.convert_dsnorm(model) model.cuda() optimizer = build_optimizer(model, cfg.OPTIMIZATION) # load checkpoint if it is possible start_epoch = it = 0 last_epoch = -1 if args.pretrained_model is not None: model.load_params_from_file( filename=args.pretrained_model, to_cpu=dist, logger=logger ) if args.ckpt is not None: it, start_epoch = model.load_params_with_optimizer( args.ckpt, to_cpu=dist, optimizer=optimizer, logger=logger ) last_epoch = start_epoch + 1 else: ckpt_list = glob.glob(str(ckpt_dir / "*checkpoint_epoch_*.pth")) if len(ckpt_list) > 0: ckpt_list.sort(key=os.path.getmtime) it, start_epoch = model.load_params_with_optimizer( ckpt_list[-1], to_cpu=dist, optimizer=optimizer, logger=logger ) last_epoch = start_epoch + 1 model.train() # before wrap to DistributedDataParallel to support fixed some parameters if dist_train: model = nn.parallel.DistributedDataParallel( model, device_ids=[cfg.LOCAL_RANK % torch.cuda.device_count()] ) logger.info(model) if cfg.get("SELF_TRAIN", None): total_iters_each_epoch = ( len(target_loader) if not args.merge_all_iters_to_one_epoch else len(target_loader) // args.epochs ) else: total_iters_each_epoch = ( len(source_loader) if not args.merge_all_iters_to_one_epoch else len(source_loader) // args.epochs ) lr_scheduler, lr_warmup_scheduler = build_scheduler( optimizer, total_iters_each_epoch=total_iters_each_epoch, total_epochs=args.epochs, last_epoch=last_epoch, optim_cfg=cfg.OPTIMIZATION, ) # select proper trainer train_func = train_model_st if cfg.get("SELF_TRAIN", None) else train_model # -----------------------start training--------------------------- logger.info( "**********************Start training %s/%s(%s)**********************" % (cfg.EXP_GROUP_PATH, cfg.TAG, args.extra_tag) ) cmd_args_str = " ".join(sys.argv) train_func( model, optimizer, source_loader, target_loader, test_loader, model_func=model_fn_decorator(), lr_scheduler=lr_scheduler, optim_cfg=cfg.OPTIMIZATION, start_epoch=start_epoch, total_epochs=args.epochs, start_iter=it, rank=cfg.LOCAL_RANK, tb_log=tb_log, ckpt_save_dir=ckpt_dir, ps_label_dir=ps_label_dir, source_sampler=source_sampler, target_sampler=target_sampler, lr_warmup_scheduler=lr_warmup_scheduler, ckpt_save_interval=args.ckpt_save_interval, max_ckpt_save_num=args.max_ckpt_save_num, merge_all_iters_to_one_epoch=args.merge_all_iters_to_one_epoch, logger=logger, ema_model=None, cfg=cfg, cmd_args_str=cmd_args_str, ) logger.info( "**********************End training %s/%s(%s)**********************\n\n\n" % (cfg.EXP_GROUP_PATH, cfg.TAG, args.extra_tag) ) if __name__ == "__main__": main()
yxlao/lit
24
(NeurIPS 2024) LiT: Unifying LiDAR "Languages" with LiDAR Translator
Python
yxlao
Yixing Lao
HKU-CS
tools/train_utils/optimization/__init__.py
Python
from functools import partial import torch.nn as nn import torch.optim as optim import torch.optim.lr_scheduler as lr_sched from .fastai_optim import OptimWrapper from .learning_schedules_fastai import CosineWarmupLR, OneCycle def build_optimizer(model, optim_cfg): if optim_cfg.OPTIMIZER == "adam": optimizer = optim.Adam( model.parameters(), lr=optim_cfg.LR, weight_decay=optim_cfg.WEIGHT_DECAY ) elif optim_cfg.OPTIMIZER == "sgd": optimizer = optim.SGD( model.parameters(), lr=optim_cfg.LR, weight_decay=optim_cfg.WEIGHT_DECAY, momentum=optim_cfg.MOMENTUM, ) elif optim_cfg.OPTIMIZER == "adam_onecycle": def children(m: nn.Module): return list(m.children()) def num_children(m: nn.Module) -> int: return len(children(m)) flatten_model = lambda m: ( sum(map(flatten_model, m.children()), []) if num_children(m) else [m] ) get_layer_groups = lambda m: [nn.Sequential(*flatten_model(m))] optimizer_func = partial(optim.Adam, betas=(0.9, 0.99)) optimizer = OptimWrapper.create( optimizer_func, 3e-3, get_layer_groups(model), wd=optim_cfg.WEIGHT_DECAY, true_wd=True, bn_wd=True, ) else: raise NotImplementedError return optimizer def build_scheduler( optimizer, total_iters_each_epoch, total_epochs, last_epoch, optim_cfg ): decay_steps = [x * total_iters_each_epoch for x in optim_cfg.DECAY_STEP_LIST] def lr_lbmd(cur_epoch): cur_decay = 1 for decay_step in decay_steps: if cur_epoch >= decay_step: cur_decay = cur_decay * optim_cfg.LR_DECAY return max(cur_decay, optim_cfg.LR_CLIP / optim_cfg.LR) lr_warmup_scheduler = None total_steps = total_iters_each_epoch * total_epochs if optim_cfg.OPTIMIZER == "adam_onecycle": lr_scheduler = OneCycle( optimizer, total_steps, optim_cfg.LR, list(optim_cfg.MOMS), optim_cfg.DIV_FACTOR, optim_cfg.PCT_START, ) else: lr_scheduler = lr_sched.LambdaLR(optimizer, lr_lbmd, last_epoch=last_epoch) if optim_cfg.LR_WARMUP: lr_warmup_scheduler = CosineWarmupLR( optimizer, T_max=optim_cfg.WARMUP_EPOCH * len(total_iters_each_epoch), eta_min=optim_cfg.LR / optim_cfg.DIV_FACTOR, ) return lr_scheduler, lr_warmup_scheduler
yxlao/lit
24
(NeurIPS 2024) LiT: Unifying LiDAR "Languages" with LiDAR Translator
Python
yxlao
Yixing Lao
HKU-CS
tools/train_utils/optimization/fastai_optim.py
Python
# This file is modified from https://github.com/traveller59/second.pytorch from collections import Iterable import torch from torch import nn from torch._utils import _unflatten_dense_tensors from torch.nn.utils import parameters_to_vector bn_types = (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d, nn.SyncBatchNorm) def split_bn_bias(layer_groups): "Split the layers in `layer_groups` into batchnorm (`bn_types`) and non-batchnorm groups." split_groups = [] for l in layer_groups: l1, l2 = [], [] for c in l.children(): if isinstance(c, bn_types): l2.append(c) else: l1.append(c) split_groups += [nn.Sequential(*l1), nn.Sequential(*l2)] return split_groups def get_master(layer_groups, flat_master: bool = False): "Return two lists, one for the model parameters in FP16 and one for the master parameters in FP32." split_groups = split_bn_bias(layer_groups) model_params = [ [param for param in lg.parameters() if param.requires_grad] for lg in split_groups ] if flat_master: master_params = [] for lg in model_params: if len(lg) != 0: mp = parameters_to_vector([param.data.float() for param in lg]) mp = torch.nn.Parameter(mp, requires_grad=True) if mp.grad is None: mp.grad = mp.new(*mp.size()) master_params.append([mp]) else: master_params.append([]) return model_params, master_params else: master_params = [ [param.clone().float().detach() for param in lg] for lg in model_params ] for mp in master_params: for param in mp: param.requires_grad = True return model_params, master_params def model_g2master_g(model_params, master_params, flat_master: bool = False) -> None: "Copy the `model_params` gradients to `master_params` for the optimizer step." if flat_master: for model_group, master_group in zip(model_params, master_params): if len(master_group) != 0: master_group[0].grad.data.copy_( parameters_to_vector([p.grad.data.float() for p in model_group]) ) else: for model_group, master_group in zip(model_params, master_params): for model, master in zip(model_group, master_group): if model.grad is not None: if master.grad is None: master.grad = master.data.new(*master.data.size()) master.grad.data.copy_(model.grad.data) else: master.grad = None def master2model(model_params, master_params, flat_master: bool = False) -> None: "Copy `master_params` to `model_params`." if flat_master: for model_group, master_group in zip(model_params, master_params): if len(model_group) != 0: for model, master in zip( model_group, _unflatten_dense_tensors(master_group[0].data, model_group), ): model.data.copy_(master) else: for model_group, master_group in zip(model_params, master_params): for model, master in zip(model_group, master_group): model.data.copy_(master.data) def listify(p=None, q=None): "Make `p` listy and the same length as `q`." if p is None: p = [] elif isinstance(p, str): p = [p] elif not isinstance(p, Iterable): p = [p] n = q if type(q) == int else len(p) if q is None else len(q) if len(p) == 1: p = p * n assert len(p) == n, f"List len mismatch ({len(p)} vs {n})" return list(p) def trainable_params(m: nn.Module): "Return list of trainable params in `m`." res = filter(lambda p: p.requires_grad, m.parameters()) return res def is_tuple(x) -> bool: return isinstance(x, tuple) # copy from fastai. class OptimWrapper: "Basic wrapper around `opt` to simplify hyper-parameters changes." def __init__(self, opt, wd, true_wd: bool = False, bn_wd: bool = True): self.opt, self.true_wd, self.bn_wd = opt, true_wd, bn_wd self.opt_keys = list(self.opt.param_groups[0].keys()) self.opt_keys.remove("params") self.read_defaults() self.wd = wd @classmethod def create(cls, opt_func, lr, layer_groups, **kwargs): "Create an `optim.Optimizer` from `opt_func` with `lr`. Set lr on `layer_groups`." split_groups = split_bn_bias(layer_groups) opt = opt_func([{"params": trainable_params(l), "lr": 0} for l in split_groups]) opt = cls(opt, **kwargs) opt.lr, opt.opt_func = listify(lr, layer_groups), opt_func return opt def new(self, layer_groups): "Create a new `OptimWrapper` from `self` with another `layer_groups` but the same hyper-parameters." opt_func = getattr(self, "opt_func", self.opt.__class__) split_groups = split_bn_bias(layer_groups) opt = opt_func([{"params": trainable_params(l), "lr": 0} for l in split_groups]) return self.create( opt_func, self.lr, layer_groups, wd=self.wd, true_wd=self.true_wd, bn_wd=self.bn_wd, ) def __repr__(self) -> str: return f"OptimWrapper over {repr(self.opt)}.\nTrue weight decay: {self.true_wd}" # Pytorch optimizer methods def step(self) -> None: "Set weight decay and step optimizer." # weight decay outside of optimizer step (AdamW) if self.true_wd: for lr, wd, pg1, pg2 in zip( self._lr, self._wd, self.opt.param_groups[::2], self.opt.param_groups[1::2], ): for p in pg1["params"]: # When some parameters are fixed: Shaoshuai Shi if p.requires_grad is False: continue p.data.mul_(1 - wd * lr) if self.bn_wd: for p in pg2["params"]: # When some parameters are fixed: Shaoshuai Shi if p.requires_grad is False: continue p.data.mul_(1 - wd * lr) self.set_val("weight_decay", listify(0, self._wd)) self.opt.step() def zero_grad(self) -> None: "Clear optimizer gradients." self.opt.zero_grad() # Passthrough to the inner opt. def __getattr__(self, k: str): return getattr(self.opt, k, None) def clear(self): "Reset the state of the inner optimizer." sd = self.state_dict() sd["state"] = {} self.load_state_dict(sd) # Hyperparameters as properties @property def lr(self) -> float: return self._lr[-1] @lr.setter def lr(self, val: float) -> None: self._lr = self.set_val("lr", listify(val, self._lr)) @property def mom(self) -> float: return self._mom[-1] @mom.setter def mom(self, val: float) -> None: if "momentum" in self.opt_keys: self.set_val("momentum", listify(val, self._mom)) elif "betas" in self.opt_keys: self.set_val("betas", (listify(val, self._mom), self._beta)) self._mom = listify(val, self._mom) @property def beta(self) -> float: return None if self._beta is None else self._beta[-1] @beta.setter def beta(self, val: float) -> None: "Set beta (or alpha as makes sense for given optimizer)." if val is None: return if "betas" in self.opt_keys: self.set_val("betas", (self._mom, listify(val, self._beta))) elif "alpha" in self.opt_keys: self.set_val("alpha", listify(val, self._beta)) self._beta = listify(val, self._beta) @property def wd(self) -> float: return self._wd[-1] @wd.setter def wd(self, val: float) -> None: "Set weight decay." if not self.true_wd: self.set_val("weight_decay", listify(val, self._wd), bn_groups=self.bn_wd) self._wd = listify(val, self._wd) # Helper functions def read_defaults(self) -> None: "Read the values inside the optimizer for the hyper-parameters." self._beta = None if "lr" in self.opt_keys: self._lr = self.read_val("lr") if "momentum" in self.opt_keys: self._mom = self.read_val("momentum") if "alpha" in self.opt_keys: self._beta = self.read_val("alpha") if "betas" in self.opt_keys: self._mom, self._beta = self.read_val("betas") if "weight_decay" in self.opt_keys: self._wd = self.read_val("weight_decay") def set_val(self, key: str, val, bn_groups: bool = True): "Set `val` inside the optimizer dictionary at `key`." if is_tuple(val): val = [(v1, v2) for v1, v2 in zip(*val)] for v, pg1, pg2 in zip( val, self.opt.param_groups[::2], self.opt.param_groups[1::2] ): pg1[key] = v if bn_groups: pg2[key] = v return val def read_val(self, key: str): "Read a hyperparameter `key` in the optimizer dictionary." val = [pg[key] for pg in self.opt.param_groups[::2]] if is_tuple(val[0]): val = [o[0] for o in val], [o[1] for o in val] return val class FastAIMixedOptim(OptimWrapper): @classmethod def create( cls, opt_func, lr, layer_groups, model, flat_master=False, loss_scale=512.0, **kwargs, ): "Create an `optim.Optimizer` from `opt_func` with `lr`. Set lr on `layer_groups`." opt = OptimWrapper.create(opt_func, lr, layer_groups, **kwargs) opt.model_params, opt.master_params = get_master(layer_groups, flat_master) opt.flat_master = flat_master opt.loss_scale = loss_scale opt.model = model # Changes the optimizer so that the optimization step is done in FP32. # opt = self.learn.opt mom, wd, beta = opt.mom, opt.wd, opt.beta lrs = [lr for lr in opt._lr for _ in range(2)] opt_params = [ {"params": mp, "lr": lr} for mp, lr in zip(opt.master_params, lrs) ] opt.opt = opt_func(opt_params) opt.mom, opt.wd, opt.beta = mom, wd, beta return opt def step(self): model_g2master_g(self.model_params, self.master_params, self.flat_master) for group in self.master_params: for param in group: param.grad.div_(self.loss_scale) super(FastAIMixedOptim, self).step() self.model.zero_grad() # Update the params from master to model. master2model(self.model_params, self.master_params, self.flat_master)
yxlao/lit
24
(NeurIPS 2024) LiT: Unifying LiDAR "Languages" with LiDAR Translator
Python
yxlao
Yixing Lao
HKU-CS
tools/train_utils/optimization/learning_schedules_fastai.py
Python
# This file is modified from https://github.com/traveller59/second.pytorch import math from functools import partial import numpy as np import torch.optim.lr_scheduler as lr_sched from .fastai_optim import OptimWrapper class LRSchedulerStep(object): def __init__(self, fai_optimizer: OptimWrapper, total_step, lr_phases, mom_phases): # if not isinstance(fai_optimizer, OptimWrapper): # raise TypeError('{} is not a fastai OptimWrapper'.format( # type(fai_optimizer).__name__)) self.optimizer = fai_optimizer self.total_step = total_step self.lr_phases = [] for i, (start, lambda_func) in enumerate(lr_phases): if len(self.lr_phases) != 0: assert self.lr_phases[-1][0] < start if isinstance(lambda_func, str): lambda_func = eval(lambda_func) if i < len(lr_phases) - 1: self.lr_phases.append( ( int(start * total_step), int(lr_phases[i + 1][0] * total_step), lambda_func, ) ) else: self.lr_phases.append( (int(start * total_step), total_step, lambda_func) ) assert self.lr_phases[0][0] == 0 self.mom_phases = [] for i, (start, lambda_func) in enumerate(mom_phases): if len(self.mom_phases) != 0: assert self.mom_phases[-1][0] < start if isinstance(lambda_func, str): lambda_func = eval(lambda_func) if i < len(mom_phases) - 1: self.mom_phases.append( ( int(start * total_step), int(mom_phases[i + 1][0] * total_step), lambda_func, ) ) else: self.mom_phases.append( (int(start * total_step), total_step, lambda_func) ) assert self.mom_phases[0][0] == 0 def step(self, step): for start, end, func in self.lr_phases: if step >= start: self.optimizer.lr = func((step - start) / (end - start)) for start, end, func in self.mom_phases: if step >= start: self.optimizer.mom = func((step - start) / (end - start)) def annealing_cos(start, end, pct): # print(pct, start, end) "Cosine anneal from `start` to `end` as pct goes from 0.0 to 1.0." cos_out = np.cos(np.pi * pct) + 1 return end + (start - end) / 2 * cos_out class OneCycle(LRSchedulerStep): def __init__(self, fai_optimizer, total_step, lr_max, moms, div_factor, pct_start): self.lr_max = lr_max self.moms = moms self.div_factor = div_factor self.pct_start = pct_start a1 = int(total_step * self.pct_start) a2 = total_step - a1 low_lr = self.lr_max / self.div_factor lr_phases = ( (0, partial(annealing_cos, low_lr, self.lr_max)), (self.pct_start, partial(annealing_cos, self.lr_max, low_lr / 1e4)), ) mom_phases = ( (0, partial(annealing_cos, *self.moms)), (self.pct_start, partial(annealing_cos, *self.moms[::-1])), ) fai_optimizer.lr, fai_optimizer.mom = low_lr, self.moms[0] super().__init__(fai_optimizer, total_step, lr_phases, mom_phases) class CosineWarmupLR(lr_sched._LRScheduler): def __init__(self, optimizer, T_max, eta_min=0, last_epoch=-1): self.T_max = T_max self.eta_min = eta_min super(CosineWarmupLR, self).__init__(optimizer, last_epoch) def get_lr(self): return [ self.eta_min + (base_lr - self.eta_min) * (1 - math.cos(math.pi * self.last_epoch / self.T_max)) / 2 for base_lr in self.base_lrs ] class FakeOptim: def __init__(self): self.lr = 0 self.mom = 0 if __name__ == "__main__": import matplotlib.pyplot as plt opt = FakeOptim() # 3e-3, wd=0.4, div_factor=10 schd = OneCycle(opt, 100, 3e-3, (0.95, 0.85), 10.0, 0.1) lrs = [] moms = [] for i in range(100): schd.step(i) lrs.append(opt.lr) moms.append(opt.mom) plt.plot(lrs) # plt.plot(moms) plt.show() plt.plot(moms) plt.show()
yxlao/lit
24
(NeurIPS 2024) LiT: Unifying LiDAR "Languages" with LiDAR Translator
Python
yxlao
Yixing Lao
HKU-CS
tools/train_utils/train_st_utils.py
Python
import glob import os import torch import tqdm from torch.nn.utils import clip_grad_norm_ from pcdet.config import cfg from pcdet.models.model_utils.dsnorm import set_ds_source, set_ds_target from pcdet.utils import common_utils, self_training_utils from .train_utils import checkpoint_state, save_checkpoint def train_one_epoch_st( model, optimizer, source_reader, target_loader, model_func, lr_scheduler, accumulated_iter, optim_cfg, rank, tbar, total_it_each_epoch, dataloader_iter, tb_log=None, leave_pbar=False, ema_model=None, cur_epoch=None, ): if total_it_each_epoch == len(target_loader): dataloader_iter = iter(target_loader) if rank == 0: pbar = tqdm.tqdm( total=total_it_each_epoch, leave=leave_pbar, desc="train", dynamic_ncols=True, ) ps_bbox_nmeter = common_utils.NAverageMeter(len(cfg.CLASS_NAMES)) ign_ps_bbox_nmeter = common_utils.NAverageMeter(len(cfg.CLASS_NAMES)) loss_meter = common_utils.AverageMeter() st_loss_meter = common_utils.AverageMeter() disp_dict = {} for cur_it in range(total_it_each_epoch): lr_scheduler.step(accumulated_iter) try: cur_lr = float(optimizer.lr) except: cur_lr = optimizer.param_groups[0]["lr"] if tb_log is not None: tb_log.add_scalar("meta_data/learning_rate", cur_lr, accumulated_iter) model.train() optimizer.zero_grad() if cfg.SELF_TRAIN.SRC.USE_DATA: # forward source data with labels source_batch = source_reader.read_data() if cfg.SELF_TRAIN.get("DSNORM", None): model.apply(set_ds_source) loss, tb_dict, disp_dict = model_func(model, source_batch) loss = cfg.SELF_TRAIN.SRC.get("LOSS_WEIGHT", 1.0) * loss loss.backward() loss_meter.update(loss.item()) disp_dict.update( {"loss": "{:.3f}({:.3f})".format(loss_meter.val, loss_meter.avg)} ) if not cfg.SELF_TRAIN.SRC.get("USE_GRAD", None): optimizer.zero_grad() if cfg.SELF_TRAIN.TAR.USE_DATA: try: target_batch = next(dataloader_iter) except StopIteration: dataloader_iter = iter(target_loader) target_batch = next(dataloader_iter) print("new iters") if cfg.SELF_TRAIN.get("DSNORM", None): model.apply(set_ds_target) # parameters for save pseudo label on the fly st_loss, st_tb_dict, st_disp_dict = model_func(model, target_batch) st_loss = cfg.SELF_TRAIN.TAR.get("LOSS_WEIGHT", 1.0) * st_loss st_loss.backward() st_loss_meter.update(st_loss.item()) # count number of used ps bboxes in this batch pos_pseudo_bbox = target_batch["pos_ps_bbox"].mean(dim=0).cpu().numpy() ign_pseudo_bbox = target_batch["ign_ps_bbox"].mean(dim=0).cpu().numpy() ps_bbox_nmeter.update(pos_pseudo_bbox.tolist()) ign_ps_bbox_nmeter.update(ign_pseudo_bbox.tolist()) pos_ps_result = ps_bbox_nmeter.aggregate_result() ign_ps_result = ign_ps_bbox_nmeter.aggregate_result() st_tb_dict = common_utils.add_prefix_to_dict(st_tb_dict, "st_") disp_dict.update(common_utils.add_prefix_to_dict(st_disp_dict, "st_")) disp_dict.update( { "st_loss": "{:.3f}({:.3f})".format( st_loss_meter.val, st_loss_meter.avg ), "pos_ps_box": pos_ps_result, "ign_ps_box": ign_ps_result, } ) clip_grad_norm_(model.parameters(), optim_cfg.GRAD_NORM_CLIP) optimizer.step() accumulated_iter += 1 # log to console and tensorboard if rank == 0: pbar.update() pbar.set_postfix( dict( total_it=accumulated_iter, pos_ps_box=pos_ps_result, ign_ps_box=ign_ps_result, ) ) tbar.set_postfix(disp_dict) tbar.refresh() if tb_log is not None: tb_log.add_scalar("meta_data/learning_rate", cur_lr, accumulated_iter) if cfg.SELF_TRAIN.SRC.USE_DATA: tb_log.add_scalar("train/loss", loss, accumulated_iter) for key, val in tb_dict.items(): tb_log.add_scalar("train/" + key, val, accumulated_iter) if cfg.SELF_TRAIN.TAR.USE_DATA: tb_log.add_scalar("train/st_loss", st_loss, accumulated_iter) for key, val in st_tb_dict.items(): tb_log.add_scalar("train/" + key, val, accumulated_iter) if rank == 0: pbar.close() for i, class_names in enumerate(target_loader.dataset.class_names): tb_log.add_scalar( "ps_box/pos_%s" % class_names, ps_bbox_nmeter.meters[i].avg, cur_epoch ) tb_log.add_scalar( "ps_box/ign_%s" % class_names, ign_ps_bbox_nmeter.meters[i].avg, cur_epoch, ) return accumulated_iter def train_model_st( model, optimizer, source_loader, target_loader, test_loader, model_func, lr_scheduler, optim_cfg, start_epoch, total_epochs, start_iter, rank, tb_log, ckpt_save_dir, ps_label_dir, source_sampler=None, target_sampler=None, lr_warmup_scheduler=None, ckpt_save_interval=1, max_ckpt_save_num=50, merge_all_iters_to_one_epoch=False, logger=None, ema_model=None, cfg=None, cmd_args_str=None, # For logging ): accumulated_iter = start_iter source_reader = common_utils.DataReader(source_loader, source_sampler) source_reader.construct_iter() # for continue training. # if already exist generated pseudo label result ps_pkl = self_training_utils.check_already_exsit_pseudo_label( ps_label_dir, start_epoch ) if ps_pkl is not None: logger.info("==> Loading pseudo labels from {}".format(ps_pkl)) # for continue training if ( cfg.SELF_TRAIN.get("PROG_AUG", None) and cfg.SELF_TRAIN.PROG_AUG.ENABLED and start_epoch > 0 ): for cur_epoch in range(start_epoch): if cur_epoch in cfg.SELF_TRAIN.PROG_AUG.UPDATE_AUG: target_loader.dataset.data_augmentor.re_prepare( augmentor_configs=None, intensity=cfg.SELF_TRAIN.PROG_AUG.SCALE ) with tqdm.trange( start_epoch, total_epochs, desc="epochs", dynamic_ncols=True, leave=(rank == 0) ) as tbar: total_it_each_epoch = len(target_loader) if merge_all_iters_to_one_epoch: assert hasattr(target_loader.dataset, "merge_all_iters_to_one_epoch") target_loader.dataset.merge_all_iters_to_one_epoch( merge=True, epochs=total_epochs ) total_it_each_epoch = len(target_loader) // max(total_epochs, 1) dataloader_iter = iter(target_loader) for cur_epoch in tbar: if target_sampler is not None: target_sampler.set_epoch(cur_epoch) source_reader.set_cur_epoch(cur_epoch) # train one epoch if lr_warmup_scheduler is not None and cur_epoch < optim_cfg.WARMUP_EPOCH: cur_scheduler = lr_warmup_scheduler else: cur_scheduler = lr_scheduler # update pseudo label if (cur_epoch in cfg.SELF_TRAIN.UPDATE_PSEUDO_LABEL) or ( (cur_epoch % cfg.SELF_TRAIN.UPDATE_PSEUDO_LABEL_INTERVAL == 0) and cur_epoch != 0 ): target_loader.dataset.eval() self_training_utils.save_pseudo_label_epoch( model, target_loader, rank, leave_pbar=True, ps_label_dir=ps_label_dir, cur_epoch=cur_epoch, ) target_loader.dataset.train() # curriculum data augmentation if ( cfg.SELF_TRAIN.get("PROG_AUG", None) and cfg.SELF_TRAIN.PROG_AUG.ENABLED and (cur_epoch in cfg.SELF_TRAIN.PROG_AUG.UPDATE_AUG) ): target_loader.dataset.data_augmentor.re_prepare( augmentor_configs=None, intensity=cfg.SELF_TRAIN.PROG_AUG.SCALE ) accumulated_iter = train_one_epoch_st( model, optimizer, source_reader, target_loader, model_func, lr_scheduler=cur_scheduler, accumulated_iter=accumulated_iter, optim_cfg=optim_cfg, rank=rank, tbar=tbar, tb_log=tb_log, leave_pbar=(cur_epoch + 1 == total_epochs), total_it_each_epoch=total_it_each_epoch, dataloader_iter=dataloader_iter, ema_model=ema_model, cur_epoch=cur_epoch, ) # save trained model trained_epoch = cur_epoch + 1 if trained_epoch % ckpt_save_interval == 0 and rank == 0: ckpt_list = glob.glob(str(ckpt_save_dir / "checkpoint_epoch_*.pth")) ckpt_list.sort(key=os.path.getmtime) if ckpt_list.__len__() >= max_ckpt_save_num: for cur_file_idx in range( 0, len(ckpt_list) - max_ckpt_save_num + 1 ): os.remove(ckpt_list[cur_file_idx]) ckpt_name = ckpt_save_dir / ("checkpoint_epoch_%d" % trained_epoch) state = checkpoint_state( model, optimizer, trained_epoch, accumulated_iter ) save_checkpoint(state, filename=ckpt_name)
yxlao/lit
24
(NeurIPS 2024) LiT: Unifying LiDAR "Languages" with LiDAR Translator
Python
yxlao
Yixing Lao
HKU-CS
tools/train_utils/train_utils.py
Python
import glob import os import sys import tempfile from pathlib import Path import numpy as np import open3d as o3d import torch import tqdm from torch.nn.utils import clip_grad_norm_ from lit.recon_utils import bboxes_to_lineset _script_dir = Path(__file__).resolve().parent _lit_root = _script_dir.parent.parent _tools_dir = _lit_root / "tools" sys.path.append(str(_tools_dir)) from test import eval_single_ckpt from eval_utils import eval_utils def train_one_epoch( model, optimizer, train_loader, model_func, lr_scheduler, accumulated_iter, optim_cfg, rank, tbar, total_it_each_epoch, dataloader_iter, tb_log=None, leave_pbar=False, ): if total_it_each_epoch == len(train_loader): dataloader_iter = iter(train_loader) if rank == 0: pbar = tqdm.tqdm( total=total_it_each_epoch, leave=leave_pbar, desc="train", dynamic_ncols=True, ) for cur_it in range(total_it_each_epoch): try: batch = next(dataloader_iter) except StopIteration: dataloader_iter = iter(train_loader) batch = next(dataloader_iter) print("new iters") lr_scheduler.step(accumulated_iter) try: cur_lr = float(optimizer.lr) except: cur_lr = optimizer.param_groups[0]["lr"] if tb_log is not None: tb_log.add_scalar("meta_data/learning_rate", cur_lr, accumulated_iter) model.train() optimizer.zero_grad() visualize = False if visualize: points = batch["points"][:, 1:4] pcd = o3d.geometry.PointCloud() pcd.points = o3d.utility.Vector3dVector(points) gt_boxes = batch["gt_boxes"][0] gt_ls = bboxes_to_lineset(gt_boxes, frame_pose=np.eye(4)) gt_ls.paint_uniform_color([0, 0, 1]) axes = o3d.geometry.TriangleMesh.create_coordinate_frame(size=1) o3d.visualization.draw_geometries([pcd, gt_ls, axes]) loss, tb_dict, disp_dict = model_func(model, batch) loss.backward() clip_grad_norm_(model.parameters(), optim_cfg.GRAD_NORM_CLIP) optimizer.step() accumulated_iter += 1 disp_dict.update({"loss": loss.item(), "lr": cur_lr}) # log to console and tensorboard if rank == 0: pbar.update() pbar.set_postfix(dict(total_it=accumulated_iter)) tbar.set_postfix(disp_dict) tbar.refresh() if tb_log is not None: tb_log.add_scalar("train/loss", loss, accumulated_iter) tb_log.add_scalar("meta_data/learning_rate", cur_lr, accumulated_iter) for key, val in tb_dict.items(): tb_log.add_scalar("train/" + key, val, accumulated_iter) if rank == 0: pbar.close() return accumulated_iter def train_model( model, optimizer, train_loader, target_loader, test_loader, model_func, lr_scheduler, optim_cfg, start_epoch, total_epochs, start_iter, rank, tb_log, ckpt_save_dir, ps_label_dir, source_sampler=None, target_sampler=None, lr_warmup_scheduler=None, ckpt_save_interval=1, max_ckpt_save_num=50, merge_all_iters_to_one_epoch=False, logger=None, ema_model=None, cfg=None, cmd_args_str=None, # For logging ): accumulated_iter = start_iter with tqdm.trange( start_epoch, total_epochs, desc="epochs", dynamic_ncols=True, leave=(rank == 0), ) as tbar: total_it_each_epoch = len(train_loader) if merge_all_iters_to_one_epoch: assert hasattr(train_loader.dataset, "merge_all_iters_to_one_epoch") train_loader.dataset.merge_all_iters_to_one_epoch( merge=True, epochs=total_epochs ) total_it_each_epoch = len(train_loader) // max(total_epochs, 1) dataloader_iter = iter(train_loader) for cur_epoch in tbar: if source_sampler is not None: source_sampler.set_epoch(cur_epoch) # train one epoch if lr_warmup_scheduler is not None and cur_epoch < optim_cfg.WARMUP_EPOCH: cur_scheduler = lr_warmup_scheduler else: cur_scheduler = lr_scheduler accumulated_iter = train_one_epoch( model, optimizer, train_loader, model_func, lr_scheduler=cur_scheduler, accumulated_iter=accumulated_iter, optim_cfg=optim_cfg, rank=rank, tbar=tbar, tb_log=tb_log, leave_pbar=(cur_epoch + 1 == total_epochs), total_it_each_epoch=total_it_each_epoch, dataloader_iter=dataloader_iter, ) # save trained model trained_epoch = cur_epoch + 1 if trained_epoch % ckpt_save_interval == 0 and rank == 0: # Save ckpt (unchanged) ckpt_list = glob.glob(str(ckpt_save_dir / "checkpoint_epoch_*.pth")) ckpt_list.sort(key=os.path.getmtime) if ckpt_list.__len__() >= max_ckpt_save_num: for cur_file_idx in range( 0, len(ckpt_list) - max_ckpt_save_num + 1 ): os.remove(ckpt_list[cur_file_idx]) ckpt_path = ckpt_save_dir / ("checkpoint_epoch_%d" % trained_epoch) save_checkpoint( checkpoint_state(model, optimizer, trained_epoch, accumulated_iter), filename=ckpt_path, ) # For simplicity, test data loader and eval are always single GPU if test_loader is not None and rank == 0: assert cfg is not None, "cfg should be provided for evaluation" model.eval() with tempfile.TemporaryDirectory() as temp_eval_dir: temp_eval_dir = Path(temp_eval_dir) ret_dict, result_str = eval_utils.eval_one_epoch( cfg=cfg, # cfg.LOCAL_RANK, etc. model=model, dataloader=test_loader, epoch_id=trained_epoch, logger=logger, dist_test=False, result_dir=temp_eval_dir, save_to_file=False, # We only need the result_str args=None, # Not used. ) ckpt_dir = ckpt_path.parent metric_dir = ckpt_dir.parent / "metric" metric_path = metric_dir / f"{ckpt_path.stem}.txt" metric_dir.mkdir(parents=True, exist_ok=True) metric_path.parent.mkdir(parents=True, exist_ok=True) # Place cmd_args_str on top if cmd_args_str is not None: result_str = cmd_args_str + "\n" + result_str with open(metric_path, "w") as f: f.write(result_str) model.train() def model_state_to_cpu(model_state): model_state_cpu = type(model_state)() # ordered dict for key, val in model_state.items(): model_state_cpu[key] = val.cpu() return model_state_cpu def checkpoint_state(model=None, optimizer=None, epoch=None, it=None): optim_state = optimizer.state_dict() if optimizer is not None else None if model is not None: if isinstance(model, torch.nn.parallel.DistributedDataParallel): model_state = model_state_to_cpu(model.module.state_dict()) else: model_state = model.state_dict() else: model_state = None try: import pcdet version = "pcdet+" + pcdet.__version__ except: version = "none" return { "epoch": epoch, "it": it, "model_state": model_state, "optimizer_state": optim_state, "version": version, } def save_checkpoint(state, filename="checkpoint"): if False and "optimizer_state" in state: optimizer_state = state["optimizer_state"] state.pop("optimizer_state", None) optimizer_filename = "{}_optim.pth".format(filename) torch.save({"optimizer_state": optimizer_state}, optimizer_filename) filename = "{}.pth".format(filename) torch.save(state, filename)
yxlao/lit
24
(NeurIPS 2024) LiT: Unifying LiDAR "Languages" with LiDAR Translator
Python
yxlao
Yixing Lao
HKU-CS
tools/visual_utils/open3d_vis_utils.py
Python
""" Open3d visualization tool box Written by Jihan YANG All rights preserved from 2021 - present. """ import matplotlib import numpy as np import open3d import torch box_colormap = [ [1, 1, 1], [0, 1, 0], [0, 1, 1], [1, 1, 0], ] def get_coor_colors(obj_labels): """ Args: obj_labels: 1 is ground, labels > 1 indicates different instance cluster Returns: rgb: [N, 3]. color for each point. """ colors = matplotlib.colors.XKCD_COLORS.values() max_color_num = obj_labels.max() color_list = list(colors)[: max_color_num + 1] colors_rgba = [matplotlib.colors.to_rgba_array(color) for color in color_list] label_rgba = np.array(colors_rgba)[obj_labels] label_rgba = label_rgba.squeeze()[:, :3] return label_rgba def draw_scenes( points, gt_boxes=None, ref_boxes=None, ref_labels=None, ref_scores=None, point_colors=None, draw_origin=True, white_background=True, src_points=None, vertices=None, triangles=None, rays_o=None, rays_d=None, rays_length=10, rays_subsample=0.01, ): if isinstance(points, torch.Tensor): points = points.cpu().numpy() if isinstance(gt_boxes, torch.Tensor): gt_boxes = gt_boxes.cpu().numpy() if isinstance(ref_boxes, torch.Tensor): ref_boxes = ref_boxes.cpu().numpy() vis = open3d.visualization.Visualizer() vis.create_window() vis.get_render_option().point_size = 1.0 if not white_background: vis.get_render_option().background_color = np.zeros(3) # draw origin if draw_origin: axis_pcd = open3d.geometry.TriangleMesh.create_coordinate_frame( size=5.0, origin=[0, 0, 0] ) vis.add_geometry(axis_pcd) pts = open3d.geometry.PointCloud() pts.points = open3d.utility.Vector3dVector(points[:, :3]) vis.add_geometry(pts) if point_colors is None: if white_background: pts.colors = open3d.utility.Vector3dVector(np.zeros((points.shape[0], 3))) else: pts.colors = open3d.utility.Vector3dVector(np.ones((points.shape[0], 3))) else: pts.colors = open3d.utility.Vector3dVector(point_colors) if gt_boxes is not None: vis = draw_box(vis, gt_boxes, (0, 0, 1)) if ref_boxes is not None: vis = draw_box(vis, ref_boxes, (0, 1, 0), ref_labels, ref_scores) # Draw src_points in red if src_points is not None: src_pts = open3d.geometry.PointCloud() src_pts.points = open3d.utility.Vector3dVector(src_points[:, :3]) src_pts.paint_uniform_color([1, 0, 0]) vis.add_geometry(src_pts) # Draw mesh if vertices is not None and triangles is not None: mesh = open3d.geometry.TriangleMesh( vertices=open3d.utility.Vector3dVector(vertices), triangles=open3d.utility.Vector3iVector(triangles), ) mesh.compute_vertex_normals() vis.add_geometry(mesh) # Draw rays as lineset if rays_o is not None and rays_d is not None: # Subsample rays num_rays = int(rays_o.shape[0] * rays_subsample) frame_indices = np.random.choice(rays_o.shape[0], num_rays, replace=False) rays_o = rays_o[frame_indices] rays_d = rays_d[frame_indices] rays_t = rays_o + rays_d * rays_length ls = open3d.geometry.LineSet() points = np.concatenate([rays_o, rays_t], axis=0) lines = np.array([[i, i + rays_o.shape[0]] for i in range(rays_o.shape[0])]) ls.points = open3d.utility.Vector3dVector(points) ls.lines = open3d.utility.Vector2iVector(lines) ls.colors = open3d.utility.Vector3dVector( np.tile([0, 0, 1], (rays_o.shape[0], 1)) ) vis.add_geometry(ls) vis.run() vis.destroy_window() def translate_boxes_to_open3d_instance(gt_boxes): """ 4-------- 6 /| /| 5 -------- 3 . | | | | . 7 -------- 1 |/ |/ 2 -------- 0 """ center = gt_boxes[0:3] lwh = gt_boxes[3:6] axis_angles = np.array([0, 0, gt_boxes[6] + 1e-10]) rot = open3d.geometry.get_rotation_matrix_from_axis_angle(axis_angles) box3d = open3d.geometry.OrientedBoundingBox(center, rot, lwh) line_set = open3d.geometry.LineSet.create_from_oriented_bounding_box(box3d) # import ipdb; ipdb.set_trace(context=20) lines = np.asarray(line_set.lines) lines = np.concatenate([lines, np.array([[1, 4], [7, 6]])], axis=0) line_set.lines = open3d.utility.Vector2iVector(lines) return line_set, box3d def draw_box(vis, gt_boxes, color=(0, 1, 0), ref_labels=None, score=None): for i in range(gt_boxes.shape[0]): line_set, box3d = translate_boxes_to_open3d_instance(gt_boxes[i]) if ref_labels is None: line_set.paint_uniform_color(color) else: line_set.paint_uniform_color(box_colormap[ref_labels[i]]) vis.add_geometry(line_set) # if score is not None: # corners = box3d.get_box_points() # vis.add_3d_label(corners[5], '%.2f' % score[i]) return vis
yxlao/lit
24
(NeurIPS 2024) LiT: Unifying LiDAR "Languages" with LiDAR Translator
Python
yxlao
Yixing Lao
HKU-CS
tools/visual_utils/visualize_utils.py
Python
import mayavi.mlab as mlab import numpy as np import torch box_colormap = [ [1, 1, 1], [0, 1, 0], [0, 1, 1], [1, 1, 0], ] def check_numpy_to_torch(x): if isinstance(x, np.ndarray): return torch.from_numpy(x).float(), True return x, False def rotate_points_along_z(points, angle): """ Args: points: (B, N, 3 + C) angle: (B), angle along z-axis, angle increases x ==> y Returns: """ points, is_numpy = check_numpy_to_torch(points) angle, _ = check_numpy_to_torch(angle) cosa = torch.cos(angle) sina = torch.sin(angle) zeros = angle.new_zeros(points.shape[0]) ones = angle.new_ones(points.shape[0]) rot_matrix = ( torch.stack((cosa, sina, zeros, -sina, cosa, zeros, zeros, zeros, ones), dim=1) .view(-1, 3, 3) .float() ) points_rot = torch.matmul(points[:, :, 0:3], rot_matrix) points_rot = torch.cat((points_rot, points[:, :, 3:]), dim=-1) return points_rot.numpy() if is_numpy else points_rot def boxes_to_corners_3d(boxes3d): """ 7 -------- 4 /| /| 6 -------- 5 . | | | | . 3 -------- 0 |/ |/ 2 -------- 1 Args: boxes3d: (N, 7) [x, y, z, dx, dy, dz, heading], (x, y, z) is the box center Returns: """ boxes3d, is_numpy = check_numpy_to_torch(boxes3d) template = ( boxes3d.new_tensor( ( [1, 1, -1], [1, -1, -1], [-1, -1, -1], [-1, 1, -1], [1, 1, 1], [1, -1, 1], [-1, -1, 1], [-1, 1, 1], ) ) / 2 ) corners3d = boxes3d[:, None, 3:6].repeat(1, 8, 1) * template[None, :, :] corners3d = rotate_points_along_z(corners3d.view(-1, 8, 3), boxes3d[:, 6]).view( -1, 8, 3 ) corners3d += boxes3d[:, None, 0:3] return corners3d.numpy() if is_numpy else corners3d def visualize_pts( pts, fig=None, bgcolor=(0, 0, 0), fgcolor=(1.0, 1.0, 1.0), show_intensity=False, size=(600, 600), draw_origin=True, ): if not isinstance(pts, np.ndarray): pts = pts.cpu().numpy() if fig is None: fig = mlab.figure( figure=None, bgcolor=bgcolor, fgcolor=fgcolor, engine=None, size=size ) if show_intensity: G = mlab.points3d( pts[:, 0], pts[:, 1], pts[:, 2], pts[:, 3], mode="point", colormap="gnuplot", scale_factor=1, figure=fig, ) else: G = mlab.points3d( pts[:, 0], pts[:, 1], pts[:, 2], mode="point", colormap="gnuplot", scale_factor=1, figure=fig, ) if draw_origin: mlab.points3d(0, 0, 0, color=(1, 1, 1), mode="cube", scale_factor=0.2) mlab.plot3d([0, 3], [0, 0], [0, 0], color=(0, 0, 1), tube_radius=0.1) mlab.plot3d([0, 0], [0, 3], [0, 0], color=(0, 1, 0), tube_radius=0.1) mlab.plot3d([0, 0], [0, 0], [0, 3], color=(1, 0, 0), tube_radius=0.1) return fig def draw_sphere_pts( pts, color=(0, 1, 0), fig=None, bgcolor=(0, 0, 0), scale_factor=0.2 ): if not isinstance(pts, np.ndarray): pts = pts.cpu().numpy() if fig is None: fig = mlab.figure( figure=None, bgcolor=bgcolor, fgcolor=None, engine=None, size=(600, 600) ) if isinstance(color, np.ndarray) and color.shape[0] == 1: color = color[0] color = (color[0] / 255.0, color[1] / 255.0, color[2] / 255.0) if isinstance(color, np.ndarray): pts_color = np.zeros((pts.__len__(), 4), dtype=np.uint8) pts_color[:, 0:3] = color pts_color[:, 3] = 255 G = mlab.points3d( pts[:, 0], pts[:, 1], pts[:, 2], np.arange(0, pts_color.__len__()), mode="sphere", scale_factor=scale_factor, figure=fig, ) G.glyph.color_mode = "color_by_scalar" G.glyph.scale_mode = "scale_by_vector" G.module_manager.scalar_lut_manager.lut.table = pts_color else: mlab.points3d( pts[:, 0], pts[:, 1], pts[:, 2], mode="sphere", color=color, colormap="gnuplot", scale_factor=scale_factor, figure=fig, ) mlab.points3d(0, 0, 0, color=(1, 1, 1), mode="cube", scale_factor=0.2) mlab.plot3d( [0, 3], [0, 0], [0, 0], color=(0, 0, 1), line_width=3, tube_radius=None, figure=fig, ) mlab.plot3d( [0, 0], [0, 3], [0, 0], color=(0, 1, 0), line_width=3, tube_radius=None, figure=fig, ) mlab.plot3d( [0, 0], [0, 0], [0, 3], color=(1, 0, 0), line_width=3, tube_radius=None, figure=fig, ) return fig def draw_grid(x1, y1, x2, y2, fig, tube_radius=None, color=(0.5, 0.5, 0.5)): mlab.plot3d( [x1, x1], [y1, y2], [0, 0], color=color, tube_radius=tube_radius, line_width=1, figure=fig, ) mlab.plot3d( [x2, x2], [y1, y2], [0, 0], color=color, tube_radius=tube_radius, line_width=1, figure=fig, ) mlab.plot3d( [x1, x2], [y1, y1], [0, 0], color=color, tube_radius=tube_radius, line_width=1, figure=fig, ) mlab.plot3d( [x1, x2], [y2, y2], [0, 0], color=color, tube_radius=tube_radius, line_width=1, figure=fig, ) return fig def draw_multi_grid_range(fig, grid_size=20, bv_range=(-60, -60, 60, 60)): for x in range(bv_range[0], bv_range[2], grid_size): for y in range(bv_range[1], bv_range[3], grid_size): fig = draw_grid(x, y, x + grid_size, y + grid_size, fig) return fig def draw_scenes( points, gt_boxes=None, ref_boxes=None, ref_scores=None, ref_labels=None ): if not isinstance(points, np.ndarray): points = points.cpu().numpy() if ref_boxes is not None and not isinstance(ref_boxes, np.ndarray): ref_boxes = ref_boxes.cpu().numpy() if gt_boxes is not None and not isinstance(gt_boxes, np.ndarray): gt_boxes = gt_boxes.cpu().numpy() if ref_scores is not None and not isinstance(ref_scores, np.ndarray): ref_scores = ref_scores.cpu().numpy() if ref_labels is not None and not isinstance(ref_labels, np.ndarray): ref_labels = ref_labels.cpu().numpy() fig = visualize_pts(points) fig = draw_multi_grid_range(fig, bv_range=(0, -40, 80, 40)) if gt_boxes is not None: corners3d = boxes_to_corners_3d(gt_boxes) fig = draw_corners3d(corners3d, fig=fig, color=(0, 0, 1), max_num=100) if ref_boxes is not None and len(ref_boxes) > 0: ref_corners3d = boxes_to_corners_3d(ref_boxes) if ref_labels is None: fig = draw_corners3d( ref_corners3d, fig=fig, color=(0, 1, 0), cls=ref_scores, max_num=100 ) else: for k in range(ref_labels.min(), ref_labels.max() + 1): cur_color = tuple(box_colormap[k % len(box_colormap)]) mask = ref_labels == k fig = draw_corners3d( ref_corners3d[mask], fig=fig, color=cur_color, cls=ref_scores[mask], max_num=100, ) mlab.view(azimuth=-179, elevation=54.0, distance=104.0, roll=90.0) return fig def draw_corners3d( corners3d, fig, color=(1, 1, 1), line_width=2, cls=None, tag="", max_num=500, tube_radius=None, ): """ :param corners3d: (N, 8, 3) :param fig: :param color: :param line_width: :param cls: :param tag: :param max_num: :return: """ import mayavi.mlab as mlab num = min(max_num, len(corners3d)) for n in range(num): b = corners3d[n] # (8, 3) if cls is not None: if isinstance(cls, np.ndarray): mlab.text3d( b[6, 0], b[6, 1], b[6, 2], "%.2f" % cls[n], scale=(0.3, 0.3, 0.3), color=color, figure=fig, ) else: mlab.text3d( b[6, 0], b[6, 1], b[6, 2], "%s" % cls[n], scale=(0.3, 0.3, 0.3), color=color, figure=fig, ) for k in range(0, 4): i, j = k, (k + 1) % 4 mlab.plot3d( [b[i, 0], b[j, 0]], [b[i, 1], b[j, 1]], [b[i, 2], b[j, 2]], color=color, tube_radius=tube_radius, line_width=line_width, figure=fig, ) i, j = k + 4, (k + 1) % 4 + 4 mlab.plot3d( [b[i, 0], b[j, 0]], [b[i, 1], b[j, 1]], [b[i, 2], b[j, 2]], color=color, tube_radius=tube_radius, line_width=line_width, figure=fig, ) i, j = k, k + 4 mlab.plot3d( [b[i, 0], b[j, 0]], [b[i, 1], b[j, 1]], [b[i, 2], b[j, 2]], color=color, tube_radius=tube_radius, line_width=line_width, figure=fig, ) i, j = 0, 5 mlab.plot3d( [b[i, 0], b[j, 0]], [b[i, 1], b[j, 1]], [b[i, 2], b[j, 2]], color=color, tube_radius=tube_radius, line_width=line_width, figure=fig, ) i, j = 1, 4 mlab.plot3d( [b[i, 0], b[j, 0]], [b[i, 1], b[j, 1]], [b[i, 2], b[j, 2]], color=color, tube_radius=tube_radius, line_width=line_width, figure=fig, ) return fig
yxlao/lit
24
(NeurIPS 2024) LiT: Unifying LiDAR "Languages" with LiDAR Translator
Python
yxlao
Yixing Lao
HKU-CS
nerfmirror.py
Python
from pathlib import Path import urllib import urllib.request import os import hashlib from tqdm import tqdm import zipfile import shutil import argparse import contextlib import tempfile _dataset_registry = dict() @contextlib.contextmanager def _make_dir_or_temp_dir(cache_dir): """ Args: cache_dir: Path to the cache directory. - If cache_dir is not None, this function will attempt to create cache_dir. The cache_dir will not be deleted once the context exits. - If cache_dir is None, a temporary cache_dir will be created. The entire cache_dir will be deleted once the context exits. """ if cache_dir: cache_dir = Path(cache_dir) if cache_dir.is_file(): raise ValueError( f"Cache dir {cache_dir} already exists and it is a file.") else: cache_dir.mkdir(exist_ok=True, parents=True) is_temp_dir = False else: cache_dir = Path(tempfile.mkdtemp()) is_temp_dir = True try: yield cache_dir finally: if is_temp_dir: shutil.rmtree(cache_dir) def _lookahead(iterable): """ Yields (item, has_more) for an iterable. Ref:https://stackoverflow.com/a/1630350/1255535 """ it = iter(iterable) last = next(it) for val in it: yield last, True last = val yield last, False class RegisterDataset(object): def __init__(self, dataset_name): self.dataset_name = dataset_name def __call__(self, cls): _dataset_registry[self.dataset_name] = cls class wrapped_cls(cls): cls.dataset_name = self.dataset_name return wrapped_cls class Dataset: def __init__(self, download_dir, cache_dir): self.download_dir = Path(download_dir).resolve() if cache_dir is None: self.cache_dir = cache_dir else: self.cache_dir = Path(cache_dir).resolve() def download(self): raise NotImplementedError("Abstract method not implemented.") @staticmethod def download_url(url, output_path): class DownloadProgressBar(tqdm): def update_to(self, b=1, bsize=1, tsize=None): if tsize is not None: self.total = tsize self.update(b * bsize - self.n) with DownloadProgressBar(unit="B", unit_scale=True, miniters=1, desc=url.split("/")[-1]) as t: urllib.request.urlretrieve(url, filename=output_path, reporthook=t.update_to) @staticmethod def sha256sum(file_path): file_path = Path(file_path) if not file_path.is_file(): raise FileNotFoundError(f"{file_path} not found.") sha256 = hashlib.sha256() with open(file_path, "rb") as f: for byte_block in iter(lambda: f.read(4096), b""): sha256.update(byte_block) return sha256.hexdigest() @staticmethod def download_single_file( url, sha256, byproduct_dir_name, delete_dir_name, download_dir, cache_dir, ): """ Args: url: URL of the file to download. sha256: SHA256 hash of the file. byproduct_dir_name: The relative directory inside download_dir after extraction for sanity check. This must be a string and be relative to download_dir. delete_dir_name: Sometimes, some extracted dirs (e.g. "__MACOSX") are not needed. Specify this to delete them after extraction. This must be a string and be relative to download_dir. download_dir: Download root dir. A directory within this directory will be created. E.g. {download_dir}/nerf_llff. cache_dir: Cache directory. If cache_dir is not None, the original download file will be cached in cache_dir. """ with _make_dir_or_temp_dir(cache_dir) as cache_dir: # Wrap dirs. download_dir = Path(download_dir).resolve() cache_dir = Path(cache_dir).resolve() if not isinstance(byproduct_dir_name, str): raise ValueError("byproduct_dir_name must be a string.") # Print dirs. print(f"download_dir: {download_dir}") print(f"cache_dir: {cache_dir}") # Check cache. file_name = os.path.basename(urllib.parse.urlparse(url).path) file_path = cache_dir / file_name sha256_valid = False if file_path.is_file(): print(f"{file_path} exists, checking checksum.") sha256_valid = Dataset.sha256sum(file_path) == sha256 if sha256_valid: print(f"{file_path} checksum matches, skipping download.") else: print( f"{file_path} checksum mismatches, will download again." ) # Download. if not sha256_valid: Dataset.download_url(url, file_path) sha256_valid = Dataset.sha256sum(file_path) == sha256 if sha256_valid: print(f"{file_path} downloaded successfully.") else: raise ValueError( f"{file_path} checksum mismatch." f"Expected checksum {sha256}. " f"Please download {url} to {cache_dir} manually.") # Extract. with zipfile.ZipFile(file_path, "r") as zip_ref: zip_ref.extractall(download_dir) # Check byproducts. byproduct_dir = (download_dir / byproduct_dir_name).resolve() if not byproduct_dir.exists(): raise FileNotFoundError( f"byproduct_dir {byproduct_dir} not found after extraction." ) # Delete delete_dir_name. if delete_dir_name is not None: delete_dir = (download_dir / delete_dir_name).resolve() if delete_dir.exists(): shutil.rmtree(delete_dir) # List directory of byproduct_dir. print(f"Extracted:") print(f"{byproduct_dir}") for f, has_more in _lookahead(byproduct_dir.iterdir()): if has_more: print(f"├── {f.name}") else: print(f"└── {f.name}") @RegisterDataset("nerf_synthetic") class NeRFSynthetic(Dataset): """ Args: download_dir: The parent directory to save the dataset. The resulting folder structure: ${download_dir}/nerf_synthetic ├── chair ├── drums ├── ficus ├── hotdog ├── lego ├── materials ├── mic ├── README.txt └── ship """ def __init__(self, download_dir, cache_dir): super().__init__(download_dir, cache_dir) def download(self): Dataset.download_single_file( url= "https://github.com/yxlao/nerfmirror/releases/download/20220618/nerf_synthetic.zip", sha256= "f01fd1b4ab045b0d453917346f26f898657bb5bec4834b95fdad1f361826e45e", byproduct_dir_name="nerf_synthetic", delete_dir_name="__MACOSX", download_dir=self.download_dir, cache_dir=self.cache_dir, ) @RegisterDataset("nerf_llff") class NeRFLLFF(Dataset): """ Args: download_dir: The parent directory to save the dataset. The resulting folder structure: ${download_dir}/nerf_llff_data ├── fern ├── flower ├── fortress ├── horns ├── leaves ├── orchids ├── room └── trex """ def __init__(self, download_dir, cache_dir): super().__init__(download_dir, cache_dir) def download(self): Dataset.download_single_file( url= "https://github.com/yxlao/nerfmirror/releases/download/20220618/nerf_llff_data.zip", sha256= "5794b432feaf4f25bcd603addc6ad0270cec588fed6a364b7952001f07466635", byproduct_dir_name="nerf_llff_data", delete_dir_name=None, download_dir=self.download_dir, cache_dir=self.cache_dir, ) def main(): parser = argparse.ArgumentParser( description="Datamirror: downloader for common NeRF datasets.") parser.add_argument("dataset_name", type=str, help="Dataset name", choices=sorted(list(_dataset_registry.keys()))) parser.add_argument("--download_dir", dest="download_dir", default="data", help="Download directory") parser.add_argument("--cache_dir", dest="cache_dir", default=None, help="Cache directory") args = parser.parse_args() dataset_class = _dataset_registry[args.dataset_name]( download_dir=args.download_dir, cache_dir=args.cache_dir, ) dataset_class.download() if __name__ == "__main__": main()
yxlao/nerfmirror
0
Python
yxlao
Yixing Lao
HKU-CS
build.gradle.kts
Kotlin
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile plugins { kotlin("jvm") version "1.4.30" apply false kotlin("android") version "1.4.30" apply false id("com.google.devtools.ksp") version "1.4.30-1.0.0-alpha02" apply false } buildscript { dependencies { classpath(kotlin("gradle-plugin", version = "1.4.30")) classpath("com.android.tools.build:gradle:7.0.0-alpha06") } } group = "com.zachklipp" version = "1.0-SNAPSHOT" repositories { mavenCentral() gradlePluginPortal() google() } subprojects { repositories { mavenCentral() google() jcenter() } tasks.withType<KotlinCompile>() { kotlinOptions.jvmTarget = "1.8" } }
zach-klippenstein/compose-model
36
Kotlin
zach-klippenstein
Zach Klippenstein
Square
demo/build.gradle
Gradle
plugins { id 'com.android.application' id 'kotlin-android' id 'com.google.devtools.ksp' id 'idea' } android { compileSdkVersion 30 defaultConfig { applicationId "com.zachklipp.composedata.demo" minSdkVersion 21 targetSdkVersion 30 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = '1.8' useIR = true } buildFeatures { compose true } composeOptions { kotlinCompilerExtensionVersion "1.0.0-alpha12" } } idea { module { sourceDirs += file("$buildDir/generated/ksp/debug/kotlin") sourceDirs += file("$buildDir/generated/ksp/main/kotlin") // Just these doesn't seem to work. generatedSourceDirs += file("$buildDir/generated/ksp/debug/kotlin") generatedSourceDirs += file("$buildDir/generated/ksp/main/kotlin") } } dependencies { ksp project(":processor") implementation project(":runtime") implementation "androidx.compose.ui:ui:1.0.0-alpha12" implementation "androidx.compose.foundation:foundation:1.0.0-alpha12" implementation 'androidx.appcompat:appcompat:1.2.0' implementation 'androidx.activity:activity-compose:1.3.0-alpha02' debugImplementation "androidx.compose.ui:ui-tooling:1.0.0-alpha12" debugImplementation "org.jetbrains.kotlin:kotlin-reflect:1.4.30" testImplementation 'junit:junit:4.13.2' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' }
zach-klippenstein/compose-model
36
Kotlin
zach-klippenstein
Zach Klippenstein
Square
demo/src/main/java/com/zachklipp/composedata/demo/AddressModel.kt
Kotlin
package com.zachklipp.composedata.demo import androidx.compose.runtime.Composable import androidx.compose.ui.tooling.preview.Preview import com.zachklipp.composedata.ComposeModel @ComposeModel interface AddressModel { val street: String get() = "" val city: String get() = "" val state: String get() = "" fun onStreetChanged(street: String) fun onCityChanged(city: String) fun onStateChanged(state: String) } @Composable fun AddressModel() = rememberAddressModel { onStreetChanged { street = it } onCityChanged { city = it } onStateChanged { state = it } } @Preview(showBackground = true) @Composable fun AddressPreview() { AddressModel() }
zach-klippenstein/compose-model
36
Kotlin
zach-klippenstein
Zach Klippenstein
Square
demo/src/main/java/com/zachklipp/composedata/demo/ContactInfoModel.kt
Kotlin
package com.zachklipp.composedata.demo import androidx.compose.runtime.Composable import androidx.compose.ui.tooling.preview.Preview import com.zachklipp.composedata.ComposeModel /** * Represents some contact info about a person. * Because it's annotated with a [ComposeModel] annotation, a [rememberContactInfoModel] function is * automatically generated for it. The [ContactInfoModel] function below uses the generated function * to implement business logic. */ @ComposeModel interface ContactInfoModel { val name: String val addressModel: AddressModel // Is excluded from builder function parameters. val edits: Int get() = 0 fun onNameChanged(name: String) fun onSubmitClicked() // Generates a warning. fun badlyNamedHandler() // This function is excluded from the builder since it has a default value. fun log(message: String) = println("ContactInfoModel: $message") } /** * This function doesn't draw UI - it is only responsible for driving a [ContactInfoModel]. */ @Composable fun ContactInfoModel(initialName: String = "world") = rememberContactInfoModel( name = initialName, addressModel = AddressModel() ) { onNameChanged { name = it edits++ } } @Preview(showBackground = true) @Composable fun ContactInfoPreview() { ContactInfoModel() }
zach-klippenstein/compose-model
36
Kotlin
zach-klippenstein
Zach Klippenstein
Square
demo/src/main/java/com/zachklipp/composedata/demo/DemoActivity.kt
Kotlin
package com.zachklipp.composedata.demo import android.os.Bundle import androidx.activity.compose.setContent import androidx.appcompat.app.AppCompatActivity import androidx.compose.foundation.border import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.text.BasicText import androidx.compose.foundation.text.BasicTextField import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontStyle.Italic import androidx.compose.ui.unit.dp class DemoActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { App() } } } @Composable fun App() { val contactInfo = ContactInfoModel() Column { BasicText("Hello, ${contactInfo.name}!") BasicTextField( value = contactInfo.name, onValueChange = contactInfo::onNameChanged, Modifier.border(1.dp, Color.Black).padding(4.dp) ) BasicText("${contactInfo.edits} edits", style = TextStyle(fontStyle = Italic)) Spacer(Modifier.size(16.dp)) AddressEditor(contactInfo.addressModel) } } @Composable private fun AddressEditor(addressModel: AddressModel) { Column { BasicText("Street:") BasicTextField( addressModel.street, onValueChange = addressModel::onStreetChanged, Modifier.border(1.dp, Color.Black).padding(4.dp) ) BasicText("City:") BasicTextField( addressModel.city, onValueChange = addressModel::onCityChanged, Modifier.border(1.dp, Color.Black).padding(4.dp) ) BasicText("State:") BasicTextField( addressModel.state, onValueChange = addressModel::onStateChanged, Modifier.border(1.dp, Color.Black).padding(4.dp) ) } }
zach-klippenstein/compose-model
36
Kotlin
zach-klippenstein
Zach Klippenstein
Square
processor/build.gradle.kts
Kotlin
plugins { kotlin("jvm") } group = "com.zachklipp" version = "1.0-SNAPSHOT" repositories { mavenCentral() google() } dependencies { implementation("com.google.devtools.ksp:symbol-processing-api:1.4.30-1.0.0-alpha02") implementation("com.squareup.okio:okio:2.10.0") implementation("com.squareup:kotlinpoet:1.7.2") // Just need these to reflect on some names. implementation(project(":runtime")) // compileOnly("androidx.compose.foundation:foundation:1.0.0-alpha12") { // this.artifact { // this.extension="aar" // } // } }
zach-klippenstein/compose-model
36
Kotlin
zach-klippenstein
Zach Klippenstein
Square
processor/src/main/kotlin/com/zachklipp/composedata/BuilderInterfaceSpec.kt
Kotlin
package com.zachklipp.composedata import com.squareup.kotlinpoet.FunSpec import com.squareup.kotlinpoet.LambdaTypeName import com.squareup.kotlinpoet.PropertySpec import com.squareup.kotlinpoet.TypeSpec data class BuilderInterfaceSpec( val modelInterface: ModelInterface, val spec: TypeSpec, val properties: List<Pair<ModelProperty, PropertySpec>>, val eventHandlers: List<EventHandlerSpec> ) data class EventHandlerSpec( val name: String, val eventHandler: ModelEventHandler, val lambdaTypeName: LambdaTypeName, val setter: FunSpec )
zach-klippenstein/compose-model
36
Kotlin
zach-klippenstein
Zach Klippenstein
Square
processor/src/main/kotlin/com/zachklipp/composedata/ComposeDataProcessor.kt
Kotlin
package com.zachklipp.composedata import com.google.devtools.ksp.processing.CodeGenerator import com.google.devtools.ksp.processing.Dependencies import com.google.devtools.ksp.processing.KSPLogger import com.google.devtools.ksp.processing.Resolver import com.google.devtools.ksp.processing.SymbolProcessor import com.google.devtools.ksp.symbol.KSAnnotated import com.google.devtools.ksp.symbol.KSClassDeclaration import com.google.devtools.ksp.validate import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.FileSpec import java.io.PrintWriter class ComposeDataProcessor : SymbolProcessor { private lateinit var codeGenerator: CodeGenerator private lateinit var logger: KSPLogger private lateinit var parser: Parser private lateinit var typeConverter: TypeConverter override fun init( options: Map<String, String>, kotlinVersion: KotlinVersion, codeGenerator: CodeGenerator, logger: KSPLogger ) { this.codeGenerator = codeGenerator this.logger = logger parser = Parser(logger) typeConverter = TypeConverter(logger) } override fun process(resolver: Resolver): List<KSAnnotated> { val annotatedSymbols = resolver.getSymbolsWithAnnotation(COMPOSE_DATA_ANNOTATION.qualifiedName!!) if (annotatedSymbols.isEmpty()) { return emptyList() } val invalidSymbols = mutableListOf<KSAnnotated>() annotatedSymbols.forEach { symbol -> if (symbol !is KSClassDeclaration) return@forEach if (!symbol.validate()) { logger.warn("Invalid", symbol) invalidSymbols += symbol return@forEach } processComposeDataClass(symbol, resolver) } return invalidSymbols } override fun finish() = Unit private fun processComposeDataClass(symbol: KSClassDeclaration, resolver: Resolver) { val modelInterface = parser.parseModelInterface(symbol, resolver.builtIns) ?: return val implClassName = ClassName(modelInterface.packageName, "${modelInterface.simpleName}Impl") val config = parser.parseConfig(modelInterface, resolver) val builderInterface = generateBuilderInterface(modelInterface, typeConverter) val implClass = generateImplClass(modelInterface, builderInterface, implClassName, config, typeConverter) val rememberFunction = generateRememberFunction(modelInterface, builderInterface, implClass, typeConverter) val packageName = symbol.packageName.asString() val generatedFile = FileSpec.builder(packageName, builderInterface.spec.name!!) .addFunction(rememberFunction) .addType(builderInterface.spec) .addType(implClass.spec) .apply { implClass.imports.takeUnless { it.isEmpty() }?.forEach { addImport(it.packageName, it.simpleName) } } .build() codeGenerator.createNewFile( Dependencies(aggregating = false, symbol.containingFile!!), packageName = packageName, fileName = generatedFile.name ).let(::PrintWriter).use { generatedFile.writeTo(it) } } companion object { val COMPOSE_DATA_ANNOTATION = ComposeModel::class } }
zach-klippenstein/compose-model
36
Kotlin
zach-klippenstein
Zach Klippenstein
Square
processor/src/main/kotlin/com/zachklipp/composedata/Config.kt
Kotlin
package com.zachklipp.composedata /** * TODO write documentation */ data class Config( val saveable: Boolean, )
zach-klippenstein/compose-model
36
Kotlin
zach-klippenstein
Zach Klippenstein
Square
processor/src/main/kotlin/com/zachklipp/composedata/Generators.kt
Kotlin
package com.zachklipp.composedata import com.google.devtools.ksp.symbol.KSPropertyDeclaration import com.squareup.kotlinpoet.AnnotationSpec import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.CodeBlock import com.squareup.kotlinpoet.FunSpec import com.squareup.kotlinpoet.KModifier.ABSTRACT import com.squareup.kotlinpoet.KModifier.INTERNAL import com.squareup.kotlinpoet.KModifier.OVERRIDE import com.squareup.kotlinpoet.KModifier.PRIVATE import com.squareup.kotlinpoet.LambdaTypeName import com.squareup.kotlinpoet.MemberName import com.squareup.kotlinpoet.ParameterSpec import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import com.squareup.kotlinpoet.PropertySpec import com.squareup.kotlinpoet.TypeName import com.squareup.kotlinpoet.TypeSpec import com.squareup.kotlinpoet.asClassName private val COMPOSABLE_ANNOTATION = ClassName("androidx.compose.runtime", "Composable") private val STABLE_ANNOTATION = ClassName("androidx.compose.runtime", "Stable") private val REMEMBER_FUN = MemberName("androidx.compose.runtime", "remember") private val REMEMBER_SAVEABLE_FUN = MemberName("androidx.compose.runtime.saveable", "rememberSaveable") private val MAP_OF_FUN = MemberName("kotlin.collections", "mapOf") private val MUTABLE_STATE_OF_FUN = MemberName("androidx.compose.runtime", "mutableStateOf") private val UNIT_NAME = Unit::class.asClassName() private val SAVER_INTERFACE = ClassName("androidx.compose.runtime.saveable", "Saver") fun generateRememberFunction( model: ModelInterface, builderInterfaceSpec: BuilderInterfaceSpec, implSpec: ModelImplSpec, converter: TypeConverter ): FunSpec { with(converter) { val interfaceName = ClassName(model.packageName, model.simpleName) val updateLambdaType = LambdaTypeName.get( receiver = ClassName(model.packageName, builderInterfaceSpec.spec.name!!), returnType = UNIT_NAME ).copy(annotations = listOf(AnnotationSpec.builder(COMPOSABLE_ANNOTATION).build())) val updateParam = ParameterSpec("update", updateLambdaType) val requiredParams = model.properties.filter { !it.hasDefault } .map { property -> ParameterSpec(property.name, property.declaration.type.toTypeName()) } return FunSpec.builder("remember${model.simpleName}") // Builder function is always internal – the code should wrap the builder with // its own actual function that includes the implementation. .addModifiers(INTERNAL) .addAnnotation(COMPOSABLE_ANNOTATION) .addParameters(requiredParams) // This must be the last parameter trailing lambda syntax. .addParameter(updateParam) .returns(interfaceName) .addCode( CodeBlock.builder() .add("return %L", rememberMaybeSaveable(implSpec.saverName) { add( generateImplConstructorCall( implSpec.name, requiredParams.associate { it.name to CodeBlock.of("%N", it.name) }) ) // add("%N(", implSpec.spec) // requiredParams.forEach { add("%N, ", it.name) } // add(")\n") }) .add(".also { %N(it) }", updateParam) .build() ) .build() } } fun generateBuilderInterface( model: ModelInterface, converter: TypeConverter ): BuilderInterfaceSpec { with(converter) { val builderInterfaceName = ClassName(model.packageName, "${model.simpleName}Builder") val propertySpecs = model.properties.map { it to PropertySpec.builder(it.declaration.simpleName.asString(), it.declaration.type.toTypeName()) .mutable(true) .build() } val eventHandlerSpecs = model.eventHandlers.map { eventHandler -> val declaration = eventHandler.declaration val eventHandlerLambda = LambdaTypeName.get( parameters = declaration.parameters.map { eventParam -> ParameterSpec(eventParam.name!!.asString(), eventParam.type.toTypeName()) }, returnType = UNIT_NAME ) EventHandlerSpec( declaration.simpleName.asString(), eventHandler, eventHandlerLambda, setter = FunSpec.builder(declaration.simpleName.asString()) .addModifiers(ABSTRACT) .addParameter("handler", eventHandlerLambda) .build() ) } return BuilderInterfaceSpec( model, spec = TypeSpec.interfaceBuilder(builderInterfaceName) // Internal for the same reason that the remember function is. .addModifiers(INTERNAL) .addAnnotation(STABLE_ANNOTATION) .addProperties(propertySpecs.map { it.second }) .addFunctions(eventHandlerSpecs.map { it.setter }) .build(), propertySpecs, eventHandlerSpecs ) } } fun generateImplClass( model: ModelInterface, builder: BuilderInterfaceSpec, implClassName: ClassName, config: Config, converter: TypeConverter ): ModelImplSpec { with(converter) { val constructorParamsByName = model.properties.filter { !it.hasDefault } .associate { val name = it.declaration.simpleName.asString() name to ParameterSpec(name, it.declaration.type.toTypeName()) } val properties = model.properties.map { property -> PropertySpec.builder(property.name, property.declaration.type.toTypeName()) .addModifiers(OVERRIDE) .mutable(true) .delegate(mutableStateOf(property.declaration.defaultOr(CodeBlock.of("%N", property.name)))) .build() } val eventHandlerProperties: Map<String, PropertySpec> = builder.eventHandlers.associate { val property = PropertySpec .builder("${it.name}\$handler", it.lambdaTypeName.copy(nullable = true)) .addModifiers(PRIVATE) .mutable(true) .initializer("null") .build() Pair(it.name, property) } val eventHandlerSetters = builder.eventHandlers.map { it.setter.toBuilder() .apply { modifiers -= ABSTRACT } .addModifiers(OVERRIDE) .addCode("%N = handler", eventHandlerProperties.getValue(it.name)) .build() } val eventHandlers = model.eventHandlers.map { eventHandler -> val backingProperty = eventHandlerProperties.getValue(eventHandler.name) val parameters = eventHandler.declaration.parameters.map { ParameterSpec(it.name!!.asString(), it.type.toTypeName()) } FunSpec.builder(eventHandler.name) .addModifiers(OVERRIDE) .addParameters(parameters) .addCode("%N?.invoke(", backingProperty) .apply { parameters.forEach { addCode("%N, ", it) } } .addCode(")") .build() } val implBuilder = TypeSpec.classBuilder(implClassName) .addModifiers(PRIVATE) .addAnnotation(STABLE_ANNOTATION) .addSuperinterface(ClassName(model.packageName, model.simpleName)) .addSuperinterface(ClassName(model.packageName, builder.spec.name!!)) .primaryConstructor( FunSpec.constructorBuilder() .addParameters(constructorParamsByName.values) .build() ) .addProperties(properties) .addProperties(eventHandlerProperties.values) .addFunctions(eventHandlerSetters) .addFunctions(eventHandlers) val saverSpec = if (config.saveable) { generateSaver(implClassName, constructorParamsByName.values.toList(), properties) .also(implBuilder::addType) } else null return ModelImplSpec( implBuilder.build(), name = implClassName, saverSpec = saverSpec, saverName = saverSpec?.name?.let(implClassName::nestedClass), imports = listOf( MemberName("androidx.compose.runtime", "getValue"), MemberName("androidx.compose.runtime", "setValue"), ) ) } } private fun generateSaver( implType: TypeName, implConstructorParams: List<ParameterSpec>, properties: List<PropertySpec> ): TypeSpec { val savedType = Map::class.parameterizedBy(String::class, Any::class) val saveFunction = FunSpec.builder("save") .addModifiers(OVERRIDE) .receiver(ClassName("androidx.compose.runtime.saveable", "SaverScope")) .addParameter(ParameterSpec("value", implType)) .returns(savedType.copy(nullable = true)) .addCode( "return %L", stringMapOf( properties.map { it.name to CodeBlock.of("value.%N", it.name) } ) ) .build() val constructorParamNames = implConstructorParams.mapTo(mutableSetOf()) { it.name } val nonConstructorProperties = properties.filterNot { it.name in constructorParamNames } val restoreConstructor = generateImplConstructorCall(implType, implConstructorParams.associate { it.name to CodeBlock.of("value.getValue(%S)·as·%T", it.name, it.type) }) val restoreInitializers = nonConstructorProperties.map { CodeBlock.of("%1N·=·value.getValue(%1S)·as·%2T", it.name, it.type) } val restoreFunction = FunSpec.builder("restore") .addModifiers(OVERRIDE) .addParameter(ParameterSpec("value", savedType)) .returns(implType.copy(nullable = true)) .addCode( CodeBlock.builder() .add("return %L", restoreConstructor) .apply { if (restoreInitializers.isNotEmpty()) { beginControlFlow(".apply") restoreInitializers.forEach { addStatement("%L", it) } endControlFlow() } } .build() ) .build() return TypeSpec.objectBuilder("Saver") .addSuperinterface(SAVER_INTERFACE.parameterizedBy(implType, savedType)) // .primaryConstructor( // FunSpec.constructorBuilder() // .addParameter("propertySaver", propertySaverType) // .build() // ) // .addProperty( // PropertySpec.builder("propertySaver", propertySaverType) // .initializer("propertySaver") // .build() // ) .addFunction(saveFunction) .addFunction(restoreFunction) .build() } private fun mutableStateOf(initializer: CodeBlock) = CodeBlock.of("%M(%L)", MUTABLE_STATE_OF_FUN, initializer) private fun rememberMaybeSaveable( saverName: TypeName?, initializer: CodeBlock.Builder.() -> Unit ): CodeBlock { val rememberCall = saverName?.let { CodeBlock.of("%M(saver = %T)", REMEMBER_SAVEABLE_FUN, it) } ?: CodeBlock.of("%M", REMEMBER_FUN) return CodeBlock.builder() .beginControlFlow("%L", rememberCall) .apply(initializer) .endControlFlow() .build() } private fun stringMapOf(entries: Iterable<Pair<String, CodeBlock>>) = CodeBlock.builder() .addStatement("%M(", MAP_OF_FUN) .apply { entries.forEach { (name, value) -> addStatement("%S·to·%L,", name, value) } } .add(")") .build() private fun generateImplConstructorCall( implName: TypeName, propertyValues: Map<String, CodeBlock> ): CodeBlock = CodeBlock.builder() .addStatement("%T(", implName) .apply { propertyValues.forEach { (name, value) -> addStatement("%N·=·%L,", name, value) } } .addStatement(")") .build() private fun KSPropertyDeclaration.defaultOr(initialValue: CodeBlock): CodeBlock = getter?.let { CodeBlock.of("super.%N", simpleName.getShortName()) } ?: initialValue /* object Saver : androidx.compose.runtime.saveable.Saver<ViewModelImpl, Map<String,Any>>{ override fun SaverScope.save(value: ViewModelImpl): Map<String, Any>? { return mapOf( "name" to value.name, "address" to value.address, "edits" to value.edits, ) } override fun restore(value: Map<String, Any>): ViewModelImpl? { return ViewModelImpl( name = value.getValue("name") as String, address = value.getValue("address") as Address ).apply { edits = value.getValue("edits") as Int } } } */
zach-klippenstein/compose-model
36
Kotlin
zach-klippenstein
Zach Klippenstein
Square
processor/src/main/kotlin/com/zachklipp/composedata/ModelImplSpec.kt
Kotlin
package com.zachklipp.composedata import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.MemberName import com.squareup.kotlinpoet.TypeName import com.squareup.kotlinpoet.TypeSpec /** * TODO write documentation */ data class ModelImplSpec( val spec: TypeSpec, val name: ClassName, val imports: List<MemberName>, val saverSpec: TypeSpec?, val saverName: TypeName? )
zach-klippenstein/compose-model
36
Kotlin
zach-klippenstein
Zach Klippenstein
Square
processor/src/main/kotlin/com/zachklipp/composedata/ModelInterface.kt
Kotlin
package com.zachklipp.composedata import com.google.devtools.ksp.symbol.KSClassDeclaration import com.google.devtools.ksp.symbol.KSFunctionDeclaration import com.google.devtools.ksp.symbol.KSPropertyDeclaration import com.google.devtools.ksp.symbol.Visibility /** * TODO write documentation */ data class ModelInterface( val packageName: String, val simpleName: String, val declaration: KSClassDeclaration, val visibility: Visibility, val properties: List<ModelProperty>, val eventHandlers: List<ModelEventHandler>, ) data class ModelProperty( val name: String, val declaration: KSPropertyDeclaration, val hasDefault: Boolean = declaration.getter != null ) data class ModelEventHandler( val name: String, val declaration: KSFunctionDeclaration, val hasDefault: Boolean = !declaration.isAbstract, )
zach-klippenstein/compose-model
36
Kotlin
zach-klippenstein
Zach Klippenstein
Square
processor/src/main/kotlin/com/zachklipp/composedata/Parser.kt
Kotlin
package com.zachklipp.composedata import com.google.devtools.ksp.getClassDeclarationByName import com.google.devtools.ksp.getDeclaredFunctions import com.google.devtools.ksp.getDeclaredProperties import com.google.devtools.ksp.getVisibility import com.google.devtools.ksp.processing.KSBuiltIns import com.google.devtools.ksp.processing.KSPLogger import com.google.devtools.ksp.processing.Resolver import com.google.devtools.ksp.symbol.ClassKind.INTERFACE import com.google.devtools.ksp.symbol.KSAnnotation import com.google.devtools.ksp.symbol.KSClassDeclaration import com.google.devtools.ksp.symbol.KSFunctionDeclaration import com.google.devtools.ksp.symbol.KSPropertyDeclaration import com.zachklipp.composedata.ComposeDataProcessor.Companion.COMPOSE_DATA_ANNOTATION import kotlin.reflect.KProperty1 class Parser(private val logger: KSPLogger) { fun parseModelInterface(symbol: KSClassDeclaration, builtins: KSBuiltIns): ModelInterface? { if (symbol.classKind != INTERFACE) { logger.error( "Only interfaces may be annotated with ${COMPOSE_DATA_ANNOTATION}, but this is a ${symbol.classKind}", symbol ) return null } if (symbol.superTypes.isNotEmpty()) { logger.error( "$COMPOSE_DATA_ANNOTATION-annotated interfaces must not extend any interfaces, " + "but this interface extends ${symbol.superTypes}", symbol ) return null } if (symbol.typeParameters.isNotEmpty()) { logger.error( "$COMPOSE_DATA_ANNOTATION-annotated interfaces must not have type parameters.", symbol ) return null } val properties = symbol.getDeclaredProperties().map { parseModelProperty(it) ?: return null } val eventHandlers = symbol.getDeclaredFunctions().mapNotNull { parseModelEventHandler(it, builtins) } return ModelInterface( symbol.packageName.asString(), symbol.simpleName.asString(), symbol, symbol.getVisibility(), properties, eventHandlers ) } fun parseConfig(model: ModelInterface, resolver: Resolver): Config { val composeDataAnnotationType = resolver.getClassDeclarationByName<ComposeModel>() val annotation = model.declaration.annotations.single { it.annotationType.resolve().declaration == composeDataAnnotationType } return Config( saveable = annotation[ComposeModel::saveable] ?: true, ) } private fun parseModelProperty(declaration: KSPropertyDeclaration): ModelProperty? { if (declaration.isMutable) { logger.error( "$COMPOSE_DATA_ANNOTATION interfaces must not declare mutable properties: $declaration", declaration ) return null } return ModelProperty(declaration.simpleName.asString(), declaration) } private fun parseModelEventHandler( declaration: KSFunctionDeclaration, builtins: KSBuiltIns ): ModelEventHandler? { // Ignore functions with a default implementation. if (!declaration.isAbstract) { logger.info( "Skipping function $declaration because it has a default implementation.", declaration ) return null } if (declaration.returnType == null) { logger.error("Unknown return type", declaration) return null } if (declaration.returnType!!.resolve() != builtins.unitType) { logger.error( "$COMPOSE_DATA_ANNOTATION event handler functions must return Unit", declaration ) return null } if (declaration.typeParameters.isNotEmpty()) { logger.error( "$COMPOSE_DATA_ANNOTATION interfaces must not declare generic functions: $declaration", declaration ) return null } if (!declaration.simpleName.asString().startsWith("on")) { logger.warn( "Event handler functions should have the prefix \"on\": $declaration", declaration ) } return ModelEventHandler( name = declaration.simpleName.asString(), declaration, hasDefault = !declaration.isAbstract ) } @Suppress("UNCHECKED_CAST") private operator fun <T> KSAnnotation.get(name: KProperty1<*, T>): T? = arguments.single { it.name!!.asString() == name.name }.value as T? }
zach-klippenstein/compose-model
36
Kotlin
zach-klippenstein
Zach Klippenstein
Square
processor/src/main/kotlin/com/zachklipp/composedata/TypeConverter.kt
Kotlin
package com.zachklipp.composedata import com.google.devtools.ksp.processing.KSPLogger import com.google.devtools.ksp.symbol.KSClassifierReference import com.google.devtools.ksp.symbol.KSTypeReference import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import com.squareup.kotlinpoet.TypeName /** * TODO write documentation */ class TypeConverter(private val logger: KSPLogger) { fun KSTypeReference.toTypeName(): TypeName { logger.warn("toTypeName($this)") val resolved = resolve() return ClassName( resolved.declaration.packageName.asString(), resolved.declaration.simpleName.getShortName() ) return when (val element = element) { is KSClassifierReference -> { ClassName.bestGuess(element.referencedName()) .apply { if (element.typeArguments.isNotEmpty()) { parameterizedBy(element.typeArguments.map { it.type!!.toTypeName() }) } } } // is KSCallableReference -> { // TODO() // } null -> { logger.error("Type element is null", this) TODO() } else -> { logger.error("Unsupported type: ${element::class.simpleName}: $this", this) TODO() } } } }
zach-klippenstein/compose-model
36
Kotlin
zach-klippenstein
Zach Klippenstein
Square
runtime/build.gradle.kts
Kotlin
plugins { kotlin("jvm") } group = "com.zachklipp" version = "1.0-SNAPSHOT" repositories { mavenCentral() } dependencies { // TODO make multiplatform // api("androidx.compose.runtime:runtime:1.0.0-alpha12") }
zach-klippenstein/compose-model
36
Kotlin
zach-klippenstein
Zach Klippenstein
Square
runtime/src/main/kotlin/com/zachklipp/composedata/ComposeModel.kt
Kotlin
package com.zachklipp.composedata import kotlin.annotation.AnnotationRetention.BINARY import kotlin.annotation.AnnotationTarget.CLASS /** * Annotates an interface as a model. The interface must contain no mutable properties, but * properties may have default getters. All functions must either have a default implementation or * return `Unit`. * * A composable function will then be generated for an interface `Foo` named `rememberFoo`. This * function will create an remember a `Foo` and return it. It takes a parameter for each property * of the interface without a default value, as well as a function that should implement the model's * business logic. The function parameter has a receiver of type `FooBuilder` – this is a generated * class that mirrors `Foo`, but does not implement it: * - For each property in `Foo`, `FooBuilder` has a mutable property of the same name. This * property will be initialized to either the original property's default value or the value * passed to `rememberFoo`. When the property is changed, it will notify observers of the * property on the original interface of the change. * - For each abstract function in `Foo`, `FooBuilder` has a function of the same name that takes * a _lambda_ with the same signature as the original function. The lambda passed to this * function will be invoked whenever the function on the returned interface is called. * * @param saveable Whether to generate a `Saver` for the model and save it using `rememberSaveable`. * All properties on the class will be saved. All properties much have a type that is automatically * saveable in a bundle. Default is true. */ @MustBeDocumented @Target(CLASS) @Retention(BINARY) // TODO @StableMarker annotation class ComposeModel( val saveable: Boolean = true, )
zach-klippenstein/compose-model
36
Kotlin
zach-klippenstein
Zach Klippenstein
Square
settings.gradle.kts
Kotlin
pluginManagement { repositories { gradlePluginPortal() google() } } rootProject.name = "ComposeModel" include( "demo", "processor", "runtime" )
zach-klippenstein/compose-model
36
Kotlin
zach-klippenstein
Zach Klippenstein
Square
build.gradle.kts
Kotlin
import org.jetbrains.compose.compose import org.jetbrains.compose.desktop.application.dsl.TargetFormat import org.jetbrains.kotlin.gradle.tasks.KotlinCompile plugins { kotlin("jvm") version "1.5.21" id("org.jetbrains.compose") version "1.0.0-alpha1" } group = "com.zachklipp" version = "1.0" repositories { mavenCentral() maven("https://maven.pkg.jetbrains.space/public/p/compose/dev") google() mavenLocal() } dependencies { implementation(compose.desktop.currentOs) // Not on a public repository, build manually from // https://github.com/shannah/Java-Objective-C-Bridge. implementation("ca.weblite:java-objc-bridge:1.1-SNAPSHOT") } tasks.withType<KotlinCompile>() { kotlinOptions.jvmTarget = "11" } compose.desktop { application { mainClass = "MainKt" nativeDistributions { targetFormats(TargetFormat.Dmg, TargetFormat.Msi, TargetFormat.Deb) packageName = "ComposeTouchbar" packageVersion = "1.0.0" } } }
zach-klippenstein/compose-touchbar
17
Kotlin
zach-klippenstein
Zach Klippenstein
Square
settings.gradle.kts
Kotlin
pluginManagement { repositories { gradlePluginPortal() maven("https://maven.pkg.jetbrains.space/public/p/compose/dev") } } rootProject.name = "ComposeTouchbar"
zach-klippenstein/compose-touchbar
17
Kotlin
zach-klippenstein
Zach Klippenstein
Square
src/main/kotlin/ButtonItem.kt
Kotlin
import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.graphics.Color @Composable fun TouchBarScope.ButtonItem( title: String, alternateTitle: String = "", image: TouchBarImage? = null, alternateImage: TouchBarImage? = null, bezelColor: Color? = null, onClick: () -> Unit, ) { val updatedOnClick by rememberUpdatedState(onClick) TouchBarViewNode( viewFactory = { val actionTarget = object : GenericActionTarget() { override fun triggerNullary() { updatedOnClick() } } client.sendProxy( "NSButton", "buttonWithTitle:target:action:", /* title */ title, /* target */ actionTarget, /* action(selector) */ "triggerNullary" ) }, update = { set(title) { viewImpl!!.send("setStringValue:", it) } set(alternateTitle) { viewImpl!!["alternateTitle"] = it } set(image) { viewImpl!!["image"] = it } set(alternateImage) { viewImpl!!["alternateImage"] = it } set(bezelColor) { it?.let { color -> viewImpl!!["bezelColor"] = color.toNSColor() } } } ) }
zach-klippenstein/compose-touchbar
17
Kotlin
zach-klippenstein
Zach Klippenstein
Square
src/main/kotlin/ColorPickerItem.kt
Kotlin
import ColorPickerButtonType.Standard import ColorPickerButtonType.Stroke import ColorPickerButtonType.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.key import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.colorspace.ColorSpaces import ca.weblite.objc.Client import ca.weblite.objc.Proxy import ca.weblite.objc.RuntimeUtils.sel sealed interface ColorPickerButtonType { object Standard : ColorPickerButtonType object Text : ColorPickerButtonType object Stroke : ColorPickerButtonType } @Composable fun TouchBarScope.ColorPickerItem( color: Color, onColorChange: (Color) -> Unit, buttonType: ColorPickerButtonType = Standard, ) { val updatedOnColorChange by rememberUpdatedState(onColorChange) // Just recreate the entire component if the button type changes since we need to create with a // different constructor. key(buttonType) { TouchBarItemNode( factory = { id -> val constructor = when (buttonType) { Standard -> "colorPickerWithIdentifier:" Stroke -> "strokeColorPickerWithIdentifier:" Text -> "textColorPickerWithIdentifier:" } val item = client.sendProxy("NSColorPickerTouchBarItem", constructor, id) val actionTarget = object : GenericActionTarget() { override fun triggerNullary() { val currentColor = item.getProxy("color") // NSColor updatedOnColorChange(currentColor.nsColorToComposeColor()) } } item["target"] = actionTarget // For some reason we can't set this property using .set(), it has its own set selector. item.send("setAction:", sel("triggerNullary")) TouchBarItemNode(id, item) }, update = { set(color) { itemImpl["color"] = color.toNSColor() } } ) } }
zach-klippenstein/compose-touchbar
17
Kotlin
zach-klippenstein
Zach Klippenstein
Square
src/main/kotlin/Colors.kt
Kotlin
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.colorspace.ColorSpaces import ca.weblite.objc.Client import ca.weblite.objc.Proxy private val SharedColorSpaceNS = Client.getInstance() .sendProxy("NSColorSpace", "extendedSRGBColorSpace") internal fun Color.toNSColor(): Proxy { val rgbColor = this.convert(ColorSpaces.ExtendedSrgb) return Client.getInstance().sendProxy( // TODO create the NSColor in the extendedSrgb space as well. "NSColor", "colorWithSRGBRed:green:blue:alpha:", rgbColor.red, rgbColor.green, rgbColor.blue, rgbColor.alpha ) } internal fun Proxy.nsColorToComposeColor(): Color { val convertedColor = this.sendProxy("colorUsingColorSpace:", SharedColorSpaceNS) return Color( red = (convertedColor.sendRaw("redComponent") as Double).toFloat(), green = (convertedColor.sendRaw("greenComponent") as Double).toFloat(), blue = (convertedColor.sendRaw("blueComponent") as Double).toFloat(), alpha = (convertedColor.sendRaw("alphaComponent") as Double).toFloat(), colorSpace = ColorSpaces.ExtendedSrgb ) }
zach-klippenstein/compose-touchbar
17
Kotlin
zach-klippenstein
Zach Klippenstein
Square
src/main/kotlin/GenericActionTarget.kt
Kotlin
import ca.weblite.objc.NSObject import ca.weblite.objc.annotations.Msg /** * Generic parent class for views that need to take callbacks. * It has different optional methods you can override depending the callback parameters you need. */ internal abstract class GenericActionTarget : NSObject("NSObject") { @Msg(selector = "triggerNullary", signature = "v@:") open fun triggerNullary() { } // @Msg(selector = "triggerNullary:", signature = "v@:d?") // open fun triggerNullary() { // } }
zach-klippenstein/compose-touchbar
17
Kotlin
zach-klippenstein
Zach Klippenstein
Square
src/main/kotlin/GroupItem.kt
Kotlin
import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCompositionContext import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.setValue import ca.weblite.objc.Proxy @Composable fun TouchBarScope.GroupItem( content: @Composable TouchBarScope.() -> Unit ) { var groupItem: Proxy? by remember { mutableStateOf(null) } TouchBarItemNode( factory = { id -> val item = client.sendProxy("NSGroupTouchBarItem", "alloc") .sendProxy("initWithIdentifier:", id) groupItem = item TouchBarItemNode(id, item) }, update = {} ) TouchBarComposition( onTouchBarInvalidated = { val group = groupItem ?: return@TouchBarComposition group["groupTouchBar"] = client.createNSTouchBar(it) }, content = content ) }
zach-klippenstein/compose-touchbar
17
Kotlin
zach-klippenstein
Zach Klippenstein
Square
src/main/kotlin/NSTouchBars.kt
Kotlin
@file:Suppress("JAVA_MODULE_DOES_NOT_EXPORT_PACKAGE") import ca.weblite.objc.Client import ca.weblite.objc.NSObject import ca.weblite.objc.Proxy import ca.weblite.objc.RuntimeUtils.cls import ca.weblite.objc.annotations.Msg import com.sun.jna.Pointer import sun.lwawt.LWWindowPeer import sun.lwawt.macosx.CPlatformWindow import java.awt.Component internal data class KTouchBarSpec( val defaultIdentifiers: List<String> = emptyList(), val customizableIdentifiers: List<String> = emptyList(), val principleItemIdentifier: String? = null, val customizationIdentifier: String? = null, val itemProvider: (identifier: String) -> Proxy ) private val EmptyKTouchBarSpec = KTouchBarSpec { error("Invalid identifier: $it") } private val componentClass = Component::class.java private val peerField = componentClass.getDeclaredField("peer").apply { isAccessible = true } internal fun Component.getNSWindow(client: Client): Proxy { // See https://github.com/Thizzer/jtouchbar/blob/e55d6e1f3e8b9e84bb668371de2eb92a5117ed1c/src/main/objective-c%2B%2B/Bridged/JNI/JTouchBarBridge.mm#L36-L49 // First dig through the Swing classes to find the native pointer to the view that Swing is // using. val peer = peerField.get(this) as? LWWindowPeer ?: error("Invalid peer") val platformWindow = peer.platformWindow as? CPlatformWindow ?: error("Invalid platform window") val awtViewPointer = Pointer(platformWindow.contentView.awtView) // Next try to figure out what that actually points to. val isView = client.send(awtViewPointer, "isKindOfClass:", cls("NSView")) == 1.toByte() val isWindow = client.send(awtViewPointer, "isKindOfClass:", cls("NSWindow")) == 1.toByte() return when { isView -> { client.sendProxy(awtViewPointer, "window") } isWindow -> { TODO() } else -> { error("Invalid view type") } } } internal fun Client.createEmptyNSTouchBar(): Proxy = createNSTouchBar(EmptyKTouchBarSpec) internal fun Client.createNSTouchBar(spec: KTouchBarSpec): Proxy { // See https://github.com/Thizzer/jtouchbar/blob/e55d6e1f3e8b9e84bb668371de2eb92a5117ed1c/src/main/objective-c%2B%2B/Bridged/JavaTouchBar.mm#L129 val nsTouchBar = sendProxy("NSTouchBar", "alloc") .sendProxy("init") val defaultIdentifiers = sendProxy("NSMutableArray", "alloc") .sendProxy("init") // TODO customizable spec.defaultIdentifiers.forEach { identifier -> defaultIdentifiers.send("addObject:", identifier) } nsTouchBar["defaultItemIdentifiers"] = defaultIdentifiers nsTouchBar["delegate"] = TouchBarDelegate(spec.itemProvider) return nsTouchBar } private class TouchBarDelegate( private val itemProvider: (identifier: String) -> Proxy ) : NSObject("NSObject") { /* -(NSTouchBarItem *) touchBar:(NSTouchBar *)touchBar makeItemForIdentifier:(NSTouchBarItemIdentifier)identifier { return [JTouchBarUtils touchBar:touchBar makeItemForIdentifier:identifier usingJavaTouchBar:_jTouchBar]; */ @Suppress("UNUSED_PARAMETER") @Msg(selector = "touchBar:makeItemForIdentifier:", signature = "@@:@@") fun makeItemForIdentifier(touchBar: Proxy, identifier: String): Proxy { return itemProvider(identifier) } }
zach-klippenstein/compose-touchbar
17
Kotlin
zach-klippenstein
Zach Klippenstein
Square
src/main/kotlin/PopoverItem.kt
Kotlin
import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import ca.weblite.objc.NSObject import ca.weblite.objc.Proxy import ca.weblite.objc.RuntimeUtils.sel import ca.weblite.objc.annotations.Msg @Composable fun TouchBarScope.PopoverItem( collapsedLabel: String, popoverController: PopoverController = remember { PopoverController() }, showCloseButton: Boolean = true, showOnPressAndHold: Boolean = true, content: @Composable TouchBarScope.() -> Unit, ) { PopoverItem( collapsedLabel = collapsedLabel, popoverController = popoverController, showCloseButton = showCloseButton, popoverContent = content, pressAndHoldContent = if (showOnPressAndHold) content else null ) } @Composable fun TouchBarScope.PopoverItem( collapsedLabel: String, popoverController: PopoverController = remember { PopoverController() }, showCloseButton: Boolean = true, popoverContent: @Composable (TouchBarScope.() -> Unit)?, pressAndHoldContent: @Composable (TouchBarScope.() -> Unit)?, ) { var popoverItem: Proxy by remember { mutableStateOf(Proxy()) } if (popoverContent != null) { TouchBarComposition( onTouchBarInvalidated = { spec -> popoverItem["popoverTouchBar"] = client.createNSTouchBar(spec) }, onDispose = { popoverItem["popoverTouchBar"] = client.createEmptyNSTouchBar() }, content = popoverContent ) } if (pressAndHoldContent != null) { TouchBarComposition( onTouchBarInvalidated = { spec -> popoverItem["pressAndHoldTouchBar"] = client.createNSTouchBar(spec) }, onDispose = { popoverItem["pressAndHoldTouchBar"] = null }, content = pressAndHoldContent ) } TouchBarItemNode( factory = { id -> popoverItem = client.sendProxy("NSPopoverTouchBarItem", "alloc") .sendProxy("initWithIdentifier:", id) TouchBarItemNode(id, popoverItem) }, update = { set(collapsedLabel) { itemImpl["collapsedRepresentationLabel"] = it } set(showCloseButton) { itemImpl.send("setShowsCloseButton:", it) } } ) DisposableEffect(popoverController) { // We don't need to key the effect on popoverItem since it will only be set once, and by the // time the effect runs it will already have been set. popoverController.popoverItems += popoverItem onDispose { popoverController.popoverItems -= popoverItem } } } class PopoverController { internal var popoverItems = listOf<Proxy>() /** Helper object to execute show/dismiss methods on the AppKit main thread. */ private val executor = object : NSObject("NSObject") { @Msg(selector = "showAll", signature = "v@:") fun showAll() { popoverItems.forEach { it.send("showPopover:", /* sender */ this) } } @Msg(selector = "dismissAll", signature = "v@:") fun dismissAll() { popoverItems.forEach { it.send("dismissPopover:", /* sender */ this) } } } fun show() { executor.send( "performSelectorOnMainThread:withObject:waitUntilDone:", sel("showAll"), executor, /* waitUntilDone */ false ) } fun dismiss() { executor.send( "performSelectorOnMainThread:withObject:waitUntilDone:", sel("dismissAll"), executor, /* waitUntilDone */ false ) } }
zach-klippenstein/compose-touchbar
17
Kotlin
zach-klippenstein
Zach Klippenstein
Square
src/main/kotlin/Sample.kt
Kotlin
import ColorPickerButtonType.Standard import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.IntrinsicSize import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.height import androidx.compose.material.Button import androidx.compose.material.Checkbox import androidx.compose.material.MaterialTheme import androidx.compose.material.RadioButton import androidx.compose.material.Text import androidx.compose.material.TextField import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment.Companion.CenterVertically import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.window.singleWindowApplication import kotlin.math.roundToInt fun main() = singleWindowApplication { var text by remember { mutableStateOf("Hello, World!") } var showTouchBar by remember { mutableStateOf(true) } var sliderValue by remember { mutableStateOf(5f) } var showCloseButton by remember { mutableStateOf(true) } val popoverController = remember { PopoverController() } var colorPickerType: ColorPickerButtonType by remember { mutableStateOf(Standard) } var color by remember { mutableStateOf(Color.Blue) } MaterialTheme { Column { Button(onClick = { text = "Hello, Desktop!" }) { Text(text) } TextField(text, onValueChange = { text = it }) Text("Slider: $sliderValue") Row(verticalAlignment = CenterVertically) { Text("Show TouchBar: ") Checkbox(showTouchBar, onCheckedChange = { showTouchBar = it }) } Row(verticalAlignment = CenterVertically) { Text("Show popover close button: ") Checkbox(showCloseButton, onCheckedChange = { showCloseButton = it }) Button(onClick = popoverController::show) { Text("Open") } Button(onClick = popoverController::dismiss) { Text("Close") } } Row(verticalAlignment = CenterVertically, modifier = Modifier.height(IntrinsicSize.Min)) { Box( Modifier .fillMaxHeight() .aspectRatio(1f, matchHeightConstraintsFirst = true) .background(color) ) Text("Color picker type: ") RadioButton( selected = colorPickerType == Standard, onClick = { colorPickerType = Standard } ) Text("Standard") RadioButton( selected = colorPickerType == ColorPickerButtonType.Text, onClick = { colorPickerType = ColorPickerButtonType.Text } ) Text("Text") RadioButton( selected = colorPickerType == ColorPickerButtonType.Stroke, onClick = { colorPickerType = ColorPickerButtonType.Stroke } ) Text("Stroke") } } if (showTouchBar) { TouchBar { TextItem(text) ButtonItem("Click me!", onClick = { sliderValue = 1f }) GroupItem { TextItem("child!") ButtonItem("child button", onClick = { sliderValue = 9f }) } PopoverItem( collapsedLabel = "Open Slider", popoverController = popoverController, showCloseButton = showCloseButton ) { SliderItem( value = sliderValue, minValue = 0f, maxValue = 10f, onValueChanged = { sliderValue = it } ) TextItem(sliderValue.roundToInt().toString()) } ColorPickerItem(color, onColorChange = { color = it }) } } } }
zach-klippenstein/compose-touchbar
17
Kotlin
zach-klippenstein
Zach Klippenstein
Square
src/main/kotlin/SliderItem.kt
Kotlin
import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberUpdatedState import ca.weblite.objc.RuntimeUtils.sel @Composable fun TouchBarScope.SliderItem( value: Float, onValueChanged: (Float) -> Unit, label: String? = null, minValue: Float = 0f, maxValue: Float = 1f ) { val updatedOnValueChanged by rememberUpdatedState(onValueChanged) TouchBarItemNode( factory = { id -> val item = client.sendProxy("NSSliderTouchBarItem", "alloc") .sendProxy("initWithIdentifier:", id) val actionTarget = object : GenericActionTarget() { override fun triggerNullary() { // getDouble returns an NSNumber proxy, not an actual double. Bug? val currentValue = item.sendRaw("doubleValue") as Double updatedOnValueChanged(currentValue.toFloat()) } } item["target"] = actionTarget // For some reason we can't set this property using .set(), it has its own set selector. item.send("setAction:", sel("triggerNullary")) val slider = item.getProxy("slider") TouchBarItemNode(id, item, slider) }, update = { set(label) { itemImpl["label"] = it } set(minValue) { viewImpl!!.sendRaw("setMinValue:", it.toDouble()) } set(maxValue) { viewImpl!!.sendRaw("setMaxValue:", it.toDouble()) } // This must be done after setting min and max, in case the new value is outside the previous // range. set(value) { itemImpl.sendRaw("setDoubleValue:", it.toDouble()) } } ) }
zach-klippenstein/compose-touchbar
17
Kotlin
zach-klippenstein
Zach Klippenstein
Square
src/main/kotlin/TextItem.kt
Kotlin
import androidx.compose.runtime.Composable import ca.weblite.objc.RuntimeUtils.str @Composable fun TouchBarScope.TextItem(text: String) { TouchBarViewNode( viewFactory = { client.sendProxy("NSTextField", "labelWithString:", text) }, update = { set(text) { viewImpl!!.send("setStringValue:", str(it)) } } ) }
zach-klippenstein/compose-touchbar
17
Kotlin
zach-klippenstein
Zach Klippenstein
Square
src/main/kotlin/TouchBar.kt
Kotlin
import androidx.compose.runtime.Composable import androidx.compose.runtime.ComposeNode import androidx.compose.runtime.DisallowComposableCalls import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.Updater import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCompositionContext import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.window.WindowScope import ca.weblite.objc.Client import ca.weblite.objc.Proxy import java.util.UUID class TouchBarScope internal constructor(internal val client: Client) @Composable fun WindowScope.TouchBar(content: @Composable TouchBarScope.() -> Unit) { val composition = rememberCompositionContext() val updatedContent by rememberUpdatedState(content) DisposableEffect(window) { val client = Client.getInstance() val nsWindow = window.getNSWindow(client) val scope = TouchBarScope(client) val touchBarComposition = scope.createTouchBarComposition( parentComposition = composition, onTouchBarInvalidated = { nsWindow["touchBar"] = client.createNSTouchBar(it) } ) { updatedContent() } onDispose { touchBarComposition.dispose() nsWindow["touchBar"] = null } } } @Composable internal inline fun TouchBarItemNode( noinline factory: (identifier: String) -> TouchBarItemNode, update: @DisallowComposableCalls (Updater<TouchBarItemNode>.() -> Unit) ) { // currentCompositeKeyHash is returning the same key for all invocations of a given function // within the same lambda. I didn't think that was how it was supposd to work – wouldn't that // break rememberSaveable? // currentCompositeKeyHash.toString(36) val identifier = remember { UUID.randomUUID().toString() } ComposeNode<TouchBarItemNode, TouchBarApplier>( factory = { factory(identifier) }, update = update ) } @Composable internal inline fun TouchBarScope.TouchBarViewNode( crossinline viewFactory: () -> Proxy, update: @DisallowComposableCalls (Updater<TouchBarItemNode>.() -> Unit) ) { TouchBarItemNode( factory = { id -> val item = client.sendProxy("NSCustomTouchBarItem", "alloc") .sendProxy("initWithIdentifier:", id) val view = viewFactory() item["view"] = view TouchBarItemNode(id, item, view) }, update = update ) }
zach-klippenstein/compose-touchbar
17
Kotlin
zach-klippenstein
Zach Klippenstein
Square
src/main/kotlin/TouchBarApplier.kt
Kotlin
import androidx.compose.runtime.AbstractApplier import androidx.compose.runtime.Composable import androidx.compose.runtime.Composition import androidx.compose.runtime.CompositionContext import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberCompositionContext import androidx.compose.runtime.rememberUpdatedState import ca.weblite.objc.Client import ca.weblite.objc.Proxy internal data class TouchBarItemNode( val identifier: String, val itemImpl: Proxy, val viewImpl: Proxy? = null ) private val RootTouchBarItemNode = TouchBarItemNode("", Proxy(), null) internal class TouchBarApplier( private val onTouchBarInvalidated: (List<TouchBarItemNode>) -> Unit ) : AbstractApplier<TouchBarItemNode>(RootTouchBarItemNode) { private var previousIdentifiers = emptyList<String>() private val items = mutableListOf<TouchBarItemNode>() override fun insertTopDown(index: Int, instance: TouchBarItemNode) { items.add(index, instance) } override fun insertBottomUp(index: Int, instance: TouchBarItemNode) { // Ignore. } override fun move(from: Int, to: Int, count: Int) { items.move(from, to, count) } override fun remove(index: Int, count: Int) { items.remove(index, count) } override fun onClear() { items.clear() } override fun onEndChanges() { val newIdentifiers = items.map { it.identifier } if (newIdentifiers != previousIdentifiers) { // Need to set a new NSTouchBar on the NSWindow. onTouchBarInvalidated(items.toList()) } previousIdentifiers = newIdentifiers } } @Composable internal fun TouchBarScope.TouchBarComposition( onTouchBarInvalidated: (KTouchBarSpec) -> Unit, onDispose: () -> Unit = {}, content: @Composable TouchBarScope.() -> Unit ) { val composition = rememberCompositionContext() val updatedContent by rememberUpdatedState(content) val updatedOnDispose by rememberUpdatedState(onDispose) DisposableEffect(this) { val touchBarComposition = createTouchBarComposition( parentComposition = composition, onTouchBarInvalidated = onTouchBarInvalidated, ) { updatedContent() } onDispose { touchBarComposition.dispose() updatedOnDispose() } } } internal fun TouchBarScope.createTouchBarComposition( parentComposition: CompositionContext, onTouchBarInvalidated: (KTouchBarSpec) -> Unit, content: @Composable TouchBarScope.() -> Unit ): Composition { val applier = TouchBarApplier { items -> val spec = KTouchBarSpec( defaultIdentifiers = items.map { it.identifier }, itemProvider = { identifier -> items.first { it.identifier == identifier }.itemImpl } ) onTouchBarInvalidated(spec) } return Composition(applier, parentComposition).apply { setContent { content() } } }
zach-klippenstein/compose-touchbar
17
Kotlin
zach-klippenstein
Zach Klippenstein
Square
src/main/kotlin/TouchBarImage.kt
Kotlin
import ca.weblite.objc.Proxy class TouchBarImage internal constructor(internal val nsImage: Proxy) { override fun equals(other: Any?): Boolean = (other as? TouchBarImage)?.nsImage == nsImage override fun hashCode(): Int = nsImage.hashCode() }
zach-klippenstein/compose-touchbar
17
Kotlin
zach-klippenstein
Zach Klippenstein
Square
src/main/kotlin/TouchBarImages.kt
Kotlin
// import ca.weblite.objc.Client // // object TouchBarImages { // val TouchBarAddDetail by lazy { loadImageNamed("NSImageNameTouchBarAddDetailTemplate") } // val TouchBarAdd by lazy { loadImageNamed("NSImageNameTouchBarAddTemplate") } // val TouchBarAlarm by lazy { loadImageNamed("NSImageNameTouchBarAlarmTemplate") } // val TouchBarAudioInputMute by lazy { loadImageNamed("NSImageNameTouchBarAudioInputMuteTemplate") } // val TouchBarAudioInput by lazy { loadImageNamed("NSImageNameTouchBarAudioInputTemplate") } // val TouchBarAudioOutputMute by lazy { loadImageNamed("NSImageNameTouchBarAudioOutputMuteTemplate") } // val TouchBarAudioOutputVolumeHigh by lazy { loadImageNamed("NSImageNameTouchBarAudioOutputVolumeHighTemplate") } // val TouchBarAudioOutputVolumeLow by lazy { loadImageNamed("NSImageNameTouchBarAudioOutputVolumeLowTemplate") } // val TouchBarAudioOutputVolumeMedium by lazy { loadImageNamed("NSImageNameTouchBarAudioOutputVolumeMediumTemplate") } // val TouchBarAudioOutputVolumeOff by lazy { loadImageNamed("NSImageNameTouchBarAudioOutputVolumeOffTemplate") } // val TouchBarBookmarks by lazy { loadImageNamed("NSImageNameTouchBarBookmarksTemplate") } // val TouchBarColorPickerFill by lazy { loadImageNamed("NSImageNameTouchBarColorPickerFill") } // val TouchBarColorPickerFont by lazy { loadImageNamed("NSImageNameTouchBarColorPickerFont") } // val TouchBarColorPickerStroke by lazy { loadImageNamed("NSImageNameTouchBarColorPickerStroke") } // val TouchBarCommunicationAudio by lazy { loadImageNamed("NSImageNameTouchBarCommunicationAudioTemplate") } // val TouchBarCommunicationVideo by lazy { loadImageNamed("NSImageNameTouchBarCommunicationVideoTemplate") } // val TouchBarCompose by lazy { loadImageNamed("NSImageNameTouchBarComposeTemplate") } // val TouchBarDelete by lazy { loadImageNamed("NSImageNameTouchBarDeleteTemplate") } // val TouchBarDownload by lazy { loadImageNamed("NSImageNameTouchBarDownloadTemplate") } // val TouchBarEnterFullScreen by lazy { loadImageNamed("NSImageNameTouchBarEnterFullScreenTemplate") } // val TouchBarExitFullScreen by lazy { loadImageNamed("NSImageNameTouchBarExitFullScreenTemplate") } // val TouchBarFastForward by lazy { loadImageNamed("NSImageNameTouchBarFastForwardTemplate") } // val TouchBarFolder by lazy { loadImageNamed("NSImageNameTouchBarFolderTemplate") } // val TouchBarFolderCopyTo by lazy { loadImageNamed("NSImageNameTouchBarFolderCopyToTemplate") } // val TouchBarFolderMoveTo by lazy { loadImageNamed("NSImageNameTouchBarFolderMoveToTemplate") } // val TouchBarGetInfo by lazy { loadImageNamed("NSImageNameTouchBarGetInfoTemplate") } // val TouchBarGoBack by lazy { loadImageNamed("NSImageNameTouchBarGoBackTemplate") } // val TouchBarGoDown by lazy { loadImageNamed("NSImageNameTouchBarGoDownTemplate") } // val TouchBarGoForward by lazy { loadImageNamed("NSImageNameTouchBarGoForwardTemplate") } // val TouchBarGoUp by lazy { loadImageNamed("NSImageNameTouchBarGoUpTemplate") } // val TouchBarHistory by lazy { loadImageNamed("NSImageNameTouchBarHistoryTemplate") } // val TouchBarIconView by lazy { loadImageNamed("NSImageNameTouchBarIconViewTemplate") } // val TouchBarListView by lazy { loadImageNamed("NSImageNameTouchBarListViewTemplate") } // val TouchBarMail by lazy { loadImageNamed("NSImageNameTouchBarMailTemplate") } // val TouchBarNewFolder by lazy { loadImageNamed("NSImageNameTouchBarNewFolderTemplate") } // val TouchBarNewMessage by lazy { loadImageNamed("NSImageNameTouchBarNewMessageTemplate") } // val TouchBarOpenInBrowser by lazy { loadImageNamed("NSImageNameTouchBarOpenInBrowserTemplate") } // val TouchBarPause by lazy { loadImageNamed("NSImageNameTouchBarPauseTemplate") } // val TouchBarPlay by lazy { loadImageNamed("NSImageNameTouchBarPlayTemplate") } // val TouchBarPlayPause by lazy { loadImageNamed("NSImageNameTouchBarPlayPauseTemplate") } // val TouchBarPlayhead by lazy { loadImageNamed("NSImageNameTouchBarPlayheadTemplate") } // val TouchBarQuickLook by lazy { loadImageNamed("NSImageNameTouchBarQuickLookTemplate") } // val TouchBarRecordStart by lazy { loadImageNamed("NSImageNameTouchBarRecordStartTemplate") } // val TouchBarRecordStop by lazy { loadImageNamed("NSImageNameTouchBarRecordStopTemplate") } // val TouchBarRefresh by lazy { loadImageNamed("NSImageNameTouchBarRefreshTemplate") } // val TouchBarRewind by lazy { loadImageNamed("NSImageNameTouchBarRewindTemplate") } // val TouchBarRotateLeft by lazy { loadImageNamed("NSImageNameTouchBarRotateLeftTemplate") } // val TouchBarRotateRight by lazy { loadImageNamed("NSImageNameTouchBarRotateRightTemplate") } // val TouchBarSearch by lazy { loadImageNamed("NSImageNameTouchBarSearchTemplate") } // val TouchBarShare by lazy { loadImageNamed("NSImageNameTouchBarShareTemplate") } // val TouchBarSidebar by lazy { loadImageNamed("NSImageNameTouchBarSidebarTemplate") } // val TouchBarSkipBack by lazy { loadImageNamed("NSImageNameTouchBarSkipBackTemplate") } // val TouchBarSkipToStart by lazy { loadImageNamed("NSImageNameTouchBarSkipToStartTemplate") } // val TouchBarSkipBack30Seconds by lazy { loadImageNamed("NSImageNameTouchBarSkipBack30SecondsTemplate") } // val TouchBarSkipBack15Seconds by lazy { loadImageNamed("NSImageNameTouchBarSkipBack15SecondsTemplate") } // val TouchBarSkipAhead15Seconds by lazy { loadImageNamed("NSImageNameTouchBarSkipAhead15SecondsTemplate") } // val TouchBarSkipAhead30Seconds by lazy { loadImageNamed("NSImageNameTouchBarSkipAhead30SecondsTemplate") } // val TouchBarSkipToEnd by lazy { loadImageNamed("NSImageNameTouchBarSkipToEndTemplate") } // val TouchBarSkipAhead by lazy { loadImageNamed("NSImageNameTouchBarSkipAheadTemplate") } // val TouchBarSlideshow by lazy { loadImageNamed("NSImageNameTouchBarSlideshowTemplate") } // val TouchBarTagIcon by lazy { loadImageNamed("NSImageNameTouchBarTagIconTemplate") } // val TouchBarTextBox by lazy { loadImageNamed("NSImageNameTouchBarTextBoxTemplate") } // val TouchBarTextList by lazy { loadImageNamed("NSImageNameTouchBarTextListTemplate") } // val TouchBarTextBold by lazy { loadImageNamed("NSImageNameTouchBarTextBoldTemplate") } // val TouchBarTextItalic by lazy { loadImageNamed("NSImageNameTouchBarTextItalicTemplate") } // val TouchBarTextUnderline by lazy { loadImageNamed("NSImageNameTouchBarTextUnderlineTemplate") } // val TouchBarTextStrikethrough by lazy { loadImageNamed("NSImageNameTouchBarTextStrikethroughTemplate") } // val TouchBarTextJustifiedAlign by lazy { loadImageNamed("NSImageNameTouchBarTextJustifiedAlignTemplate") } // val TouchBarTextLeftAlign by lazy { loadImageNamed("NSImageNameTouchBarTextLeftAlignTemplate") } // val TouchBarTextCenterAlign by lazy { loadImageNamed("NSImageNameTouchBarTextCenterAlignTemplate") } // val TouchBarTextRightAlign by lazy { loadImageNamed("NSImageNameTouchBarTextRightAlignTemplate") } // val TouchBarUser by lazy { loadImageNamed("NSImageNameTouchBarUserTemplate") } // val TouchBarUserAdd by lazy { loadImageNamed("NSImageNameTouchBarUserAddTemplate") } // val TouchBarUserGroup by lazy { loadImageNamed("NSImageNameTouchBarUserGroupTemplate") } // val TouchBarVolumeUp by lazy { loadImageNamed("NSImageNameTouchBarVolumeUpTemplate") } // val TouchBarVolumeDown by lazy { loadImageNamed("NSImageNameTouchBarVolumeDownTemplate") } // // private val client = Client.getInstance() // private fun loadImageNamed(name: String): TouchBarImage { // val imageName = client.sendProxy("NSTouchBarItem", name) // return client.sendProxy("NSImage", "imageNamed:", imageName) // .let(::TouchBarImage) // } // }
zach-klippenstein/compose-touchbar
17
Kotlin
zach-klippenstein
Zach Klippenstein
Square
build.gradle
Gradle
buildscript { ext { compose_ui_version = '1.3.0-beta02' } }// Top-level build file where you can add configuration options common to all sub-projects/modules. plugins { id 'com.android.application' version '7.4.0-alpha10' apply false id 'com.android.library' version '7.4.0-alpha10' apply false id 'org.jetbrains.kotlin.android' version '1.7.10' apply false id 'com.vanniktech.maven.publish' version '0.22.0' apply false }
zach-klippenstein/compose-undo
149
Undo snapshot state changes in Compose.
Kotlin
zach-klippenstein
Zach Klippenstein
Square
demo/build.gradle
Gradle
plugins { id 'com.android.application' id 'org.jetbrains.kotlin.android' } android { namespace 'com.zachklipp.statehistory.demo' compileSdk 33 defaultConfig { applicationId "com.zachklipp.statehistory.demo" minSdk 21 targetSdk 33 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" vectorDrawables { useSupportLibrary true } } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = '1.8' } buildFeatures { compose true } composeOptions { kotlinCompilerExtensionVersion '1.3.1' } packagingOptions { resources { excludes += '/META-INF/{AL2.0,LGPL2.1}' } } } dependencies { implementation project(':statehistory') implementation 'androidx.core:core-ktx:1.9.0' implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.5.1' implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:2.5.1' implementation 'androidx.activity:activity-compose:1.5.1' implementation "androidx.compose.ui:ui:$compose_ui_version" implementation "androidx.compose.ui:ui-tooling-preview:$compose_ui_version" implementation 'androidx.compose.material:material:1.2.1' testImplementation 'junit:junit:4.13.2' androidTestImplementation 'androidx.test.ext:junit:1.1.3' androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_ui_version" androidTestImplementation 'com.google.truth:truth:1.1.3' debugImplementation "androidx.compose.ui:ui-tooling:$compose_ui_version" debugImplementation "androidx.compose.ui:ui-test-manifest:$compose_ui_version" }
zach-klippenstein/compose-undo
149
Undo snapshot state changes in Compose.
Kotlin
zach-klippenstein
Zach Klippenstein
Square
demo/src/androidTest/java/com/zachklipp/statehistory/demo/DemoTest.kt
Kotlin
package com.zachklipp.statehistory.demo import androidx.compose.ui.semantics.SemanticsActions import androidx.compose.ui.semantics.SemanticsProperties import androidx.compose.ui.semantics.progressBarRangeInfo import androidx.compose.ui.test.* import androidx.compose.ui.test.junit4.createComposeRule import androidx.test.ext.junit.runners.AndroidJUnit4 import com.google.common.truth.Truth.assertThat import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class DemoTest { @get:Rule val rule = createComposeRule() @Test fun typingUpdatesFrameCount() { rule.setContent { AppWithInspector() } rule.onNode(hasSetTextAction()).performTextInput("a") rule.onNodeWithText("Frame 1 of 1").assertIsDisplayed() rule.onNode(hasSetTextAction()).performTextInput("b") rule.onNodeWithText("Frame 2 of 2").assertIsDisplayed() } @Test fun addingToListUpdatesFrameCount() { rule.setContent { AppWithInspector() } rule.onNode(hasSetTextAction()).performTextInput("a") rule.onNodeWithText("Add to list").performClick() rule.onNodeWithText("Frame 2 of 2").assertIsDisplayed() } @Test fun sliderScrubsHistory() { rule.setContent { AppWithInspector() } rule.onNode(hasSetTextAction()).performTextInput("a") rule.onNode(hasSetTextAction()).performTextInput("b") rule.onNode(hasSetTextAction()).assertTextEquals("ab") rule.onNode(hasSetProgressAction()).assertProgressValue(2f) rule.onNode(hasSetProgressAction()).performSetProgress(1f) rule.onNode(hasSetTextAction()).assertTextEquals("a") rule.onNodeWithText("Frame 1 of 2").assertIsDisplayed() } private fun hasSetProgressAction() = SemanticsMatcher("has setProgress action") { it.config.contains(SemanticsActions.SetProgress) } private fun SemanticsNodeInteraction.assertProgressValue(value: Float) { assertThat( fetchSemanticsNode().config[SemanticsProperties.ProgressBarRangeInfo].current ).isEqualTo(value) } private fun SemanticsNodeInteraction.performSetProgress(value: Float) { fetchSemanticsNode().config[SemanticsActions.SetProgress].action!!.invoke(value) } }
zach-klippenstein/compose-undo
149
Undo snapshot state changes in Compose.
Kotlin
zach-klippenstein
Zach Klippenstein
Square
demo/src/main/java/com/zachklipp/statehistory/demo/App.kt
Kotlin
package com.zachklipp.statehistory.demo import androidx.compose.foundation.border import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.material.TextField import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.zachklipp.statehistory.trackStateHistory @Preview(showBackground = true, showSystemUi = true) @Composable fun AppPreview() { App() } @Composable fun App() { var textValue by remember { mutableStateOf(TextFieldValue("")) }.trackStateHistory() val valueList = remember { mutableStateListOf<String>() }.trackStateHistory() fun addValueToList() { valueList += textValue.text textValue = TextFieldValue("") } Column(Modifier.padding(8.dp)) { TextField( modifier = Modifier.fillMaxWidth(), value = textValue, onValueChange = { textValue = it }, keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send), keyboardActions = KeyboardActions { addValueToList() } ) Button( modifier = Modifier.fillMaxWidth(), onClick = { addValueToList() } ) { Text("Add to list") } LazyColumn( reverseLayout = true, modifier = Modifier .border(1.dp, Color.Black) .fillMaxWidth() ) { items(valueList) { Text(it, modifier = Modifier.padding(16.dp)) } } } }
zach-klippenstein/compose-undo
149
Undo snapshot state changes in Compose.
Kotlin
zach-klippenstein
Zach Klippenstein
Square
demo/src/main/java/com/zachklipp/statehistory/demo/AppWithInspector.kt
Kotlin
package com.zachklipp.statehistory.demo import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.lifecycle.ViewModel import androidx.lifecycle.viewmodel.compose.viewModel import com.zachklipp.statehistory.StateHistory import com.zachklipp.statehistory.demo.ui.theme.StateHistoryDemoTheme @Composable fun AppWithInspector() { val stateHistory = viewModel<StateHistoryViewModel>().stateHistory StateHistoryDemoTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background ) { StateHistoryInspector(stateHistory) { App() } } } } class StateHistoryViewModel : ViewModel() { val stateHistory = StateHistory() }
zach-klippenstein/compose-undo
149
Undo snapshot state changes in Compose.
Kotlin
zach-klippenstein
Zach Klippenstein
Square
demo/src/main/java/com/zachklipp/statehistory/demo/MainActivity.kt
Kotlin
package com.zachklipp.statehistory.demo import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.ui.Modifier import androidx.lifecycle.ViewModel import androidx.lifecycle.viewmodel.compose.viewModel import com.zachklipp.statehistory.StateHistory import com.zachklipp.statehistory.demo.ui.theme.StateHistoryDemoTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { AppWithInspector() } } }
zach-klippenstein/compose-undo
149
Undo snapshot state changes in Compose.
Kotlin
zach-klippenstein
Zach Klippenstein
Square
demo/src/main/java/com/zachklipp/statehistory/demo/StateHistoryInspector.kt
Kotlin
package com.zachklipp.statehistory.demo import androidx.compose.foundation.layout.* import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.ArrowForward import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.zachklipp.statehistory.* import kotlin.math.roundToInt @Composable fun StateHistoryInspector( stateHistory: StateHistory, modifier: Modifier = Modifier, content: @Composable () -> Unit ) { Column(modifier) { Box(propagateMinConstraints = true, modifier = Modifier.weight(1f)) { CompositionLocalProvider(LocalStateHistory provides stateHistory, content = content) } HistoryScrubber(stateHistory) } } @Composable private fun HistoryScrubber(stateHistory: StateHistory, modifier: Modifier = Modifier) { var recording by remember { mutableStateOf(true) } if (recording) { LaunchedEffect(stateHistory) { stateHistory.recordChanges { // Save a new frame every time something changes. This could also be done on a // timer, or only after significant actions. stateHistory.saveFrame() } } } Column(modifier.padding(8.dp)) { if (stateHistory.frameCount > 1) { Text( "Frame ${stateHistory.currentFrame} of ${stateHistory.frameCount - 1}", modifier = Modifier.align(Alignment.CenterHorizontally), style = MaterialTheme.typography.caption, ) Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, ) { Slider( value = stateHistory.currentFrame.toFloat(), valueRange = 0f..(stateHistory.frameCount - 1).toFloat(), steps = stateHistory.frameCount - 2, onValueChange = { stateHistory.setCurrentFrameGlobally(it.roundToInt()) }, modifier = Modifier .weight(1f) .padding(horizontal = 16.dp) ) } Row(modifier = Modifier.fillMaxWidth()) { IconButton( onClick = { stateHistory.undo() }, enabled = stateHistory.canUndo, modifier = Modifier.weight(1f) ) { Icon(Icons.Default.ArrowBack, contentDescription = "undo") } Button(onClick = { recording = !recording }) { Text(if (recording) "Stop recording" else "Start recording") } IconButton( onClick = { stateHistory.redo() }, enabled = stateHistory.canRedo, modifier = Modifier.weight(1f) ) { Icon(Icons.Default.ArrowForward, contentDescription = "redo") } } } } }
zach-klippenstein/compose-undo
149
Undo snapshot state changes in Compose.
Kotlin
zach-klippenstein
Zach Klippenstein
Square
demo/src/main/java/com/zachklipp/statehistory/demo/ui/theme/Color.kt
Kotlin
package com.zachklipp.statehistory.demo.ui.theme import androidx.compose.ui.graphics.Color val Purple200 = Color(0xFFBB86FC) val Purple500 = Color(0xFF6200EE) val Purple700 = Color(0xFF3700B3) val Teal200 = Color(0xFF03DAC5)
zach-klippenstein/compose-undo
149
Undo snapshot state changes in Compose.
Kotlin
zach-klippenstein
Zach Klippenstein
Square
demo/src/main/java/com/zachklipp/statehistory/demo/ui/theme/Shape.kt
Kotlin
package com.zachklipp.statehistory.demo.ui.theme import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Shapes import androidx.compose.ui.unit.dp val Shapes = Shapes( small = RoundedCornerShape(4.dp), medium = RoundedCornerShape(4.dp), large = RoundedCornerShape(0.dp) )
zach-klippenstein/compose-undo
149
Undo snapshot state changes in Compose.
Kotlin
zach-klippenstein
Zach Klippenstein
Square
demo/src/main/java/com/zachklipp/statehistory/demo/ui/theme/Theme.kt
Kotlin
package com.zachklipp.statehistory.demo.ui.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.MaterialTheme import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.runtime.Composable private val DarkColorPalette = darkColors( primary = Purple200, primaryVariant = Purple700, secondary = Teal200 ) private val LightColorPalette = lightColors( primary = Purple500, primaryVariant = Purple700, secondary = Teal200 /* Other default colors to override background = Color.White, surface = Color.White, onPrimary = Color.White, onSecondary = Color.Black, onBackground = Color.Black, onSurface = Color.Black, */ ) @Composable fun StateHistoryDemoTheme( darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit ) { val colors = if (darkTheme) { DarkColorPalette } else { LightColorPalette } MaterialTheme( colors = colors, typography = Typography, shapes = Shapes, content = content ) }
zach-klippenstein/compose-undo
149
Undo snapshot state changes in Compose.
Kotlin
zach-klippenstein
Zach Klippenstein
Square
demo/src/main/java/com/zachklipp/statehistory/demo/ui/theme/Type.kt
Kotlin
package com.zachklipp.statehistory.demo.ui.theme import androidx.compose.material.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( body1 = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp ) /* Other default text styles to override button = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.W500, fontSize = 14.sp ), caption = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 12.sp ) */ )
zach-klippenstein/compose-undo
149
Undo snapshot state changes in Compose.
Kotlin
zach-klippenstein
Zach Klippenstein
Square
settings.gradle
Gradle
pluginManagement { repositories { google() mavenCentral() gradlePluginPortal() } } dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) repositories { google() mavenCentral() } } rootProject.name = "State History" include ':demo' include ':statehistory'
zach-klippenstein/compose-undo
149
Undo snapshot state changes in Compose.
Kotlin
zach-klippenstein
Zach Klippenstein
Square
statehistory/build.gradle
Gradle
plugins { id 'com.android.library' id 'org.jetbrains.kotlin.android' id 'com.vanniktech.maven.publish' } android { namespace 'com.zachklipp.statehistory' compileSdk 33 defaultConfig { minSdk 21 targetSdk 33 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = '1.8' } buildFeatures { compose true } composeOptions { kotlinCompilerExtensionVersion '1.3.1' } packagingOptions { resources { excludes += '/META-INF/{AL2.0,LGPL2.1}' } } } dependencies { api "androidx.compose.runtime:runtime:$compose_ui_version" testImplementation 'junit:junit:4.13.2' testImplementation 'com.google.truth:truth:1.1.3' androidTestImplementation 'androidx.test.ext:junit:1.1.3' androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_ui_version" androidTestImplementation 'com.google.truth:truth:1.1.3' debugImplementation "androidx.compose.ui:ui-tooling:$compose_ui_version" debugImplementation "androidx.compose.ui:ui-test-manifest:$compose_ui_version" }
zach-klippenstein/compose-undo
149
Undo snapshot state changes in Compose.
Kotlin
zach-klippenstein
Zach Klippenstein
Square
statehistory/src/androidTest/java/com/zachklipp/statehistory/demo/StateHistoryTest.kt
Kotlin
package com.zachklipp.statehistory.demo import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.test.junit4.createComposeRule import androidx.test.ext.junit.runners.AndroidJUnit4 import com.google.common.truth.Truth.assertThat import com.zachklipp.statehistory.StateHistory import com.zachklipp.statehistory.WithStateHistory import com.zachklipp.statehistory.trackStateHistory import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class StateHistoryTest { @get:Rule val rule = createComposeRule() @Test fun withStateHistory_recordsChanges() { val state = mutableStateOf(0) lateinit var stateHistory: StateHistory rule.setContent { WithStateHistory { stateHistory = it state.trackStateHistory() } } rule.runOnIdle { assertThat(stateHistory.frameCount).isEqualTo(0) state.value = 1 } rule.runOnIdle { assertThat(stateHistory.frameCount).isEqualTo(1) } } }
zach-klippenstein/compose-undo
149
Undo snapshot state changes in Compose.
Kotlin
zach-klippenstein
Zach Klippenstein
Square
statehistory/src/main/java/com/zachklipp/statehistory/StateHistory.kt
Kotlin
package com.zachklipp.statehistory import androidx.compose.runtime.* import androidx.compose.runtime.collection.mutableVectorOf import androidx.compose.runtime.snapshots.* import kotlinx.coroutines.awaitCancellation import java.util.* import kotlin.contracts.ExperimentalContracts import kotlin.contracts.contract private const val DEBUG = true private const val TAG = "StateHistory" val LocalStateHistory: ProvidableCompositionLocal<StateHistory?> = staticCompositionLocalOf { null } /** * Convenience function for simple usage of [StateHistory]. * * Inside [content], call [MutableState.trackStateHistory], [SnapshotStateList.trackStateHistory], * and [SnapshotStateMap.trackStateHistory] to register state objects for change tracking, or pass * them to [StateHistory.startTrackingState]. Then use the [StateHistory.undo], [StateHistory.redo], * and [StateHistory.setCurrentFrameGlobally] methods to restore state. */ @Composable fun WithStateHistory(content: @Composable (StateHistory) -> Unit) { val stateHistory = remember { StateHistory() } LaunchedEffect(stateHistory) { stateHistory.recordChanges { stateHistory.saveFrame() } } CompositionLocalProvider(LocalStateHistory provides stateHistory) { content(stateHistory) } } /** * Records changes to state objects that are registered via [startTrackingState] (or * [trackStateHistory]) and allows restoring state to previous values. * * ## Usage * * ### Simple * * 1. Wrap your composition in [WithStateHistory]. * 2. Call [MutableState.trackStateHistory] on the states you want to track. (See also * [SnapshotStateList.trackStateHistory], [SnapshotStateMap.trackStateHistory].) * 3. Call [StateHistory.undo] to undo changes. * * ### Advanced * * 1. Create an instance of this that will live across recompositions (e.g. use remember or store * near the top of your DI object graph). * 1. Provide the instance to your composition through the [LocalStateHistory] composition local. * 1. Call [recordChanges] from a coroutine to start recording changes. To save a new history frame * every time some state changes are applied, pass a callback that calls [saveFrame]. * 1. Register states you want to track with [startTrackingState]. Make sure to call * [stopTrackingState] when finished with the state object to allow it to be garbage-collected. * If creating the state directly in a composition (e.g. with [remember]), you can also pass the * state object to [trackStateHistory] to automatically stop tracking it when it leaves the * composition. * 1. Call [setCurrentFrameGlobally] to restore the state of all tracked objects to the states they * had at the given frame, or call the convenience methods [undo]/[redo] to move the frame by one. * * ## Defining save points * * History frames will only be pushed onto the stack when [safeFrame] is called. You can call this * method whenever you want, so the granularity of the history is up to you. To get the most detail, * call it from the [recordChanges] callback, which will be invoked every time a snapshot is applied * to the global snapshot that changes one or more tracked state objects. If that's too much detail * for your use case, you can pass a null callback to [recordChanges] and call [saveFrame] only * whenever something significant happens in your app, at regular intervals with a timer, etc. * * **Key point: State changes from a single snapshot will always be saved to the same frame.** * * @sample WithStateHistory */ @Stable class StateHistory { /** * Used to guard access to [frames], [trackedStates], and [nextFrame]. */ private val lock = Any() /** * The set of all state objects we're currently tracking via [startTrackingState]. */ private val trackedStates = WeakHashMap<StateObject, Unit>() private var handle: ObserverHandle? = null /** * By storing and restoring [StateRecord]s directly, we don't have to care what types the state * objects are or even what data they hold. The records already implement all the operations * we need. */ private val frames = mutableVectorOf<WeakHashMap<StateObject, StateRecord>>() /** * We "start" recording the next frame as soon as the previous one is committed to the [frames] * list. This way we can eagerly record the initial value of newly-tracked objects from * [startTrackingState] so that their initial values will be saved on the next frame, even if * they're not recorded as changed. Maybe unnecessary? */ private var nextFrame = WeakHashMap<StateObject, StateRecord>() private var onTrackStateApplied: (() -> Unit)? = null /** * The total number of history frames that have been recorded. */ var frameCount: Int by mutableStateOf(0) private set /** * The index of frame that represents the current state. When the global snapshot is advanced * with changes to tracked state, this value will be incremented. It can also be set to a lower * value by calling [setCurrentFrameGlobally]. */ var currentFrame: Int by mutableStateOf(NoFrame) private set /** * Starts recording changes and suspends until cancelled. * * @param onTrackStateApplied Called every time a snapshot is applied to the global snapshot * that changes any of the state objects tracked via [startTrackingState]. Call [saveFrame] from * this callback to save every change to the history. */ suspend fun recordChanges(onTrackStateApplied: (() -> Unit)? = null) { if (!startRecording(onTrackStateApplied)) return try { awaitCancellation() } finally { stopRecording(clearOnTrackStateApplied = true) } } /** * Saves any changes to tracked state objects since the last call to this method to the history. * * If [currentFrame] is not the last frame, any frames after it will be removed. */ fun saveFrame() { // Take the lock outside the snapshot so // This won't conflict with the lock in the apply observer when the snapshot is applied // because the none of the states changed in this snapshot are tracked. synchronized(lock) { withGlobalMutableSnapshot { if (DEBUG) println("[$TAG] Recording frame ${currentFrame + 1}: $nextFrame") // If committing a new frame while peeking into the history, clear the // frames after this point and start recording fresh. if (frames.lastIndex > currentFrame) { frames.removeRange(currentFrame + 1, frames.size) } frames += nextFrame nextFrame = WeakHashMap() frameCount = frames.size currentFrame = frames.lastIndex } } } /** * Starts tracking changes [stateObject]. The current value of the object will be recorded in * the next frame, i.e. the next time the global snapshot is applied while * [recording][startRecording]. * * Calling [stopTrackingState] after this method is optional. If it's not called, the history * for the state object will be cleaned up when it's garbage collected. * * @param stateObject Must be a snapshot state object, such as a [MutableState], * [SnapshotStateList], etc. The concrete object must implement [StateObject]. */ fun <S : Any> startTrackingState(stateObject: S) { ensureValidStateObject(stateObject) if (stateObject in trackedStates) return // Record the initial state of the object in the next frame to be committed. val initialRecord = stateObject.copyCurrentRecord() synchronized(lock) { trackedStates[stateObject] = Unit nextFrame[stateObject] = initialRecord } if (DEBUG) println( "[$TAG] Starting to track object $stateObject with initial record $initialRecord" ) } /** * Stops tracking changes to [stateObject]. * * Calling this method after [startTrackingState] is optional. If it's not called, the history * for the state object will be cleaned up when it's garbage collected. */ fun stopTrackingState(stateObject: Any) { stateObject as StateObject if (DEBUG) println("[$TAG] Stopping tracking object $stateObject") synchronized(lock) { trackedStates -= stateObject nextFrame -= stateObject // Remove all references to the state object from the history so it can be GC'd. // TODO Figure out a way to do this without iterating through the entire history. // WeakRefs? frames.forEach { it -= stateObject } } } /** * Restores the values of all tracked state objects to the values they had at the frame at * [frameIndex]. Calling this method will not change [frameCount] immediately, although the next * time a tracked state is changed and applied to the global snapshot, all frames between * [currentFrame] and [frameCount] will be removed and replaced with a new frame. * * The [frameIndex] will be coerced into the valid frame range, and this function will do * nothing if equal to [currentFrame]. */ fun setCurrentFrameGlobally(frameIndex: Int) { if (frameIndex == currentFrame) return // Stop recording so we don't record the application of the mutable snapshot below as a // new frame. Use the return value instead of isRecording to avoid a race. // Don't clear the callback so we can re-use it after. val wasRecording = stopRecording(clearOnTrackStateApplied = false) if (DEBUG) println( "[$TAG] Pausing recording to set current frame (wasRecording=$wasRecording)" ) // Peeking in non-global snapshots is not currently supported. synchronized(lock) { withGlobalMutableSnapshot { @Suppress("NAME_SHADOWING") val frameIndex = frameIndex.coerceIn(0, frames.lastIndex) if (DEBUG) println("[$TAG] Setting current frame to $frameIndex") // Check again after coercing. if (frameIndex == currentFrame) return currentFrame = frameIndex trackedStates.forEach { (stateObject, _) -> // Find the latest frame containing the state object, if any. var readFrameIndex = frameIndex while (readFrameIndex >= 0 && stateObject !in frames[readFrameIndex]) { readFrameIndex-- } if (readFrameIndex >= 0) { val frame = frames[readFrameIndex] val record = frame.getValue(stateObject) if (DEBUG) println("[$TAG] Restoring $stateObject to $record") stateObject.restoreFrom(record) } else if (DEBUG) { println("[$TAG] Couldn't find value for $stateObject in history") } } // When the mutableSnapshot is applied, we'll synchronously get an apply // observer callback - or we would, if we hadn't stopped recording. After that, // it's safe to stop recording again. } } if (wasRecording) { if (DEBUG) println("[$TAG] Resuming recording after setting current frame") // Keep using the old callback. startRecording(onTrackStateApplied) } } /** * Starts recording state changes. This is a no-op if recording has already been started. * * @return True if recording was successfully started, false if already recording. */ private fun startRecording(onTrackStateApplied: (() -> Unit)?): Boolean { if (handle != null) { if (DEBUG) println("[$TAG] Recording already started, ignoring start request") return false } if (DEBUG) println("[$TAG] Starting recording") synchronized(lock) { if (handle != null) return false this.onTrackStateApplied = onTrackStateApplied handle = Snapshot.registerApplyObserver(this::onApply) return true } } /** * Stops recording state changes. * * @return True if recording was stopped, false if it was not started. */ private fun stopRecording(clearOnTrackStateApplied: Boolean): Boolean { if (DEBUG) println("[$TAG] Stopping recording") if (handle == null) return false synchronized(lock) { if (handle == null) return false handle!!.dispose() handle = null if (clearOnTrackStateApplied) { onTrackStateApplied = null } return true } } private fun onApply(changedStates: Set<Any>, snapshot: Snapshot) { var atLeastOneTrackedStateChanged = false // Read values inside the snapshot to avoid race conditions. snapshot.withNestedSnapshot { synchronized(lock) { changedStates.forEach { stateObject -> stateObject as StateObject if (stateObject in trackedStates) { atLeastOneTrackedStateChanged = true nextFrame[stateObject] = stateObject.copyCurrentRecord() } } } } if (atLeastOneTrackedStateChanged) { if (DEBUG) println("[$TAG] Tracked state changes were applied, invoking callback") onTrackStateApplied?.invoke() } } private inline fun withGlobalMutableSnapshot(block: () -> Unit) { Snapshot.global { Snapshot.withMutableSnapshot(block) } } private inline fun Snapshot.withNestedSnapshot(block: () -> Unit) { takeNestedSnapshot().run { try { enter(block) } finally { dispose() } } } /** * Returns a copy of this object's current readable record, without recording a read. The record * is a copy since the original record could be reused at any point in the future. */ private fun StateObject.copyCurrentRecord(): StateRecord { val newRecord = firstStateRecord.create() firstStateRecord.withCurrent { current -> newRecord.assign(current) } return newRecord } /** * Copies [record] into the write record for this state object in the current snapshot. */ private fun StateObject.restoreFrom(record: StateRecord) { firstStateRecord.writable(this) { assign(record) } } companion object { const val NoFrame: Int = -1 } } @Composable fun <S : Any> trackStateHistory(stateObject: S): S { ensureValidStateObject(stateObject) val stateHistory = LocalStateHistory.current ?: return stateObject DisposableEffect(stateHistory, stateObject) { stateHistory.startTrackingState(stateObject) onDispose { stateHistory.stopTrackingState(stateObject) } } return stateObject } val StateHistory.canUndo: Boolean get() = currentFrame > 0 val StateHistory.canRedo: Boolean get() = currentFrame < frameCount - 1 /** * Sets the current frame to the previous frame. */ fun StateHistory.undo() { setCurrentFrameGlobally(currentFrame - 1) } /** * Sets the current frame to the next frame. */ fun StateHistory.redo() { setCurrentFrameGlobally(currentFrame + 1) } @Suppress("NOTHING_TO_INLINE") @Composable inline fun <T> MutableState<T>.trackStateHistory(): MutableState<T> = trackStateHistory(this) @Suppress("NOTHING_TO_INLINE") @Composable inline fun <T> SnapshotStateList<T>.trackStateHistory(): SnapshotStateList<T> = trackStateHistory(this) @Suppress("NOTHING_TO_INLINE") @Composable inline fun <K, V> SnapshotStateMap<K, V>.trackStateHistory(): SnapshotStateMap<K, V> = trackStateHistory(this) @OptIn(ExperimentalContracts::class) private fun ensureValidStateObject(stateObject: Any) { contract { returns() implies (stateObject is StateObject) } require(stateObject is StateObject) { "Can only track objects that are instance of StateObject, which this is not: $stateObject" } }
zach-klippenstein/compose-undo
149
Undo snapshot state changes in Compose.
Kotlin
zach-klippenstein
Zach Klippenstein
Square
statehistory/src/test/java/com/zachklipp/statehistory/demo/StateHistoryTest.kt
Kotlin
package com.zachklipp.statehistory.demo import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.snapshots.Snapshot import com.google.common.truth.Truth.assertThat import com.zachklipp.statehistory.StateHistory import com.zachklipp.statehistory.redo import com.zachklipp.statehistory.undo import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.cancel import kotlinx.coroutines.launch import org.junit.After import org.junit.Test class StateHistoryTest { private val stateHistory = StateHistory() private val scope = CoroutineScope(Dispatchers.Unconfined) @After fun tearDown() { scope.cancel() } @Test fun initialFrameCount() { assertThat(stateHistory.frameCount).isEqualTo(0) } @Test fun initialCurrentFrame() { assertThat(stateHistory.currentFrame).isEqualTo(StateHistory.NoFrame) } @Test fun recordsChanges_whenStartTrackingAfterRecording() { scope.launch { stateHistory.recordChanges { stateHistory.saveFrame() } } val state = mutableStateOf(0) stateHistory.startTrackingState(state) assertThat(stateHistory.frameCount).isEqualTo(0) Snapshot.sendApplyNotifications() assertThat(stateHistory.frameCount).isEqualTo(0) Snapshot.withMutableSnapshot { state.value = 1 } assertThat(stateHistory.frameCount).isEqualTo(1) assertThat(stateHistory.currentFrame).isEqualTo(0) } @Test fun recordsChanges_whenStartRecordingAfterTracking() { val state = mutableStateOf(0) stateHistory.startTrackingState(state) assertThat(stateHistory.frameCount).isEqualTo(0) Snapshot.sendApplyNotifications() assertThat(stateHistory.frameCount).isEqualTo(0) scope.launch { stateHistory.recordChanges { stateHistory.saveFrame() } } Snapshot.withMutableSnapshot { state.value = 1 } assertThat(stateHistory.frameCount).isEqualTo(1) assertThat(stateHistory.currentFrame).isEqualTo(0) } @Test fun noops_whenChangeCallbackIsNull() { scope.launch { stateHistory.recordChanges() } val state = mutableStateOf(0) stateHistory.startTrackingState(state) Snapshot.withMutableSnapshot { state.value = 1 } assertThat(stateHistory.frameCount).isEqualTo(0) assertThat(stateHistory.currentFrame).isEqualTo(StateHistory.NoFrame) } @Test fun setCurrentFrameGlobally_restoresState() { scope.launch { stateHistory.recordChanges { stateHistory.saveFrame() } } val state = mutableStateOf(0) stateHistory.startTrackingState(state) Snapshot.withMutableSnapshot { state.value = 1 } Snapshot.withMutableSnapshot { state.value = 2 } assertThat(stateHistory.frameCount).isEqualTo(2) assertThat(stateHistory.currentFrame).isEqualTo(1) assertThat(state.value).isEqualTo(2) stateHistory.setCurrentFrameGlobally(0) assertThat(stateHistory.frameCount).isEqualTo(2) assertThat(stateHistory.currentFrame).isEqualTo(0) assertThat(state.value).isEqualTo(1) } @Test fun settingState_afterUndo_clearsPreviousFutureState() { scope.launch { stateHistory.recordChanges { stateHistory.saveFrame() } } val state = mutableStateOf(0) stateHistory.startTrackingState(state) Snapshot.withMutableSnapshot { state.value = 1 } Snapshot.withMutableSnapshot { state.value = 2 } assertThat(stateHistory.frameCount).isEqualTo(2) assertThat(stateHistory.currentFrame).isEqualTo(1) assertThat(state.value).isEqualTo(2) // Undo one and change the value. stateHistory.setCurrentFrameGlobally(0) Snapshot.withMutableSnapshot { state.value = 3 } // That should have overwritten the previous frame in which state was 2. assertThat(stateHistory.frameCount).isEqualTo(2) assertThat(stateHistory.currentFrame).isEqualTo(1) assertThat(state.value).isEqualTo(3) // But preserve the frame where state is 1. stateHistory.setCurrentFrameGlobally(0) assertThat(stateHistory.frameCount).isEqualTo(2) assertThat(stateHistory.currentFrame).isEqualTo(0) assertThat(state.value).isEqualTo(1) } @Test fun tracksMultipleStateChanges() { scope.launch { stateHistory.recordChanges { stateHistory.saveFrame() } } val state1 = mutableStateOf(0) stateHistory.startTrackingState(state1) Snapshot.withMutableSnapshot { state1.value = 1 } assertThat(stateHistory.frameCount).isEqualTo(1) val state2 = mutableStateOf(10) stateHistory.startTrackingState(state2) Snapshot.withMutableSnapshot { state2.value = 20 } assertThat(stateHistory.frameCount).isEqualTo(2) } @Test fun restoresMultipleStateChanges() { scope.launch { stateHistory.recordChanges { stateHistory.saveFrame() } } val state1 = mutableStateOf(0) stateHistory.startTrackingState(state1) Snapshot.withMutableSnapshot { state1.value = 1 } val state2 = mutableStateOf(0) stateHistory.startTrackingState(state2) Snapshot.withMutableSnapshot { state2.value = 10 } Snapshot.withMutableSnapshot { state2.value = 20 } // Add a frame where both are set at once. Snapshot.withMutableSnapshot { state1.value = 2 state2.value = 30 } stateHistory.undo() assertThat(state1.value).isEqualTo(1) assertThat(state2.value).isEqualTo(20) stateHistory.undo() assertThat(state1.value).isEqualTo(1) assertThat(state2.value).isEqualTo(10) stateHistory.redo() assertThat(state1.value).isEqualTo(1) assertThat(state2.value).isEqualTo(20) } @Test fun stopTracking_whenStateObjectUnregistered() { scope.launch { stateHistory.recordChanges { stateHistory.saveFrame() } } val state = mutableStateOf(0) stateHistory.startTrackingState(state) Snapshot.withMutableSnapshot { state.value = 1 } assertThat(stateHistory.frameCount).isEqualTo(1) assertThat(stateHistory.currentFrame).isEqualTo(0) stateHistory.stopTrackingState(state) Snapshot.withMutableSnapshot { state.value = 2 } assertThat(stateHistory.frameCount).isEqualTo(1) assertThat(stateHistory.currentFrame).isEqualTo(0) } @Test fun stopTracking_whenRecordingStopped() { val job = scope.launch { stateHistory.recordChanges { stateHistory.saveFrame() } } val state = mutableStateOf(0) stateHistory.startTrackingState(state) Snapshot.withMutableSnapshot { state.value = 1 } assertThat(stateHistory.frameCount).isEqualTo(1) assertThat(stateHistory.currentFrame).isEqualTo(0) job.cancel() Snapshot.withMutableSnapshot { state.value = 2 } assertThat(stateHistory.frameCount).isEqualTo(1) assertThat(stateHistory.currentFrame).isEqualTo(0) } }
zach-klippenstein/compose-undo
149
Undo snapshot state changes in Compose.
Kotlin
zach-klippenstein
Zach Klippenstein
Square
build.gradle.kts
Kotlin
plugins { alias(libs.plugins.android.library) alias(libs.plugins.kotlin.android) alias(libs.plugins.publish) } android { namespace = "com.zachklipp.constraintsexplorer" compileSdk = 35 defaultConfig { minSdk = 21 testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { isMinifyEnabled = false } } compileOptions { sourceCompatibility = JavaVersion.VERSION_11 targetCompatibility = JavaVersion.VERSION_11 } kotlin { explicitApi() } kotlinOptions { jvmTarget = "11" } buildFeatures { compose = true } composeOptions { kotlinCompilerExtensionVersion = "1.5.14" } testOptions { targetSdk = 35 } } dependencies { api(libs.compose.ui) implementation(platform(libs.compose.bom)) implementation(libs.compose.foundation) implementation(libs.compose.tooling.preview) debugImplementation(libs.compose.tooling) testImplementation(libs.test.junit) androidTestImplementation(libs.test.androidx.junit) androidTestImplementation(libs.test.androidx.junit.ktx) androidTestImplementation(libs.test.androidx.espresso.core) androidTestImplementation(libs.test.compose.base) androidTestImplementation(libs.test.compose.composeRule) androidTestImplementation(libs.test.kotlin.junit) }
zach-klippenstein/constraints-explorer
124
A lightweight tool to help understand and debug how Compose's layout constraints affect your composables.
Kotlin
zach-klippenstein
Zach Klippenstein
Square
settings.gradle.kts
Kotlin
pluginManagement { repositories { google { content { includeGroupByRegex("com\\.android.*") includeGroupByRegex("com\\.google.*") includeGroupByRegex("androidx.*") } } // google() mavenCentral() gradlePluginPortal() } } dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) repositories { google() mavenCentral() } } rootProject.name = "constraints-explorer" include(":constraintsexplorer")
zach-klippenstein/constraints-explorer
124
A lightweight tool to help understand and debug how Compose's layout constraints affect your composables.
Kotlin
zach-klippenstein
Zach Klippenstein
Square
src/androidTest/java/com/zachklipp/constraintsexplorer/ConstraintsExplorerTest.kt
Kotlin
package com.zachklipp.constraintsexplorer import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.layout import androidx.compose.ui.test.isDisplayed import androidx.compose.ui.test.isNotDisplayed import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.onRoot import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performTouchInput import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.constrain import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import kotlin.test.assertEquals import kotlin.test.assertTrue @RunWith(AndroidJUnit4::class) class ConstraintsExplorerTest { @get:Rule val rule = createComposeRule() @Before fun setUp() { // This component has meaningfully different behavior on the first frame vs subsequent frames, // so tests need to control frames individually. rule.mainClock.autoAdvance = false } @Test fun controlsAreaShownOnFirstFrameWhenEnabled() { rule.setContent { ConstraintsExplorer(enabled = true) { Box(Modifier.sizePx(10)) } } val rootNode = rule.onRoot().fetchSemanticsNode() with(rule.density) { assertEquals(10 + ControlsSize.roundToPx(), rootNode.size.width) assertEquals(10 + ControlsSize.roundToPx(), rootNode.size.height) } } @Test fun controlsAreaNotShownWhenNotEnabled() { rule.setContent { ConstraintsExplorer(enabled = false) { Box(Modifier.sizePx(10)) } } with(rule.onRoot().fetchSemanticsNode()) { assertEquals(10, size.width) assertEquals(10, size.height) } repeat(3) { rule.mainClock.advanceTimeByFrame() } with(rule.onRoot().fetchSemanticsNode()) { assertEquals(10, size.width) assertEquals(10, size.height) } } @Test fun previewHeaderOnlyShownOnFirstFrame() { rule.setContent { ConstraintsExplorer(enabled = true) { Box(Modifier.sizePx(10)) } } rule.onNodeWithText(PreviewHeaderText).isDisplayed() rule.mainClock.advanceTimeByFrame() rule.onNodeWithText(PreviewHeaderText).isNotDisplayed() } @Test fun clickingMaxWidthHandleTogglesBounds() { var constraints: Constraints? = null rule.mainClock.autoAdvance = true val min = 1000 rule.setContent { ConstraintsExplorerImpl( showControls = true, modifier = Modifier .background(Color.Blue) .constrain( with(rule.density) { Constraints( minWidth = 0, maxWidth = min + ControlsSize.roundToPx(), minHeight = 0, maxHeight = min + ControlsSize.roundToPx() ) } ) ) { Box( Modifier .onConstraints { constraints = it } .sizePx(min) .background(Color.Red) ) } } rule.onNodeWithTag(MaxWidthHandleTag).isDisplayed() rule.runOnIdle { assertEquals( with(rule.density) { Constraints( minWidth = 0, maxWidth = min, minHeight = 0, maxHeight = min ) }, constraints ) } rule.onNodeWithTag(MaxWidthHandleTag).performClick() rule.runOnIdle { assertEquals( Constraints( minWidth = 0, maxWidth = Constraints.Infinity, minHeight = 0, maxHeight = min ), constraints ) } rule.onNodeWithTag(MaxWidthHandleTag).performClick() rule.runOnIdle { assertEquals( Constraints( minWidth = 0, maxWidth = min, minHeight = 0, maxHeight = min ), constraints ) } } @Test fun clickingMaxHeightHandleTogglesBounds() { var constraints: Constraints? = null rule.mainClock.autoAdvance = true val min = 1000 rule.setContent { ConstraintsExplorerImpl( showControls = true, modifier = Modifier .background(Color.Blue) .constrain( with(rule.density) { Constraints( minWidth = 0, maxWidth = min + ControlsSize.roundToPx(), minHeight = 0, maxHeight = min + ControlsSize.roundToPx() ) } ) ) { Box( Modifier .onConstraints { constraints = it } .sizePx(min) .background(Color.Red) ) } } rule.onNodeWithTag(MaxHeightHandleTag).isDisplayed() rule.runOnIdle { assertEquals( with(rule.density) { Constraints( minWidth = 0, maxWidth = min, minHeight = 0, maxHeight = min ) }, constraints ) } rule.onNodeWithTag(MaxHeightHandleTag).performClick() rule.runOnIdle { assertEquals( Constraints( minWidth = 0, maxWidth = min, minHeight = 0, maxHeight = Constraints.Infinity ), constraints ) } rule.onNodeWithTag(MaxHeightHandleTag).performClick() rule.runOnIdle { assertEquals( Constraints( minWidth = 0, maxWidth = min, minHeight = 0, maxHeight = min ), constraints ) } } @Test fun draggingMaxWidthHandleEnablesBounds() { var constraints: Constraints? = null rule.mainClock.autoAdvance = true val min = 1000 rule.setContent { ConstraintsExplorerImpl( showControls = true, modifier = Modifier .background(Color.Blue) .constrain( with(rule.density) { Constraints( minWidth = 0, maxWidth = min + ControlsSize.roundToPx(), minHeight = 0, maxHeight = min + ControlsSize.roundToPx() ) } ) ) { Box( Modifier .onConstraints { constraints = it } .sizePx(min) .background(Color.Red) ) } } rule.onNodeWithTag(MaxWidthHandleTag).performClick() rule.runOnIdle { assertEquals( with(rule.density) { Constraints( minWidth = 0, maxWidth = Constraints.Infinity, minHeight = 0, maxHeight = min ) }, constraints ) } rule.onNodeWithTag(MaxWidthHandleTag).performTouchInput { down(center) moveBy(center - Offset(10f + viewConfiguration.touchSlop, 0f)) up() } rule.runOnIdle { assertTrue(constraints!!.maxWidth < min) assertEquals(min, constraints!!.maxHeight) } } @Test fun draggingMaxHeightHandleEnablesBounds() { var constraints: Constraints? = null rule.mainClock.autoAdvance = true val min = 1000 rule.setContent { ConstraintsExplorerImpl( showControls = true, modifier = Modifier .background(Color.Blue) .constrain( with(rule.density) { Constraints( minWidth = 0, maxWidth = min + ControlsSize.roundToPx(), minHeight = 0, maxHeight = min + ControlsSize.roundToPx() ) } ) ) { Box( Modifier .onConstraints { constraints = it } .sizePx(min) .background(Color.Red) ) } } rule.onNodeWithTag(MaxHeightHandleTag).performClick() rule.runOnIdle { assertEquals( with(rule.density) { Constraints( minWidth = 0, maxWidth = min, minHeight = 0, maxHeight = Constraints.Infinity ) }, constraints ) } rule.onNodeWithTag(MaxHeightHandleTag).performTouchInput { down(center) moveBy(center - Offset(0f, 10f + viewConfiguration.touchSlop)) up() } rule.runOnIdle { assertTrue(constraints!!.maxHeight < min) assertEquals(min, constraints!!.maxWidth) } } private fun Modifier.sizePx(size: Int) = layout { measurable, constraints -> val childSize = constraints.constrain(IntSize(size, size)) val childConstraints = Constraints.fixed(childSize.width, childSize.height) val placeable = measurable.measure(childConstraints) layout(placeable.width, placeable.height) { placeable.place(0, 0) } } private fun Modifier.constrain( constraints: Constraints ) = layout { measurable, parentConstraints -> val childConstraints = parentConstraints.constrain(constraints) val placeable = measurable.measure(childConstraints) layout(placeable.width, placeable.height) { placeable.place(0, 0) } } private fun Modifier.onConstraints( onConstraints: (Constraints) -> Unit ): Modifier = layout { measurable, constraints -> onConstraints(constraints) val placeable = measurable.measure(constraints) layout(placeable.width, placeable.height) { placeable.place(0, 0) } } }
zach-klippenstein/constraints-explorer
124
A lightweight tool to help understand and debug how Compose's layout constraints affect your composables.
Kotlin
zach-klippenstein
Zach Klippenstein
Square
src/main/java/com/zachklipp/constraintsexplorer/ConstraintsExplorer.kt
Kotlin
package com.zachklipp.constraintsexplorer import android.annotation.SuppressLint import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.DraggableState import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.gestures.Orientation.Horizontal import androidx.compose.foundation.gestures.Orientation.Vertical import androidx.compose.foundation.gestures.draggable import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.sizeIn import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.text.BasicText import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.produceState import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.runtime.withFrameMillis import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.draw.drawWithCache import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.ClipOp import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.PathEffect.Companion.dashPathEffect import androidx.compose.ui.graphics.drawscope.Fill import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.graphics.drawscope.clipRect import androidx.compose.ui.graphics.drawscope.withTransform import androidx.compose.ui.layout.Layout import androidx.compose.ui.layout.layout import androidx.compose.ui.platform.LocalInspectionMode import androidx.compose.ui.platform.LocalViewConfiguration import androidx.compose.ui.platform.ViewConfiguration import androidx.compose.ui.platform.testTag import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.offset import androidx.compose.ui.unit.sp import kotlin.math.roundToInt internal const val PreviewHeaderText = "Constraints explorer available" internal const val MinWidthHandleTag = "min width handle" internal const val MaxWidthHandleTag = "max width handle" internal const val MinHeightHandleTag = "min height handle" internal const val MaxHeightHandleTag = "max height handle" internal val ControlsSize = 20.dp internal val ConstraintHandleSize = 5.dp private val ControlsFontSize = 10.sp private val UnboundedConstraintsViewportPadding = 50.dp private val ControlsBackgroundColor = Color.DarkGray private val ControlsForegroundColor = Color.White /** * Provides a set of interactive controls to manipulate the constraints passed to [content]. * * By default, this component will no-op when not running in a preview so it won't accidentally * show controls in production. You can override this behavior by passing the [enabled] flag. * * The preview will show a controls gutter on the top and right of the preview, and a label * indicating the explorer is available. To access the explorer, enter “Interactive mode” using the * the button over the top-right of the preview frame. Once in interactive mode, the controls will * be shown in the gutters: drag the left/top arrows to adjust minimum width/height constraints, and * the bottom/right arrows to adjust maximum constraints. * * In interactive mode, the preview will grow to fill the maximum incoming constraints. If the * constraints are unbounded, the preview will grow by a small amount to indicate that the content * is not filling maximum constraints, and the max constraints arrows will be drawn as outlines. * When a constraint is unbounded, dragging the maximum constraint handle past the current * viewport's bounds will grow the viewport. Clicking on a maximum constraint handle will toggle * whether that constraint is “unbounded” or not. An unbounded maximum constraint has value * [Constraints.Infinity] and is indicated by the arrow being drawn with a dotted outline. Dragging * an unbounded handle will re-enable its bound automatically. * * ## Want to learn more? * * - To learn more about constraints and layout, see the * [Developer Android docs](https://developer.android.com/develop/ui/compose/layouts/basics). * - For a use-case-specific case study of how constraints are used to achieve centering, see * [this article](https://blog.zachklipp.com/centering-in-compose/). * * ## A note on `fillMax*` modifiers in previews * * If you're passing any size-related modifier to the root composable inside your preview, you might * want to move it to [ConstraintsExplorer] instead. It won't affect the static preview and it * allows the explorer to actually “explore” more of your component. * * E.g. if you have this: * * ```kotlin * @Preview * @Composable * private fun YourComposablePreview() { * ConstraintsExplorer { * YourComposable(Modifier.fillMaxSize()) * } * } * ``` * * consider changing it to this: * * ```kotlin * @Preview * @Composable * private fun YourComposablePreview() { * ConstraintsExplorer(Modifier.fillMaxSize()) { * YourComposable() * } * } * ``` * * _If you're just setting the size to an exact size, you can also do that by passing `widthDp` and * `heightDp` parameters to the [Preview] annotation itself._ * * If you're modifying the size (or more precisely, the constraints) of your composable inside the * [ConstraintsExplorer], then when you're playing with the sliders in interactive mode you won't * get to see how your unmodified component reacts; you'll be seeing how it reacts with the * additional constraints modifier. That isn't very useful, since that modifier is only applied in * the preview. * * [ConstraintsExplorer] will always fill all available space in interactive mode in order to allow * you to modify the min/max constraints within that space and it doesn't modify the constraints at * all in non-interactive mode. So moving size modifiers to [ConstraintsExplorer] won't change the * non-interactive preview but allows your component to see and react to the constraints you can * adjust in interactive mode. * * For example, when you have [fillMaxSize] inside [ConstraintsExplorer], your composable will * ignore the incoming minimum constraints (the arrows pointing right and down), so moving those * sliders won't have any effect, and you're not going to see how your unmodified component will * actually behave in other contexts. If your component itself always fills available space, then * this won't make any difference but then using [fillMaxSize] in your preview is redundant anyway. */ @Composable public fun ConstraintsExplorer( modifier: Modifier = Modifier, enabled: Boolean = LocalInspectionMode.current, content: @Composable () -> Unit ) { if (enabled) { ConstraintsExplorerImpl( showControls = detectInteractivePreviewMode(), modifier = modifier, content = content ) } else { Box(modifier, propagateMinConstraints = true) { content() } } } @Composable internal fun ConstraintsExplorerImpl( showControls: Boolean, modifier: Modifier = Modifier, content: @Composable () -> Unit ) { val state = remember { ConstraintsExplorerState() } state.showControls = showControls ConstraintsControlsLayout( modifier = modifier.drawBehind { // Draw the controls background only behind the controls: clip out the content area. clipRect( right = size.width - ControlsSize.toPx(), top = ControlsSize.toPx(), clipOp = ClipOp.Difference ) { drawRect(ControlsBackgroundColor) } }, widthControls = { if (!showControls) { StaticPreviewHeader() } else { WidthConstraintsControls( min = state.minWidth, max = state.maxWidth, fillMax = state.incomingConstraints.hasBoundedWidth && !state.widthUnbounded, dottedOutline = state.widthUnbounded, onMinDrag = { state.offsetMinWidth(it.roundToInt()) }, onMaxDrag = { state.offsetMaxWidth(it.roundToInt()) }, onMaxClick = { state.toggleWidthBounded() }, ) } }, heightControls = { if (showControls) { HeightConstraintsControls( min = state.minHeight, max = state.maxHeight, fillMax = state.incomingConstraints.hasBoundedHeight && !state.heightUnbounded, dottedOutline = state.heightUnbounded, onMinDrag = { state.offsetMinHeight(it.roundToInt()) }, onMaxDrag = { state.offsetMaxHeight(it.roundToInt()) }, onMaxClick = { state.toggleHeightBounded() }, ) } }, content = content, contentModifier = Modifier.then(state.contentModifier) ) } private class ConstraintsExplorerState { var incomingConstraints: Constraints by mutableStateOf(Constraints()) private set private var viewportSize: IntSize by mutableStateOf(IntSize.Zero) /** * Whether the controls are being shown. When false, [contentModifier] will always measure itself * to be the size of the content. When true, it will fill max size. */ var showControls: Boolean by mutableStateOf(false) var minWidth by mutableIntStateOf(0) private set var maxWidth by mutableIntStateOf(Constraints.Infinity) private set var minHeight by mutableIntStateOf(0) private set var maxHeight by mutableIntStateOf(Constraints.Infinity) private set var widthUnbounded by mutableStateOf(false) private set var heightUnbounded by mutableStateOf(false) private set val contentModifier: Modifier = Modifier.layout { measurable, constraints -> val placeable = if (viewportSize == IntSize.Zero) { incomingConstraints = constraints val placeable = measurable.measure(constraints) val viewportWidth = if (constraints.hasBoundedWidth) { constraints.maxWidth } else { widthUnbounded = true placeable.width + UnboundedConstraintsViewportPadding.roundToPx() } val viewportHeight = if (constraints.hasBoundedHeight) { constraints.maxHeight } else { heightUnbounded = true placeable.height + UnboundedConstraintsViewportPadding.roundToPx() } minWidth = constraints.minWidth maxWidth = viewportWidth minHeight = constraints.minHeight maxHeight = viewportHeight viewportSize = IntSize(viewportWidth, viewportHeight) placeable } else { val childMaxWidth = if (widthUnbounded) Constraints.Infinity else maxWidth val childMaxHeight = if (heightUnbounded) Constraints.Infinity else maxHeight val childConstraints = Constraints(minWidth, childMaxWidth, minHeight, childMaxHeight) measurable.measure(childConstraints) } val width = if (showControls) { viewportSize.width } else { placeable.width } val height = if (showControls) { viewportSize.height } else { placeable.height } layout(width, height) { placeable.place(0, 0) } } fun offsetMinWidth(delta: Int) { minWidth = (minWidth + delta).coerceIn(0, incomingConstraints.maxWidth) maxWidth = maxWidth.coerceAtLeast(minWidth) updateViewport() } fun offsetMaxWidth(delta: Int) { maxWidth = (maxWidth + delta).coerceIn(0, incomingConstraints.maxWidth) minWidth = minWidth.coerceAtMost(maxWidth) widthUnbounded = false updateViewport() } fun offsetMinHeight(delta: Int) { minHeight = (minHeight + delta).coerceIn(0, incomingConstraints.maxHeight) maxHeight = maxHeight.coerceAtLeast(minHeight) updateViewport() } fun offsetMaxHeight(delta: Int) { maxHeight = (maxHeight + delta).coerceIn(0, incomingConstraints.maxHeight) minHeight = minHeight.coerceAtMost(maxHeight) heightUnbounded = false updateViewport() } fun toggleWidthBounded() { widthUnbounded = !widthUnbounded } fun toggleHeightBounded() { heightUnbounded = !heightUnbounded } private fun updateViewport() { viewportSize = IntSize( width = viewportSize.width.coerceAtLeast(maxWidth).coerceAtMost(incomingConstraints.maxWidth), height = viewportSize.height.coerceAtLeast(maxHeight) .coerceAtMost(incomingConstraints.maxHeight) ) } } /** * Hack to figure out if we're in "interactive mode" or not. In interactive mode, frames will be * rendered continuously, but in non-interactive mode, only the first two frames are rendered. The * initial frame will create this LaunchedEffect, and then the frame callback will run for the * second frame, but the coroutine will never resume after the second frame completes. So if we * hit the code that sets the flag, we must be in interactive mode. */ @Composable private fun detectInteractivePreviewMode(): Boolean = produceState(false) { withFrameMillis {} value = true }.value /** * Layout [content] with a thin bar on top for [widthControls] and a thin bar on the right for * [heightControls]. */ @Composable private fun ConstraintsControlsLayout( modifier: Modifier, widthControls: @Composable () -> Unit, heightControls: @Composable () -> Unit, corner: @Composable () -> Unit = {}, content: @Composable () -> Unit, contentModifier: Modifier, ) { Layout( modifier = modifier, content = { // Enforce a single Measurable per slot. Box(propagateMinConstraints = true) { widthControls() } Box(propagateMinConstraints = true) { heightControls() } Box(propagateMinConstraints = true) { corner() } Box(contentModifier, propagateMinConstraints = true) { content() } } ) { measureables, constraints -> val ( widthControlsMeasurable, heightControlsMeasurable, cornerMeasurable, contentMeasurable ) = measureables val controlsSizePx = ControlsSize.roundToPx() val contentConstraints = constraints.offset( horizontal = -controlsSizePx, vertical = -controlsSizePx ) val contentPlaceable = contentMeasurable.measure(contentConstraints) val widthControlsConstraints = Constraints.fixed( width = contentPlaceable.width, height = controlsSizePx ) val heightControlsConstraints = Constraints.fixed( width = controlsSizePx, height = contentPlaceable.height ) val cornerConstraints = Constraints.fixed(controlsSizePx, controlsSizePx) val widthControlsPlaceable = widthControlsMeasurable.measure(widthControlsConstraints) val heightControlsPlaceable = heightControlsMeasurable.measure(heightControlsConstraints) val cornerPlaceable = cornerMeasurable.measure(cornerConstraints) layout( width = heightControlsPlaceable.width + contentPlaceable.width, height = widthControlsPlaceable.height + contentPlaceable.height ) { contentPlaceable.place(0, widthControlsPlaceable.height) cornerPlaceable.place(contentPlaceable.width, 0) widthControlsPlaceable.place(0, 0) heightControlsPlaceable.place(contentPlaceable.width, widthControlsPlaceable.height) } } } @Composable private fun WidthConstraintsControls( min: Int, max: Int, fillMax: Boolean, dottedOutline: Boolean, onMinDrag: (Float) -> Unit, onMaxDrag: (Float) -> Unit, onMaxClick: () -> Unit, ) { Layout( content = { DisableTouchSlop { ConstraintHandle( orientation = Horizontal, min = true, fill = true, dotted = false, onDrag = onMinDrag, onClick = null, modifier = Modifier.testTag(MinWidthHandleTag), ) ConstraintHandle( orientation = Horizontal, min = false, fill = fillMax, dotted = dottedOutline, onDrag = onMaxDrag, onClick = onMaxClick, modifier = Modifier.testTag(MaxWidthHandleTag), ) } }, modifier = Modifier.drawBehind { drawLine( ControlsForegroundColor, strokeWidth = 1.dp.toPx(), start = Offset(min.toFloat() + ConstraintHandleSize.toPx(), size.height / 2), end = Offset(max.toFloat() - ConstraintHandleSize.toPx(), size.height / 2f) ) drawRect( Color.Black, topLeft = Offset.Zero, size = Size(min.toFloat(), size.height) ) drawRect( Color.Black, topLeft = Offset(max.toFloat(), 0f), size = Size(size.width - max.toFloat(), size.height) ) } ) { measureables, constraints -> val (minHandleMeasurable, maxHandleMeasurable) = measureables val handleConstraints = Constraints.fixed( width = ConstraintHandleSize.roundToPx(), height = ControlsSize.roundToPx() ) val minHandlePlaceable = minHandleMeasurable.measure(handleConstraints) val maxHandlePlaceable = maxHandleMeasurable.measure(handleConstraints) layout(constraints.maxWidth, constraints.maxHeight) { minHandlePlaceable.place(min, 0) maxHandlePlaceable.place(max - maxHandlePlaceable.width, 0) } } } @Composable private fun HeightConstraintsControls( min: Int, max: Int, fillMax: Boolean, dottedOutline: Boolean, onMinDrag: (Float) -> Unit, onMaxDrag: (Float) -> Unit, onMaxClick: () -> Unit, ) { Layout( content = { DisableTouchSlop { ConstraintHandle( orientation = Vertical, min = true, fill = true, dotted = false, onDrag = onMinDrag, onClick = null, modifier = Modifier.testTag(MinHeightHandleTag), ) ConstraintHandle( orientation = Vertical, min = false, fill = fillMax, dotted = dottedOutline, onDrag = onMaxDrag, onClick = onMaxClick, modifier = Modifier.testTag(MaxHeightHandleTag), ) } }, modifier = Modifier.drawBehind { drawLine( ControlsForegroundColor, strokeWidth = 1.dp.toPx(), start = Offset(size.width / 2, min.toFloat() + ConstraintHandleSize.toPx()), end = Offset(size.width / 2, max.toFloat() - ConstraintHandleSize.toPx()) ) drawRect( Color.Black, topLeft = Offset.Zero, size = Size(size.width, min.toFloat()) ) drawRect( Color.Black, topLeft = Offset(0f, max.toFloat()), size = Size(size.width, size.height - max.toFloat()) ) } ) { measureables, constraints -> val (minHandleMeasurable, maxHandleMeasurable) = measureables val handleConstraints = Constraints.fixed( width = ControlsSize.roundToPx(), height = ConstraintHandleSize.roundToPx() ) val minHandlePlaceable = minHandleMeasurable.measure(handleConstraints) val maxHandlePlaceable = maxHandleMeasurable.measure(handleConstraints) layout(constraints.maxWidth, constraints.maxHeight) { minHandlePlaceable.place(0, min) maxHandlePlaceable.place(0, max - maxHandlePlaceable.height) } } } @Composable private fun DisableTouchSlop(content: @Composable () -> Unit) { val originalConfig = LocalViewConfiguration.current val config = remember(originalConfig) { object : ViewConfiguration by originalConfig { override val touchSlop: Float get() = 0f } } CompositionLocalProvider(LocalViewConfiguration provides config, content = content) } @Composable private fun ConstraintHandle( orientation: Orientation, min: Boolean, fill: Boolean, dotted: Boolean, onDrag: (Float) -> Unit, onClick: (() -> Unit)?, modifier: Modifier, ) { val state = remember { DraggableState(onDrag) } Box( modifier .draggable(state, orientation = orientation) .then(onClick?.let { Modifier.clickable(onClick = onClick) } ?: Modifier) .drawWithCache { val arrow = Path().apply { moveTo(0f, 0f) when (orientation) { Horizontal -> { lineTo(size.width, size.height / 2) lineTo(0f, size.height) } Vertical -> { lineTo(size.width / 2, size.height) lineTo(size.width, 0f) } } close() } val arrowStyle = if (fill) { Fill } else { Stroke( width = 1.dp.toPx(), pathEffect = if (dotted) { dashPathEffect(floatArrayOf(2.dp.toPx(), 2.dp.toPx())) } else { null } ) } onDrawBehind { withTransform({ if (!min) rotate(180f) }) { drawPath(arrow, ControlsForegroundColor, style = arrowStyle) } } } ) } @Composable private fun StaticPreviewHeader() { BasicText( PreviewHeaderText, modifier = Modifier .fillMaxSize() .wrapContentSize(), style = TextStyle( color = ControlsForegroundColor, textAlign = TextAlign.Center, fontSize = ControlsFontSize, ), overflow = TextOverflow.Ellipsis, ) } @SuppressLint("UnusedBoxWithConstraintsScope") @Preview(backgroundColor = 0xff0000, showBackground = true) @Composable private fun PreviewWithPreferredSizeSmallerThanPreviewSize() { val size = 200.dp ConstraintsExplorer( Modifier .wrapContentSize() .sizeIn( minWidth = 100.dp, minHeight = 100.dp, maxWidth = 300.dp, maxHeight = 300.dp ) ) { BoxWithConstraints( contentAlignment = Alignment.Center, propagateMinConstraints = true, modifier = Modifier.background(Color.LightGray) ) { BasicText( "Preferred size: $size\n" + "Width: [${constraints.minWidth}, ${constraints.maxWidth.toInfinityString()}]\n" + "Height: [${constraints.minHeight}, ${constraints.maxHeight.toInfinityString()}]", style = TextStyle( fontSize = 12.sp, textAlign = TextAlign.Center, ), modifier = Modifier .size(size) .wrapContentSize() ) } } } @Preview(backgroundColor = 0xff0000, showBackground = true) @Composable private fun PreviewWithWrapContentSizeAndDefaultPreviewSize() { ConstraintsExplorer(Modifier.wrapContentSize()) { BasicText( "wrapContentSize", modifier = Modifier .background(Color.LightGray) .wrapContentSize(), ) } } @Preview(backgroundColor = 0xff0000, showBackground = true) @Composable private fun PreviewWithFillMaxSizeAndDefaultPreviewSize() { ConstraintsExplorer(Modifier.wrapContentSize()) { BasicText( "fillMaxSize", modifier = Modifier .background(Color.LightGray) .fillMaxSize() .wrapContentSize(), ) } } @Preview(backgroundColor = 0xff0000, showBackground = true) @Composable private fun PreviewWithInfiniteConstraints() { ConstraintsExplorer( Modifier .horizontalScroll(rememberScrollState()) .verticalScroll(rememberScrollState()) ) { BasicText( "wrapContentSize", modifier = Modifier .background(Color.LightGray) .wrapContentSize(), ) } } @Suppress("KotlinConstantConditions") private fun Int.toInfinityString(): String = if (this == Constraints.Infinity) "∞" else this.toString()
zach-klippenstein/constraints-explorer
124
A lightweight tool to help understand and debug how Compose's layout constraints affect your composables.
Kotlin
zach-klippenstein
Zach Klippenstein
Square
build.gradle.kts
Kotlin
import org.jetbrains.compose.compose import org.jetbrains.compose.desktop.application.dsl.TargetFormat import org.jetbrains.kotlin.gradle.tasks.KotlinCompile plugins { kotlin("jvm") version "1.4.20" id("org.jetbrains.compose") version "0.2.0-build132" } group = "com.zachklipp" version = "1.0" repositories { jcenter() mavenCentral() maven { url = uri("https://maven.pkg.jetbrains.space/public/p/compose/dev") } } dependencies { testImplementation(kotlin("test-junit")) implementation(compose.desktop.currentOs) } tasks.test { useJUnit() } tasks.withType<KotlinCompile>() { kotlinOptions.jvmTarget = "11" } compose.desktop { application { mainClass = "MainKt" nativeDistributions { targetFormats(TargetFormat.Dmg, TargetFormat.Msi, TargetFormat.Deb) packageName = "snapshot-linked-list-blog" } } }
zach-klippenstein/snapshot-linked-list-blog
1
Kotlin
zach-klippenstein
Zach Klippenstein
Square
settings.gradle.kts
Kotlin
pluginManagement { repositories { gradlePluginPortal() mavenCentral() maven { url = uri("https://maven.pkg.jetbrains.space/public/p/compose/dev") } } } rootProject.name = "snapshot-linked-list-blog"
zach-klippenstein/snapshot-linked-list-blog
1
Kotlin
zach-klippenstein
Zach Klippenstein
Square
src/main/kotlin/SnapshotList.kt
Kotlin
class SnapshotList { private var head: Node? = null private var tail: Node? = null var size: Int = 0 private set fun addFirst(item: Any) { val newHead = Node(data = item, next = head, previous = null) head?.previous = newHead head = newHead size++ // Special case when the list is empty. if (tail === null) { tail = head } } fun removeLast(): Any? { val removedNode = tail ?: return null tail = removedNode.previous tail?.next = null size-- // Special case when the last item is being removed. if (head === removedNode) { head = null } return removedNode.data } fun contains(item: Any): Boolean { forEach { if (it == item) return true } return false } private inline fun forEach(block: (Any) -> Unit) { var currentNode = head while (currentNode != null) { block(currentNode.data) currentNode = currentNode.next } } private class Node( val data: Any, var next: Node?, var previous: Node? ) }
zach-klippenstein/snapshot-linked-list-blog
1
Kotlin
zach-klippenstein
Zach Klippenstein
Square
src/test/kotlin/SnapshotListTest.kt
Kotlin
import org.junit.Test import kotlin.test.* class SnapshotListTest { @Test fun `empty list has size zero`() { assertEquals(0, SnapshotList().size) } @Test fun `addFirst works`() { val list = SnapshotList() list.addFirst("hello") assertEquals(1, list.size) assertTrue(list.contains("hello")) } @Test fun `removeLast works`() { val list = SnapshotList() list.addFirst("hello") val last = list.removeLast() assertEquals("hello", last) assertEquals(0, list.size) assertFalse(list.contains("hello")) } @Test fun `list can hold multiple items`() { val list = SnapshotList() list.addFirst("one") list.addFirst("two") list.addFirst("three") assertEquals(3, list.size) assertTrue(list.contains("one")) assertTrue(list.contains("two")) assertTrue(list.contains("three")) } @Test fun `list adds and removes are ordered`() { val list = SnapshotList() list.addFirst("one") list.addFirst("two") list.addFirst("three") val first = list.removeLast() val second = list.removeLast() val third = list.removeLast() assertEquals("one", first) assertEquals("two", second) assertEquals("three", third) } @Test fun `list can hold lots of stuff`() { val list = SnapshotList() repeat(10_000) { list.addFirst(it) } assertEquals(10_000, list.size) repeat(10_000) { assertTrue(list.contains(it)) } repeat(10_000) { list.removeLast() } assertEquals(0, list.size) } @Test fun `removeLast returns null when empty`() { val list = SnapshotList() val lastItem = list.removeLast() assertNull(lastItem) } }
zach-klippenstein/snapshot-linked-list-blog
1
Kotlin
zach-klippenstein
Zach Klippenstein
Square
src/test/kotlin/SnapshotListThreadStressTest.kt
Kotlin
import org.junit.Test import java.util.concurrent.CountDownLatch import kotlin.concurrent.thread import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertTrue class SnapshotListThreadStressTest { private val processorCount = Runtime.getRuntime().availableProcessors() private val itemsPerProcessor = 1_000 private val totalSize = processorCount * itemsPerProcessor @Test fun `add in parallel`() { val list = SnapshotList() // First processor adds 0-99, second processor adds 100-199, etc. runInParallel { processor -> repeat(itemsPerProcessor) { i -> list.addFirst((processor * itemsPerProcessor) + i) } } assertEquals(totalSize, list.size) repeat(totalSize) { i -> assertTrue(list.contains(i), "Expected list to contain $i") } } @Test fun `remove in parallel`() { val list = SnapshotList() repeat(totalSize) { i -> list.addFirst(i) } // Remove all the items, using each processor to remove a subset of the items. runInParallel { repeat(itemsPerProcessor) { // Removes will be interleaved, so we don't know which values any particular // processor will get, but since we're not removing more items than the list // contains we _do_ know the list will always contain at least one item, so this // should never return null. val removedItem = list.removeLast() assertNotNull(removedItem) } } assertEquals(0, list.size) } @Test fun `add and remove in parallel`() { val list = SnapshotList() // Each processor adds some items, then removes them. runInParallel { processor -> repeat(itemsPerProcessor) { i -> list.addFirst((processor * itemsPerProcessor) + i) } repeat(itemsPerProcessor) { i -> assertTrue(list.contains(i), "Expected list to contain $i") } repeat(itemsPerProcessor) { val removedItem = list.removeLast() assertNotNull(removedItem) } } assertEquals(0, list.size) } /** * Runs [block] on each processor. The block is passed the index of the processor it's using. */ private fun runInParallel(block: (processor: Int) -> Unit) { // Use a latch so no blocks will execute until all threads are started. val allReady = CountDownLatch(1) // Launch as many threads as we have processors and store them in a list, so we can clean // them up later. val threads = List(processorCount) { processor -> thread(start = true, isDaemon = false) { allReady.await() block(processor) } } // Tell all threads to start executing their blocks. allReady.countDown() // Wait for all threads to finish. threads.forEach { it.join() } } }
zach-klippenstein/snapshot-linked-list-blog
1
Kotlin
zach-klippenstein
Zach Klippenstein
Square
build.gradle.kts
Kotlin
plugins { alias(libs.plugins.android.application) apply false alias(libs.plugins.android.library) apply false alias(libs.plugins.kotlin.multiplatform) apply false alias(libs.plugins.maven.publish) apply false } tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> { compilerOptions { freeCompilerArgs.addAll("-Xskip-prerelease-check", "-Xdont-warn-on-error-suppression") } }
zacharee/KMPPlatform
1
Kotlin
zacharee
Zachary Wander
library/build.gradle.kts
Kotlin
import org.jetbrains.kotlin.gradle.dsl.JvmTarget import org.jetbrains.kotlin.gradle.ExperimentalWasmDsl plugins { alias(libs.plugins.android.library) alias(libs.plugins.kotlin.multiplatform) alias(libs.plugins.maven.publish) } group = "dev.zwander.kmp.platform" kotlin.sourceSets.all { languageSettings.optIn("kotlin.RequiresOptIn") } val javaVersionEnum: JavaVersion = JavaVersion.VERSION_21 kotlin { jvmToolchain(javaVersionEnum.toString().toInt()) androidTarget { compilations.all { compileTaskProvider.configure { compilerOptions { freeCompilerArgs.addAll("-opt-in=kotlin.RequiresOptIn", "-Xdont-warn-on-error-suppression") jvmTarget = JvmTarget.fromTarget(javaVersionEnum.toString()) } } } } jvm { compilations.all { compileTaskProvider.configure { compilerOptions { jvmTarget = JvmTarget.fromTarget(javaVersionEnum.toString()) } } } } listOf( iosX64(), iosArm64(), iosSimulatorArm64(), macosX64(), macosArm64(), tvosX64(), tvosArm64(), tvosSimulatorArm64(), watchosX64(), watchosArm32(), watchosArm64(), watchosDeviceArm64(), watchosSimulatorArm64(), ).forEach { it.binaries.framework { baseName = "KMPPlatform" isStatic = true } } @OptIn(ExperimentalWasmDsl::class) listOf( js(IR), wasmJs(), ).forEach { it.moduleName = "KMPPlatform" it.browser() } androidNativeArm32() androidNativeArm64() androidNativeX86() androidNativeX64() mingwX64 { compilations.getByName("main") { cinterops.create("Windows") { includeDirs("$projectDir/src/nativeInterop/cinterop/Windows") definitionFile.set(file("$projectDir/src/nativeInterop/cinterop/Windows.def")) } } } linuxArm64() linuxX64() targets.all { compilations.all { compileTaskProvider.configure { compilerOptions { freeCompilerArgs.addAll("-Xexpect-actual-classes", "-Xdont-warn-on-error-suppression") } } } } sourceSets { val commonMain by getting { dependencies { implementation(libs.kotlin.stdlib) } } val jvmMain by getting { dependsOn(commonMain) dependencies { implementation(libs.oshi.core) } } val androidMain by getting { dependsOn(commonMain) } val darwinMain by creating { dependsOn(commonMain) } val iosMain by creating { dependsOn(darwinMain) } val iosX64Main by getting { dependsOn(iosMain) } val iosArm64Main by getting { dependsOn(iosMain) } val iosSimulatorArm64Main by getting { dependsOn(iosMain) } val macosMain by creating { dependsOn(darwinMain) } val macosArm64Main by getting { dependsOn(macosMain) } val macosX64Main by getting { dependsOn(macosMain) } val tvosMain by creating { dependsOn(darwinMain) } val tvosX64Main by getting { dependsOn(tvosMain) } val tvosArm64Main by getting { dependsOn(tvosMain) } val tvosSimulatorArm64Main by getting { dependsOn(tvosMain) } val watchosMain by creating { dependsOn(darwinMain) } val watchosX64Main by getting { dependsOn(watchosMain) } val watchosArm32Main by getting { dependsOn(watchosMain) } val watchosArm64Main by getting { dependsOn(watchosMain) } val watchosDeviceArm64Main by getting { dependsOn(watchosMain) } val watchosSimulatorArm64Main by getting { dependsOn(watchosMain) } val jsMain by getting { dependsOn(commonMain) } val wasmJsMain by getting { dependsOn(commonMain) } val androidNativeMain by creating { dependsOn(commonMain) } val androidNativeArm32Main by getting { dependsOn(androidNativeMain) } val androidNativeArm64Main by getting { dependsOn(androidNativeMain) } val androidNativeX86Main by getting { dependsOn(androidNativeMain) } val androidNativeX64Main by getting { dependsOn(androidNativeMain) } val mingwMain by creating { dependsOn(commonMain) } val mingwX64Main by getting { dependsOn(mingwMain) } val linuxMain by creating { dependsOn(commonMain) } val linuxArm64Main by getting { dependsOn(linuxMain) } val linuxX64Main by getting { dependsOn(linuxMain) } } } android { this.compileSdk = 34 defaultConfig { this.minSdk = 21 } namespace = "dev.zwander.kmp.platform" compileOptions { sourceCompatibility = javaVersionEnum targetCompatibility = javaVersionEnum } buildFeatures { aidl = true } sourceSets["main"].manifest.srcFile("src/androidMain/AndroidManifest.xml") sourceSets["main"].res.srcDirs("src/androidMain/res") } tasks.withType<Copy> { duplicatesStrategy = DuplicatesStrategy.EXCLUDE }
zacharee/KMPPlatform
1
Kotlin
zacharee
Zachary Wander
library/src/androidMain/kotlin/dev/zwander/kmp/platform/HostArch.android.kt
Kotlin
package dev.zwander.kmp.platform internal actual val hostArch: HostArch get() { return when (val osArch = System.getProperty("os.arch")) { "x86_64", "amd64" -> HostArch.X64 "aarch64" -> HostArch.Arm64 else -> throw Error("Unknown arch $osArch") } }
zacharee/KMPPlatform
1
Kotlin
zacharee
Zachary Wander
library/src/androidMain/kotlin/dev/zwander/kmp/platform/HostOS.android.kt
Kotlin
package dev.zwander.kmp.platform internal actual val hostOS: HostOS = HostOS.Android
zacharee/KMPPlatform
1
Kotlin
zacharee
Zachary Wander
library/src/androidMain/kotlin/dev/zwander/kmp/platform/HostOSVersion.android.kt
Kotlin
package dev.zwander.kmp.platform import android.os.Build internal actual val hostOSVersion: OSVersion get() { val release = Build.VERSION.RELEASE val split = release.split(".") return OSVersion( major = split.getOrNull(0)?.toIntOrNull(), minor = split.getOrNull(1)?.toIntOrNull(), patch = split.getOrNull(2)?.toIntOrNull(), build = Build.VERSION.SDK_INT.toLong(), ) }
zacharee/KMPPlatform
1
Kotlin
zacharee
Zachary Wander
library/src/androidMain/kotlin/dev/zwander/kmp/platform/KotlinBackend.android.kt
Kotlin
package dev.zwander.kmp.platform internal actual val hostBackend: KotlinBackend = KotlinBackend.JVM
zacharee/KMPPlatform
1
Kotlin
zacharee
Zachary Wander
library/src/androidNativeArm32Main/kotlin/dev/zwander/kmp/platform/HostArch.androidNativeArm32.kt
Kotlin
package dev.zwander.kmp.platform internal actual val hostArch: HostArch = HostArch.Arm32
zacharee/KMPPlatform
1
Kotlin
zacharee
Zachary Wander
library/src/androidNativeArm64Main/kotlin/dev/zwander/kmp/platform/HostArch.androidNativeArm64.kt
Kotlin
package dev.zwander.kmp.platform internal actual val hostArch: HostArch = HostArch.Arm64
zacharee/KMPPlatform
1
Kotlin
zacharee
Zachary Wander
library/src/androidNativeMain/kotlin/dev/zwander/kmp/platform/HostOS.androidNative.kt
Kotlin
package dev.zwander.kmp.platform internal actual val hostOS: HostOS = HostOS.Android
zacharee/KMPPlatform
1
Kotlin
zacharee
Zachary Wander
library/src/androidNativeMain/kotlin/dev/zwander/kmp/platform/HostOSVersion.androidNative.kt
Kotlin
package dev.zwander.kmp.platform import kotlinx.cinterop.ByteVar import kotlinx.cinterop.ExperimentalForeignApi import kotlinx.cinterop.allocArray import kotlinx.cinterop.memScoped import kotlinx.cinterop.toKStringFromUtf8 import platform.posix.__system_property_get @OptIn(ExperimentalForeignApi::class) internal actual val hostOSVersion: OSVersion get() = memScoped { val releaseString = allocArray<ByteVar>(92) val sdkString = allocArray<ByteVar>(92) __system_property_get("ro.build.version.release", releaseString) __system_property_get("ro.build.version.sdk", sdkString) val releaseSplit = releaseString.toKStringFromUtf8().split(".") return OSVersion( major = releaseSplit.getOrNull(0)?.toIntOrNull(), minor = releaseSplit.getOrNull(1)?.toIntOrNull(), patch = releaseSplit.getOrNull(2)?.toIntOrNull(), build = sdkString.toKStringFromUtf8().toLongOrNull(), ) }
zacharee/KMPPlatform
1
Kotlin
zacharee
Zachary Wander
library/src/androidNativeMain/kotlin/dev/zwander/kmp/platform/KotlinBackend.androidNative.kt
Kotlin
package dev.zwander.kmp.platform internal actual val hostBackend: KotlinBackend = KotlinBackend.Native
zacharee/KMPPlatform
1
Kotlin
zacharee
Zachary Wander
library/src/androidNativeX64Main/kotlin/dev/zwander/kmp/platform/HostArch.androidNativeX64.kt
Kotlin
package dev.zwander.kmp.platform internal actual val hostArch: HostArch = HostArch.X64
zacharee/KMPPlatform
1
Kotlin
zacharee
Zachary Wander
library/src/androidNativeX86Main/kotlin/dev/zwander/kmp/platform/HostArch.androidNativeX86.kt
Kotlin
package dev.zwander.kmp.platform internal actual val hostArch: HostArch = HostArch.X86
zacharee/KMPPlatform
1
Kotlin
zacharee
Zachary Wander
library/src/commonMain/kotlin/dev/zwander/kmp/platform/HostArch.kt
Kotlin
package dev.zwander.kmp.platform /** * The CPU architecture of the host system. */ enum class HostArch(val id: String) { /** * Intel x86. */ X86("x86"), /** * AMD64 * x86_64 */ X64("x64"), /** * 32-bit ARM. */ Arm32("arm32"), /** * 64-bit ARM. */ Arm64("arm64"), /** * x64 app running on an ARM64 host. */ EmulatedX64("emulated_x64"), /** * x86 app running on an ARM64 host. */ EmulatedX86("emulated_x86"), /** * Unknown architecture. */ Unknown("Unknown"), ; companion object { val current: HostArch get() = hostArch } } internal expect val hostArch: HostArch
zacharee/KMPPlatform
1
Kotlin
zacharee
Zachary Wander
library/src/commonMain/kotlin/dev/zwander/kmp/platform/HostOS.kt
Kotlin
package dev.zwander.kmp.platform /** * The operating system the application is currently running on. */ enum class HostOS(val id: String) { Android("android"), Linux("linux"), Windows("windows"), MacOS("macos"), IOS("ios"), TvOS("tvos"), WatchOS("watchos"), Unknown("unknown"), ; companion object { val current: HostOS get() = hostOS } } internal expect val hostOS: HostOS
zacharee/KMPPlatform
1
Kotlin
zacharee
Zachary Wander
library/src/commonMain/kotlin/dev/zwander/kmp/platform/HostOSVersion.kt
Kotlin
package dev.zwander.kmp.platform data class OSVersion( val major: Int?, val minor: Int?, val patch: Int?, val build: Long?, ) { companion object { val Unknown = OSVersion(null, null, null, null) val current: OSVersion get() = hostOSVersion } } internal expect val hostOSVersion: OSVersion
zacharee/KMPPlatform
1
Kotlin
zacharee
Zachary Wander
library/src/commonMain/kotlin/dev/zwander/kmp/platform/KotlinBackend.kt
Kotlin
package dev.zwander.kmp.platform enum class KotlinBackend(val id: String) { JVM("jvm"), JS("js"), Native("native"), Wasm("wasm"), ; companion object { val current: KotlinBackend get() = hostBackend } } internal expect val hostBackend: KotlinBackend
zacharee/KMPPlatform
1
Kotlin
zacharee
Zachary Wander
library/src/darwinMain/kotlin/dev/zwander/kmp/platform/HostOSVersion.darwin.kt
Kotlin
package dev.zwander.kmp.platform import kotlinx.cinterop.ExperimentalForeignApi import kotlinx.cinterop.UnsafeNumber import kotlinx.cinterop.memScoped import kotlinx.cinterop.pointed import platform.Foundation.NSProcessInfo @Suppress("RemoveRedundantCallsOfConversionMethods") @OptIn(ExperimentalForeignApi::class, UnsafeNumber::class) internal actual val hostOSVersion: OSVersion get() = memScoped { val osVersion = NSProcessInfo.processInfo.operatingSystemVersion.ptr.pointed return OSVersion( major = osVersion.majorVersion.toInt(), minor = osVersion.minorVersion.toInt(), patch = osVersion.patchVersion.toInt(), build = null, ) }
zacharee/KMPPlatform
1
Kotlin
zacharee
Zachary Wander
library/src/iosArm64Main/kotlin/dev/zwander/kmp/platform/HostArch.iosArm64.kt
Kotlin
package dev.zwander.kmp.platform internal actual val hostArch: HostArch = HostArch.Arm64
zacharee/KMPPlatform
1
Kotlin
zacharee
Zachary Wander
library/src/iosMain/kotlin/dev/zwander/kmp/platform/HostOS.ios.kt
Kotlin
package dev.zwander.kmp.platform internal actual val hostOS: HostOS = HostOS.IOS
zacharee/KMPPlatform
1
Kotlin
zacharee
Zachary Wander
library/src/iosMain/kotlin/dev/zwander/kmp/platform/KotlinBackend.ios.kt
Kotlin
package dev.zwander.kmp.platform internal actual val hostBackend: KotlinBackend = KotlinBackend.Native
zacharee/KMPPlatform
1
Kotlin
zacharee
Zachary Wander
library/src/iosSimulatorArm64Main/kotlin/dev/zwander/kmp/platform/HostArch.iosSimulatorArm64.kt
Kotlin
package dev.zwander.kmp.platform internal actual val hostArch: HostArch = HostArch.Arm64
zacharee/KMPPlatform
1
Kotlin
zacharee
Zachary Wander
library/src/iosX64Main/kotlin/dev/zwander/kmp/platform/HostArch.iosX64.kt
Kotlin
package dev.zwander.kmp.platform internal actual val hostArch: HostArch = HostArch.X64
zacharee/KMPPlatform
1
Kotlin
zacharee
Zachary Wander
library/src/jsMain/kotlin/dev/zwander/kmp/platform/HostArch.js.kt
Kotlin
package dev.zwander.kmp.platform internal actual val hostArch: HostArch = HostArch.Unknown
zacharee/KMPPlatform
1
Kotlin
zacharee
Zachary Wander
library/src/jsMain/kotlin/dev/zwander/kmp/platform/HostOS.js.kt
Kotlin
package dev.zwander.kmp.platform import kotlinx.browser.window /** * A string identifying the platform on which the user's browser is running; for example: * "MacIntel", "Win32", "Linux x86_64", "Linux x86_64". * See https://developer.mozilla.org/en-US/docs/Web/API/Navigator/platform - deprecated * * A string containing the platform brand. For example, "Windows". * See https://developer.mozilla.org/en-US/docs/Web/API/NavigatorUAData/platform - new API, * but not supported in all browsers */ internal fun getNavigatorInfo(): String = js("navigator.userAgentData ? navigator.userAgentData.platform : navigator.platform") as String /** * In a browser, user platform can be obtained from different places: * - we attempt to use not-deprecated but experimental option first (not available in all browsers) * - then we attempt to use a deprecated option * - if both above return an empty string, we attempt to get `Platform` from `userAgent` * * Note: a client can spoof these values, so it's okay only for non-critical use cases. */ internal fun detectHostOs(): HostOS { val platformInfo = getNavigatorInfo().takeIf { it.isNotEmpty() } ?: window.navigator.userAgent return when { platformInfo.contains("Android", true) -> HostOS.Android platformInfo.contains("iPhone", true) -> HostOS.IOS platformInfo.contains("iOS", true) -> HostOS.IOS platformInfo.contains("iPad", true) -> HostOS.IOS platformInfo.contains("Linux", true) -> HostOS.Linux platformInfo.contains("Mac", true) -> HostOS.MacOS platformInfo.contains("Win", true) -> HostOS.Windows else -> HostOS.Unknown } } internal actual val hostOS: HostOS get() = detectHostOs()
zacharee/KMPPlatform
1
Kotlin
zacharee
Zachary Wander
library/src/jsMain/kotlin/dev/zwander/kmp/platform/HostOSVersion.js.kt
Kotlin
package dev.zwander.kmp.platform internal actual val hostOSVersion: OSVersion = OSVersion.Unknown
zacharee/KMPPlatform
1
Kotlin
zacharee
Zachary Wander
library/src/jsMain/kotlin/dev/zwander/kmp/platform/KotlinBackend.js.kt
Kotlin
package dev.zwander.kmp.platform internal actual val hostBackend: KotlinBackend = KotlinBackend.JS
zacharee/KMPPlatform
1
Kotlin
zacharee
Zachary Wander
library/src/jvmMain/kotlin/dev/zwander/kmp/platform/HostArch.jvm.kt
Kotlin
package dev.zwander.kmp.platform internal actual val hostArch: HostArch get() { return when (val osArch = System.getProperty("os.arch")) { "x86_64", "amd64" -> HostArch.X64 "aarch64" -> HostArch.Arm64 else -> throw Error("Unknown arch $osArch") } }
zacharee/KMPPlatform
1
Kotlin
zacharee
Zachary Wander
library/src/jvmMain/kotlin/dev/zwander/kmp/platform/HostOS.jvm.kt
Kotlin
package dev.zwander.kmp.platform internal actual val hostOS: HostOS get() { val osName = System.getProperty("os.name") return when { osName == "Mac OS X" -> HostOS.MacOS osName.startsWith("Win") -> HostOS.Windows "The Android Project" == System.getProperty("java.specification.vendor") -> HostOS.Android osName == "Linux" -> HostOS.Linux else -> HostOS.Unknown } }
zacharee/KMPPlatform
1
Kotlin
zacharee
Zachary Wander
library/src/jvmMain/kotlin/dev/zwander/kmp/platform/HostOSVersion.jvm.kt
Kotlin
package dev.zwander.kmp.platform internal actual val hostOSVersion: OSVersion get() { val versionInfo = oshi.SystemInfo().operatingSystem.versionInfo val version = versionInfo.version val build = versionInfo.buildNumber val split = version.split(".") return OSVersion( major = split.getOrNull(0)?.toIntOrNull(), minor = split.getOrNull(1)?.toIntOrNull(), patch = split.getOrNull(2)?.toIntOrNull(), build = build?.toLongOrNull(), ) }
zacharee/KMPPlatform
1
Kotlin
zacharee
Zachary Wander