Snapshot of the Umamo working tree as it is
Uploaded as-is from /home/litruv/dev/vtsmaker/umamo on 2026-11-03. 1347 files. Includes the uncommitted work in progress in :edit, :runtime, and :ui, and the untracked files under module/edit/src/jvmAndroidMain/. History is not carried over. The source repo is https://github.com/umamoorg/umamo.
This commit is contained in:
Binary file not shown.
|
After Width: | Height: | Size: 6.9 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 211 KiB |
@@ -0,0 +1,65 @@
|
||||
{
|
||||
"localization": {
|
||||
"locale": "en"
|
||||
},
|
||||
"input": {
|
||||
"keybinding": {
|
||||
"preset": "default",
|
||||
"overrides": {}
|
||||
},
|
||||
"pen": {
|
||||
"backend": "auto"
|
||||
}
|
||||
},
|
||||
"interface": {
|
||||
"theme": "dark",
|
||||
"historyLimit": 200,
|
||||
"layout": {
|
||||
"workspaces": []
|
||||
},
|
||||
"viewport": {
|
||||
"showToolbar": true,
|
||||
"showSidebar": false
|
||||
}
|
||||
},
|
||||
"viewport": {
|
||||
"zoomStepPercent": 1.0,
|
||||
"zoomStepCoarsePercent": 5.0,
|
||||
"selectionHighlightColor": "#FF338CFF",
|
||||
"activeSelectionHighlightColor": "#FF7DE400",
|
||||
"warningColor": "#FFFF5A5A",
|
||||
"pinnedPlacementColor": "#FFB266FF",
|
||||
"grid": {
|
||||
"scale": 100.0,
|
||||
"subdivisions": 10
|
||||
},
|
||||
"rendering": {
|
||||
"supersample": true,
|
||||
"supersampleWhileResizing": true
|
||||
},
|
||||
"meshEdit": {
|
||||
"vertexIdle": "#FFFF00EC",
|
||||
"vertexSelected": "#FFFF7A00",
|
||||
"vertexActive": "#FF7DE400",
|
||||
"vertexOffKey": "#66888888",
|
||||
"edgeIdle": "#99000000",
|
||||
"edgeSelected": "#FFFF7A00",
|
||||
"edgeActive": "#FF7DE400",
|
||||
"edgeOffKey": "#44888888",
|
||||
"faceIdle": "#22000000",
|
||||
"faceSelected": "#66FF7A00",
|
||||
"faceActive": "#FF7DE400",
|
||||
"faceOffKey": "#44888888"
|
||||
}
|
||||
},
|
||||
"import": {
|
||||
"parameterTemplate": "humanoid",
|
||||
"alignment": "center",
|
||||
"watchMode": "auto",
|
||||
"deleteArtIgnoresLayer": false,
|
||||
"layerPositionsFromWorldAxes": false
|
||||
},
|
||||
"app": {
|
||||
"launchCount": 0
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,697 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
Korean UI string catalog; the English default is in values/strings.xml. Format-level identifiers
|
||||
(ParamAngleX, …) stay verbatim — they are document/interop data, not chrome. A key absent here
|
||||
resolves to the default catalog, so this file may be filled in incrementally.
|
||||
-->
|
||||
<resources>
|
||||
<string name="app_name">Umamo</string>
|
||||
<string name="common_expand">펼치기</string>
|
||||
<string name="common_collapse">접기</string>
|
||||
<string name="common_filters">필터</string>
|
||||
<string name="workspace_modelling">모델링</string>
|
||||
<string name="workspace_texture">텍스처</string>
|
||||
<string name="workspace_physics">물리</string>
|
||||
<string name="workspace_new">새 워크스페이스</string>
|
||||
<string name="workspace_new_name">워크스페이스</string>
|
||||
<string name="workspace_rename">이름 변경</string>
|
||||
<string name="workspace_duplicate">복제</string>
|
||||
<string name="workspace_copy_suffix">복사</string>
|
||||
<string name="workspace_delete">삭제</string>
|
||||
<string name="cmd_workspace_prev">이전 워크스페이스</string>
|
||||
<string name="cmd_workspace_next">다음 워크스페이스</string>
|
||||
<string name="cmd_workspace_reset">워크스페이스 초기화</string>
|
||||
<string name="space_viewport2d">2D 뷰포트</string>
|
||||
<string name="space_uv">UV 에디터</string>
|
||||
<string name="space_outliner">아웃라이너</string>
|
||||
<string name="space_parameters">파라미터</string>
|
||||
<string name="space_properties">속성</string>
|
||||
<string name="space_tooldetails">도구 설정</string>
|
||||
<string name="space_history">작업 내역</string>
|
||||
<string name="space_logs">로그</string>
|
||||
<string name="logs_copy">클립보드에 복사</string>
|
||||
<string name="logs_export">파일로 내보내기…</string>
|
||||
<string name="logs_empty">아직 로그 출력이 없습니다</string>
|
||||
<string name="area_split_left_right">왼쪽/오른쪽으로 분할</string>
|
||||
<string name="area_split_top_bottom">위/아래로 분할</string>
|
||||
<string name="area_close">영역 닫기</string>
|
||||
<string name="area_change_editor">에디터 유형 변경</string>
|
||||
<string name="menu_file">파일</string>
|
||||
<string name="menu_open_recent">최근 항목 열기</string>
|
||||
<string name="menu_import">가져오기</string>
|
||||
<string name="menu_export">내보내기</string>
|
||||
<string name="menu_import_cmo3">CMO3…</string>
|
||||
<string name="menu_import_moc3">MOC3…</string>
|
||||
<string name="menu_export_cmo3">CMO3…</string>
|
||||
<string name="menu_export_moc3">MOC3…</string>
|
||||
<string name="cmd_import_cmo3">CMO3 가져오기…</string>
|
||||
<string name="cmd_import_moc3">MOC3 가져오기…</string>
|
||||
<string name="cmd_export_cmo3">CMO3 내보내기…</string>
|
||||
<string name="cmd_export_moc3">MOC3 내보내기…</string>
|
||||
<string name="menu_exit">종료</string>
|
||||
<string name="menu_edit">편집</string>
|
||||
<string name="menu_undo">실행 취소</string>
|
||||
<string name="menu_redo">다시 실행</string>
|
||||
<string name="menu_preferences">설정…</string>
|
||||
<string name="menu_workspace">워크스페이스</string>
|
||||
<string name="menu_workspace_reset">워크스페이스 초기화</string>
|
||||
<string name="menu_workspace_export_this">이 워크스페이스 내보내기…</string>
|
||||
<string name="menu_workspace_export_all">모든 워크스페이스 내보내기…</string>
|
||||
<string name="menu_workspace_import">워크스페이스 가져오기…</string>
|
||||
<string name="dialog_confirm">확인</string>
|
||||
<string name="dialog_cancel">취소</string>
|
||||
<string name="confirm_reset_workspace">이 워크스페이스를 기본 레이아웃으로 초기화하시겠습니까?</string>
|
||||
<string name="confirm_import_replace">모든 워크스페이스를 가져온 파일로 교체하시겠습니까?</string>
|
||||
<string name="confirm_discard_unsaved">문서에 저장하지 않은 변경 사항이 있습니다. 변경 사항을 취소하시겠습니까?</string>
|
||||
<string name="export_report_message_cmo3">파일을 내보냈지만, 다음 항목은 CMO3에 포함할 수 없습니다:</string>
|
||||
<string name="export_report_message_moc3">파일을 내보냈지만, 다음 항목은 MOC3에 포함할 수 없습니다:</string>
|
||||
<string name="repack_report_message">아틀라스를 다시 패킹하지 못했습니다. 다음 타일은 패킹할 수 없습니다:</string>
|
||||
<string name="repack_report_larger_than_page">드로어블 메쉬가 아틀라스 페이지 크기보다 큽니다.</string>
|
||||
<string name="repack_report_no_opaque_pixels">원본 아트워크 레이어에 불투명한 픽셀이 없습니다.</string>
|
||||
<string name="repack_report_below_minimum_coverage">원본 아트워크 레이어의 불투명 영역이 최소 범위보다 작습니다.</string>
|
||||
<string name="repack_report_undecodable">원본 아트워크 레이어를 디코딩할 수 없습니다.</string>
|
||||
<string name="repack_report_degenerate_placement">드로어블의 현재 배치를 역변환할 수 없습니다.</string>
|
||||
<string name="repack_report_pinned_off_page">고정된 배치가 최대 페이지 크기에 맞지 않습니다.</string>
|
||||
<string name="export_weld_divergence">기본 지오메트리 또는 UV가 다음에서 편집되었습니다: %1$s. 내보내기에서는 작성된 상태 그대로 유지되지만, Cubism Editor에서 해당 메시 또는 아틀라스를 편집하면 UV 매핑이 다시 계산되어 손상될 수 있습니다.</string>
|
||||
<string name="export_missing_source_art">이 모델에는 원본 아트워크가 없습니다(MOC3에서 가져온 모델로, MOC3에는 패킹된 텍스처 아틀라스만 저장됩니다). %1$d개의 아틀라스 페이지를 기반으로 대체용 원본 문서를 재구성했기 때문에 이 파일에는 전체 리깅 정보가 포함되어 있으며 Umamo와 Cubism Editor에서 모두 열 수 있습니다. 하지만 이 문서의 각 레이어는 이 리그를 제작할 때 사용한 원본 아트워크가 아니라, 구워진 아틀라스 페이지를 잘라낸 이미지입니다. 실제 편집 가능한 레이어를 내보내려면 원본 레이어 아트워크(PSD/CLIP/KRA)를 이 문서에 맞춰 통합하세요.</string>
|
||||
<string name="export_feature_stripped">%1$s은(는) 대상 런타임 버전에서 사용할 수 없으므로 %2$s에서 제거되었습니다.</string>
|
||||
<string name="export_more_subjects">(+%1$d개 더)</string>
|
||||
<string name="export_category_parameter">파라미터</string>
|
||||
<string name="export_category_parameter_group">파라미터 그룹</string>
|
||||
<string name="export_category_part">파트</string>
|
||||
<string name="export_category_deformer">디포머</string>
|
||||
<string name="export_category_drawable">드로어블</string>
|
||||
<string name="export_category_glue">글루</string>
|
||||
<string name="export_category_document">문서</string>
|
||||
<string name="export_category_keyform">키폼</string>
|
||||
<string name="export_reason_drawable_has_no_mesh">메쉬가 없는 드로어블은 저장할 수 없습니다.</string>
|
||||
<string name="export_reason_channel_demoted_to_static">%1$s의 키 범위가 오브젝트 격자보다 좁아 상수로 출력되었습니다. MOC3는 오브젝트당 하나의 격자만 저장합니다.</string>
|
||||
<string name="export_reason_sketch_part_not_runtime_content">가이드 이미지(스케치) 파트는 런타임 콘텐츠가 아니므로 제외되었습니다.</string>
|
||||
<string name="export_reason_hidden_part_omitted_by_option">파트가 숨겨져 있고 내보내기 옵션에서 숨겨진 파트 제외가 설정되어 있어 해당 내용이 제외되었습니다.</string>
|
||||
<string name="export_reason_hidden_drawable_omitted_by_option">드로어블이 숨겨져 있고 내보내기 옵션에서 숨겨진 아트메쉬 제외가 설정되어 있어 제외되었습니다.</string>
|
||||
<string name="export_reason_unkeyed_drawable_under_deformer">디포머 아래의 키가 지정되지 않은 드로어블에는 기록할 상위 공간 지오메트리가 없어 제외되었습니다.</string>
|
||||
<string name="export_reason_rest_mesh_conversion_size_mismatch">캔버스에서 상위 공간으로의 변환 결과 %2$d에 대해 %1$d개의 좌표만 반환되어, 나머지 메쉬에는 변환을 적용하지 않고 기록했습니다.</string>
|
||||
<string name="export_reason_no_atlas_page_bound">이 드로어블에 연결된 아틀라스 페이지가 없어 0번 페이지를 가리키도록 기록했습니다.</string>
|
||||
<string name="export_reason_clipping_mask_not_in_export">클리핑 마스크 %1$s가 이 내보내기에 포함되지 않아 메쉬에 해당 마스크를 적용하지 않은 상태로 기록했습니다.</string>
|
||||
<string name="export_reason_offscreen_mask_not_in_export">클리핑 마스크가 기록할 수 없는 드로어블을 지정하고 있어 오프스크린에서 제외되었습니다.</string>
|
||||
<string name="export_reason_warp_has_no_lattice">컨트롤 포인트 그리드가 없는 워프 디포머에는 기록할 래티스가 없습니다. 파일을 정상적으로 읽을 수 있도록 그 대신 빈 래티스 하나를 기록했으며, 이 디포머에 연결된 모든 항목은 원점으로 이동합니다.</string>
|
||||
<string name="export_reason_rotation_has_no_pivot">기준점 없는 회전 디포머에는 기록할 변환이 없어 그 대신 항등 변환을 기록했습니다.</string>
|
||||
<string name="export_reason_glue_names_unknown_drawable">이 내보내기에 포함되지 않은 드로어블을 지정하는 글루가 제외되었습니다.</string>
|
||||
<string name="export_reason_id_truncated">ID가 MOC의 %1$d바이트 ID 레코드에 맞지 않아 “%2$s”로 잘라서 기록했습니다.</string>
|
||||
<string name="export_reason_id_truncated_disambiguated">ID가 MOC의 %1$d바이트 ID 레코드에 맞지 않고, 잘라낼 경우 다른 객체의 ID와 충돌하므로 “%2$s”로 변경하여 기록했습니다.</string>
|
||||
<string name="export_reason_no_matching_source">대조할 일치하는 CMO3 원본이 없어 변경 사항을 기록하지 않았습니다.</string>
|
||||
<string name="export_reason_parameter_kind_change">파라미터 종류 변경(일반 / 블렌드 셰이프)은 하위 버전으로 변환되지 않습니다.</string>
|
||||
<string name="export_reason_deformer_kind_change">디포머 종류 변경은 하위 버전으로 변환되지 않습니다.</string>
|
||||
<string name="export_reason_deformer_needs_warp_source">CMO3 원본이 워프 디포머가 아니므로 워프 전용 편집 사항(이중선형 모드, 래티스, 키폼)은 기록하지 않았습니다.</string>
|
||||
<string name="export_reason_deformer_needs_rotation_source">CMO3 원본이 회전 디포머가 아니므로 회전 전용 편집 사항(기본 각도, 키폼)은 기록하지 않았습니다.</string>
|
||||
<string name="export_reason_texture_rebinding_editor_only">텍스처 소 재연결은 에디터에서만 사용하는 상태이므로 CMO3에 기록되지 않습니다.</string>
|
||||
<string name="export_reason_base_geometry_vertex_mismatch">기본 지오메트리의 정점 수가 CMO3 원본과 일치하지 않아 기록하지 않았습니다.</string>
|
||||
<string name="export_reason_no_uvs_to_reconcile">대조할 UV가 드로어블에 없어 UV를 기록하지 않았습니다.</string>
|
||||
<string name="export_reason_deformer_no_part_to_move_to">디포머를 이동할 CMO3 파트가 없어 해당 파트는 변경하지 않았습니다.</string>
|
||||
<string name="export_reason_static_draw_order_shadowed">고정 그리기 순서가 키폼 트랙에 의해 가려져 있어 CMO3에서 별도로 저장할 수 없습니다.</string>
|
||||
<string name="export_reason_composite_statics_shadowed">컴포지트의 고정 값이 파트의 키폼 트랙에 의해 가려져 있어 CMO3에서 별도로 저장할 수 없습니다.</string>
|
||||
<string name="export_reason_part_masks_flatten">파트 유형의 컴포지트 마스크는 CMO3에서 하위 드로어블로 평탄화됩니다.</string>
|
||||
<string name="export_reason_no_source_set_to_create_into">CMO3 모델에 이 유형의 항목을 생성할 세트가 없어 새 항목을 생성하지 않았습니다.</string>
|
||||
<string name="export_reason_created_entity_has_no_source">새로 생성된 항목에는 아직 CMO3 원본이 없어 패널 순서에서 제외되었습니다.</string>
|
||||
<string name="export_reason_created_group_not_in_tree">생성된 그룹이 편집된 파라미터 트리에 없어 생성하지 않았습니다.</string>
|
||||
<string name="export_reason_created_drawable_no_texture_source">생성된 드로어블에 복제할 텍스처 소스가 없어 생성하지 않았습니다.</string>
|
||||
<string name="export_reason_glued_drawable_has_no_source">글루가 적용된 드로어블에 CMO3 원본이 없어 글루를 생성하지 않았습니다.</string>
|
||||
<string name="export_reason_vertex_count_exceeds_edge_table">메쉬에 %1$d개의 정점이 있으며, 편집 가능한 메쉬의 간선 테이블이 인덱싱할 수 있는 %2$d개를 초과하므로 간선 테이블을 다시 생성하지 않았습니다.</string>
|
||||
<string name="export_reason_glued_mesh_no_uid_table">글루가 적용된 메쉬에 편집 가능한 메쉬의 정점 ID 테이블이 없어 글루를 다시 연결할 수 없습니다.</string>
|
||||
<string name="export_reason_glue_pair_past_uid_table">글루 쌍의 인덱스가 해당 메쉬의 정점 ID 테이블 범위를 초과하여 글루를 다시 연결하지 않았습니다.</string>
|
||||
<string name="export_reason_keyform_cannot_bundle">%1$s CMO3는 객체당 하나의 그리드만 저장합니다.</string>
|
||||
<string name="export_reason_axis_parameter_no_source">그리드 축 파라미터 %1$s에 CMO3 원본이 없어 키폼 그리드를 기록하지 않았습니다.</string>
|
||||
<string name="export_reason_blend_shape_parameter_no_source">블렌드 셰이프 파라미터 %1$s에 CMO3 원본이 없어 블렌드 셰이프를 기록하지 않았습니다.</string>
|
||||
<string name="export_reason_keyforms_without_base_mesh">기본 메쉬가 없는 키폼은 CMO3에 포함할 수 없습니다.</string>
|
||||
<string name="export_reason_fractional_draw_order">CMO3는 정수 단위의 드로우 순서만 저장하므로 소수 값은 기록하지 않았습니다.</string>
|
||||
<string name="export_reason_static_glue_intensity_without_keyforms">키폼이 없는 고정 글루 강도는 CMO3에 저장할 수 없습니다.</string>
|
||||
<string name="export_bundle_keys_outside_geometry_span">지오메트리의 키가 지정된 범위를 벗어난 키는 하나의 그리드에 포함할 수 없습니다.</string>
|
||||
<string name="export_bundle_channel_keys_without_geometry">지오메트리가 없는 채널 키는 하나의 그리드에 포함할 수 없습니다.</string>
|
||||
<string name="export_bundle_keys_outside_channel_span">%1$s 트랙의 범위를 벗어난 키는 하나의 그리드에 포함할 수 없습니다.</string>
|
||||
<string name="export_reason_no_authored_world_origin">CMO3에는 지정된 월드 원점을 저장하지 않으므로 파일을 다시 열 때 캔버스 중앙을 기준으로 원점을 계산합니다.</string>
|
||||
<string name="export_reason_no_root_parameter_group">모델에 루트 파라미터 그룹이 없어 파라미터 트리를 다시 생성하지 않았습니다.</string>
|
||||
<string name="export_reason_no_root_part">모델에 루트 파트가 없어 파트 패널 순서를 다시 생성하지 않았습니다.</string>
|
||||
<string name="export_reason_no_parameter_source_set">모델에 파라미터 세트가 없어 파라미터 순서를 기록하지 않았습니다.</string>
|
||||
<string name="export_reason_combined_pair_reordered">결합된 쌍 %1$s + %2$s가 서로 인접하도록 파라미터 순서를 조정했습니다.</string>
|
||||
<string name="export_reason_no_canvas_to_reconcile">모델에 캔버스가 없어 캔버스 크기를 기록하지 않았습니다.</string>
|
||||
<string name="export_reason_no_texture_manager">이 문서에 텍스처 관리자가 없어 원본 아트워크 표시 모드를 기록할 수 없습니다.</string>
|
||||
<string name="export_reason_no_texture_input_for_display">이 드로어블에는 선택한 표시 모드에 사용할 텍스처 입력이 없어 기존 표시 모드를 유지합니다.</string>
|
||||
<string name="export_reason_no_atlas_entry">이 아트워크는 어떤 아틀라스 페이지에도 패킹되어 있지 않아 업데이트할 배치가 없습니다.</string>
|
||||
<string name="export_reason_atlas_page_not_recomposed">이 아트워크가 아틀라스 페이지에서 이동했지만 페이지 이미지에는 여전히 이전 위치에 표시됩니다. 다시 패킹하여 해당 위치를 갱신하세요.</string>
|
||||
<string name="export_reason_atlas_tile_metadata">이 아트워크의 이름 또는 크기가 변경되어 아틀라스 배치에 반영할 수 없습니다. 대신 아트워크를 다시 가져오세요.</string>
|
||||
<string name="export_reason_atlas_tile_rebinding">이 드로어블이 다른 아트워크에 연결되어 있으므로 다시 패킹하는 대신 아트워크를 다시 가져와야 합니다.</string>
|
||||
<string name="export_reason_fractional_canvas_size">CMO3는 캔버스 크기를 정수 픽셀 단위로 저장하므로 소수 값은 기록하지 않았습니다.</string>
|
||||
<string name="confirm_export_overwrite">내보내기를 진행하면 기존 파일 %1$d개를 덮어씁니다: %2$s</string>
|
||||
<string name="export_options_title_moc3">MOC3 내보내기 옵션</string>
|
||||
<string name="export_options_export">내보내기</string>
|
||||
<string name="export_options_section_content">콘텐츠</string>
|
||||
<string name="export_options_section_sidecars">부속 파일</string>
|
||||
<string name="export_options_section_scale">크기</string>
|
||||
<string name="export_options_hidden_parts">숨겨진 파트 내보내기</string>
|
||||
<string name="export_options_hidden_drawables">숨겨진 드로어블 내보내기</string>
|
||||
<string name="export_options_guide_parts">스케치 파트 내보내기</string>
|
||||
<string name="export_options_include_physics">물리 설정 (physics3.json)</string>
|
||||
<string name="export_options_include_userdata">유저 데이터 (userdata3.json)</string>
|
||||
<string name="export_options_include_displayinfo">표시 정보 (cdi3.json)</string>
|
||||
<string name="export_options_pixels_per_unit">유닛당 픽셀 수</string>
|
||||
<string name="export_options_canvas_in_units">캔버스: %1$s × %2$s 유닛</string>
|
||||
<string name="dialog_okay">확인</string>
|
||||
<string name="open_failed_read">%1$s을(를) 읽을 수 없습니다.</string>
|
||||
<string name="open_failed_unrecognized">%1$s은(는) 호환되지 않는 파일 형식입니다.</string>
|
||||
<string name="open_failed_not_openable">%1$s을(를) 아직 에디터에서 열 수 없습니다.</string>
|
||||
<string name="open_failed_parse">%1$s을(를) 열 수 없습니다. 파일이 손상되었을 수 있습니다.</string>
|
||||
<string name="open_failed_missing_manifest">%1$s을(를) 가져올 수 없습니다. 동일한 위치에서 model3.json 매니페스트 파일을 찾을 수 없습니다.</string>
|
||||
<string name="open_failed_missing_texture">%1$s을(를) 가져올 수 없습니다. model3.json에서 참조하는 텍스처가 없거나 읽을 수 없습니다.</string>
|
||||
<string name="menu_help">도움말</string>
|
||||
<string name="menu_source_code">소스 코드…</string>
|
||||
<string name="menu_web_site">웹사이트…</string>
|
||||
<string name="menu_documentation">공식 문서…</string>
|
||||
<string name="menu_credits">제작진…</string>
|
||||
<string name="menu_quick_setup">빠른 설정…</string>
|
||||
<string name="menu_about">Umamo에 대해서…</string>
|
||||
<string name="about_title">Umamo에 대해서</string>
|
||||
<string name="about_version">버전 %1$s</string>
|
||||
<string name="about_license">GNU General Public License v3.0에 따라 라이선스가 부여됨</string>
|
||||
<string name="credits_title">제작진 및 오픈소스 라이선스</string>
|
||||
<string name="dialog_close">닫기</string>
|
||||
<string name="cmd_view_fit">뷰 맞춤</string>
|
||||
<string name="cmd_frame_all">전체 프레임 맞춤</string>
|
||||
<string name="cmd_view_actual_size">실제 크기 (100%)</string>
|
||||
<string name="cmd_view_zoom_in">확대</string>
|
||||
<string name="cmd_view_zoom_out">축소</string>
|
||||
<string name="cmd_view_zoom_in_coarse">크게 확대</string>
|
||||
<string name="cmd_view_zoom_out_coarse">크게 축소</string>
|
||||
<string name="cmd_view_zoom_region">영역 확대</string>
|
||||
<string name="cmd_select_clear">선택 해제</string>
|
||||
<string name="cmd_select_all">전체 선택</string>
|
||||
<string name="cmd_select_invert">선택 반전</string>
|
||||
<string name="cmd_mode_toggle_edit">편집 모드 전환</string>
|
||||
<string name="cmd_mode_object">오브젝트 모드</string>
|
||||
<string name="cmd_mode_edit">편집 모드</string>
|
||||
<string name="cmd_mesh_grab">정점 잡기</string>
|
||||
<string name="cmd_mesh_mirror_h">좌우 위치 맞바꾸기</string>
|
||||
<string name="cmd_mesh_mirror_v">상하 위치 맞바꾸기</string>
|
||||
<string name="cmd_mesh_scale">정점 크기 조절</string>
|
||||
<string name="cmd_mesh_rotate">정점 회전</string>
|
||||
<string name="cmd_mesh_select_mode_vertex">정점 선택 모드</string>
|
||||
<string name="cmd_mesh_select_mode_edge">간선 선택 모드</string>
|
||||
<string name="cmd_mesh_select_mode_face">면 선택 모드</string>
|
||||
<string name="cmd_mesh_box_select">사각형 선택</string>
|
||||
<string name="cmd_mesh_circle_select">원형 선택</string>
|
||||
<string name="cmd_mesh_circle_grow">원형 반경 확대</string>
|
||||
<string name="cmd_mesh_circle_shrink">원형 반경 축소</string>
|
||||
<string name="cmd_uv_mirror_u">UV 수평 반전</string>
|
||||
<string name="cmd_uv_mirror_v">UV 수직 반전</string>
|
||||
<string name="menu_uv_mirror_x">X축 대칭</string>
|
||||
<string name="menu_uv_mirror_y">Y축 대칭</string>
|
||||
<string name="uv_texture_selector_follow">선택 항목 추적</string>
|
||||
<string name="uv_texture_selector_page">%1$d페이지</string>
|
||||
<string name="uv_texture_selector_page_row">%1$d페이지 · %2$d × %3$d · 메쉬 %4$d개</string>
|
||||
<string name="uv_texture_selector_layer">원본 레이어</string>
|
||||
<string name="uv_layer_picker_title">아트워크에서 찾기</string>
|
||||
<string name="uv_layer_picker_row">%1$s · %2$d × %3$d · 메쉬 %4$d개</string>
|
||||
<string name="uv_layer_picker_no_matches">일치하는 아트워크가 없습니다</string>
|
||||
<string name="uv_layer_picker_empty">이 문서에는 원본 아트워크가 없습니다.</string>
|
||||
<string name="cmd_document_toggle_source_artwork">원본 아트워크 표시 전환</string>
|
||||
<string name="cmd_document_repack_atlas">아틀라스 재배치</string>
|
||||
<string name="cmd_uv_page_next">다음 텍스처 페이지</string>
|
||||
<string name="cmd_uv_page_previous">이전 텍스처 페이지</string>
|
||||
<string name="cmd_uv_page_follow">텍스처 페이지: 선택 항목 추적</string>
|
||||
<string name="cmd_uv_pin_placement">핀 아트 배치</string>
|
||||
<string name="cmd_uv_unpin_placement">핀 아트 배치 해제</string>
|
||||
<string name="cmd_undo">실행 취소</string>
|
||||
<string name="cmd_redo">다시 실행</string>
|
||||
<string name="cmd_adjust_last_operation">이전 작업 조정</string>
|
||||
<string name="cmd_toggle_visibility">표시/숨기기</string>
|
||||
<string name="search_hint">검색</string>
|
||||
<string name="search_clear">검색 초기화</string>
|
||||
<string name="text_menu_cut">잘라내기</string>
|
||||
<string name="text_menu_copy">복사</string>
|
||||
<string name="text_menu_paste">붙여넣기</string>
|
||||
<string name="text_menu_select_all">전체 선택</string>
|
||||
<string name="history_open">열기</string>
|
||||
<string name="history_unknown">편집</string>
|
||||
<string name="history_selection">선택</string>
|
||||
<string name="history_mode">모드 변경</string>
|
||||
<string name="history_part_visibility">파트 표시/숨기기 전환</string>
|
||||
<string name="history_part_rename">파트 이름 변경</string>
|
||||
<string name="history_part_selectable">파트 선택 가능/불가능 전환</string>
|
||||
<string name="history_part_move">파트 이동</string>
|
||||
<string name="history_drawable_visibility">메쉬 표시/숨기기 전환</string>
|
||||
<string name="history_drawable_rename">메쉬 이름 변경</string>
|
||||
<string name="history_drawable_selectable">메쉬 선택 가능/불가능 전환</string>
|
||||
<string name="history_drawable_move">메쉬 이동</string>
|
||||
<string name="history_deformer_rename">디포머 이름 변경</string>
|
||||
<string name="history_deformer_selectable">디포머 선택 가능/불가능 전환</string>
|
||||
<string name="history_deformer_move">디포머 이동</string>
|
||||
<string name="history_keyform_insert">키프레임 삽입</string>
|
||||
<string name="history_keyform_move">키프레임 이동</string>
|
||||
<string name="history_keyform_remove">키프레임 제거</string>
|
||||
<string name="history_keyform_select">키프레임 선</string>
|
||||
<string name="history_parameter_select">파라미터 선택</string>
|
||||
<string name="history_parameter_value">파라미터 조정</string>
|
||||
<string name="history_parameter_range">파라미터 범위 편집</string>
|
||||
<string name="history_parameter_link">파라미터 연결</string>
|
||||
<string name="history_parameter_unlink">파라미터 연결 해제</string>
|
||||
<string name="history_parameter_move">파라미터 이동</string>
|
||||
<string name="history_parameter_group_create">그룹 만들기</string>
|
||||
<string name="history_parameter_group_delete">그룹 삭제</string>
|
||||
<string name="history_parameter_group_rename">그룹 이름 변경</string>
|
||||
<string name="history_parameter_create">파라미터 추가</string>
|
||||
<string name="history_parameter_rename">파라미터 이름 변경</string>
|
||||
<string name="history_parameter_delete">파라미터 삭제</string>
|
||||
<string name="history_parameter_delete_move">파라미터 삭제 (키 이동)</string>
|
||||
<string name="history_mesh_move">정점 이동</string>
|
||||
<string name="history_mesh_mirror">위치 맞바꾸기</string>
|
||||
<string name="history_object_mirror">위치 맞바꾸기</string>
|
||||
<string name="history_mesh_scale">정점 크기 조절</string>
|
||||
<string name="history_mesh_rotate">정점 회전</string>
|
||||
<string name="history_mesh_slide">정점 슬라이드</string>
|
||||
<string name="history_uv_move">UV 이동</string>
|
||||
<string name="history_uv_scale">UV 크기 조절</string>
|
||||
<string name="history_uv_rotate">UV 회전</string>
|
||||
<string name="history_uv_mirror">UV 대칭</string>
|
||||
<string name="history_object_move">오브젝트 이동</string>
|
||||
<string name="history_object_scale">오브젝트 크기 조절</string>
|
||||
<string name="history_object_rotate">오브젝트 회전</string>
|
||||
<string name="history_mesh_select">요소 선택</string>
|
||||
<string name="history_mesh_select_mode">선택 모드 변경</string>
|
||||
<string name="history_part_delete">파트 삭제</string>
|
||||
<string name="history_drawable_delete">메쉬 삭제</string>
|
||||
<string name="history_deformer_delete">디포머 삭제</string>
|
||||
<string name="history_part_sketch">가이드 이미지 표시/숨기기 전환</string>
|
||||
<string name="history_part_draw_order">파트 그리기 순서 설정</string>
|
||||
<string name="history_part_group_mode">그룹 모드 설정</string>
|
||||
<string name="history_part_composite">컴포지트 설정</string>
|
||||
<string name="history_drawable_blend_mode">혼합 모드 설정</string>
|
||||
<string name="history_drawable_alpha_blend_mode">알파 모드 설정</string>
|
||||
<string name="history_drawable_culling">후면 제거 전환</string>
|
||||
<string name="history_drawable_invert_mask">마스크 반전 전환</string>
|
||||
<string name="history_drawable_parent_deformer">상위 디포머 설정</string>
|
||||
<string name="history_drawable_masked_by">마스크 설정</string>
|
||||
<string name="history_drawable_multiply_color">곱하기 색상 설정</string>
|
||||
<string name="history_drawable_screen_color">스크린 색상 설정</string>
|
||||
<string name="history_drawable_opacity">불투명도 설정</string>
|
||||
<string name="history_drawable_draw_order">그리기 순서 설정</string>
|
||||
<string name="history_deformer_opacity">디포머 불투명도 설정</string>
|
||||
<string name="history_deformer_multiply_color">디포머 곱하기 색상 설정</string>
|
||||
<string name="history_deformer_screen_color">디포머 스크린 색상 설정</string>
|
||||
<string name="history_deformer_flip_x">X축 반전 설정</string>
|
||||
<string name="history_deformer_flip_y">Y축 반전 설정</string>
|
||||
<string name="history_deformer_part">파트 설정</string>
|
||||
<string name="history_deformer_base_angle">기본 각도 설정</string>
|
||||
<string name="history_deformer_quad_transform">바이리니어 워프 전환</string>
|
||||
<string name="history_deformer_grid">워프 그리드 변경</string>
|
||||
<string name="history_document_canvas_size">캔버스 크기 설정</string>
|
||||
<string name="history_document_world_origin">월드 원점 설정</string>
|
||||
<string name="history_document_source_layer_display">텍스처 표시 변경</string>
|
||||
<string name="history_document_atlas_placement">아틀라스 내부 아트 이동</string>
|
||||
<string name="history_document_atlas_placement_rotate">아틀라스 내부 아트 회전</string>
|
||||
<string name="history_document_atlas_placement_scale">아틀라스 내부 아트 크기 조절</string>
|
||||
<string name="history_document_atlas_pin">아틀라스 내부 아트 고정</string>
|
||||
<string name="history_document_atlas_unpin">아틀라스 내부 아트 고정 해제</string>
|
||||
<string name="history_document_atlas_repack">아틀라스 재배치</string>
|
||||
<string name="history_document_runtime_target">런타임 타겟 설정</string>
|
||||
<string name="outliner_root">퍼펫</string>
|
||||
<string name="outliner_armature">아마추어</string>
|
||||
<string name="outliner_filter_parts">파트</string>
|
||||
<string name="outliner_filter_deformers">디포머</string>
|
||||
<string name="outliner_filter_drawables">드로어블</string>
|
||||
<string name="outliner_restriction_toggles">제한 활성/비활성 전환</string>
|
||||
<string name="outliner_column_selectable">선택 가능 열</string>
|
||||
<string name="outliner_column_visibility">표시 열</string>
|
||||
<string name="placeholder_empty">빈 오브젝트</string>
|
||||
<string name="outliner_menu_visibility">표시/숨기기 전환</string>
|
||||
<string name="outliner_menu_selectable">선택 가능/불가능 전환</string>
|
||||
<string name="outliner_menu_rename">이름 변경</string>
|
||||
<string name="outliner_menu_delete">삭제</string>
|
||||
<string name="outliner_menu_delete_hierarchy">계층 삭제</string>
|
||||
<string name="status_parts">파트: %1$d</string>
|
||||
<string name="status_drawables">드로어블: %1$d</string>
|
||||
<string name="status_parameters">파라미터: %1$d</string>
|
||||
<string name="status_deformers">디포머: %1$d</string>
|
||||
<string name="status_glues">글루: %1$d</string>
|
||||
<string name="status_bind_confirm">LMB / Enter: 확인</string>
|
||||
<string name="status_bind_cancel">RMB / Esc: 취소</string>
|
||||
<string name="status_bind_edit_mode">편집 모드</string>
|
||||
<string name="status_bind_visibility">표시</string>
|
||||
<string name="status_bind_grab">그랩</string>
|
||||
<string name="status_bind_scale">크기 조절</string>
|
||||
<string name="status_bind_rotate">회전</string>
|
||||
<string name="status_bind_insert_key">키 추가</string>
|
||||
<string name="status_bind_delete_key">키 삭제</string>
|
||||
<string name="status_bind_pin">고정</string>
|
||||
<string name="status_select_mode">선택 모드</string>
|
||||
<string name="status_mesh_vertices">%1$d/%2$d개 정점</string>
|
||||
<string name="status_mesh_edges">%1$d/%2$d개 간선</string>
|
||||
<string name="status_mesh_faces">%1$d/%2$d개 면</string>
|
||||
<string name="status_verts">정점 수: %1$d</string>
|
||||
<string name="status_verts_selected">정점 수: %1$d/%2$d</string>
|
||||
<string name="status_tris">삼각면: %1$d</string>
|
||||
<string name="status_tris_selected">삼각면: %1$d/%2$d</string>
|
||||
<string name="notice_transform_only_drawables">선택에 변형할 수 있는 항목이 없습니다. 디포머는 아직 지원되지 않습니다.</string>
|
||||
<string name="notice_transform_deformed">메쉬가 변형된 상태에서는 변형할 수 없습니다. 먼저 모든 파라미터를 초기화해 주세요.</string>
|
||||
<string name="notice_deformer_create_warp_none">워프 디포머로 감쌀 메시가 있는 드로어블 또는 파트를 선택하세요.</string>
|
||||
<string name="cmd_deformer_create_warp">워프 디포머 만들기</string>
|
||||
<string name="status_bind_create_warp">워프 디포머 만들기</string>
|
||||
<string name="outliner_menu_create_warp">워프 디포머 만들기</string>
|
||||
<string name="deformer_default_warp_name">워프 디포머</string>
|
||||
<string name="history_deformer_create">워프 디포머 만들기</string>
|
||||
<string name="notice_unknown">작업을 수행할 수 없습니다.</string>
|
||||
<string name="hud_along_x">X축 기준</string>
|
||||
<string name="hud_along_z">Z축 기준</string>
|
||||
<string name="cmd_transform_pivot_pie">기준점</string>
|
||||
<string name="cmd_transform_pivot_median">중간점</string>
|
||||
<string name="cmd_transform_pivot_individual">개별 원점</string>
|
||||
<string name="cmd_transform_pivot_active">활성 요소</string>
|
||||
<string name="cmd_transform_pivot_cursor">2D 커서</string>
|
||||
<string name="cmd_snap_pie">스냅</string>
|
||||
<string name="cmd_snap_cursor_world_origin">월드 원점으로 커서 이동</string>
|
||||
<string name="cmd_snap_cursor_selected">선택 항목으로 커서 이동</string>
|
||||
<string name="cmd_snap_cursor_active">활성 요소로 커서 이동</string>
|
||||
<string name="cmd_snap_cursor_grid">그리드로 커서 이동</string>
|
||||
<string name="cmd_snap_selection_grid">그리드로 선택 항목 이동</string>
|
||||
<string name="cmd_snap_selection_cursor">커서로 선택 항목 이동</string>
|
||||
<string name="cmd_snap_selection_cursor_offset">커서로 선택 항목 이동 (간격 유지)</string>
|
||||
<string name="cmd_snap_selection_active">활성 요소로 선택 항목 이동</string>
|
||||
<string name="cmd_uv_snap_selection_pixels">픽셀로 선택 항목 이동</string>
|
||||
<string name="cmd_uv_snap_selection_cursor">커서로 선택 항목 이동</string>
|
||||
<string name="cmd_uv_snap_selection_cursor_offset">커서로 선택 항목 이동 (간격 유지)</string>
|
||||
<string name="cmd_uv_snap_selection_grid">그리드로 선택 항목 이동</string>
|
||||
<string name="cmd_uv_snap_cursor_pixels">픽셀로 커서 이동</string>
|
||||
<string name="cmd_uv_snap_cursor_selected">선택 항목으로 커서 이동</string>
|
||||
<string name="cmd_uv_snap_cursor_grid">그리드로 커서 이동</string>
|
||||
<string name="cmd_mesh_select_linked_cursor">커서 아래 연결된 항목 선택</string>
|
||||
<string name="cmd_mesh_select_linked">연결된 항목 선택</string>
|
||||
<string name="cmd_view_frame_selected">선택 항목 프레임 맞춤</string>
|
||||
<string name="cmd_switch_object_under_cursor">편집 중인 메쉬 전환</string>
|
||||
<string name="cmd_outliner_select_hierarchy">계층 선택</string>
|
||||
<string name="outliner_menu_select_hierarchy">계층 선택</string>
|
||||
<string name="cmd_mesh_duplicate">복제</string>
|
||||
<string name="cmd_mesh_merge">정점 병합</string>
|
||||
<string name="cmd_mesh_merge_at_center">중심점에 병합</string>
|
||||
<string name="cmd_mesh_merge_at_first">첫 번째 점에 병합</string>
|
||||
<string name="cmd_mesh_merge_at_last">마지막 점에 병합</string>
|
||||
<string name="cmd_mesh_rip">분리</string>
|
||||
<string name="cmd_mesh_connect">정점 연결</string>
|
||||
<string name="cmd_mesh_insert_vertex">정점 추가</string>
|
||||
<string name="cmd_mesh_vertex_slide">정점 슬라이드</string>
|
||||
<string name="history_mesh_duplicate">복제</string>
|
||||
<string name="history_mesh_merge">정점 병합</string>
|
||||
<string name="history_mesh_rip">분리</string>
|
||||
<string name="history_mesh_connect">정점 연결</string>
|
||||
<string name="history_mesh_add_vertex">정점 추가</string>
|
||||
<string name="history_mesh_delete_vertex">정점 삭제</string>
|
||||
<string name="history_drawable_duplicate">드로어블 복제</string>
|
||||
<string name="notice_merge_needs_vertices">병합하려면 정점 모드에서 두 개 이상의 정점을 선택해야 합니다.</string>
|
||||
<string name="notice_connect_needs_two_vertices">연결하려면 정점 모드에서 정확히 두 개의 정점을 선택해야 합니다.</string>
|
||||
<string name="notice_connect_refused">연결할 수 없습니다: 절단선이 교차하는 대상이 없거나 지오메트리가 비정상적입니다.</string>
|
||||
<string name="notice_add_vertex_refused">정점 추가를 적용할 수 없습니다. 삼각형을 닫은 뒤 Enter. 자세한 내용은 로그를 보세요.</string>
|
||||
<string name="notice_rip_nothing">분리할 수 없습니다: 선택 영역에 분할할 수 있는 팬이 존재하지 않습니다.</string>
|
||||
<string name="notice_display_partial_source_artwork">일부 드로어블에 원본 아트워크가 없지만 여전히 아틀라스에서 표시되고 있습니다.</string>
|
||||
<string name="notice_display_source_artwork_unavailable">모든 드로어블에 원본 아트워크 레이어가 없으며 아틀라스에서 표시되고 있습니다.</string>
|
||||
<string name="notice_atlas_repacked">아틀라스 재배치 완료.</string>
|
||||
<string name="notice_atlas_repack_superseded">재배치 취소됨: 배치되는 동안 아틀라스가 변경되었습니다.</string>
|
||||
<string name="notice_atlas_repack_unchanged">아틀라스가 이미 배치되어 있습니다. 변경된 사항이 없습니다.</string>
|
||||
<string name="notice_uv_no_uvs">선택 영역에 편집할 수 있는 UV가 없습니다.</string>
|
||||
<string name="notice_uv_no_selection">대칭 복사할 대상이 없습니다.</string>
|
||||
<string name="notice_uv_placement_layer_addressed">퍼펫의 UV가 아틀라스가 아닌 원본 아트워크를 참조하고 있으므로 이동할 배치가 없습니다.</string>
|
||||
<string name="notice_uv_placement_no_placed_art">선택한 항목이 아틀라스 페이지에 패킹되어 있지 않거나 원본 아트워크가 없습니다.</string>
|
||||
<string name="notice_uv_placement_page_view_only">배치를 이동하려면 UV 편집기에서 아틀라스 페이지를 표시하세요.</string>
|
||||
<string name="notice_uv_placement_not_on_page">이 페이지에 배치된 선택 항목이 없습니다.</string>
|
||||
<string name="notice_uv_placement_not_derivable">원본 아트에서 아틀라스를 재구성할 수 없으므로 배치를 이동할 수 없습니다.</string>
|
||||
<string name="notice_uv_placement_overlap">배치가 다른 타일과 겹칩니다. 충돌을 해결하려면 아틀라스를 다시 배치하세요.</string>
|
||||
<string name="notice_uv_placement_off_page">배치가 페이지 경계를 벗어납니다. 튀어나간 영역은 잘려 나갑니다.</string>
|
||||
<string name="notice_uv_placement_pinned">선택한 타일이 고정되어 있습니다. 변형하려면 고정을 해제하세요.</string>
|
||||
<string name="notice_edit_no_editable_geometry">선택한 모든 드로어블이 상위 항목에 숨겨져 있어 편집할 수 없습니다.</string>
|
||||
<string name="cmd_mesh_proportional_toggle">비례 편집 켜기/끄기 전</string>
|
||||
<string name="cmd_mesh_proportional_falloff_smooth">비례 편집 감쇠: 부드럽게</string>
|
||||
<string name="cmd_mesh_proportional_falloff_sphere">비례 편집 감쇠: 구체</string>
|
||||
<string name="cmd_mesh_proportional_falloff_root">비례 편집 감쇠: 루트</string>
|
||||
<string name="cmd_mesh_proportional_falloff_sharp">비례 편집 감쇠: 날카롭게</string>
|
||||
<string name="cmd_mesh_proportional_falloff_linear">비례 편집 감쇠: 선형</string>
|
||||
<string name="cmd_mesh_proportional_falloff_constant">비례 편집 감쇠: 균일</string>
|
||||
<string name="falloff_smooth">부드럽게</string>
|
||||
<string name="falloff_sphere">구형</string>
|
||||
<string name="falloff_root">루트</string>
|
||||
<string name="falloff_sharp">날카롭게</string>
|
||||
<string name="falloff_linear">선형</string>
|
||||
<string name="falloff_constant">균일</string>
|
||||
<string name="hud_proportional">비례 %1$s · %2$d</string>
|
||||
<string name="notice_proportional_on">비례 편집 켜짐.</string>
|
||||
<string name="notice_proportional_off">비례 편집 꺼짐.</string>
|
||||
<string name="header_proportional_falloff">비례 감쇠</string>
|
||||
<string name="header_more">더 보기</string>
|
||||
<string name="cmd_mesh_proportional_connected">연결된 요소만 비례 편집 전환</string>
|
||||
<string name="hud_connected">연결됨</string>
|
||||
<string name="hud_placement">배치</string>
|
||||
<string name="hud_overlapping">겹침</string>
|
||||
<string name="hud_off_page">페이지 바깥</string>
|
||||
<string name="hud_delta_px">Δ %1$d, %2$d px</string>
|
||||
<string name="hud_angle_degrees">%1$s°</string>
|
||||
<string name="hud_scale_factor">×%1$s</string>
|
||||
<string name="notice_proportional_connected_on">비례 편집: 연결된 요소만.</string>
|
||||
<string name="notice_proportional_connected_off">비례 편집: 반경 내 모두.</string>
|
||||
<string name="pie_title_pivot">기준점</string>
|
||||
<string name="pie_title_snap">스냅</string>
|
||||
<string name="pie_title_uv_snap">UV 스냅</string>
|
||||
<string name="pie_title_merge">병합</string>
|
||||
<string name="cmd_view_toggle_toolbar">툴바 전환</string>
|
||||
<string name="cmd_view_toggle_sidebar">사이드바 전환</string>
|
||||
<string name="sidebar_title">사이드바</string>
|
||||
<string name="sidebar_empty_hint">도구 및 항목 패널이 여기에 표시됩니다.</string>
|
||||
<string name="properties_part_ref">상위 파트</string>
|
||||
<string name="properties_parent_deformer">상위 디포머</string>
|
||||
<string name="properties_mask_count">마스크: %1$d</string>
|
||||
<string name="properties_mesh">메쉬: 정점 %1$d개, 삼각면 %2$d개</string>
|
||||
<string name="properties_no_mesh">메쉬 없음</string>
|
||||
<string name="properties_warp_grid">그리드: %1$d × %2$d</string>
|
||||
<string name="properties_warp_grid_x">그리드 X: %1$d</string>
|
||||
<string name="properties_warp_grid_y">그리드 Y: %1$d</string>
|
||||
<string name="properties_field_warp_grid">그리드</string>
|
||||
<string name="properties_field_warp_grid_description">워프 격자 각 축의 분할 수(2–16). 값을 올리면 현재 변형을 샘플링해 제어점을 추가하므로, 모양은 유지한 채 격자를 더 촘촘하게 만들 수 있습니다.</string>
|
||||
<string name="status_multi_selected">%1$d 선택됨</string>
|
||||
<string name="properties_no_matches">일치하는 속성이 없습니다.</string>
|
||||
<string name="properties_tab_document">문서</string>
|
||||
<string name="properties_tab_object">오브젝트</string>
|
||||
<string name="properties_tab_data">데이터</string>
|
||||
<string name="properties_section_canvas">캔버스</string>
|
||||
<string name="properties_section_display">표시</string>
|
||||
<string name="properties_field_source_layer_display">원본 아트워크 표시</string>
|
||||
<string name="properties_section_runtime">런타임</string>
|
||||
<string name="properties_section_transform">변형</string>
|
||||
<string name="properties_section_relations">관계</string>
|
||||
<string name="properties_section_mesh">메쉬</string>
|
||||
<string name="properties_section_texture">텍스처</string>
|
||||
<string name="properties_section_blend">혼합</string>
|
||||
<string name="properties_section_deformer">디포머</string>
|
||||
<string name="properties_section_part">파트</string>
|
||||
<string name="properties_canvas_none">캔버스 없음</string>
|
||||
<string name="properties_field_runtime_target">타겟</string>
|
||||
<string name="runtime_target_no_target">타겟 없음 (모든 기능)</string>
|
||||
<string name="runtime_target_ayagami">Ayagami (Cubism %1$s 호환)</string>
|
||||
<string name="properties_runtime_restricted">제한된 기능:</string>
|
||||
<string name="properties_runtime_no_restrictions">모든 기능을 사용할 수 있습니다.</string>
|
||||
<string name="properties_runtime_feature_in_use">%1$s - 현재 사용 중</string>
|
||||
<string name="runtime_feature_warp_quad_transform">새로운 워프 디포머 방식</string>
|
||||
<string name="runtime_feature_reversed_mask">마스크 반전</string>
|
||||
<string name="runtime_feature_mesh_warp_blend_shapes">블렌드 셰이프 (아트 메쉬 및 워프 디포머)</string>
|
||||
<string name="runtime_feature_blend_shape_parameters">블렌드 셰이프 파라미터</string>
|
||||
<string name="runtime_feature_multiply_color">곱하기 색상</string>
|
||||
<string name="runtime_feature_screen_color">스크린 색상</string>
|
||||
<string name="runtime_feature_extended_blend_shapes">블렌드 셰이프 (파트, 회전 디포머, 글루)</string>
|
||||
<string name="runtime_feature_motion_sync">모션-싱크</string>
|
||||
<string name="runtime_feature_extended_blend_modes">혼합 모드</string>
|
||||
<string name="runtime_feature_part_composite">파트 컴포지트 (오프스크린 드로잉)</string>
|
||||
<string name="runtime_feature_parameter_repeat">파라미터 반복</string>
|
||||
<string name="runtime_feature_art_path">아트 패스</string>
|
||||
<string name="properties_texture_source">텍스처 소스: %1$s</string>
|
||||
<string name="properties_texture_own">개별 아틀라스 바인딩</string>
|
||||
<string name="properties_field_pinned">고정</string>
|
||||
<string name="properties_field_canvas_width">너비</string>
|
||||
<string name="properties_field_canvas_height">높이</string>
|
||||
<string name="properties_field_origin_x">X 중심</string>
|
||||
<string name="properties_field_origin_z">Z 중심</string>
|
||||
<string name="properties_field_position_x">X 위치</string>
|
||||
<string name="properties_field_position_z">Z 위치</string>
|
||||
<string name="properties_field_size_x">X 크기</string>
|
||||
<string name="properties_field_size_z">Z 크기</string>
|
||||
<string name="properties_transform_lock_aspect">종횡비 고정</string>
|
||||
<string name="properties_field_blend_mode">혼합</string>
|
||||
<string name="properties_field_alpha_mode">알파</string>
|
||||
<string name="properties_field_culling">후면 제거</string>
|
||||
<string name="properties_field_invert_mask">마스크 반전</string>
|
||||
<string name="properties_field_flip_x">X축 반전</string>
|
||||
<string name="properties_field_flip_y">Y축 반전</string>
|
||||
<string name="properties_field_base_angle">기본 각도</string>
|
||||
<string name="properties_field_quad_transform">이중선형(사각형)</string>
|
||||
<string name="properties_field_sketch">가이드 이미지</string>
|
||||
<string name="properties_field_draw_order">그리기 순서</string>
|
||||
<string name="properties_field_group_mode">그룹 모드</string>
|
||||
<string name="properties_field_opacity">불투명도</string>
|
||||
<string name="properties_field_multiply_color">곱하기 색상</string>
|
||||
<string name="properties_field_screen_color">스크린 색상</string>
|
||||
<string name="properties_field_masked_by">마스크 적용 대상</string>
|
||||
<string name="properties_mask_add">마스크 추가…</string>
|
||||
<string name="properties_mask_remove">마스크 제거</string>
|
||||
<string name="properties_relation_clear">관계 초기화</string>
|
||||
<string name="properties_relation_pick">뷰포트 또는 아웃라이너에서 선택하세요.</string>
|
||||
<string name="unit_pixels">px</string>
|
||||
<string name="unit_degrees">°</string>
|
||||
<string name="unit_percent">%</string>
|
||||
<string name="repack_options_page_size">최대 페이지 크기</string>
|
||||
<string name="repack_options_gutter">여백</string>
|
||||
<string name="repack_options_extrude">돌출</string>
|
||||
<string name="repack_options_allow_rotation">회전 허용</string>
|
||||
<string name="repack_options_keep_pinned">고정된 타일 유지</string>
|
||||
<string name="repack_options_power_of_two">2의 거듭제곱 페이지</string>
|
||||
<string name="repack_options_square_pages">정사각형 페이지</string>
|
||||
<string name="repack_options_shrink_pages">페이지 축소</string>
|
||||
<string name="repack_options_alpha_threshold">알파 임계값</string>
|
||||
<string name="placement_options_move_x">X 이동</string>
|
||||
<string name="placement_options_move_y">Y 이동</string>
|
||||
<string name="placement_options_angle">각도</string>
|
||||
<string name="placement_options_scale_x">X 크기 조절</string>
|
||||
<string name="placement_options_scale_y">Y 크기 조절</string>
|
||||
<!-- The mesh / object / UV transform rows of the operation settings strip. -->
|
||||
<string name="transform_options_move_z">Z 이동</string> <!-- NEEDS HUMAN REVIEW: LLM Translated-->
|
||||
<string name="transform_options_scale_z">Z 크기 조절</string> <!-- NEEDS HUMAN REVIEW: LLM Translated-->
|
||||
<string name="transform_options_proportional">비례 편집</string> <!-- NEEDS HUMAN REVIEW: LLM Translated-->
|
||||
<string name="transform_options_falloff">감쇠</string> <!-- NEEDS HUMAN REVIEW: LLM Translated-->
|
||||
<string name="transform_options_proportional_size">비례 편집 크기</string> <!-- NEEDS HUMAN REVIEW: LLM Translated-->
|
||||
<string name="transform_options_connected">연결된 것만</string> <!-- NEEDS HUMAN REVIEW: LLM Translated-->
|
||||
<string name="transform_options_slide_factor">계수</string> <!-- NEEDS HUMAN REVIEW: LLM Translated-->
|
||||
<!-- The Merge row of the operation settings strip and its choices. -->
|
||||
<string name="merge_options_target">병합 위치</string> <!-- NEEDS HUMAN REVIEW: LLM Translated-->
|
||||
<string name="merge_target_center">중심</string> <!-- NEEDS HUMAN REVIEW: LLM Translated-->
|
||||
<string name="merge_target_first">처음</string> <!-- NEEDS HUMAN REVIEW: LLM Translated-->
|
||||
<string name="merge_target_last">마지막</string> <!-- NEEDS HUMAN REVIEW: LLM Translated-->
|
||||
<string name="blend_mode_normal">표준</string>
|
||||
<string name="blend_mode_additive">가산</string>
|
||||
<string name="blend_mode_multiply">곱하기</string>
|
||||
<string name="blend_mode_additive_premultiplied">가산 (레거시)</string>
|
||||
<string name="blend_mode_additive_glow">가산 (발광)</string>
|
||||
<string name="blend_mode_darken">어둡게 하기</string>
|
||||
<string name="blend_mode_multiply_premultiplied">곱하기 (레거시)</string>
|
||||
<string name="blend_mode_color_burn">색상 번</string>
|
||||
<string name="blend_mode_linear_burn">선형 번</string>
|
||||
<string name="blend_mode_lighten">밝게 하기</string>
|
||||
<string name="blend_mode_screen">스크린</string>
|
||||
<string name="blend_mode_color_dodge">색상 닷지</string>
|
||||
<string name="blend_mode_overlay">오버레이</string>
|
||||
<string name="blend_mode_soft_light">소프트 라이트</string>
|
||||
<string name="blend_mode_hard_light">하드 라이트</string>
|
||||
<string name="blend_mode_linear_light">선형 라이트</string>
|
||||
<string name="blend_mode_hue">색조</string>
|
||||
<string name="blend_mode_color">색상</string>
|
||||
<string name="alpha_blend_over">위에 놓기</string>
|
||||
<string name="alpha_blend_atop">위에 합성</string>
|
||||
<string name="alpha_blend_out">제외</string>
|
||||
<string name="alpha_blend_conjoint">결합</string>
|
||||
<string name="alpha_blend_disjoint">분리</string>
|
||||
<string name="part_group_pass_through">통과</string>
|
||||
<string name="part_group_grouped">그룹화</string>
|
||||
<string name="part_group_isolated">격리</string>
|
||||
<string name="parameter_reset">기본으로 초기화</string>
|
||||
<string name="parameter_reset_all">전체 초기화</string>
|
||||
<string name="parameter_range_section">범위</string>
|
||||
<string name="parameter_link">아래 파라미터와 연결</string>
|
||||
<string name="parameter_unlink">연결 해제 후 두 슬라이더로 분리</string>
|
||||
<string name="parameter_reorder_handle">드래그하여 순서 변경</string>
|
||||
<string name="parameter_new_group">새 그룹</string>
|
||||
<string name="parameter_group_default_name">새 그룹</string>
|
||||
<string name="parameter_menu_rename">이름 변경</string>
|
||||
<string name="parameter_menu_delete_group">그룹 삭제</string>
|
||||
<string name="parameter_menu_add">파라미터 추가</string>
|
||||
<string name="parameter_menu_add_keyform">키폼 파라미터 추가</string>
|
||||
<string name="parameter_menu_add_blendshape">블렌드 셰이프 파라미터 추가</string>
|
||||
<string name="parameter_menu_delete">파라미터 삭제</string>
|
||||
<string name="parameter_menu_delete_discard">키 버리기</string>
|
||||
<string name="parameter_menu_delete_move_keys">키 이동…</string>
|
||||
<string name="parameter_default_name">새 파라미터</string>
|
||||
<string name="parameter_filter_selected">선택 항목이 사용하는 파라미터만 표시</string>
|
||||
<string name="parameter_range_min">최소</string>
|
||||
<string name="parameter_range_default">기본</string>
|
||||
<string name="parameter_range_max">최대</string>
|
||||
<string name="cmd_preferences">설정</string>
|
||||
<string name="settings_title">설정</string>
|
||||
<string name="settings_close">설정 닫기</string>
|
||||
<string name="quick_setup_title">빠른 설정</string>
|
||||
<string name="quick_setup_continue">계속</string>
|
||||
<string name="settings_category_interface">인터페이스</string>
|
||||
<string name="settings_category_colors">색상</string>
|
||||
<string name="settings_category_viewport">뷰포트</string>
|
||||
<string name="settings_category_keybindings">단축키 설정</string>
|
||||
<string name="settings_category_pen">펜</string>
|
||||
<string name="settings_interface_theme">테마</string>
|
||||
<string name="settings_theme_dark">다크</string>
|
||||
<string name="settings_theme_light">라이트</string>
|
||||
<string name="settings_theme_system">시스템</string>
|
||||
<string name="settings_interface_language">언어</string>
|
||||
<string name="settings_interface_history_steps">작업 내역 단계</string>
|
||||
<string name="settings_keybindings_preset">프리셋</string>
|
||||
<string name="settings_keybindings_preset_quick">단축키 프리셋</string>
|
||||
<string name="settings_keymap_preset_default">기본</string>
|
||||
<string name="settings_keymap_preset_cubism">Cubism</string>
|
||||
<string name="settings_keymap_preset_blender">Blender</string>
|
||||
<string name="settings_keybindings_reset">프리셋으로 초기화</string>
|
||||
<string name="settings_keybindings_press_shortcut">단축키를 누르세요…</string>
|
||||
<string name="settings_keybindings_unbound">지정되지 않음</string>
|
||||
<string name="settings_keybindings_clear">단축키 지우기</string>
|
||||
<string name="settings_keybindings_conflict">%1$s은(는) 이미 “%2$s”에 지정되어 있습니다. 다시 지정하시겠습니까?</string>
|
||||
<string name="settings_keybindings_reassign">다시 지정</string>
|
||||
<string name="settings_pen_coming_soon">펜 설정은 곧 지원될 예정입니다.</string>
|
||||
<string name="settings_viewport_zoom_step">확대/축소 단계(%)</string>
|
||||
<string name="settings_viewport_zoom_step_coarse">확대/축소 큰 단계(%)</string>
|
||||
<string name="settings_viewport_grid_scale">그리드 크기</string>
|
||||
<string name="settings_viewport_grid_subdivisions">그리드 세분화</string>
|
||||
<string name="settings_viewport_supersample">슈퍼샘플링(2배 렌더링 품질)</string>
|
||||
<string name="settings_viewport_supersample_while_resizing">패널 크기 조정 중에도 슈퍼샘플링 유지</string>
|
||||
<string name="settings_colors_viewport">뷰포트</string>
|
||||
<string name="settings_colors_selection_highlight">선택 강조</string>
|
||||
<string name="settings_colors_active_selection_highlight">활성 선택 강조</string>
|
||||
<string name="settings_colors_warning">경고</string>
|
||||
<string name="settings_colors_pinned_placement">고정된 배치</string>
|
||||
<string name="settings_colors_mesh_edit">메쉬 편집</string>
|
||||
<string name="settings_colors_group_vertex">정점</string>
|
||||
<string name="settings_colors_group_edge">간선</string>
|
||||
<string name="settings_colors_group_face">면</string>
|
||||
<string name="settings_colors_role_idle">대기</string>
|
||||
<string name="settings_colors_role_selected">선택됨</string>
|
||||
<string name="settings_colors_role_active">활성</string>
|
||||
<string name="settings_colors_role_offkey">키 외</string>
|
||||
<string name="pick_hover_drawable">드로어블: %1$s</string>
|
||||
<string name="pick_hover_part">파트: %1$s</string>
|
||||
<string name="pick_hover_deformer">디포머: %1$s</string>
|
||||
<string name="space_keyformsheet">키폼 시트</string>
|
||||
<string name="keyform_choose_parameter_insert">어떤 파라미터에 키를 삽입하시겠습니까?</string>
|
||||
<string name="keyform_choose_parameter_remove">어떤 파라미터에서 키를 제거하시겠습니까?</string>
|
||||
<string name="keyform_sheet_select_owner">%1$s 선택</string>
|
||||
<string name="keyform_sheet_all_filtered">필터로 인해 모든 트랙이 숨겨져 있습니다.</string>
|
||||
<string name="keyform_sheet_filter_geometry">변형 트랙</string>
|
||||
<string name="keyform_sheet_filter_channels">속성 트랙</string>
|
||||
<string name="keyform_sheet_filter_blend_shapes">블렌드 셰이프 트랙</string>
|
||||
<string name="keyform_sheet_no_tracks">이 파라미터에는 아직 키가 지정되지 않았습니다.</string>
|
||||
<string name="owner_kind_drawable">드로어블</string>
|
||||
<string name="owner_kind_warp_deformer">워프 디포머</string>
|
||||
<string name="owner_kind_rotation_deformer">회전 디포머</string>
|
||||
<string name="owner_kind_part">파트</string>
|
||||
<string name="owner_kind_glue">글루</string>
|
||||
<string name="track_geometry">지오메트리</string>
|
||||
<string name="track_blend_shape">블렌드 셰이프</string>
|
||||
<string name="channel_draw_order">그리기 순서</string>
|
||||
<string name="channel_opacity">불투명도</string>
|
||||
<string name="channel_multiply_color">곱하기</string>
|
||||
<string name="channel_screen_color">스크린</string>
|
||||
<string name="channel_flip_x">X축 뒤집기</string>
|
||||
<string name="channel_flip_y">Y축 뒤집기</string>
|
||||
<string name="channel_glue_intensity">글루 강도</string>
|
||||
<string name="cmd_keyform_insert">키프레임 추가</string>
|
||||
<string name="cmd_keyform_frame_all">모든 키에 맞추기</string>
|
||||
<string name="cmd_keyform_nudge_left">키프레임 왼쪽으로 미세 이동</string>
|
||||
<string name="cmd_keyform_nudge_right">키프레임 오른쪽으로 미세 이동</string>
|
||||
<string name="cmd_keyform_delete_keys">선택된 키 삭제</string>
|
||||
<string name="cmd_keyform_delete">키프레임 삭제</string>
|
||||
<string name="notice_keyform_no_target">키를 지정할 수 있는 속성을 가리켜 키프레임을 삽입하세요.</string>
|
||||
<string name="notice_keyform_no_parameter">키를 추가할 파라미터를 선택하세요.</string>
|
||||
</resources>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,78 @@
|
||||
package org.umamo.ui
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.produceState
|
||||
import androidx.compose.runtime.staticCompositionLocalOf
|
||||
import org.umamo.settings.Settings
|
||||
import org.umamo.storage.AppStorage
|
||||
import org.umamo.ui.l10n.LOCALE_SETTINGS_KEY
|
||||
import org.umamo.ui.l10n.UI_LANGUAGE_ENDONYMS
|
||||
import org.umamo.ui.l10n.matchUiLanguage
|
||||
import org.umamo.ui.l10n.systemLanguageTags
|
||||
import org.umamo.ui.resources.Res
|
||||
|
||||
/**
|
||||
* App-wide settings, provided once at the Compose root by [ProvideSettings]. Reading it before it is
|
||||
* provided is a programming error (the `error` default fires). `static` because the [Settings] instance
|
||||
* is stable for the app's life - individual values change through its `changes` flow, not by swapping the
|
||||
* local - so Compose need not track reads of this local for recomposition.
|
||||
*/
|
||||
val LocalSettings = staticCompositionLocalOf<Settings> { error("LocalSettings not provided — wrap content in ProvideSettings") }
|
||||
|
||||
/**
|
||||
* Loads [Settings] over the platform [storage] (bundled `defaultSettings.json` ← the user's file) and
|
||||
* provides it as [LocalSettings] to [content]. The load is async (the bundled default is a Compose
|
||||
* resource), so [content] renders once settings are ready; for a tiny config file that's an imperceptible
|
||||
* first frame. Each app supplies the right [storage] (`desktopAppStorage` / `androidAppStorage`).
|
||||
*
|
||||
* @param AppStorage storage The platform storage (config directory + IO).
|
||||
* @param Function content The app content that may read [LocalSettings].
|
||||
*/
|
||||
@Composable
|
||||
fun ProvideSettings(storage: AppStorage, content: @Composable () -> Unit) {
|
||||
val settings by produceState<Settings?>(initialValue = null, storage) {
|
||||
value = loadAppSettings(storage)
|
||||
}
|
||||
settings?.let { loaded ->
|
||||
CompositionLocalProvider(LocalSettings provides loaded, content = content)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the bundled `defaultSettings.json` (a Compose Multiplatform resource, so desktop and Android share
|
||||
* one baseline) as text.
|
||||
*
|
||||
* @return String The default settings JSON.
|
||||
*/
|
||||
suspend fun defaultSettingsJson(): String = Res.readBytes("files/defaultSettings.json").decodeToString()
|
||||
|
||||
/**
|
||||
* Loads the app's settings - the bundled defaults under the user's file - and seeds a first run's choices, so
|
||||
* every platform starts from the same state. The one load path both apps take: the desktop entrypoint calls
|
||||
* it directly (it must hold settings before its window opens), and [ProvideSettings] calls it for Android.
|
||||
*
|
||||
* @param AppStorage storage The platform storage (config directory + IO).
|
||||
* @return Settings The loaded, first-run-seeded settings.
|
||||
*/
|
||||
suspend fun loadAppSettings(storage: AppStorage): Settings = Settings.load(storage, defaultSettingsJson()).also { settings -> seedFirstRunSettings(settings) }
|
||||
|
||||
/**
|
||||
* Seeds what a first run decides before anything is shown: the UI language, matched from the operating
|
||||
* system's preferred languages (English when none has a catalog). Runs only when no user settings file was
|
||||
* found at load, so a language the rigger chose is never overridden.
|
||||
*
|
||||
* The match is written even when it is English: it pins the language the app first opened in, and it creates
|
||||
* the user file, so the next launch finds settings and does not treat itself as a first run. The Quick Setup
|
||||
* modal a first run opens then shows this language already selected.
|
||||
*
|
||||
* @param Settings settings The freshly loaded settings.
|
||||
* @param List systemTags The operating system's preferred language tags, most preferred first.
|
||||
*/
|
||||
fun seedFirstRunSettings(settings: Settings, systemTags: List<String> = systemLanguageTags()) {
|
||||
if (settings.foundUserFile) {
|
||||
return
|
||||
}
|
||||
settings.setString(LOCALE_SETTINGS_KEY, matchUiLanguage(systemTags, UI_LANGUAGE_ENDONYMS.keys))
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
package org.umamo.ui
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.MutableState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import org.umamo.settings.Settings
|
||||
|
||||
/**
|
||||
* A write-through, reactive binding to one string setting: reading the returned state yields the current
|
||||
* value (the user override, else the default), and assigning to it persists immediately via
|
||||
* [Settings.setString] - the auto-save the preferences UI is built on, with no commit step. A change to
|
||||
* the same key from elsewhere (another control, a future shortcut) flows back in through the settings
|
||||
* `changes` flow, so the binding stays in sync without the read-once-then-collect boilerplate each call
|
||||
* site would otherwise repeat (cf. ProvideAppThemeFromSettings, PersistentEditorShell).
|
||||
*
|
||||
* @param String key The dotted settings key (e.g. "interface.theme").
|
||||
* @param String default The value used when the key is absent (rarely hit; defaultSettings.json seeds most).
|
||||
* @return MutableState A state whose getter reads the merged value and whose setter persists to the user layer.
|
||||
*/
|
||||
@Composable
|
||||
fun rememberStringSetting(key: String, default: String): MutableState<String> {
|
||||
val settings = LocalSettings.current
|
||||
val backing = remember(settings, key) { mutableStateOf(settings.getString(key) ?: default) }
|
||||
// Re-read when this key is written from anywhere, so a value changed by another control or command
|
||||
// (not just this binding's own setter) reflects here too.
|
||||
LaunchedEffect(settings, key) {
|
||||
settings.changes.collect { changedKey ->
|
||||
if (changedKey == key) {
|
||||
backing.value = settings.getString(key) ?: default
|
||||
}
|
||||
}
|
||||
}
|
||||
return remember(settings, key, backing) { WriteThroughSettingState(settings, key, backing) }
|
||||
}
|
||||
|
||||
/**
|
||||
* The [MutableState] returned by [rememberStringSetting]: reads delegate to [backing] (kept current by
|
||||
* the settings `changes` collector), and a write both persists through [Settings.setString] and updates
|
||||
* [backing] at once so the new value is visible on the very next read without waiting for the flow to
|
||||
* round-trip.
|
||||
*
|
||||
* @property Settings settings The settings instance the write persists into.
|
||||
* @property String key The dotted key being bound.
|
||||
* @property MutableState backing The local state mirroring the merged value.
|
||||
*/
|
||||
private class WriteThroughSettingState(
|
||||
private val settings: Settings,
|
||||
private val key: String,
|
||||
private val backing: MutableState<String>,
|
||||
) : MutableState<String> {
|
||||
override var value: String
|
||||
get() = backing.value
|
||||
set(newValue) {
|
||||
// Update the local mirror first so the read is immediate, then persist (which also emits on
|
||||
// `changes`; the collector re-reading the now-identical value is a harmless no-op).
|
||||
backing.value = newValue
|
||||
settings.setString(key, newValue)
|
||||
}
|
||||
|
||||
override fun component1(): String = value
|
||||
|
||||
override fun component2(): (String) -> Unit = { newValue -> value = newValue }
|
||||
}
|
||||
|
||||
/**
|
||||
* A write-through, reactive binding to one number-valued setting - the [rememberStringSetting]
|
||||
* counterpart for numeric keys, with the same auto-save and external-change semantics.
|
||||
*
|
||||
* @param String key The dotted settings key (e.g. "viewport.zoomStepPercent").
|
||||
* @param Int default The value used when the key is absent (rarely hit; defaultSettings.json seeds most).
|
||||
* @return MutableState A state whose getter reads the merged value and whose setter persists to the user layer.
|
||||
*/
|
||||
@Composable
|
||||
fun rememberIntSetting(key: String, default: Int): MutableState<Int> {
|
||||
val settings = LocalSettings.current
|
||||
val backing = remember(settings, key) { mutableStateOf(settings.getInt(key) ?: default) }
|
||||
// Re-read when this key is written from anywhere, so a value changed by another control or command
|
||||
// (not just this binding's own setter) reflects here too.
|
||||
LaunchedEffect(settings, key) {
|
||||
settings.changes.collect { changedKey ->
|
||||
if (changedKey == key) {
|
||||
backing.value = settings.getInt(key) ?: default
|
||||
}
|
||||
}
|
||||
}
|
||||
return remember(settings, key, backing) { WriteThroughIntSettingState(settings, key, backing) }
|
||||
}
|
||||
|
||||
/**
|
||||
* The [MutableState] returned by [rememberIntSetting]: the numeric twin of
|
||||
* [WriteThroughSettingState], persisting through [Settings.setInt].
|
||||
*
|
||||
* @property Settings settings The settings instance the write persists into.
|
||||
* @property String key The dotted key being bound.
|
||||
* @property MutableState backing The local state mirroring the merged value.
|
||||
*/
|
||||
private class WriteThroughIntSettingState(
|
||||
private val settings: Settings,
|
||||
private val key: String,
|
||||
private val backing: MutableState<Int>,
|
||||
) : MutableState<Int> {
|
||||
override var value: Int
|
||||
get() = backing.value
|
||||
set(newValue) {
|
||||
// Update the local mirror first so the read is immediate, then persist (which also emits on
|
||||
// `changes`; the collector re-reading the now-identical value is a harmless no-op).
|
||||
backing.value = newValue
|
||||
settings.setInt(key, newValue)
|
||||
}
|
||||
|
||||
override fun component1(): Int = value
|
||||
|
||||
override fun component2(): (Int) -> Unit = { newValue -> value = newValue }
|
||||
}
|
||||
|
||||
/**
|
||||
* A write-through, reactive binding to one number-valued setting - the [rememberStringSetting]
|
||||
* counterpart for numeric keys, with the same auto-save and external-change semantics.
|
||||
*
|
||||
* @param String key The dotted settings key (e.g. "viewport.zoomStepPercent").
|
||||
* @param Double default The value used when the key is absent (rarely hit; defaultSettings.json seeds most).
|
||||
* @return MutableState A state whose getter reads the merged value and whose setter persists to the user layer.
|
||||
*/
|
||||
@Composable
|
||||
fun rememberDoubleSetting(key: String, default: Double): MutableState<Double> {
|
||||
val settings = LocalSettings.current
|
||||
val backing = remember(settings, key) { mutableStateOf(settings.getDouble(key) ?: default) }
|
||||
// Re-read when this key is written from anywhere, so a value changed by another control or command
|
||||
// (not just this binding's own setter) reflects here too.
|
||||
LaunchedEffect(settings, key) {
|
||||
settings.changes.collect { changedKey ->
|
||||
if (changedKey == key) {
|
||||
backing.value = settings.getDouble(key) ?: default
|
||||
}
|
||||
}
|
||||
}
|
||||
return remember(settings, key, backing) { WriteThroughDoubleSettingState(settings, key, backing) }
|
||||
}
|
||||
|
||||
/**
|
||||
* The [MutableState] returned by [rememberDoubleSetting]: the numeric twin of
|
||||
* [WriteThroughSettingState], persisting through [Settings.setDouble].
|
||||
*
|
||||
* @property Settings settings The settings instance the write persists into.
|
||||
* @property String key The dotted key being bound.
|
||||
* @property MutableState backing The local state mirroring the merged value.
|
||||
*/
|
||||
private class WriteThroughDoubleSettingState(
|
||||
private val settings: Settings,
|
||||
private val key: String,
|
||||
private val backing: MutableState<Double>,
|
||||
) : MutableState<Double> {
|
||||
override var value: Double
|
||||
get() = backing.value
|
||||
set(newValue) {
|
||||
// Update the local mirror first so the read is immediate, then persist (which also emits on
|
||||
// `changes`; the collector re-reading the now-identical value is a harmless no-op).
|
||||
backing.value = newValue
|
||||
settings.setDouble(key, newValue)
|
||||
}
|
||||
|
||||
override fun component1(): Double = value
|
||||
|
||||
override fun component2(): (Double) -> Unit = { newValue -> value = newValue }
|
||||
}
|
||||
|
||||
/**
|
||||
* A write-through, reactive binding to one boolean-valued setting - the [rememberStringSetting]
|
||||
* counterpart for flag keys, with the same auto-save and external-change semantics.
|
||||
*
|
||||
* @param String key The dotted settings key (e.g. "viewport.rendering.supersample").
|
||||
* @param Boolean default The value used when the key is absent (rarely hit; defaultSettings.json seeds most).
|
||||
* @return MutableState A state whose getter reads the merged value and whose setter persists to the user layer.
|
||||
*/
|
||||
@Composable
|
||||
fun rememberBooleanSetting(key: String, default: Boolean): MutableState<Boolean> {
|
||||
val settings = LocalSettings.current
|
||||
val backing = remember(settings, key) { mutableStateOf(settings.getBoolean(key) ?: default) }
|
||||
// Re-read when this key is written from anywhere, so a value changed by another control or command
|
||||
// (not just this binding's own setter) reflects here too.
|
||||
LaunchedEffect(settings, key) {
|
||||
settings.changes.collect { changedKey ->
|
||||
if (changedKey == key) {
|
||||
backing.value = settings.getBoolean(key) ?: default
|
||||
}
|
||||
}
|
||||
}
|
||||
return remember(settings, key, backing) { WriteThroughBooleanSettingState(settings, key, backing) }
|
||||
}
|
||||
|
||||
/**
|
||||
* The [MutableState] returned by [rememberBooleanSetting]: the flag twin of
|
||||
* [WriteThroughSettingState], persisting through [Settings.setBoolean].
|
||||
*
|
||||
* @property Settings settings The settings instance the write persists into.
|
||||
* @property String key The dotted key being bound.
|
||||
* @property MutableState backing The local state mirroring the merged value.
|
||||
*/
|
||||
private class WriteThroughBooleanSettingState(
|
||||
private val settings: Settings,
|
||||
private val key: String,
|
||||
private val backing: MutableState<Boolean>,
|
||||
) : MutableState<Boolean> {
|
||||
override var value: Boolean
|
||||
get() = backing.value
|
||||
set(newValue) {
|
||||
// Update the local mirror first so the read is immediate, then persist (which also emits on
|
||||
// `changes`; the collector re-reading the now-identical value is a harmless no-op).
|
||||
backing.value = newValue
|
||||
settings.setBoolean(key, newValue)
|
||||
}
|
||||
|
||||
override fun component1(): Boolean = value
|
||||
|
||||
override fun component2(): (Boolean) -> Unit = { newValue -> value = newValue }
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package org.umamo.ui.action
|
||||
|
||||
/**
|
||||
* Renders [chord] as a human accelerator hint for a menu row (e.g. "Ctrl+Shift+P", "⌘O"). The primary
|
||||
* modifier resolves per platform via [primaryModifierLabel] (⌘ on macOS, Ctrl elsewhere); the rest is
|
||||
* pure and position-based.
|
||||
*
|
||||
* chord をメニュー行のアクセラレータ表記に整形する。主修飾キーはプラットフォーム依存で解決する。
|
||||
*
|
||||
* @param KeyChord chord The chord to format.
|
||||
* @return String The display hint.
|
||||
*/
|
||||
fun formatAccelerator(chord: KeyChord): String = formatAccelerator(chord, primaryModifierLabel())
|
||||
|
||||
/**
|
||||
* The pure core of [formatAccelerator]: assembles the modifier labels (primary, Alt, Shift) and the key
|
||||
* glyph into a "+"-joined hint, taking the platform-specific [primaryLabel] as a parameter so it can be
|
||||
* unit-tested deterministically (the public overload supplies the host's label). Modifiers are ordered
|
||||
* primary, Alt, Shift to match the common platform convention.
|
||||
*
|
||||
* formatAccelerator の純粋核。主修飾ラベルを引数で受け取り、決定的にテストできるようにする。
|
||||
*
|
||||
* @param KeyChord chord The chord to format.
|
||||
* @param String primaryLabel The platform label for the primary modifier ("Ctrl" or "⌘").
|
||||
* @return String The display hint.
|
||||
*/
|
||||
internal fun formatAccelerator(chord: KeyChord, primaryLabel: String): String {
|
||||
val parts =
|
||||
buildList {
|
||||
if (chord.primaryModifier) {
|
||||
add(primaryLabel)
|
||||
}
|
||||
if (chord.alt) {
|
||||
add("Alt")
|
||||
}
|
||||
if (chord.shift) {
|
||||
add("Shift")
|
||||
}
|
||||
add(keyGlyph(chord.keyName))
|
||||
}
|
||||
return parts.joinToString(separator = "+")
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps a position-based key token to its display glyph: "KeyO" to "O", "Digit0" to "0", and the few
|
||||
* named keys to short symbols. An unrecognized token falls back to itself so a newly bound key still
|
||||
* shows something readable rather than vanishing.
|
||||
*
|
||||
* 位置ベースのキートークンを表示用の字形に変換する。未知のトークンはそのまま返す。
|
||||
*
|
||||
* @param String keyName The position-based key token (e.g. "KeyO").
|
||||
* @return String The display glyph.
|
||||
*/
|
||||
internal fun keyGlyph(keyName: String): String =
|
||||
when (keyName) {
|
||||
"Space" -> "Space"
|
||||
"Escape" -> "Esc"
|
||||
"Equals" -> "="
|
||||
"Minus" -> "−"
|
||||
"PageUp" -> "Page Up"
|
||||
"PageDown" -> "Page Down"
|
||||
"NumpadAdd" -> "Num +"
|
||||
"NumpadSubtract" -> "Num −"
|
||||
"NumpadMultiply" -> "Num *"
|
||||
"NumpadDivide" -> "Num /"
|
||||
"NumpadDecimal" -> "Num ."
|
||||
"NumpadEnter" -> "Num Enter"
|
||||
else ->
|
||||
when {
|
||||
keyName.startsWith("Key") -> keyName.removePrefix("Key")
|
||||
keyName.startsWith("Digit") -> keyName.removePrefix("Digit")
|
||||
// The remaining numpad tokens are the digits: "Numpad7" reads as "Num 7".
|
||||
keyName.startsWith("Numpad") -> "Num " + keyName.removePrefix("Numpad")
|
||||
else -> keyName
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The platform's label for the primary accelerator modifier: "⌘" on macOS, "Ctrl" elsewhere. This is
|
||||
* the one platform-dependent piece of accelerator formatting (the key glyph and modifier order are
|
||||
* shared). Localizing the modifier labels is a deferred follow-up.
|
||||
*
|
||||
* 主修飾キーのプラットフォーム別ラベル。macOS は "⌘"、それ以外は "Ctrl"。
|
||||
*
|
||||
* @return String The primary modifier label.
|
||||
*/
|
||||
expect fun primaryModifierLabel(): String
|
||||
@@ -0,0 +1,67 @@
|
||||
package org.umamo.ui.action
|
||||
|
||||
import org.jetbrains.compose.resources.StringResource
|
||||
|
||||
/**
|
||||
* Receives a command invocation. A `fun interface` (Kotlin SAM) so call sites can pass a lambda -
|
||||
* `CommandHandler { argument -> … }` - instead of an anonymous object.
|
||||
*
|
||||
* コマンド実行を受け取る関数型インターフェース。ラムダで渡せる。
|
||||
*/
|
||||
fun interface CommandHandler {
|
||||
/**
|
||||
* Runs the command.
|
||||
*
|
||||
* @param Any? argument Optional context the caller passes (e.g. a target area id); null for nullary commands.
|
||||
*/
|
||||
fun run(argument: Any?)
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports whether a command currently applies - the context filter behind the command palette (an
|
||||
* Edit-mode select-mode command is hidden in Object mode) and the dispatch guard in
|
||||
* [CommandRegistry.invoke]. A `fun interface` so registration sites pass a lambda closing over live
|
||||
* session state, evaluated fresh at each query rather than captured once.
|
||||
*
|
||||
* コマンドが現在のコンテキストで有効かを返す。パレットの絞り込みとディスパッチのガードに使う。
|
||||
*/
|
||||
fun interface CommandAvailability {
|
||||
/**
|
||||
* Reports whether the command currently applies.
|
||||
*
|
||||
* @return Boolean True when the command may be shown and invoked.
|
||||
*/
|
||||
fun isAvailable(): Boolean
|
||||
|
||||
companion object {
|
||||
/** The default availability: always applicable (context-free commands like palette.toggle). */
|
||||
val Always: CommandAvailability = CommandAvailability { true }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A named, invokable editor operation - the atom the action registry dispatches. Every operation
|
||||
* (split an area, open a file, fit the view) is one of these, addressed by a stable dotted [id]
|
||||
* ("area.split.leftRight", "file.open"). Menus, the area header, the command palette, and key
|
||||
* bindings all resolve to a Command and run its [handler]; nothing hardcodes a handler, so rebinding
|
||||
* a key or relabelling a menu changes one place.
|
||||
*
|
||||
* @property String id The stable dotted identifier used to look the command up and to bind keys to it.
|
||||
* @property StringResource? title The localized menu/palette label, or null for commands never shown in UI (e.g. test-only).
|
||||
* @property CommandAvailability availability Whether the command currently applies (palette filter +
|
||||
* dispatch guard); defaults to always.
|
||||
* @property CommandSpaces spaces The editor spaces the command belongs to (palette filter + status bar
|
||||
* suggestion, never a dispatch guard); defaults to everywhere.
|
||||
* @property CommandHint? hint What the status bar suggests the command under and when, or null for a
|
||||
* command it never suggests. A hinted command's [availability] must depend on the document and the
|
||||
* mode alone - see [CommandHint] for why.
|
||||
* @property CommandHandler handler The work to perform when invoked.
|
||||
*/
|
||||
class Command(
|
||||
val id: String,
|
||||
val title: StringResource?,
|
||||
val availability: CommandAvailability = CommandAvailability.Always,
|
||||
val spaces: CommandSpaces = CommandSpaces.Everywhere,
|
||||
val hint: CommandHint? = null,
|
||||
val handler: CommandHandler,
|
||||
)
|
||||
@@ -0,0 +1,25 @@
|
||||
package org.umamo.ui.action
|
||||
|
||||
import org.jetbrains.compose.resources.StringResource
|
||||
|
||||
/**
|
||||
* What the status bar suggests a [Command] under, and when.
|
||||
*
|
||||
* A command is suggested when its own [Command.availability] and [suggestedWhen] both hold.
|
||||
* [suggestedWhen] narrows the SUGGESTION alone: dispatch and the command palette never read it, so a
|
||||
* command can run in a mode the bar does not advertise it in - Tab toggles Edit mode from either side,
|
||||
* and is worth suggesting only from Object mode.
|
||||
*
|
||||
* The status bar recomputes its suggestions when the registered table (and so the document), the editor
|
||||
* mode, the hovered space, or the keymap changes. Both predicates of a hinted command must therefore
|
||||
* depend on the document and the mode alone, or the suggestion goes stale.
|
||||
*
|
||||
* @property StringResource label The short label the command is suggested under ("Grab", where the title
|
||||
* reads "Grab Vertices"). Commands sharing one label are suggested as one entry ("1/2/3 Select Mode").
|
||||
* @property CommandAvailability suggestedWhen Whether the command is worth suggesting right now, on top
|
||||
* of being available; defaults to always.
|
||||
*/
|
||||
class CommandHint(
|
||||
val label: StringResource,
|
||||
val suggestedWhen: CommandAvailability = CommandAvailability.Always,
|
||||
)
|
||||
@@ -0,0 +1,211 @@
|
||||
package org.umamo.ui.action
|
||||
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.gestures.detectTapGestures
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.itemsIndexed
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
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
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.input.key.Key
|
||||
import androidx.compose.ui.input.key.KeyEventType
|
||||
import androidx.compose.ui.input.key.key
|
||||
import androidx.compose.ui.input.key.onPreviewKeyEvent
|
||||
import androidx.compose.ui.input.key.type
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.unit.dp
|
||||
import org.jetbrains.compose.resources.stringResource
|
||||
import org.umamo.ui.kit.Surface
|
||||
import org.umamo.ui.kit.Text
|
||||
import org.umamo.ui.kit.TextField
|
||||
import org.umamo.ui.resources.Res
|
||||
import org.umamo.ui.resources.search_hint
|
||||
import org.umamo.ui.theme.LocalUmamoColors
|
||||
import org.umamo.ui.theme.LocalUmamoShapes
|
||||
import org.umamo.ui.theme.LocalUmamoTypography
|
||||
|
||||
/**
|
||||
* The searchable command overlay: a scrim over the shell with a search field and a filtered list of the
|
||||
* registered [Command]s, each invokable by click or by keyboard. A discoverability surface that falls
|
||||
* almost free out of the registry - the caller passes the already-filtered, user-facing commands
|
||||
* (title != null) in registration order.
|
||||
*
|
||||
* It is keyboard-first (Blender-like): the search field autofocuses on open, typing narrows the list
|
||||
* (ranked by match quality; a blank query keeps registration order), Up/Down move a highlighted
|
||||
* selection, Enter invokes it, and Escape (or a scrim click) dismisses. The
|
||||
* shell yields every non-Escape key to this overlay while it is open, so the field and the navigation keys
|
||||
* receive input; the bound accelerator for each command is shown on the right via the active [Keymap].
|
||||
*
|
||||
* 検索可能なコマンドパレット。検索欄は自動でフォーカスされ、入力で絞り込み、上下で選択、Enter で実行、Esc で閉じる。
|
||||
*
|
||||
* @param List commands The commands to list (already filtered to titled, user-facing ones; registry order).
|
||||
* @param Function onDismiss Called to close the palette without invoking.
|
||||
* @param Function onInvoke Called with the chosen command.
|
||||
*/
|
||||
@Composable
|
||||
fun CommandPalette(commands: List<Command>, onDismiss: () -> Unit, onInvoke: (Command) -> Unit) {
|
||||
val colors = LocalUmamoColors.current
|
||||
val typography = LocalUmamoTypography.current
|
||||
val keymap = LocalKeymap.current
|
||||
|
||||
var query by remember { mutableStateOf("") }
|
||||
// The highlighted row, driven by Up/Down and Enter. Clamped at read (filtering can shrink the list
|
||||
// out from under it), and reset to the top whenever the query changes the result set (the effect below).
|
||||
var selectedIndex by remember { mutableStateOf(0) }
|
||||
val searchFocus = remember { FocusRequester() }
|
||||
val listState = rememberLazyListState()
|
||||
|
||||
// Labels need stringResource (a composable), so resolve them here; filtering is then plain Kotlin. The
|
||||
// list is small (~a dozen commands) so resolving every label each recomposition is cheap.
|
||||
val labeled =
|
||||
commands.map { command ->
|
||||
command to (command.title?.let { title -> stringResource(title) } ?: command.id)
|
||||
}
|
||||
val filtered =
|
||||
if (query.isBlank()) {
|
||||
labeled
|
||||
} else {
|
||||
// Ranked match over the visible label or the dotted id ("view.zoom" works directly): a label
|
||||
// prefix beats a word start beats a substring beats an id-only hit - see CommandSearch.
|
||||
rankCommandMatches(labeled, query, labelOf = { entry -> entry.second }, idOf = { entry -> entry.first.id })
|
||||
}
|
||||
val safeIndex = selectedIndex.coerceIn(0, maxOf(0, filtered.size - 1))
|
||||
|
||||
// Reset the highlight to the top result whenever the query (and thus the filtered list) changes.
|
||||
LaunchedEffect(query) {
|
||||
selectedIndex = 0
|
||||
}
|
||||
// Autofocus the search field on open. The palette is composed fresh each time it opens, so Unit keys
|
||||
// the effect to that single open.
|
||||
LaunchedEffect(Unit) {
|
||||
searchFocus.requestFocus()
|
||||
}
|
||||
// Keep the highlighted row scrolled into view as Up/Down move it.
|
||||
LaunchedEffect(safeIndex) {
|
||||
if (filtered.isNotEmpty()) {
|
||||
listState.scrollToItem(safeIndex)
|
||||
}
|
||||
}
|
||||
|
||||
Box(
|
||||
// Dismiss on an outside pointer tap only - a tap gesture, not a clickable. A keyboard-activatable
|
||||
// clickable scrim would let Space (or Enter) typed in the search field bubble up to it and fire
|
||||
// onDismiss, closing the palette mid-search; keyboard dismissal stays Escape (handled by the card's
|
||||
// onPreviewKeyEvent and the shell).
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.pointerInput(Unit) { detectTapGestures { onDismiss() } },
|
||||
contentAlignment = Alignment.TopCenter,
|
||||
) {
|
||||
Surface(
|
||||
modifier =
|
||||
Modifier.padding(top = 80.dp).width(480.dp).clickable(enabled = false, onClick = {})
|
||||
// onPreviewKeyEvent on this ancestor sees keys before the focused search field, so the
|
||||
// navigation keys drive the list while ordinary typing falls through to the field.
|
||||
.onPreviewKeyEvent { event ->
|
||||
if (event.type != KeyEventType.KeyDown) {
|
||||
false
|
||||
} else {
|
||||
when (event.key) {
|
||||
Key.DirectionDown -> {
|
||||
if (filtered.isNotEmpty()) {
|
||||
selectedIndex = (safeIndex + 1) % filtered.size
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
Key.DirectionUp -> {
|
||||
if (filtered.isNotEmpty()) {
|
||||
selectedIndex = (safeIndex - 1 + filtered.size) % filtered.size
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
Key.Enter, Key.NumPadEnter -> {
|
||||
filtered.getOrNull(safeIndex)?.let { (command, _) -> onInvoke(command) }
|
||||
true
|
||||
}
|
||||
// Belt-and-suspenders: the shell already consumes Escape to close the palette, but
|
||||
// handle it here too so the overlay stands alone if reused.
|
||||
Key.Escape -> {
|
||||
onDismiss()
|
||||
true
|
||||
}
|
||||
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
},
|
||||
color = colors.menuBackground,
|
||||
shape = LocalUmamoShapes.current.medium,
|
||||
border = BorderStroke(1.dp, colors.panelBorder),
|
||||
shadowElevation = 8.dp,
|
||||
) {
|
||||
Column(modifier = Modifier.fillMaxWidth()) {
|
||||
TextField(
|
||||
value = query,
|
||||
onValueChange = { newQuery -> query = newQuery },
|
||||
modifier = Modifier.fillMaxWidth().focusRequester(searchFocus).padding(8.dp),
|
||||
placeholder = stringResource(Res.string.search_hint),
|
||||
)
|
||||
LazyColumn(state = listState, modifier = Modifier.fillMaxWidth().heightIn(max = 360.dp)) {
|
||||
itemsIndexed(filtered) { index, entry ->
|
||||
val command = entry.first
|
||||
val label = entry.second
|
||||
val isSelected = index == safeIndex
|
||||
Row(
|
||||
modifier =
|
||||
Modifier.fillMaxWidth()
|
||||
.padding(horizontal = 4.dp, vertical = 4.dp)
|
||||
.background(
|
||||
when {
|
||||
isSelected -> colors.selection
|
||||
else -> Color.Transparent
|
||||
},
|
||||
shape = LocalUmamoShapes.current.small,
|
||||
)
|
||||
.clickable { onInvoke(command) }
|
||||
.padding(horizontal = 4.dp, vertical = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
text = label,
|
||||
style = typography.bodyMedium,
|
||||
color = if (isSelected) colors.selectionText else colors.text,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
// The command's bound accelerator (canonical chord), dimmed; omitted when unbound.
|
||||
keymap.chordFor(command.id)?.let { chord ->
|
||||
Text(
|
||||
text = formatAccelerator(chord),
|
||||
style = typography.bodySmall,
|
||||
color = if (isSelected) colors.selectionText else colors.textMuted,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package org.umamo.ui.action
|
||||
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.staticCompositionLocalOf
|
||||
|
||||
/**
|
||||
* The central table of named [Command]s and the single dispatch point for invoking them. Menus, the
|
||||
* area header, the command palette, and the keymap all go through here, so an operation has exactly
|
||||
* one implementation regardless of how it was triggered.
|
||||
*
|
||||
* Insertion order is preserved (a LinkedHashMap) so the command palette can list commands in a
|
||||
* stable, registration order rather than a hash-shuffled one.
|
||||
*/
|
||||
class CommandRegistry {
|
||||
private val commandsById = LinkedHashMap<String, Command>()
|
||||
|
||||
/**
|
||||
* Counts every change to the table, as snapshot state - what a composable listing [all] reads so that
|
||||
* it recomposes when the table changes.
|
||||
*
|
||||
* The table itself is a plain map, and the document-scoped groups re-register from effects that run
|
||||
* AFTER the composition a document swap caused. Without this, a listing recomposed by that swap
|
||||
* reads the outgoing document's commands - whose availability still answers for the old session - and
|
||||
* nothing recomposes it again once the new ones land.
|
||||
*/
|
||||
var revision: Int by mutableIntStateOf(0)
|
||||
private set
|
||||
|
||||
/**
|
||||
* Registers (or replaces) a command under its [Command.id].
|
||||
*
|
||||
* @param Command command The command to register.
|
||||
*/
|
||||
fun register(command: Command) {
|
||||
commandsById[command.id] = command
|
||||
revision++
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a command by id, if present.
|
||||
*
|
||||
* @param String id The command id to remove.
|
||||
*/
|
||||
fun unregister(id: String) {
|
||||
if (commandsById.remove(id) != null) {
|
||||
revision++
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Looks up a command by id without invoking it (e.g. to read its title for a menu).
|
||||
*
|
||||
* @param String id The command id.
|
||||
* @return Command? The command, or null if none is registered.
|
||||
*/
|
||||
operator fun get(id: String): Command? = commandsById[id]
|
||||
|
||||
/**
|
||||
* Every registered command in registration order - the source for the command palette listing.
|
||||
*
|
||||
* @return List the registered commands.
|
||||
*/
|
||||
fun all(): List<Command> = commandsById.values.toList()
|
||||
|
||||
/**
|
||||
* Invokes the command bound to [id], passing [argument] to its handler.
|
||||
*
|
||||
* Returns whether a command was found AND currently applicable, rather than throwing, so a stray
|
||||
* key chord or a menu item whose command was unregistered fails quietly instead of crashing the
|
||||
* editor - and a chord bound to a command outside its context (an Edit-mode operator pressed in
|
||||
* Object mode) falls through unconsumed rather than running a guaranteed no-op.
|
||||
*
|
||||
* @param String id The command id to invoke.
|
||||
* @param Any? argument Optional context forwarded to the handler (default null).
|
||||
* @return Boolean true if a command was found, applicable, and run; false otherwise.
|
||||
*/
|
||||
fun invoke(id: String, argument: Any? = null): Boolean {
|
||||
val command = commandsById[id] ?: return false
|
||||
if (!command.availability.isAvailable()) {
|
||||
return false
|
||||
}
|
||||
command.handler.run(argument)
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The active [CommandRegistry] for the composition. `static` because the registry instance is stable
|
||||
* for the app's lifetime (commands are registered into it, not swapped); descendants read
|
||||
* `LocalCommands.current` to dispatch. The default errors loudly so a missing provider is caught at
|
||||
* the first dispatch rather than silently no-op'ing.
|
||||
*
|
||||
* コンポジション内で有効なコマンドレジストリ。アプリ生存期間中インスタンスは不変なので static。
|
||||
*/
|
||||
val LocalCommands =
|
||||
staticCompositionLocalOf<CommandRegistry> {
|
||||
error("LocalCommands not provided — wrap the editor in a CommandRegistry provider")
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package org.umamo.ui.action
|
||||
|
||||
/**
|
||||
* Scores how well one command matches a palette query; lower is better, null is no match.
|
||||
*
|
||||
* The tiers keep the intuitive result first: a query that starts the visible label ("ac" ->
|
||||
* "Actual Size") outranks a label whose later word starts with it ("Zoom In" for "in"), which
|
||||
* outranks a mere substring hit ("Workspace" for "ac"), which outranks a match found only in the
|
||||
* dotted command id. Matching is case-insensitive.
|
||||
*
|
||||
* @param String label The command's resolved, user-visible label.
|
||||
* @param String commandId The command's dotted id (e.g. "view.zoomIn").
|
||||
* @param String query The typed query (non-blank).
|
||||
* @return Int? The match tier (0 label prefix, 1 label word start, 2 label substring, 3 id
|
||||
* substring), or null when the command matches nowhere.
|
||||
*/
|
||||
internal fun commandMatchScore(label: String, commandId: String, query: String): Int? =
|
||||
when {
|
||||
label.startsWith(query, ignoreCase = true) -> 0
|
||||
label.split(' ').any { word -> word.startsWith(query, ignoreCase = true) } -> 1
|
||||
label.contains(query, ignoreCase = true) -> 2
|
||||
commandId.contains(query, ignoreCase = true) -> 3
|
||||
else -> null
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters and ranks palette entries for a query: non-matches drop, the rest sort by match tier
|
||||
* (see [commandMatchScore]) with alphabetical label order breaking ties.
|
||||
*
|
||||
* @param List entries The candidate entries, in registry order.
|
||||
* @param String query The typed query (non-blank).
|
||||
* @param Function labelOf Extracts an entry's user-visible label.
|
||||
* @param Function idOf Extracts an entry's dotted command id.
|
||||
* @return List The matching entries, best first.
|
||||
*/
|
||||
internal fun <TEntry> rankCommandMatches(
|
||||
entries: List<TEntry>,
|
||||
query: String,
|
||||
labelOf: (TEntry) -> String,
|
||||
idOf: (TEntry) -> String,
|
||||
): List<TEntry> =
|
||||
entries
|
||||
.mapNotNull { entry ->
|
||||
commandMatchScore(labelOf(entry), idOf(entry), query)?.let { score -> entry to score }
|
||||
}
|
||||
.sortedWith(compareBy({ scored -> scored.second }, { scored -> labelOf(scored.first).lowercase() }))
|
||||
.map { scored -> scored.first }
|
||||
@@ -0,0 +1,96 @@
|
||||
package org.umamo.ui.action
|
||||
|
||||
import org.umamo.ui.workspace.SpaceKind
|
||||
|
||||
/**
|
||||
* The editor spaces a [Command] belongs to - the "where" beside [CommandAvailability]'s "when".
|
||||
*
|
||||
* A declaration about VISIBILITY and SUGGESTION only: the command palette hides a command outside its
|
||||
* spaces and the status bar suggests it only inside them. Dispatch never reads it -
|
||||
* [CommandRegistry.invoke] and the keymap run a command wherever the pointer is, and its handler goes on
|
||||
* deciding for itself what a press means there.
|
||||
*
|
||||
* The set is read off what the handler's routing actually does, never narrower: a handler that reaches
|
||||
* back to a surface the pointer has left (the lone open keyform sheet, the last work surface touched)
|
||||
* works from anywhere, and so it is [Everywhere]. Narrowing a scope past its handler hides a command that
|
||||
* would have run.
|
||||
*/
|
||||
sealed interface CommandSpaces {
|
||||
/**
|
||||
* Reports whether a command with these spaces belongs to a surface of [kind].
|
||||
*
|
||||
* @param SpaceKind? kind The space the pointer last touched, or null before it touched any.
|
||||
* @return Boolean True when the command is shown and suggested there.
|
||||
*/
|
||||
fun appliesIn(kind: SpaceKind?): Boolean
|
||||
|
||||
/** Belongs to every space, and to no space at all - the scope of a command that routes by nothing. */
|
||||
data object Everywhere : CommandSpaces {
|
||||
/**
|
||||
* Always applies.
|
||||
*
|
||||
* @param SpaceKind? kind The space the pointer last touched, or null before it touched any.
|
||||
* @return Boolean Always true.
|
||||
*/
|
||||
override fun appliesIn(kind: SpaceKind?): Boolean = true
|
||||
}
|
||||
|
||||
/**
|
||||
* Belongs to the listed spaces alone.
|
||||
*
|
||||
* @property Set<SpaceKind> kinds The spaces the command acts in; never empty, so a command that is
|
||||
* allowed nowhere cannot be declared.
|
||||
*/
|
||||
data class Only(val kinds: Set<SpaceKind>) : CommandSpaces {
|
||||
init {
|
||||
require(kinds.isNotEmpty()) { "A command scoped to no space could never be shown; use Everywhere or name a space" }
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies when [kind] is one of [kinds]. A null kind matches nothing: the pointer has touched no
|
||||
* surface, so the handler would resolve no area to act in either.
|
||||
*
|
||||
* @param SpaceKind? kind The space the pointer last touched, or null before it touched any.
|
||||
* @return Boolean True when [kind] is listed.
|
||||
*/
|
||||
override fun appliesIn(kind: SpaceKind?): Boolean = kind != null && kind in kinds
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** The kinds behind [WorkSurfaces], held once so every set built on the work surfaces follows it. */
|
||||
private val workSurfaceKinds = setOf(SpaceKind.Viewport2D, SpaceKind.UvEditor)
|
||||
|
||||
/** The 2D viewport alone: world-space operations whose overlay is the only collector. */
|
||||
val Viewport2D: CommandSpaces = Only(setOf(SpaceKind.Viewport2D))
|
||||
|
||||
/** The UV editor alone: texture-coordinate operations. */
|
||||
val UvEditor: CommandSpaces = Only(setOf(SpaceKind.UvEditor))
|
||||
|
||||
/**
|
||||
* The two work surfaces, the 2D viewport and the UV editor: the modal transforms, the select
|
||||
* tools, and the camera commands. A new camera-bearing or transform-hosting space joins here.
|
||||
*/
|
||||
val WorkSurfaces: CommandSpaces = Only(workSurfaceKinds)
|
||||
|
||||
/**
|
||||
* The work surfaces plus the keyform sheet: the commands that mean one thing over a work surface
|
||||
* and the sheet's own version of it over a sheet (Frame All, Box Select). Derived from the work
|
||||
* surfaces, so a space that joins them is covered here too.
|
||||
*/
|
||||
val WorkSurfacesAndSheet: CommandSpaces = Only(workSurfaceKinds + SpaceKind.KeyformSheet)
|
||||
|
||||
/**
|
||||
* The surfaces showing keyable properties, the keyform sheet's lanes and the Properties rows: the
|
||||
* insert / delete pair that writes to whichever keyable the pointer is over.
|
||||
*/
|
||||
val KeyableSurfaces: CommandSpaces = Only(setOf(SpaceKind.KeyformSheet, SpaceKind.Properties))
|
||||
|
||||
/**
|
||||
* Builds the scope of a command whose spaces match none of the named sets.
|
||||
*
|
||||
* @param SpaceKind kinds The spaces the command acts in; at least one.
|
||||
* @return CommandSpaces The scope over exactly those spaces.
|
||||
*/
|
||||
fun of(vararg kinds: SpaceKind): CommandSpaces = Only(kinds.toSet())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package org.umamo.ui.action
|
||||
|
||||
import org.umamo.ui.workspace.SpaceKind
|
||||
|
||||
/**
|
||||
* Reports whether this command is offered over a surface of [kind]: it belongs to that space and
|
||||
* currently applies. The one rule the command palette and the status bar share, so the two cannot
|
||||
* come to disagree about what "offered here" means.
|
||||
*
|
||||
* @param SpaceKind? kind The space the pointer last touched, or null before it touched any.
|
||||
* @return Boolean True when the command is listed and suggested there.
|
||||
*/
|
||||
internal fun Command.isOfferedIn(kind: SpaceKind?): Boolean = spaces.appliesIn(kind) && availability.isAvailable()
|
||||
|
||||
/**
|
||||
* The commands the palette offers over a surface of [hoveredKind]: titled, currently available, and
|
||||
* belonging to that space.
|
||||
*
|
||||
* A null title marks a command as not a palette entry at all (internal toggles like palette.toggle and
|
||||
* area.dragCancel, and the argument-only document commands); an unavailable command is hidden rather
|
||||
* than dimmed, and so is one outside its spaces - the palette lists what would do something from where
|
||||
* the pointer is, in the current mode. The hidden commands stay discoverable in the keybindings editor,
|
||||
* which lists the whole table.
|
||||
*
|
||||
* @param List<Command> commands The registered commands, in registration order.
|
||||
* @param SpaceKind? hoveredKind The space the pointer last touched, or null before it touched any.
|
||||
* @return List<Command> The commands to list, in the order given.
|
||||
*/
|
||||
internal fun paletteCommands(commands: List<Command>, hoveredKind: SpaceKind?): List<Command> =
|
||||
commands.filter { command -> command.title != null && command.isOfferedIn(hoveredKind) }
|
||||
@@ -0,0 +1,124 @@
|
||||
package org.umamo.ui.action
|
||||
|
||||
import androidx.compose.ui.input.key.Key
|
||||
|
||||
/**
|
||||
* Normalizes a key event's [Key] before name lookup. Desktop Compose builds its located numpad
|
||||
* constants from different AWT codes than AWT actually delivers (Key.NumPadDot is Key(VK_PERIOD,
|
||||
* NUMPAD) while the physical key arrives as VK_DECIMAL), so without normalization the numpad decimal
|
||||
* - and with it the NumpadDecimal binding - can never match. The desktop actual remaps those codes
|
||||
* (and defensively re-locates the numpad-only ones); Android keys carry no location and match their
|
||||
* constants directly, so its actual is the identity.
|
||||
*
|
||||
* @param Key key The key from a key event.
|
||||
* @return Key The key to match the named constants against.
|
||||
*/
|
||||
internal expect fun normalizeKeyPosition(key: Key): Key
|
||||
|
||||
/**
|
||||
* Maps a Compose [Key] to the position-based token a [KeyChord] stores ("KeyP", "Digit0", "F5", "ArrowUp",
|
||||
* …), or null for a key the keymap does not bind (modifiers, media keys, anything unlisted). This is the
|
||||
* single source of truth shared by the live keyboard dispatch (handleShellKey) and the rebinding editor's
|
||||
* chord capture, so a captured chord and a dispatched chord always agree on a key's name - the tokens here
|
||||
* are exactly the ones a preset spec or a stored override uses.
|
||||
*
|
||||
* Compose の Key を KeyChord が保持する位置ベースのトークンに変換する。入力ディスパッチと再割り当て UI で共有し、
|
||||
* 取り込んだコードと発火するコードのキー名が必ず一致するようにする。
|
||||
*
|
||||
* @param Key key The Compose key from a key event.
|
||||
* @return String? The position-based token, or null if the key is not bindable.
|
||||
*/
|
||||
fun keyName(key: Key): String? =
|
||||
when (normalizeKeyPosition(key)) {
|
||||
Key.A -> "KeyA"
|
||||
Key.B -> "KeyB"
|
||||
Key.C -> "KeyC"
|
||||
Key.D -> "KeyD"
|
||||
Key.E -> "KeyE"
|
||||
Key.F -> "KeyF"
|
||||
Key.G -> "KeyG"
|
||||
Key.H -> "KeyH"
|
||||
Key.I -> "KeyI"
|
||||
Key.J -> "KeyJ"
|
||||
Key.K -> "KeyK"
|
||||
Key.L -> "KeyL"
|
||||
Key.M -> "KeyM"
|
||||
Key.N -> "KeyN"
|
||||
Key.O -> "KeyO"
|
||||
Key.P -> "KeyP"
|
||||
Key.Q -> "KeyQ"
|
||||
Key.R -> "KeyR"
|
||||
Key.S -> "KeyS"
|
||||
Key.T -> "KeyT"
|
||||
Key.U -> "KeyU"
|
||||
Key.V -> "KeyV"
|
||||
Key.W -> "KeyW"
|
||||
Key.X -> "KeyX"
|
||||
Key.Y -> "KeyY"
|
||||
Key.Z -> "KeyZ"
|
||||
Key.Zero -> "Digit0"
|
||||
Key.One -> "Digit1"
|
||||
Key.Two -> "Digit2"
|
||||
Key.Three -> "Digit3"
|
||||
Key.Four -> "Digit4"
|
||||
Key.Five -> "Digit5"
|
||||
Key.Six -> "Digit6"
|
||||
Key.Seven -> "Digit7"
|
||||
Key.Eight -> "Digit8"
|
||||
Key.Nine -> "Digit9"
|
||||
Key.F1 -> "F1"
|
||||
Key.F2 -> "F2"
|
||||
Key.F3 -> "F3"
|
||||
Key.F4 -> "F4"
|
||||
Key.F5 -> "F5"
|
||||
Key.F6 -> "F6"
|
||||
Key.F7 -> "F7"
|
||||
Key.F8 -> "F8"
|
||||
Key.F9 -> "F9"
|
||||
Key.F10 -> "F10"
|
||||
Key.F11 -> "F11"
|
||||
Key.F12 -> "F12"
|
||||
Key.Spacebar -> "Space"
|
||||
Key.Enter -> "Enter"
|
||||
Key.Tab -> "Tab"
|
||||
Key.Escape -> "Escape"
|
||||
Key.Backspace -> "Backspace"
|
||||
Key.Delete -> "Delete"
|
||||
Key.Insert -> "Insert"
|
||||
Key.DirectionUp -> "ArrowUp"
|
||||
Key.DirectionDown -> "ArrowDown"
|
||||
Key.DirectionLeft -> "ArrowLeft"
|
||||
Key.DirectionRight -> "ArrowRight"
|
||||
Key.MoveHome -> "Home"
|
||||
Key.MoveEnd -> "End"
|
||||
Key.PageUp -> "PageUp"
|
||||
Key.PageDown -> "PageDown"
|
||||
Key.Comma -> "Comma"
|
||||
Key.Period -> "Period"
|
||||
Key.Minus -> "Minus"
|
||||
Key.Equals -> "Equals"
|
||||
Key.Semicolon -> "Semicolon"
|
||||
Key.Apostrophe -> "Quote"
|
||||
Key.LeftBracket -> "BracketLeft"
|
||||
Key.RightBracket -> "BracketRight"
|
||||
Key.Backslash -> "Backslash"
|
||||
Key.Slash -> "Slash"
|
||||
Key.Grave -> "Backquote"
|
||||
Key.NumPadAdd -> "NumpadAdd"
|
||||
Key.NumPadSubtract -> "NumpadSubtract"
|
||||
Key.NumPadMultiply -> "NumpadMultiply"
|
||||
Key.NumPadDivide -> "NumpadDivide"
|
||||
Key.NumPadDot -> "NumpadDecimal"
|
||||
Key.NumPadEnter -> "NumpadEnter"
|
||||
Key.NumPad0 -> "Numpad0"
|
||||
Key.NumPad1 -> "Numpad1"
|
||||
Key.NumPad2 -> "Numpad2"
|
||||
Key.NumPad3 -> "Numpad3"
|
||||
Key.NumPad4 -> "Numpad4"
|
||||
Key.NumPad5 -> "Numpad5"
|
||||
Key.NumPad6 -> "Numpad6"
|
||||
Key.NumPad7 -> "Numpad7"
|
||||
Key.NumPad8 -> "Numpad8"
|
||||
Key.NumPad9 -> "Numpad9"
|
||||
else -> null
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
package org.umamo.ui.action
|
||||
|
||||
import androidx.compose.runtime.staticCompositionLocalOf
|
||||
|
||||
/**
|
||||
* One key combination, stored logically rather than as a literal character. [primaryModifier] is the
|
||||
* platform's main accelerator (Cmd on macOS, Ctrl elsewhere) - the intent is stored, not "Ctrl", so a
|
||||
* binding resolves correctly per OS. [keyName] names the physical key by position
|
||||
* ("KeyP", "KeyK"), not the produced character, so a chord survives non-QWERTY layouts.
|
||||
*
|
||||
* @property String keyName The position-based key token (e.g. "KeyP"), layout-independent.
|
||||
* @property Boolean primaryModifier Whether the platform primary accelerator (Cmd/Ctrl) is held.
|
||||
* @property Boolean shift Whether Shift is held.
|
||||
* @property Boolean alt Whether Alt/Option is held.
|
||||
*/
|
||||
data class KeyChord(
|
||||
val keyName: String,
|
||||
val primaryModifier: Boolean = false,
|
||||
val shift: Boolean = false,
|
||||
val alt: Boolean = false,
|
||||
)
|
||||
|
||||
/**
|
||||
* Parses a human-authored chord spec like "primary+shift+KeyP" into a [KeyChord]. Tokens are split on
|
||||
* '+'; the final token is the key, the rest are modifiers ("primary", "shift", "alt"/"option", case
|
||||
* insensitive). This is the on-disk keymap form (settings input.keybinding) and the form preset files
|
||||
* use, so it must be tolerant of case and whitespace but reject a malformed spec (empty key, unknown
|
||||
* modifier) rather than silently mis-binding.
|
||||
*
|
||||
* @param String spec The chord spec, modifiers and key joined by '+'.
|
||||
* @return KeyChord? The parsed chord, or null if the spec is malformed.
|
||||
*/
|
||||
fun parseKeyChord(spec: String): KeyChord? {
|
||||
val tokens = spec.split('+').map { token -> token.trim() }.filter { token -> token.isNotEmpty() }
|
||||
if (tokens.isEmpty()) {
|
||||
return null
|
||||
}
|
||||
val keyName = tokens.last()
|
||||
if (keyName.isEmpty()) {
|
||||
return null
|
||||
}
|
||||
var primaryModifier = false
|
||||
var shift = false
|
||||
var alt = false
|
||||
for (modifierIndex in 0 until tokens.size - 1) {
|
||||
when (tokens[modifierIndex].lowercase()) {
|
||||
"primary", "cmd", "ctrl", "control" -> primaryModifier = true
|
||||
"shift" -> shift = true
|
||||
"alt", "option", "opt" -> alt = true
|
||||
else -> return null
|
||||
}
|
||||
}
|
||||
return KeyChord(keyName, primaryModifier, shift, alt)
|
||||
}
|
||||
|
||||
/**
|
||||
* Serializes a [KeyChord] back to the spec string [parseKeyChord] reads ("primary+shift+KeyP") - the form
|
||||
* stored in settings input.keybinding.overrides. Modifiers are emitted in a fixed order (primary, shift,
|
||||
* alt) so a given chord always round-trips to the same string and the stored override key stays stable;
|
||||
* parseKeyChord itself accepts any order, so this is the inverse of parsing for any chord it produced.
|
||||
*
|
||||
* @param KeyChord chord The chord to serialize.
|
||||
* @return String The spec string.
|
||||
*/
|
||||
fun chordToSpec(chord: KeyChord): String =
|
||||
buildList {
|
||||
if (chord.primaryModifier) {
|
||||
add("primary")
|
||||
}
|
||||
if (chord.shift) {
|
||||
add("shift")
|
||||
}
|
||||
if (chord.alt) {
|
||||
add("alt")
|
||||
}
|
||||
add(chord.keyName)
|
||||
}.joinToString(separator = "+")
|
||||
|
||||
/**
|
||||
* A resolved set of key-chord → command-id bindings, plus the lookup the input layer uses. Built from
|
||||
* a preset spec map; conflicts (two chords on the same command, or a re-bound chord) are resolved
|
||||
* last-write-wins at build time. The keymap holds only ids - it never references [Command] objects -
|
||||
* so it stays decoupled from registration order and from whether a command currently exists.
|
||||
*/
|
||||
class Keymap(private val commandIdByChord: Map<KeyChord, String>) {
|
||||
/**
|
||||
* The command id bound to [chord], or null if the chord is unbound.
|
||||
*
|
||||
* @param KeyChord chord The pressed chord.
|
||||
* @return String? The bound command id, or null.
|
||||
*/
|
||||
fun commandFor(chord: KeyChord): String? = commandIdByChord[chord]
|
||||
|
||||
/**
|
||||
* The first chord bound to [commandId], or null if none is - the reverse of [commandFor], used to
|
||||
* render a menu row's accelerator hint. When several chords map to one command (palette.toggle has
|
||||
* both primary+KeyP and Space) the first in insertion order wins, so a menu shows the canonical
|
||||
* accelerator (primary+KeyP) rather than whichever the map happens to yield first.
|
||||
*
|
||||
* @param String commandId The command id to find an accelerator for.
|
||||
* @return KeyChord? The first bound chord, or null.
|
||||
*/
|
||||
fun chordFor(commandId: String): KeyChord? {
|
||||
// LinkedHashMap iterates in insertion order, so the first match is the canonical binding.
|
||||
for ((chord, boundCommandId) in commandIdByChord) {
|
||||
if (boundCommandId == commandId) {
|
||||
return chord
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* The number of bindings - handy for tests and a future conflict/coverage report.
|
||||
*
|
||||
* @return Int the binding count.
|
||||
*/
|
||||
fun size(): Int = commandIdByChord.size
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* Builds a [Keymap] from a preset's chord-spec → command-id map, parsing each spec via
|
||||
* [parseKeyChord]. A spec that fails to parse is dropped (a malformed preset entry must not
|
||||
* shadow a valid one); callers that need strict validation can compare [size] to the input.
|
||||
*
|
||||
* @param Map specs The preset bindings (chord spec → command id).
|
||||
* @return Keymap the resolved keymap.
|
||||
*/
|
||||
fun fromSpecs(specs: Map<String, String>): Keymap {
|
||||
val resolved = LinkedHashMap<KeyChord, String>()
|
||||
for ((spec, commandId) in specs) {
|
||||
val chord = parseKeyChord(spec) ?: continue
|
||||
resolved[chord] = commandId
|
||||
}
|
||||
return Keymap(resolved)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The ids of the built-in keymap presets, in display order. [keymapPresetSpecs] resolves each to its
|
||||
* bindings; the persisted choice lives in settings input.keybinding.preset and user overrides layer on top.
|
||||
*/
|
||||
val KEYMAP_PRESET_IDS: List<String> = listOf("default", "cubism", "blender")
|
||||
|
||||
/**
|
||||
* The "default" preset: a small, neutral starter set. Bindings are by key position with the logical
|
||||
* primary modifier, so they hold across OSes and layouts.
|
||||
*/
|
||||
private val DEFAULT_KEYMAP_SPECS: Map<String, String> =
|
||||
presetSpecs(
|
||||
"primary+KeyP" to "palette.toggle",
|
||||
"Space" to "palette.toggle",
|
||||
"Escape" to "area.dragCancel",
|
||||
"Tab" to "mode.toggleEdit",
|
||||
"primary+PageUp" to "workspace.prev",
|
||||
"primary+PageDown" to "workspace.next",
|
||||
// The document's own chords: Open, Save, and Save As on the keys every application uses for them.
|
||||
// Import CMO3 has no chord - an import is not an open - and the File menu and the palette reach it.
|
||||
"primary+KeyN" to "file.new",
|
||||
"primary+KeyO" to "file.open",
|
||||
"primary+KeyS" to "file.save",
|
||||
"primary+shift+KeyS" to "file.saveAs",
|
||||
"primary+shift+KeyO" to "file.importArtwork",
|
||||
"primary+KeyZ" to "edit.undo",
|
||||
"primary+shift+KeyZ" to "edit.redo",
|
||||
"F9" to "edit.adjustLastOperation",
|
||||
"KeyP" to "uv.pinPlacement",
|
||||
"alt+KeyP" to "uv.unpinPlacement",
|
||||
"KeyH" to "object.toggleVisibility",
|
||||
"KeyG" to "mesh.grab",
|
||||
"KeyS" to "mesh.scale",
|
||||
"KeyR" to "mesh.rotate",
|
||||
"Digit1" to "mesh.selectMode.vertex",
|
||||
"Digit2" to "mesh.selectMode.edge",
|
||||
"Digit3" to "mesh.selectMode.face",
|
||||
"KeyA" to "select.all",
|
||||
"primary+KeyI" to "select.invert",
|
||||
"KeyI" to "keyform.insert",
|
||||
"alt+KeyI" to "keyform.delete",
|
||||
"Delete" to "keyform.deleteSelectedKeys",
|
||||
"ArrowLeft" to "keyform.nudgeKeyLeft",
|
||||
"ArrowRight" to "keyform.nudgeKeyRight",
|
||||
// Context-aware, Blender's Home semantics: frames the hovered editor (keyform sheet → the keys,
|
||||
// anything else → the viewport).
|
||||
"Home" to "frame.all",
|
||||
"KeyB" to "mesh.boxSelect",
|
||||
"KeyC" to "mesh.circleSelect",
|
||||
"shift+KeyB" to "view.zoomRegion",
|
||||
"NumpadAdd" to "mesh.circleSelect.grow",
|
||||
"NumpadSubtract" to "mesh.circleSelect.shrink",
|
||||
"Period" to "transform.pivotPie",
|
||||
"shift+KeyS" to "snap.pie",
|
||||
"KeyL" to "mesh.selectLinkedAtCursor",
|
||||
"primary+KeyL" to "mesh.selectLinked",
|
||||
"alt+KeyQ" to "edit.switchObjectUnderCursor",
|
||||
"NumpadDecimal" to "view.frameSelected",
|
||||
"shift+KeyD" to "mesh.duplicate",
|
||||
"KeyM" to "mesh.merge",
|
||||
"KeyV" to "mesh.rip",
|
||||
"KeyJ" to "mesh.connect",
|
||||
"KeyK" to "mesh.insertVertex",
|
||||
"shift+KeyV" to "mesh.vertexSlide",
|
||||
"KeyO" to "mesh.proportional.toggle",
|
||||
"alt+KeyO" to "mesh.proportional.connectedToggle",
|
||||
"KeyT" to "view.toggleToolbar",
|
||||
"KeyN" to "view.toggleSidebar",
|
||||
"primary+Comma" to "edit.preferences",
|
||||
"primary+Digit0" to "view.fit",
|
||||
"primary+Digit1" to "view.zoomActualSize",
|
||||
"primary+Equals" to "view.zoomIn",
|
||||
"primary+shift+Equals" to "view.zoomInCoarse",
|
||||
"primary+Minus" to "view.zoomOut",
|
||||
"primary+shift+Minus" to "view.zoomOutCoarse",
|
||||
)
|
||||
|
||||
/**
|
||||
* The "Cubism-like" preset for migrants from the official Cubism Editor. A starting point keyed to Cubism
|
||||
* muscle memory (the command palette on the primary modifier, no bare Space - Cubism reserves Space for
|
||||
* canvas panning); fully rebindable in the keybindings editor.
|
||||
*/
|
||||
private val CUBISM_KEYMAP_SPECS: Map<String, String> =
|
||||
presetSpecs(
|
||||
"primary+KeyP" to "palette.toggle",
|
||||
"Escape" to "area.dragCancel",
|
||||
"primary+PageUp" to "workspace.prev",
|
||||
"primary+PageDown" to "workspace.next",
|
||||
// The document's own chords: Open, Save, and Save As on the keys every application uses for them.
|
||||
// Import CMO3 has no chord - an import is not an open - and the File menu and the palette reach it.
|
||||
"primary+KeyN" to "file.new",
|
||||
"primary+KeyO" to "file.open",
|
||||
"primary+KeyS" to "file.save",
|
||||
"primary+shift+KeyS" to "file.saveAs",
|
||||
"primary+shift+KeyO" to "file.importArtwork",
|
||||
// Undo / redo: Ctrl+Z plus both redo conventions Cubism migrants carry (Ctrl+Shift+Z and Ctrl+Y).
|
||||
"primary+KeyZ" to "edit.undo",
|
||||
"primary+shift+KeyZ" to "edit.redo",
|
||||
"F9" to "edit.adjustLastOperation",
|
||||
"KeyP" to "uv.pinPlacement",
|
||||
"alt+KeyP" to "uv.unpinPlacement",
|
||||
"primary+KeyY" to "edit.redo",
|
||||
"primary+Comma" to "edit.preferences",
|
||||
"primary+Digit0" to "view.fit",
|
||||
// Frame Selected joins the Ctrl+0 fit family (Cubism has no numpad-framing convention).
|
||||
"primary+shift+Digit0" to "view.frameSelected",
|
||||
"primary+Digit1" to "view.zoomActualSize",
|
||||
"primary+Equals" to "view.zoomIn",
|
||||
"primary+shift+Equals" to "view.zoomInCoarse",
|
||||
"primary+Minus" to "view.zoomOut",
|
||||
"primary+shift+Minus" to "view.zoomOutCoarse",
|
||||
)
|
||||
|
||||
/**
|
||||
* The "Blender-like" preset for migrants from Blender (whose editing model Umamo borrows). A starting
|
||||
* point keyed to Blender muscle memory (operator search on F3, Frame All on Home - context-aware per
|
||||
* hovered editor, exactly as in Blender); fully rebindable in the keybindings editor.
|
||||
*/
|
||||
private val BLENDER_KEYMAP_SPECS: Map<String, String> =
|
||||
presetSpecs(
|
||||
"F3" to "palette.toggle",
|
||||
"Escape" to "area.dragCancel",
|
||||
"Tab" to "mode.toggleEdit",
|
||||
"primary+PageUp" to "workspace.prev",
|
||||
"primary+PageDown" to "workspace.next",
|
||||
// The document's own chords: Open, Save, and Save As on the keys every application uses for them.
|
||||
// Import CMO3 has no chord - an import is not an open - and the File menu and the palette reach it.
|
||||
"primary+KeyN" to "file.new",
|
||||
"primary+KeyO" to "file.open",
|
||||
"primary+KeyS" to "file.save",
|
||||
"primary+shift+KeyS" to "file.saveAs",
|
||||
"primary+shift+KeyO" to "file.importArtwork",
|
||||
"primary+KeyZ" to "edit.undo",
|
||||
"primary+shift+KeyZ" to "edit.redo",
|
||||
"F9" to "edit.adjustLastOperation",
|
||||
"KeyP" to "uv.pinPlacement",
|
||||
"alt+KeyP" to "uv.unpinPlacement",
|
||||
"KeyH" to "object.toggleVisibility",
|
||||
"KeyG" to "mesh.grab",
|
||||
"KeyS" to "mesh.scale",
|
||||
"KeyR" to "mesh.rotate",
|
||||
"Digit1" to "mesh.selectMode.vertex",
|
||||
"Digit2" to "mesh.selectMode.edge",
|
||||
"Digit3" to "mesh.selectMode.face",
|
||||
"KeyA" to "select.all",
|
||||
"primary+KeyI" to "select.invert",
|
||||
"KeyI" to "keyform.insert",
|
||||
"alt+KeyI" to "keyform.delete",
|
||||
"Delete" to "keyform.deleteSelectedKeys",
|
||||
"ArrowLeft" to "keyform.nudgeKeyLeft",
|
||||
"ArrowRight" to "keyform.nudgeKeyRight",
|
||||
"KeyB" to "mesh.boxSelect",
|
||||
"KeyC" to "mesh.circleSelect",
|
||||
"shift+KeyB" to "view.zoomRegion",
|
||||
"NumpadAdd" to "mesh.circleSelect.grow",
|
||||
"NumpadSubtract" to "mesh.circleSelect.shrink",
|
||||
"Period" to "transform.pivotPie",
|
||||
"shift+KeyS" to "snap.pie",
|
||||
"KeyL" to "mesh.selectLinkedAtCursor",
|
||||
"primary+KeyL" to "mesh.selectLinked",
|
||||
"alt+KeyQ" to "edit.switchObjectUnderCursor",
|
||||
"NumpadDecimal" to "view.frameSelected",
|
||||
"shift+KeyD" to "mesh.duplicate",
|
||||
"KeyM" to "mesh.merge",
|
||||
"KeyV" to "mesh.rip",
|
||||
"KeyJ" to "mesh.connect",
|
||||
"KeyK" to "mesh.insertVertex",
|
||||
"shift+KeyV" to "mesh.vertexSlide",
|
||||
"KeyO" to "mesh.proportional.toggle",
|
||||
"alt+KeyO" to "mesh.proportional.connectedToggle",
|
||||
"KeyT" to "view.toggleToolbar",
|
||||
"KeyN" to "view.toggleSidebar",
|
||||
"primary+Comma" to "edit.preferences",
|
||||
// Blender's Home is Frame All in WHICHEVER editor the pointer is over, so a single context-aware
|
||||
// binding covers both cases; two separate Home entries would collide silently under mapOf's
|
||||
// last-wins semantics.
|
||||
"Home" to "frame.all",
|
||||
"primary+Digit1" to "view.zoomActualSize",
|
||||
"Equals" to "view.zoomIn",
|
||||
"shift+Equals" to "view.zoomInCoarse",
|
||||
"Minus" to "view.zoomOut",
|
||||
"shift+Minus" to "view.zoomOutCoarse",
|
||||
)
|
||||
|
||||
/**
|
||||
* Builds a preset's chord-spec table, refusing duplicate chords.
|
||||
*
|
||||
* mapOf would keep only the LAST of two same-chord pairs, silently dropping the other - invisible even to
|
||||
* the keybindings editor's conflict detection, which only ever sees the already-collapsed map. Failing at
|
||||
* build time turns a duplicate chord into a test failure instead of a silent loss.
|
||||
*
|
||||
* @param Pair bindings The chord-spec to command-id pairs, in presentation order.
|
||||
* @return Map The bindings as a map.
|
||||
*/
|
||||
private fun presetSpecs(vararg bindings: Pair<String, String>): Map<String, String> {
|
||||
val byChord = LinkedHashMap<String, String>(bindings.size)
|
||||
for ((chord, commandId) in bindings) {
|
||||
val previous = byChord.put(chord, commandId)
|
||||
require(previous == null) { "duplicate chord $chord: bound to both $previous and $commandId" }
|
||||
}
|
||||
return byChord
|
||||
}
|
||||
|
||||
/**
|
||||
* The chord-spec → command-id bindings for the built-in preset [presetId], falling back to the default
|
||||
* preset's bindings for an unknown id so a stale or hand-edited settings value can never leave the editor
|
||||
* with no keymap at all.
|
||||
*
|
||||
* @param String presetId The preset id (see [KEYMAP_PRESET_IDS]).
|
||||
* @return Map The preset's chord-spec → command-id bindings.
|
||||
*/
|
||||
fun keymapPresetSpecs(presetId: String): Map<String, String> =
|
||||
when (presetId) {
|
||||
"cubism" -> CUBISM_KEYMAP_SPECS
|
||||
"blender" -> BLENDER_KEYMAP_SPECS
|
||||
else -> DEFAULT_KEYMAP_SPECS
|
||||
}
|
||||
|
||||
/**
|
||||
* The built-in "default" keymap preset as a resolved [Keymap]. Used directly by tests, and as
|
||||
* [org.umamo.ui.workspace.EditorShell]'s default parameter when no settings-backed keymap
|
||||
* ([org.umamo.ui.action.loadKeymap]) is supplied by the caller.
|
||||
*
|
||||
* @return Keymap the default preset.
|
||||
*/
|
||||
fun defaultKeymap(): Keymap = Keymap.fromSpecs(DEFAULT_KEYMAP_SPECS)
|
||||
|
||||
/**
|
||||
* The active [Keymap] for the composition. `static` because the keymap instance only changes when the
|
||||
* settings-resolved preset/overrides change (see [org.umamo.ui.action.loadKeymap]), so a menu rendered
|
||||
* deep in the tree can resolve a command's accelerator (via [Keymap.chordFor]) without prop-drilling
|
||||
* the keymap through every intervening composable. The default errors loudly so a missing provider is
|
||||
* caught at first use rather than silently showing no accelerators.
|
||||
*/
|
||||
val LocalKeymap =
|
||||
staticCompositionLocalOf<Keymap> {
|
||||
error("LocalKeymap not provided — wrap the editor in an EditorShell")
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
package org.umamo.ui.action
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.State
|
||||
import androidx.compose.runtime.produceState
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.contentOrNull
|
||||
import kotlinx.serialization.json.jsonPrimitive
|
||||
import org.umamo.settings.Settings
|
||||
|
||||
/** The settings key holding the selected built-in preset id (see [KEYMAP_PRESET_IDS]). */
|
||||
const val KEYMAP_PRESET_KEY: String = "input.keybinding.preset"
|
||||
|
||||
/**
|
||||
* The settings key holding the user's per-chord overrides: a JSON object of chord-spec → command-id that
|
||||
* layers over the selected preset. An empty-string value is an explicit "unbind" marker (it masks a chord
|
||||
* the preset binds); a deleted entry falls back to the preset. This mirrors the settings engine's own
|
||||
* defaults-then-overrides shape, one level down at the keymap.
|
||||
*/
|
||||
const val KEYMAP_OVERRIDES_KEY: String = "input.keybinding.overrides"
|
||||
|
||||
/**
|
||||
* Reads the user's chord overrides as a plain chord-spec → command-id map (an empty value means the chord
|
||||
* is explicitly unbound). Never throws: a malformed or absent overrides object yields an empty map, so a
|
||||
* corrupt settings value falls back to the bare preset rather than breaking input.
|
||||
*
|
||||
* ユーザーのコード上書きを「指定文字列→コマンド id」のマップとして読む(空値は明示的な解除)。例外は投げない。
|
||||
*
|
||||
* @param Settings settings The settings store to read from.
|
||||
* @return Map The override map (chord spec → command id; "" = unbound).
|
||||
*/
|
||||
internal fun readKeymapOverrides(settings: Settings): Map<String, String> {
|
||||
val element = settings.get(KEYMAP_OVERRIDES_KEY) as? JsonObject ?: return emptyMap()
|
||||
val overrides = LinkedHashMap<String, String>()
|
||||
for ((spec, value) in element) {
|
||||
val commandId = runCatching { value.jsonPrimitive.contentOrNull }.getOrNull() ?: ""
|
||||
overrides[spec] = commandId
|
||||
}
|
||||
return overrides
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the chord overrides back to settings as a JSON object (chord-spec → command-id), replacing the
|
||||
* stored value wholesale. Persists via the Settings user layer and emits the [KEYMAP_OVERRIDES_KEY] change
|
||||
* so the reactive keymap resolver rebuilds.
|
||||
*
|
||||
* コード上書きを JSON オブジェクトとして保存する(全置換)。
|
||||
*
|
||||
* @param Settings settings The settings store to write to.
|
||||
* @param Map overrides The override map to persist.
|
||||
*/
|
||||
internal fun writeKeymapOverrides(settings: Settings, overrides: Map<String, String>) {
|
||||
settings.set(KEYMAP_OVERRIDES_KEY, JsonObject(overrides.mapValues { entry -> JsonPrimitive(entry.value) }))
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the active [Keymap] from settings: the selected preset's bindings ([keymapPresetSpecs]) with the
|
||||
* user's overrides layered on top (an empty-string override unbinds the chord). This is the settings-backed
|
||||
* replacement for the bare [defaultKeymap]; the shell resolves it reactively and re-resolves on any
|
||||
* input.keybinding change.
|
||||
*
|
||||
* 設定から有効なキーマップを解決する(プリセット+ユーザー上書き、空値は解除)。
|
||||
*
|
||||
* @param Settings settings The settings store to resolve from.
|
||||
* @return Keymap The resolved keymap.
|
||||
*/
|
||||
fun loadKeymap(settings: Settings): Keymap {
|
||||
val presetId = settings.getString(KEYMAP_PRESET_KEY) ?: "default"
|
||||
val resolved = LinkedHashMap<KeyChord, String>()
|
||||
for ((spec, commandId) in keymapPresetSpecs(presetId)) {
|
||||
val chord = parseKeyChord(spec) ?: continue
|
||||
resolved[chord] = commandId
|
||||
}
|
||||
for ((spec, commandId) in readKeymapOverrides(settings)) {
|
||||
val chord = parseKeyChord(spec) ?: continue
|
||||
if (commandId.isEmpty()) {
|
||||
resolved.remove(chord) // explicit unbind: mask a chord the preset binds
|
||||
} else {
|
||||
resolved[chord] = commandId
|
||||
}
|
||||
}
|
||||
return Keymap(resolved)
|
||||
}
|
||||
|
||||
/** The prefix every keymap setting sits under; a change to any key below it re-resolves the live keymap. */
|
||||
private const val KEYMAP_SETTINGS_PREFIX: String = "input.keybinding"
|
||||
|
||||
/**
|
||||
* The active [Keymap] as live state: resolved from the selected preset plus the user's overrides, and
|
||||
* re-resolved whenever any input.keybinding setting changes, so a preset switch or a rebind in the
|
||||
* settings window reaches the menu's accelerator hints, the palette, and live dispatch at once.
|
||||
*
|
||||
* @param Settings settings The settings store to resolve from and follow.
|
||||
* @return State The live keymap.
|
||||
*/
|
||||
@Composable
|
||||
fun rememberLiveKeymap(settings: Settings): State<Keymap> =
|
||||
produceState(initialValue = loadKeymap(settings), settings) {
|
||||
settings.changes.collect { changedKey ->
|
||||
if (changedKey.startsWith(KEYMAP_SETTINGS_PREFIX)) {
|
||||
value = loadKeymap(settings)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Selects the built-in preset [presetId] (persisted; user overrides still layer on top). An unknown id is
|
||||
* stored as-is and resolves to the default preset via [keymapPresetSpecs]'s fallback.
|
||||
*
|
||||
* @param Settings settings The settings store to write to.
|
||||
* @param String presetId The preset id to select.
|
||||
*/
|
||||
fun setKeymapPreset(settings: Settings, presetId: String) {
|
||||
settings.setString(KEYMAP_PRESET_KEY, presetId)
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether [chord] is bound by the currently selected preset's base bindings (before overrides). Used when
|
||||
* releasing a chord: a preset binding must be masked with an unbind marker, while a pure override is simply
|
||||
* dropped.
|
||||
*
|
||||
* @param Settings settings The settings store (for the selected preset).
|
||||
* @param KeyChord chord The chord to test.
|
||||
* @return Boolean true if the preset base binds this chord.
|
||||
*/
|
||||
private fun isPresetChord(settings: Settings, chord: KeyChord): Boolean {
|
||||
val presetId = settings.getString(KEYMAP_PRESET_KEY) ?: "default"
|
||||
return keymapPresetSpecs(presetId).keys.any { spec -> parseKeyChord(spec) == chord }
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases [chord] in [overrides] (mutated in place): masks it with an unbind marker if the preset binds it,
|
||||
* otherwise removes the override entry. Either way the chord ends up unbound after resolution.
|
||||
*
|
||||
* @param Settings settings The settings store (for the preset check).
|
||||
* @param MutableMap overrides The override map being edited.
|
||||
* @param KeyChord chord The chord to release.
|
||||
*/
|
||||
private fun releaseChord(settings: Settings, overrides: MutableMap<String, String>, chord: KeyChord) {
|
||||
val spec = chordToSpec(chord)
|
||||
if (isPresetChord(settings, chord)) {
|
||||
overrides[spec] = ""
|
||||
} else {
|
||||
overrides.remove(spec)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Rebinds [commandId] to [newChord], persisting the change. Releases the command's existing canonical chord
|
||||
* first so the command moves rather than gaining a second binding, then binds [newChord] to it - which also
|
||||
* resolves any conflict, since the new entry wins over whatever previously held that chord (the caller is
|
||||
* expected to confirm a conflict with the user first; see the keybindings editor).
|
||||
*
|
||||
* commandId を newChord に再割り当てして保存する。既存の正規コードを解放してから新コードを束縛する。
|
||||
*
|
||||
* @param Settings settings The settings store to write to.
|
||||
* @param String commandId The command being rebound.
|
||||
* @param KeyChord newChord The chord to bind it to.
|
||||
*/
|
||||
fun rebindCommand(settings: Settings, commandId: String, newChord: KeyChord) {
|
||||
val overrides = readKeymapOverrides(settings).toMutableMap()
|
||||
val previous = loadKeymap(settings).chordFor(commandId)
|
||||
if (previous != null && previous != newChord) {
|
||||
releaseChord(settings, overrides, previous)
|
||||
}
|
||||
overrides[chordToSpec(newChord)] = commandId
|
||||
writeKeymapOverrides(settings, overrides)
|
||||
}
|
||||
|
||||
/**
|
||||
* Unbinds [commandId]'s canonical chord, persisting the change (a no-op if it has no binding). A preset
|
||||
* binding is masked with an unbind marker; a pure override is dropped.
|
||||
*
|
||||
* commandId の正規コードを解除して保存する(束縛が無ければ何もしない)。
|
||||
*
|
||||
* @param Settings settings The settings store to write to.
|
||||
* @param String commandId The command to unbind.
|
||||
*/
|
||||
fun unbindCommand(settings: Settings, commandId: String) {
|
||||
val chord = loadKeymap(settings).chordFor(commandId) ?: return
|
||||
val overrides = readKeymapOverrides(settings).toMutableMap()
|
||||
releaseChord(settings, overrides, chord)
|
||||
writeKeymapOverrides(settings, overrides)
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears all user overrides, returning the keymap to the selected preset's bindings (the preset choice is
|
||||
* left unchanged). The "reset shortcuts" action.
|
||||
*
|
||||
* すべてのユーザー上書きを消去し、選択中のプリセットに戻す(プリセットの選択はそのまま)。
|
||||
*
|
||||
* @param Settings settings The settings store to write to.
|
||||
*/
|
||||
fun resetKeymapOverrides(settings: Settings) {
|
||||
writeKeymapOverrides(settings, emptyMap())
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package org.umamo.ui.app
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
|
||||
/**
|
||||
* The host's route into the shell's quit guard.
|
||||
*
|
||||
* The host owns the ways out that the shell never sees: the window's close button, the OS's own quit, and
|
||||
* Android's back gesture. Each hands its exit to [request], and the shell, once composed, installs the
|
||||
* guard that decides whether the exit runs at once or waits on the unsaved-changes prompt. Before the
|
||||
* shell installs anything, and after it is gone, an exit runs directly, because there is no document
|
||||
* whose edits could be lost.
|
||||
*/
|
||||
class ExitGuard {
|
||||
private var installedGuard: ((() -> Unit) -> Unit)? = null
|
||||
|
||||
/**
|
||||
* Asks to exit: the installed guard receives the exit and runs it when the rigger agrees, or the exit
|
||||
* runs at once when no guard is installed.
|
||||
*
|
||||
* @param Function exit Closes the application.
|
||||
*/
|
||||
fun request(exit: () -> Unit) {
|
||||
val guard = installedGuard
|
||||
if (guard == null) {
|
||||
exit()
|
||||
} else {
|
||||
guard(exit)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Installs the guard every later request passes through.
|
||||
*
|
||||
* The returned cleanup removes this guard only while it is still the installed one, so a replacement
|
||||
* installed before the previous cleanup ran is left in place.
|
||||
*
|
||||
* @param Function guard Receives each requested exit and decides whether and when it runs.
|
||||
* @return Function The cleanup that uninstalls this guard.
|
||||
*/
|
||||
fun install(guard: (() -> Unit) -> Unit): () -> Unit {
|
||||
installedGuard = guard
|
||||
return {
|
||||
if (installedGuard === guard) {
|
||||
installedGuard = null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remembers one [ExitGuard] for the host's composition, shared by the host's exits and the shell it mounts.
|
||||
*
|
||||
* @return ExitGuard The guard.
|
||||
*/
|
||||
@Composable
|
||||
fun rememberExitGuard(): ExitGuard = remember { ExitGuard() }
|
||||
@@ -0,0 +1,44 @@
|
||||
package org.umamo.ui.document
|
||||
|
||||
/**
|
||||
* Why a file failed to open in the editor. A stable reason the shell maps to a localized message -
|
||||
* the document layer never carries display text.
|
||||
*/
|
||||
enum class DocumentOpenError {
|
||||
/** The file could not be read at all (missing, unreadable, permission revoked). */
|
||||
ReadFailed,
|
||||
|
||||
/** The contents match no format Umamo recognizes. */
|
||||
Unrecognized,
|
||||
|
||||
/** A recognized format the editor shell cannot open as a document (a JSON sidecar on its own). */
|
||||
NotOpenable,
|
||||
|
||||
/** A recognized format whose contents failed to parse or import. */
|
||||
ParseFailed,
|
||||
|
||||
/** A `.moc3` whose required model3.json manifest was not found next to it (or failed to parse). */
|
||||
MissingManifest,
|
||||
|
||||
/** A `.moc3` whose model3.json references a texture that is missing or unreadable. */
|
||||
MissingTexture,
|
||||
|
||||
/** An artwork file with no raster layer that has any pixel over the alpha threshold - nothing to rig. */
|
||||
NoArtLayers,
|
||||
|
||||
/** A `.uma` whose container is newer than this version reads - made by a newer Umamo. */
|
||||
NewerFormat,
|
||||
}
|
||||
|
||||
/**
|
||||
* The payload of the document.openFailed command: what went wrong and which file, so the shell can
|
||||
* alert the user instead of failing silently to the log. Lives in commonMain (unlike the JVM-bound
|
||||
* document loader) so the shell's command handler can receive it on every platform.
|
||||
*
|
||||
* @property DocumentOpenError error The failure reason.
|
||||
* @property String displayName The file's display name, the alert message's one format argument.
|
||||
*/
|
||||
class DocumentOpenFailure(
|
||||
val error: DocumentOpenError,
|
||||
val displayName: String,
|
||||
)
|
||||
@@ -0,0 +1,47 @@
|
||||
package org.umamo.ui.document
|
||||
|
||||
/**
|
||||
* The display name for a stored file path (titles, the Open Recent menu). A pure string helper — it
|
||||
* never touches the filesystem — so it degrades gracefully for Android SAF `content://` URIs, whose
|
||||
* last segment stands in until real SAF display-name resolution lands.
|
||||
*
|
||||
* @param String path The stored path or URI string.
|
||||
* @return String The trailing segment, with both separator conventions handled.
|
||||
*/
|
||||
fun fileDisplayName(path: String): String = path.substringAfterLast('/').substringAfterLast('\\')
|
||||
|
||||
/**
|
||||
* Whether [path] is a path the file system can probe, read, and watch, as opposed to a platform uri.
|
||||
* Android's SAF hands back `content://` handles with no path behind them, so every file-system
|
||||
* operation over a stored path asks this first and treats a uri as unknowable rather than missing.
|
||||
*
|
||||
* @param String path The stored path or uri string.
|
||||
* @return Boolean True for a file-system path, false for a uri.
|
||||
*/
|
||||
fun isFileSystemPath(path: String): Boolean = !path.contains("://")
|
||||
|
||||
/**
|
||||
* The base name to seed a Save As or an export dialog with: [displayName] minus whatever file extension it
|
||||
* carries.
|
||||
*
|
||||
* Any extension, not only the formats a rig is saved in. A document can start from an artwork file (a rig
|
||||
* built by importing `hero.psd` into a new document is still named after it), and its first save should
|
||||
* suggest `hero`, never `hero.psd.uma`; an export of it `hero.png`, never `hero.psd.png`. Only a trailing
|
||||
* extension of a few letters is stripped, so a name with a dot in it (`v1.2 sketch`) is left alone. FileKit
|
||||
* re-appends the destination's extension itself.
|
||||
*
|
||||
* @param String displayName The document's file name.
|
||||
* @return String The name without its extension.
|
||||
*/
|
||||
fun saveSuggestedName(displayName: String): String {
|
||||
val dot = displayName.lastIndexOf('.')
|
||||
val extension = if (dot > 0) displayName.substring(dot + 1) else ""
|
||||
return if (extension.length in 1..MAXIMUM_EXTENSION_LENGTH && extension.all { character -> character.isLetterOrDigit() }) {
|
||||
displayName.substring(0, dot)
|
||||
} else {
|
||||
displayName
|
||||
}
|
||||
}
|
||||
|
||||
/** The longest extension a source file plausibly carries (`.webp`, `.jpeg`, `.tiff`, `.clip`). */
|
||||
private const val MAXIMUM_EXTENSION_LENGTH = 5
|
||||
@@ -0,0 +1,29 @@
|
||||
package org.umamo.ui.document
|
||||
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import org.umamo.settings.Settings
|
||||
|
||||
private const val RECENT_FILES_KEY = "app.recentFiles"
|
||||
private const val RECENT_FILES_MAX = 10
|
||||
|
||||
/**
|
||||
* The recently-opened file paths, most-recent first (the `app.recentFiles` setting).
|
||||
*
|
||||
* @return List<String> The recent paths.
|
||||
*/
|
||||
fun Settings.recentFiles(): List<String> =
|
||||
(get(RECENT_FILES_KEY) as? JsonArray)
|
||||
?.mapNotNull { (it as? JsonPrimitive)?.takeIf { primitive -> primitive.isString }?.content }
|
||||
?: emptyList()
|
||||
|
||||
/**
|
||||
* Records [path] as the most-recently-opened, moving it to the front (de-duplicated) and capping the list.
|
||||
* Persists immediately and emits the change (so the Open Recent menu refreshes).
|
||||
*
|
||||
* @param String path The opened file path.
|
||||
*/
|
||||
fun Settings.addRecentFile(path: String) {
|
||||
val updated = (listOf(path) + recentFiles().filterNot { it == path }).take(RECENT_FILES_MAX)
|
||||
set(RECENT_FILES_KEY, JsonArray(updated.map { JsonPrimitive(it) }))
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package org.umamo.ui.graphics
|
||||
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import org.umamo.runtime.model.ColorRgb
|
||||
|
||||
/**
|
||||
* Converts the model's [ColorRgb] (three 0..1 float channels, no alpha) to a Compose [Color], forced
|
||||
* opaque. The composite tint colors are stored as [ColorRgb]; the UI edits them through Compose's
|
||||
* [Color] and the hex helpers ([formatHexColor] / [parseHexColor]), so this is the model-to-UI half of
|
||||
* that bridge.
|
||||
*
|
||||
* @return Color The opaque Compose color with the same red / green / blue.
|
||||
*/
|
||||
fun ColorRgb.toComposeColor(): Color = Color(red = red, green = green, blue = blue, alpha = 1f)
|
||||
|
||||
/**
|
||||
* Converts a Compose [Color] back to the model's [ColorRgb], dropping the alpha channel ([ColorRgb] has
|
||||
* none - the source formats' alpha is always opaque). The UI-to-model half of the composite color bridge.
|
||||
*
|
||||
* @return ColorRgb The red / green / blue as 0..1 floats.
|
||||
*/
|
||||
fun Color.toColorRgb(): ColorRgb = ColorRgb(red = red, green = green, blue = blue)
|
||||
@@ -0,0 +1,38 @@
|
||||
package org.umamo.ui.graphics
|
||||
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.toArgb
|
||||
|
||||
/**
|
||||
* Parses a hex color string into a Compose color: 8 hex digits are AARRGGBB, 6 are RRGGBB with an opaque
|
||||
* alpha. A leading '#' and surrounding whitespace are tolerated. Returns null for anything else (wrong
|
||||
* length, non-hex characters, empty), so callers can fall back to a default rather than render garbage.
|
||||
*
|
||||
* @param String text The hex string to parse (e.g. "#CCFF9800" or "2962FF").
|
||||
* @return Color? The parsed color, or null when [text] is not a valid hex color.
|
||||
*/
|
||||
fun parseHexColor(text: String): Color? {
|
||||
val cleaned = text.trim().removePrefix("#")
|
||||
// Reject signs and whitespace that toLongOrNull would tolerate: hex digits only.
|
||||
if (!cleaned.all { character -> character.isDigit() || character in 'a'..'f' || character in 'A'..'F' }) {
|
||||
return null
|
||||
}
|
||||
val packed = cleaned.toLongOrNull(16) ?: return null
|
||||
return when (cleaned.length) {
|
||||
8 -> Color(packed and 0xFFFFFFFFL)
|
||||
6 -> Color(packed or 0xFF000000L)
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats a color as the canonical uppercase "#AARRGGBB" hex string [parseHexColor] accepts, so a parsed
|
||||
* and re-formatted value round-trips exactly (the settings layer stores this canonical form).
|
||||
*
|
||||
* @param Color color The color to format.
|
||||
* @return String The canonical "#AARRGGBB" string.
|
||||
*/
|
||||
fun formatHexColor(color: Color): String {
|
||||
val packed = color.toArgb().toLong() and 0xFFFFFFFFL
|
||||
return "#" + packed.toString(16).uppercase().padStart(8, '0')
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package org.umamo.ui.graphics
|
||||
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
|
||||
/** How the RGBA bytes' alpha channel is to be interpreted when wrapped as an [ImageBitmap]. */
|
||||
enum class RgbaAlphaType {
|
||||
/** Every texel is fully opaque; the alpha bytes are ignored. */
|
||||
Opaque,
|
||||
|
||||
/** Straight (non-premultiplied) alpha: RGB is not scaled by A. */
|
||||
Straight,
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps raw top-first RGBA bytes as a Compose [ImageBitmap].
|
||||
*
|
||||
* Platform seam: desktop wraps via Skiko's Image.makeRaster, Android via android.graphics.Bitmap —
|
||||
* both preserve straight alpha so a transparent texel's leftover matte RGB does not ghost through.
|
||||
*
|
||||
* @param ByteArray rgba The pixel bytes, 4 per texel, top row first.
|
||||
* @param Int width The image width in texels.
|
||||
* @param Int height The image height in texels.
|
||||
* @param RgbaAlphaType alphaType How the alpha channel is interpreted.
|
||||
* @return ImageBitmap The wrapped Compose bitmap.
|
||||
*/
|
||||
expect fun rgbaToImageBitmap(rgba: ByteArray, width: Int, height: Int, alphaType: RgbaAlphaType): ImageBitmap
|
||||
@@ -0,0 +1,100 @@
|
||||
package org.umamo.ui.help
|
||||
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalUriHandler
|
||||
import androidx.compose.ui.unit.dp
|
||||
import org.jetbrains.compose.resources.stringResource
|
||||
import org.umamo.ui.kit.Surface
|
||||
import org.umamo.ui.kit.Text
|
||||
import org.umamo.ui.kit.button.CloseButton
|
||||
import org.umamo.ui.resources.Res
|
||||
import org.umamo.ui.resources.about_license
|
||||
import org.umamo.ui.resources.about_title
|
||||
import org.umamo.ui.resources.about_version
|
||||
import org.umamo.ui.resources.app_name
|
||||
import org.umamo.ui.resources.dialog_close
|
||||
import org.umamo.ui.theme.LocalUmamoColors
|
||||
import org.umamo.ui.theme.LocalUmamoShapes
|
||||
import org.umamo.ui.theme.LocalUmamoTypography
|
||||
|
||||
/**
|
||||
* The Help → About dialog: application name, version, license line, and the project URLs, in the
|
||||
* same scrim-plus-card modal family as the settings window (opened by the help.about command; the
|
||||
* shell owns the visible state and routes Escape, this composable only renders).
|
||||
*
|
||||
* @param Function onDismiss Closes the dialog (Escape is routed here by the shell; also the scrim / close button).
|
||||
*/
|
||||
@Composable
|
||||
fun AboutDialog(onDismiss: () -> Unit) {
|
||||
val colors = LocalUmamoColors.current
|
||||
val typography = LocalUmamoTypography.current
|
||||
Box(
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(colors.overlayScrim)
|
||||
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = onDismiss),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier.width(420.dp).clickable(enabled = false, onClick = {}),
|
||||
color = colors.panelBackground,
|
||||
shape = LocalUmamoShapes.current.medium,
|
||||
border = BorderStroke(1.dp, colors.panelBorder),
|
||||
shadowElevation = 8.dp,
|
||||
) {
|
||||
Column(modifier = Modifier.fillMaxWidth()) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().background(colors.headerBackground).padding(horizontal = 16.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(text = stringResource(Res.string.about_title), style = typography.titleSmall, modifier = Modifier.weight(1f))
|
||||
CloseButton(onClick = onDismiss, contentDescription = stringResource(Res.string.dialog_close))
|
||||
}
|
||||
Box(modifier = Modifier.fillMaxWidth().height(1.dp).background(colors.divider))
|
||||
Column(modifier = Modifier.fillMaxWidth().padding(20.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text(text = stringResource(Res.string.app_name), style = typography.titleSmall)
|
||||
Text(text = stringResource(Res.string.about_version, ProjectInfo.VERSION), style = typography.bodyMedium)
|
||||
Text(text = stringResource(Res.string.about_license), style = typography.bodySmall, color = colors.textMuted)
|
||||
LinkLine(ProjectInfo.WEB_SITE_URL)
|
||||
LinkLine(ProjectInfo.SOURCE_CODE_URL)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One clickable URL line: shown accent-colored and opened through the platform UriHandler on click,
|
||||
* failing quietly (a log line, never a crash) when the platform refuses - the same policy as the
|
||||
* Help menu's link items.
|
||||
*
|
||||
* @param String url The URL shown and opened.
|
||||
*/
|
||||
@Composable
|
||||
private fun LinkLine(url: String) {
|
||||
val uriHandler = LocalUriHandler.current
|
||||
Text(
|
||||
text = url,
|
||||
style = LocalUmamoTypography.current.bodySmall,
|
||||
color = LocalUmamoColors.current.accent,
|
||||
modifier =
|
||||
Modifier.clickable { uriHandler.openLinkQuietly(url) },
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package org.umamo.ui.help
|
||||
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.produceState
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.unit.dp
|
||||
import org.jetbrains.compose.resources.stringResource
|
||||
import org.umamo.ui.kit.Surface
|
||||
import org.umamo.ui.kit.Text
|
||||
import org.umamo.ui.kit.VerticalScrollbarOverlay
|
||||
import org.umamo.ui.kit.button.CloseButton
|
||||
import org.umamo.ui.resources.Res
|
||||
import org.umamo.ui.resources.credits_title
|
||||
import org.umamo.ui.resources.dialog_close
|
||||
import org.umamo.ui.theme.LocalUmamoColors
|
||||
import org.umamo.ui.theme.LocalUmamoShapes
|
||||
import org.umamo.ui.theme.LocalUmamoTypography
|
||||
|
||||
/**
|
||||
* The Help → Credits dialog: the bundled CREDITS.md (the single consolidated home of credits and
|
||||
* third-party license attributions) rendered as a scrollable sheet, in the same scrim-plus-card
|
||||
* modal family as the settings window. The file is read from the build-time-bundled compose
|
||||
* resource, so editing the repo-root CREDITS.md and rebuilding is the whole update path.
|
||||
*
|
||||
* The rendering is deliberately line-based, not a Markdown engine: headings get title styles, the
|
||||
* fenced license block gets monospace, everything else is body text - sufficient for this one
|
||||
* document and nothing more to maintain.
|
||||
*
|
||||
* クレジットダイアログ。ビルド時に同梱した CREDITS.md をスクロール表示する(Markdown エンジンは使わず、
|
||||
* 行単位の簡易整形のみ)。
|
||||
*
|
||||
* @param Function onDismiss Closes the dialog (Escape is routed here by the shell; also the scrim / close button).
|
||||
*/
|
||||
@Composable
|
||||
fun CreditsDialog(onDismiss: () -> Unit) {
|
||||
val colors = LocalUmamoColors.current
|
||||
val typography = LocalUmamoTypography.current
|
||||
// Null until the resource read lands (one frame, tiny file); rendered as an empty sheet meanwhile.
|
||||
val creditsText by produceState<String?>(initialValue = null) {
|
||||
value =
|
||||
runCatching { Res.readBytes("files/CREDITS.md").decodeToString() }
|
||||
.getOrElse { failure -> "CREDITS.md could not be loaded: ${failure.message}" }
|
||||
}
|
||||
Box(
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(colors.overlayScrim)
|
||||
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = onDismiss),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Surface(
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth(0.82f)
|
||||
.fillMaxHeight(0.82f)
|
||||
.widthIn(max = 760.dp)
|
||||
.heightIn(max = 560.dp)
|
||||
.clickable(enabled = false, onClick = {}),
|
||||
color = colors.panelBackground,
|
||||
shape = LocalUmamoShapes.current.medium,
|
||||
border = BorderStroke(1.dp, colors.panelBorder),
|
||||
shadowElevation = 8.dp,
|
||||
) {
|
||||
Column(modifier = Modifier.fillMaxSize()) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().background(colors.headerBackground).padding(horizontal = 16.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(text = stringResource(Res.string.credits_title), style = typography.titleSmall, modifier = Modifier.weight(1f))
|
||||
CloseButton(onClick = onDismiss, contentDescription = stringResource(Res.string.dialog_close))
|
||||
}
|
||||
Box(modifier = Modifier.fillMaxWidth().height(1.dp).background(colors.divider))
|
||||
Box(modifier = Modifier.fillMaxWidth().weight(1f).padding(20.dp)) {
|
||||
val scrollState = rememberScrollState()
|
||||
Column(modifier = Modifier.fillMaxSize().verticalScroll(scrollState)) {
|
||||
CreditsBody(creditsText.orEmpty())
|
||||
}
|
||||
VerticalScrollbarOverlay(scrollState)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the credits text line by line: "# " and "## " headings get title/label styles (with
|
||||
* breathing room above subsections), ``` fences toggle a monospace style for the embedded license
|
||||
* block (the fence lines themselves are dropped), blank lines become spacers, and everything else is
|
||||
* small body text.
|
||||
*
|
||||
* @param String text The full CREDITS.md contents.
|
||||
*/
|
||||
@Composable
|
||||
private fun CreditsBody(text: String) {
|
||||
val colors = LocalUmamoColors.current
|
||||
val typography = LocalUmamoTypography.current
|
||||
val monospace = typography.bodySmall.copy(fontFamily = FontFamily.Monospace)
|
||||
var insideFence = false
|
||||
for (line in text.lines()) {
|
||||
when {
|
||||
line.trimStart().startsWith("```") -> {
|
||||
insideFence = !insideFence
|
||||
}
|
||||
|
||||
insideFence -> {
|
||||
Text(text = line, style = monospace, color = colors.textMuted)
|
||||
}
|
||||
|
||||
line.startsWith("## ") -> {
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
Text(text = line.removePrefix("## "), style = typography.labelMedium)
|
||||
Spacer(modifier = Modifier.height(4.dp))
|
||||
}
|
||||
|
||||
line.startsWith("# ") -> {
|
||||
Text(text = line.removePrefix("# "), style = typography.titleSmall)
|
||||
Spacer(modifier = Modifier.height(4.dp))
|
||||
}
|
||||
|
||||
line.isBlank() -> {
|
||||
Spacer(modifier = Modifier.height(6.dp))
|
||||
}
|
||||
|
||||
else -> {
|
||||
Text(text = line, style = typography.bodySmall)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package org.umamo.ui.help
|
||||
|
||||
import androidx.compose.ui.platform.UriHandler
|
||||
import org.umamo.storage.UmamoLog
|
||||
|
||||
/**
|
||||
* Opens [url] through the platform's handler - the browser on desktop, an intent on Android - failing
|
||||
* quietly when the platform refuses: a log line, never a crash. A link is a convenience, and a machine
|
||||
* with no browser registered must not take the editor down for following one.
|
||||
*
|
||||
* @param String url The URL to open.
|
||||
*/
|
||||
internal fun UriHandler.openLinkQuietly(url: String) {
|
||||
runCatching { openUri(url) }.onFailure { failure -> UmamoLog.error("could not open $url", failure) }
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package org.umamo.ui.help
|
||||
|
||||
/**
|
||||
* Application identity constants: the version and the project URLs, the single source of truth the
|
||||
* About dialog and the Help menu read. This constant IS the application version; the build derives
|
||||
* its version stamps from it (gradle/project-version.gradle.kts parses the VERSION line at
|
||||
* configuration time for the Android versionName and the desktop packaging) — never introduce a
|
||||
* second definition.
|
||||
*/
|
||||
internal object ProjectInfo {
|
||||
const val VERSION = "0.3.0-dev"
|
||||
const val WEB_SITE_URL = "https://umamo.org"
|
||||
const val SOURCE_CODE_URL = "https://github.com/umamoorg/umamo"
|
||||
const val DOCUMENTATION_URL = "https://docs.umamo.org/"
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.input.pointer.PointerEventType
|
||||
import androidx.compose.ui.input.pointer.PointerKeyboardModifiers
|
||||
import androidx.compose.ui.input.pointer.isCtrlPressed
|
||||
import androidx.compose.ui.input.pointer.isMetaPressed
|
||||
import androidx.compose.ui.input.pointer.isSecondaryPressed
|
||||
import androidx.compose.ui.input.pointer.isShiftPressed
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
|
||||
/**
|
||||
* Longest gap between two presses that still counts as a double click. One fixed window for every caller
|
||||
* and platform, rather than each gesture reading its own view configuration, so a double click feels the
|
||||
* same in every panel and the timing core stays free of composition.
|
||||
*/
|
||||
private const val DOUBLE_CLICK_MILLIS = 300L
|
||||
|
||||
/**
|
||||
* The press-to-press timing behind every double click in the editor. Pure state with no Compose types:
|
||||
* [singleOrDoubleClick] runs on it, and a gesture that cannot use that modifier (the workspace tabs, whose
|
||||
* double click shares a gesture with a reorder drag) calls it from its own pointer loop.
|
||||
*
|
||||
* Only two consecutive unmodified presses pair. A modified press (one carrying a selection modifier) is
|
||||
* its own action, such as toggling a row in or out of the selection, so it never completes a double click
|
||||
* and never arms one.
|
||||
*
|
||||
* @param Long windowMillis The double-click window in milliseconds, inclusive.
|
||||
*/
|
||||
class DoubleClickTracker(private val windowMillis: Long = DOUBLE_CLICK_MILLIS) {
|
||||
/** The uptime of the press waiting for its second half, or null when none is pending. */
|
||||
private var pendingPressUptime: Long? = null
|
||||
|
||||
/**
|
||||
* Records a press and reports whether it completes a double click. A completed double clears the
|
||||
* pending press, so a third quick press starts a fresh single rather than a second double.
|
||||
*
|
||||
* @param Long uptimeMillis The press's event time.
|
||||
* @param Boolean modified Whether the press carries a selection modifier.
|
||||
* @return Boolean True when this press is the second half of a double click.
|
||||
*/
|
||||
fun registerPress(uptimeMillis: Long, modified: Boolean = false): Boolean {
|
||||
val pending = pendingPressUptime
|
||||
if (modified) {
|
||||
pendingPressUptime = null
|
||||
return false
|
||||
}
|
||||
if (pending != null && uptimeMillis - pending <= windowMillis) {
|
||||
pendingPressUptime = null
|
||||
return true
|
||||
}
|
||||
pendingPressUptime = uptimeMillis
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* Forgets the pending press, so the next press starts fresh. For a press that turned into something
|
||||
* other than a click, such as a drag.
|
||||
*/
|
||||
fun reset() {
|
||||
pendingPressUptime = null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A single- and double-click detector that fires the single-click action IMMEDIATELY on press, with no
|
||||
* wait for a possible second click. `Modifier.clickable` and `detectTapGestures(onDoubleTap = …)` both
|
||||
* defer the single click by the platform double-tap window to disambiguate it; this does not. It
|
||||
* dispatches [onSingle] on a primary press and, if the press is the second half of a double click (see
|
||||
* [DoubleClickTracker]), dispatches [onDouble] instead. So a double click runs the single action once and
|
||||
* then the double action; callers rely on the double action replacing what the single one showed (e.g. an
|
||||
* inline rename field taking over a row).
|
||||
*
|
||||
* [onSingle] receives the press's keyboard modifiers. A press holding Ctrl, Meta, or Shift, the selection
|
||||
* modifiers, always goes to [onSingle] and never takes part in a double click, so Ctrl-clicking a row twice
|
||||
* toggles it twice rather than renaming it.
|
||||
*
|
||||
* Secondary (right) presses and already-consumed presses are ignored, so a wrapping context menu still
|
||||
* opens and child controls that consume their own press are not double-handled. Uses raw pointerInput,
|
||||
* which never requests focus, so keyboard dispatch stays on the shell root. While [enabled] is false no
|
||||
* pointer handling is installed at all, and a press pending from before is forgotten.
|
||||
*
|
||||
* @param Function onSingle Called on a primary press that is not the second half of a double click.
|
||||
* @param Function onDouble Called on a second unmodified primary press within [doubleClickMillis].
|
||||
* @param Boolean enabled Whether presses are handled at all.
|
||||
* @param Long doubleClickMillis The double-click window in milliseconds.
|
||||
* @return Modifier The modifier with the press-timing detector attached.
|
||||
*/
|
||||
@Composable
|
||||
fun Modifier.singleOrDoubleClick(
|
||||
onSingle: (PointerKeyboardModifiers) -> Unit,
|
||||
onDouble: () -> Unit,
|
||||
enabled: Boolean = true,
|
||||
doubleClickMillis: Long = DOUBLE_CLICK_MILLIS,
|
||||
): Modifier {
|
||||
// The pointer loop restarts only when the window changes, so it would otherwise keep the lambdas of the
|
||||
// composition it started in; read the latest through these (matching the kit Slider).
|
||||
val currentOnSingle by rememberUpdatedState(onSingle)
|
||||
val currentOnDouble by rememberUpdatedState(onDouble)
|
||||
if (!enabled) {
|
||||
return this
|
||||
}
|
||||
return this.pointerInput(doubleClickMillis) {
|
||||
val tracker = DoubleClickTracker(doubleClickMillis)
|
||||
awaitPointerEventScope {
|
||||
while (true) {
|
||||
val event = awaitPointerEvent()
|
||||
if (
|
||||
event.type != PointerEventType.Press ||
|
||||
event.buttons.isSecondaryPressed ||
|
||||
event.changes.any { change -> change.isConsumed }
|
||||
) {
|
||||
continue
|
||||
}
|
||||
val modifiers = event.keyboardModifiers
|
||||
val modified = modifiers.isCtrlPressed || modifiers.isMetaPressed || modifiers.isShiftPressed
|
||||
if (tracker.registerPress(event.changes.first().uptimeMillis, modified)) {
|
||||
currentOnDouble()
|
||||
} else {
|
||||
currentOnSingle(modifiers)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import org.jetbrains.compose.resources.stringResource
|
||||
import org.umamo.ui.kit.button.Button
|
||||
import org.umamo.ui.resources.Res
|
||||
import org.umamo.ui.resources.dialog_cancel
|
||||
import org.umamo.ui.resources.dialog_confirm
|
||||
import org.umamo.ui.theme.LocalUmamoColors
|
||||
import org.umamo.ui.theme.LocalUmamoShapes
|
||||
import org.umamo.ui.theme.LocalUmamoTypography
|
||||
|
||||
/**
|
||||
* A dialog's third choice beside Cancel and Confirm - "Don't Save" beside "Save".
|
||||
*
|
||||
* @property String label The already-localized button label.
|
||||
* @property Function onSelect Called when the user picks it.
|
||||
*/
|
||||
class DialogChoice(
|
||||
val label: String,
|
||||
val onSelect: () -> Unit,
|
||||
)
|
||||
|
||||
/**
|
||||
* A minimal modal confirm dialog: a scrim over the whole shell with a small centered card carrying the
|
||||
* [message] and its buttons. Presentation-only and shell-agnostic so it is reusable for any destructive
|
||||
* action - the caller owns the pending-request state and supplies the actions (the kit has no dialog of its
|
||||
* own otherwise). Clicking the scrim, like Cancel, dismisses without confirming; the card swallows clicks so
|
||||
* a press inside it does not count as a scrim dismissal.
|
||||
*
|
||||
* The confirm button is the primary one - the dialog's default, which Enter activates wherever the caller
|
||||
* routes its keys. An [alternative] sits apart at the left, so a three-way choice reads as the action, the
|
||||
* escape hatch, and the other outcome rather than three peers.
|
||||
*
|
||||
* @param String message The already-localized prompt shown in the card.
|
||||
* @param Function onConfirm Called when the user confirms the action.
|
||||
* @param Function onCancel Called when the user cancels (Cancel button or scrim click).
|
||||
* @param Modifier modifier Layout modifier for the scrim.
|
||||
* @param String? confirmLabel An already-localized label for the confirm button naming its action
|
||||
* ("Discard", "Reassign"); null uses the generic "Confirm".
|
||||
* @param String? cancelLabel An already-localized label for the cancel button; null uses "Cancel".
|
||||
* @param DialogChoice? alternative A third choice shown at the left, or null for a two-button dialog.
|
||||
*/
|
||||
@Composable
|
||||
fun ConfirmDialog(
|
||||
message: String,
|
||||
onConfirm: () -> Unit,
|
||||
onCancel: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
confirmLabel: String? = null,
|
||||
cancelLabel: String? = null,
|
||||
alternative: DialogChoice? = null,
|
||||
) {
|
||||
val colors = LocalUmamoColors.current
|
||||
Box(
|
||||
// indication = null (the kit convention): a bare clickable renders the default hover/press
|
||||
// indication across the whole scrim, a stray dimming layer that toggles on pointer enter/leave.
|
||||
modifier =
|
||||
modifier
|
||||
.fillMaxSize()
|
||||
.background(colors.overlayScrim)
|
||||
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = onCancel),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Surface(
|
||||
// The card swallows clicks (enabled = false) so a press on it is not read as a scrim dismissal.
|
||||
modifier = Modifier.widthIn(min = 280.dp, max = 420.dp).clickable(enabled = false, onClick = {}),
|
||||
color = colors.panelBackground,
|
||||
shape = LocalUmamoShapes.current.medium,
|
||||
border = BorderStroke(1.dp, colors.panelBorder),
|
||||
shadowElevation = 8.dp,
|
||||
) {
|
||||
Column(modifier = Modifier.padding(20.dp)) {
|
||||
Text(text = message, style = LocalUmamoTypography.current.bodyMedium)
|
||||
Row(
|
||||
modifier = Modifier.padding(top = 20.dp).fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
alternative?.let { choice -> Button(label = choice.label, onClick = choice.onSelect, primary = false) }
|
||||
Spacer(modifier = Modifier.weight(1f))
|
||||
Button(label = cancelLabel ?: stringResource(Res.string.dialog_cancel), onClick = onCancel, primary = false)
|
||||
Button(label = confirmLabel ?: stringResource(Res.string.dialog_confirm), onClick = onConfirm, primary = true)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.compositionLocalOf
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.unit.IntOffset
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/**
|
||||
* Wraps [content] so a context-menu request - a secondary (right) click on desktop, or a long press on a
|
||||
* touch screen - opens [items] as a [Menu] at the pointer. The menu is positioned at the click point
|
||||
* rather than anchored to an element, which is what distinguishes a context menu from a dropdown.
|
||||
*
|
||||
* The items are a pre-built value, not a lambda, because their labels are localized via stringResource -
|
||||
* a @Composable call that can only run during composition, not on the pointer event that opens the menu.
|
||||
* The list is cheap to rebuild each recomposition and is therefore always current.
|
||||
*
|
||||
* 二次クリック(デスクトップ)または長押し(タッチ)で、ポインタ位置に items をメニューとして開く。
|
||||
*
|
||||
* @param List items The menu entries (built in composition, so labels can be localized).
|
||||
* @param Modifier modifier The layout modifier for the wrapping box.
|
||||
* @param Function content The content the context menu is attached to.
|
||||
*/
|
||||
@Composable
|
||||
fun ContextMenuArea(items: List<MenuItem>, modifier: Modifier = Modifier, content: @Composable () -> Unit) {
|
||||
var open by remember { mutableStateOf(false) }
|
||||
var anchorOffset by remember { mutableStateOf(IntOffset.Zero) }
|
||||
Box(
|
||||
modifier =
|
||||
modifier.contextMenuGesture { localOffset ->
|
||||
anchorOffset = localOffset
|
||||
open = true
|
||||
},
|
||||
) {
|
||||
CompositionLocalProvider(LocalContextMenuItems provides items) {
|
||||
content()
|
||||
}
|
||||
if (open) {
|
||||
Menu(
|
||||
items = items,
|
||||
onDismissRequest = { open = false },
|
||||
positionProvider = AtPointPositionProvider(anchorOffset),
|
||||
focusable = true,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The items of the innermost enclosing [ContextMenuArea], for content that has to build its OWN menu.
|
||||
*
|
||||
* A text field is the case this exists for: it cannot simply sit inside a [ContextMenuArea] and inherit the
|
||||
* behaviour, because it needs its own clipboard entries appended and its own gesture to beat the one the
|
||||
* text-field primitive installs. Reading the enclosing items here rather than passing them down means a
|
||||
* field picks up whatever menu it happens to be nested in - the keyframe menu on a Properties row, the area
|
||||
* menu in a panel header - with no call site changed.
|
||||
*
|
||||
* Empty outside any area, which reads as "no items to prepend" rather than as an error.
|
||||
*/
|
||||
internal val LocalContextMenuItems = compositionLocalOf { emptyList<MenuItem>() }
|
||||
|
||||
/**
|
||||
* Reports a context-menu request with the pointer position in the modified element's local space. The
|
||||
* trigger is platform-specific - a secondary (right) click on desktop, a long press on a touch screen -
|
||||
* because pointer-button state is a desktop-only (skiko) detail, so the detector is provided per platform.
|
||||
*
|
||||
* コンテキストメニュー要求を局所座標で通知する。トリガーはプラットフォーム依存(右クリック / 長押し)。
|
||||
*
|
||||
* @param Function onContextMenu Called with the request point in local coordinates.
|
||||
* @return Modifier The modifier with the platform's gesture detector attached.
|
||||
*/
|
||||
internal expect fun Modifier.contextMenuGesture(onContextMenu: (IntOffset) -> Unit): Modifier
|
||||
|
||||
/**
|
||||
* [contextMenuGesture]'s variant for a TEXT FIELD, which has to beat the field primitive's own handler.
|
||||
*
|
||||
* Compose installs its built-in Cut / Copy / Paste menu on the text-field node itself. That node is inside
|
||||
* ours, and the main pointer pass runs innermost-first, so an ordinary [contextMenuGesture] never sees the
|
||||
* press - the built-in menu has already consumed it. The trigger therefore has to be watched a pass earlier.
|
||||
*
|
||||
* @param Function onContextMenu Called with the request point in local coordinates.
|
||||
* @return Modifier The modifier with the detector attached.
|
||||
*/
|
||||
internal expect fun Modifier.textEditContextMenuGesture(onContextMenu: (IntOffset) -> Unit): Modifier
|
||||
|
||||
/**
|
||||
* Rounds a pointer [Offset] to the integer pixel offset the popup position providers work in.
|
||||
*
|
||||
* @return IntOffset The rounded offset.
|
||||
*/
|
||||
internal fun Offset.toIntOffset(): IntOffset = IntOffset(x.roundToInt(), y.roundToInt())
|
||||
@@ -0,0 +1,53 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.DpSize
|
||||
import androidx.compose.ui.unit.dp
|
||||
import org.jetbrains.compose.resources.stringResource
|
||||
import org.umamo.ui.kit.button.IconSlot
|
||||
import org.umamo.ui.resources.*
|
||||
import org.umamo.ui.theme.LocalUmamoIcons
|
||||
|
||||
/**
|
||||
* The expand / collapse chevron every tree in the app draws: a down glyph while open, a right glyph while
|
||||
* closed, named for the action a click performs. Consolidates what were separate copies of the same
|
||||
* conditional glyph in the panel section header, the keyform sheet, the parameter groups, and the track
|
||||
* sheet, so the art and the label stay in one place.
|
||||
*
|
||||
* The default label matters more than it looks: a disclosure row's visible text names the section but never
|
||||
* says whether it is open, so the chevron's accessible name is the only place that state is exposed. For
|
||||
* the same reason the tooltip is off by default - the chevron always sits beside its own readable label, and
|
||||
* a hover card repeating on-screen text is noise. A caller with a genuinely icon-only chevron passes
|
||||
* [hoverLabel].
|
||||
*
|
||||
* @param Boolean expanded Whether the section is open (down glyph) or closed (right glyph).
|
||||
* @param Color tint The glyph color, resolved by the caller against its own row state.
|
||||
* @param Modifier modifier Applied to the glyph's box, so a caller's toggle gesture covers it.
|
||||
* @param Dp glyphSize The drawn chevron size; the hit box matches it.
|
||||
* @param String contentDescription The accessible name, defaulting to the action the chevron performs.
|
||||
* @param String hoverLabel The tooltip text; blank (the default) attaches none.
|
||||
*/
|
||||
@Composable
|
||||
fun DisclosureChevron(
|
||||
expanded: Boolean,
|
||||
tint: Color,
|
||||
modifier: Modifier = Modifier,
|
||||
glyphSize: Dp = 12.dp,
|
||||
contentDescription: String =
|
||||
stringResource(if (expanded) Res.string.common_collapse else Res.string.common_expand),
|
||||
hoverLabel: String = "",
|
||||
) {
|
||||
val icons = LocalUmamoIcons
|
||||
IconSlot(
|
||||
icon = if (expanded) icons.chevronDown else icons.chevronRight,
|
||||
contentDescription = contentDescription,
|
||||
tint = tint,
|
||||
modifier = modifier,
|
||||
slotSize = DpSize(glyphSize, glyphSize),
|
||||
glyphSize = glyphSize,
|
||||
hoverLabel = hoverLabel,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.collectIsHoveredAsState
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.IntrinsicSize
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.requiredSize
|
||||
import androidx.compose.foundation.layout.requiredWidth
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.focus.focusProperties
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import org.umamo.ui.theme.LocalUmamoColors
|
||||
import org.umamo.ui.theme.LocalUmamoIcons
|
||||
import org.umamo.ui.theme.LocalUmamoShapes
|
||||
import org.umamo.ui.theme.LocalUmamoTypography
|
||||
import org.umamo.ui.theme.UmamoIcon
|
||||
import org.umamo.ui.theme.drawIcon
|
||||
|
||||
/**
|
||||
* The roles a [DropdownChip] plays: a [Header] chrome chip (content-width, tab-fill, an accent open
|
||||
* state, a right/down disclosure chevron), a form [Field] (fills its column over the control fill, a
|
||||
* down/up chevron pushed to the trailing edge) that sits beside the other form controls, or a [Compact]
|
||||
* header chip sized for a 22.dp list row (a 14.dp glyph in 2.dp padding, so the face is 18.dp tall
|
||||
* where a Header's 24.dp would overflow the row). Sanctioned variations of the one chip rather than
|
||||
* forks, so every role shares the anatomy.
|
||||
*/
|
||||
enum class DropdownChipStyle {
|
||||
Header,
|
||||
Field,
|
||||
Compact,
|
||||
}
|
||||
|
||||
/**
|
||||
* The header dropdown chip, Blender-style: an optional 16.dp leading glyph, an optional labelMedium
|
||||
* text, and a 12.dp chevron that points right while the dropdown is closed and down while it is open.
|
||||
* Flat like the rest of the kit - the default indication is suppressed and the chip paints its own
|
||||
* three-state border and fill: accent while open, panelBackground / panelBorderHover under the
|
||||
* pointer, tabBackground / panelBorder at rest; content is accentText while open, controlGlyph
|
||||
* otherwise. The face is explicit params rather than a content slot on purpose: the anatomy (sizes,
|
||||
* paddings, chevron) stays un-forkable across every header chip, which is the drift this component
|
||||
* exists to prevent. The dropdown stays a slot because consumers differ (a kit Menu that dismisses
|
||||
* per click vs a stay-open Popup).
|
||||
*
|
||||
* A Header chip holds its intrinsic width: the glyphs and the label ignore the incoming maximum, so a
|
||||
* parent with no room left pushes the chip off its edge instead of squeezing it down to an empty
|
||||
* padding box. A Field chip still ellipsizes its label, which is what a form column wants.
|
||||
*
|
||||
* @param Boolean expanded Whether the chip's dropdown is open (drives the accent state).
|
||||
* @param Function onExpandRequest Invoked on click to open the dropdown.
|
||||
* @param String contentDescription The accessible label (the face may be icon-only).
|
||||
* @param Modifier modifier The layout modifier.
|
||||
* @param UmamoIcon icon Optional leading 16.dp glyph.
|
||||
* @param String label Optional labelMedium text between the icon and the chevron.
|
||||
* @param Boolean enabled When false the content dims to the disabled tint and clicks are inert
|
||||
* (no-document chrome renders its chips this way rather than hiding them).
|
||||
* @param DropdownChipStyle style Which role the chip plays; see [DropdownChipStyle].
|
||||
* @param Color? iconTint A status color for the glyph at rest, or null for the chip's own content color.
|
||||
* @param Function dropdown The popup content, rendered while expanded.
|
||||
*/
|
||||
@Composable
|
||||
fun DropdownChip(
|
||||
expanded: Boolean,
|
||||
onExpandRequest: () -> Unit,
|
||||
contentDescription: String,
|
||||
modifier: Modifier = Modifier,
|
||||
icon: UmamoIcon? = null,
|
||||
label: String? = null,
|
||||
enabled: Boolean = true,
|
||||
style: DropdownChipStyle = DropdownChipStyle.Header,
|
||||
iconTint: Color? = null,
|
||||
dropdown: @Composable () -> Unit,
|
||||
) {
|
||||
val colors = LocalUmamoColors.current
|
||||
val shapes = LocalUmamoShapes.current
|
||||
val interaction = remember { MutableInteractionSource() }
|
||||
val hoveredLive by interaction.collectIsHoveredAsState()
|
||||
// A disabled chip shows no hover feedback (the border and fill stay at rest).
|
||||
val hovered = hoveredLive && enabled
|
||||
val isField = style == DropdownChipStyle.Field
|
||||
// A Compact chip keeps the Header anatomy at list-row scale: the glyph matches the row's own 14.dp
|
||||
// icons and the padding halves, so the 18.dp face sits inside a 22.dp row instead of overflowing it.
|
||||
val isCompact = style == DropdownChipStyle.Compact
|
||||
val facePadding = if (isCompact) 2.dp else 4.dp
|
||||
val glyphSize = if (isCompact) 14.dp else 16.dp
|
||||
val chevronSize = if (isCompact) 10.dp else 12.dp
|
||||
val borderColor =
|
||||
when {
|
||||
expanded -> colors.accent
|
||||
hovered -> colors.panelBorderHover
|
||||
else -> colors.panelBorder
|
||||
}
|
||||
val backgroundColor =
|
||||
when {
|
||||
expanded -> colors.accent
|
||||
hovered -> colors.panelBackground
|
||||
else -> colors.tabBackground
|
||||
}
|
||||
val chipContentColor =
|
||||
when {
|
||||
!enabled -> colors.textDisabled
|
||||
expanded -> colors.accentText
|
||||
else -> colors.text
|
||||
}
|
||||
// The popup is a child of this Box rather than of the padded chip Row: the position provider is
|
||||
// handed the anchor's bounds, and the Row's inner box excludes its own padding and background, which
|
||||
// would shift the menu off the chip's painted corner (same pattern as MenuBarLabel).
|
||||
Box(modifier = modifier) {
|
||||
// The tooltip wraps the chip face only; the popup is a sibling below, so it is never wrapped and
|
||||
// its anchor bounds (the box) stay the chip's bounds.
|
||||
Tooltip(text = contentDescription) {
|
||||
// A Field fills its column so it lines up with the other form controls. A Header chip is pinned to
|
||||
// its own intrinsic width and IGNORES the incoming maximum: a Row clamps itself to whatever width is
|
||||
// left, which would shrink the painted face out from under the glyphs. Overflowing the parent (and
|
||||
// being clipped) is the legible failure; a chip squeezed down to an empty padding box is not.
|
||||
val faceWidth =
|
||||
if (isField) {
|
||||
Modifier.fillMaxWidth()
|
||||
} else {
|
||||
Modifier.requiredWidth(IntrinsicSize.Max)
|
||||
}
|
||||
Row(
|
||||
modifier =
|
||||
faceWidth
|
||||
.clip(shapes.small)
|
||||
// NOT focusable, like SectionHeader and Checkbox: the popup owns its own focus while open,
|
||||
// and on close the keyboard must return to the shell root, not to a chip that transient
|
||||
// chrome (the operation settings strip) may dispose on the next edit.
|
||||
.focusProperties { canFocus = false }
|
||||
.clickable(interactionSource = interaction, indication = null, enabled = enabled, onClick = onExpandRequest)
|
||||
.border(width = 1.dp, color = borderColor, shape = shapes.small)
|
||||
.background(backgroundColor, shape = shapes.small)
|
||||
.padding(facePadding)
|
||||
.semantics { this.contentDescription = contentDescription },
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
if (icon != null) {
|
||||
// requiredSize, not size: size coerces to the incoming constraints, so a starved parent
|
||||
// measures the glyph at zero and the chip renders as an empty padding box. The chip holds
|
||||
// its glyphs at full size and overflows instead - being pushed off the edge is legible,
|
||||
// silently shrinking to nothing is not.
|
||||
// A status tint colors the glyph at rest only; the open and disabled faces keep their own contrast.
|
||||
val glyphColor = if (iconTint != null && enabled && !expanded) iconTint else chipContentColor
|
||||
Canvas(modifier = Modifier.requiredSize(glyphSize)) {
|
||||
drawIcon(icon, glyphColor)
|
||||
}
|
||||
}
|
||||
if (label != null) {
|
||||
// A Field weights its label so it fills the chip (ellipsizing when long) and pushes the
|
||||
// chevron to the trailing edge; a Header keeps the label content-width, which the Row's own
|
||||
// intrinsic sizing already guarantees room for.
|
||||
val labelModifier =
|
||||
if (isField) {
|
||||
Modifier.weight(1f).padding(horizontal = 4.dp)
|
||||
} else {
|
||||
Modifier.padding(horizontal = 4.dp)
|
||||
}
|
||||
Text(
|
||||
text = label,
|
||||
style = LocalUmamoTypography.current.labelMedium,
|
||||
color = chipContentColor,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = labelModifier,
|
||||
)
|
||||
}
|
||||
val chevron =
|
||||
when {
|
||||
expanded -> LocalUmamoIcons.chevronDown
|
||||
else -> LocalUmamoIcons.chevronRight
|
||||
}
|
||||
Canvas(modifier = Modifier.requiredSize(chevronSize)) {
|
||||
drawIcon(chevron, chipContentColor)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (expanded) {
|
||||
dropdown()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import org.umamo.ui.theme.LocalUmamoColors
|
||||
import org.umamo.ui.theme.LocalUmamoTypography
|
||||
import org.umamo.ui.theme.UmamoIcon
|
||||
import org.umamo.ui.theme.drawIcon
|
||||
|
||||
/** The default width of a [FieldRow]'s label column, so a column of rows aligns its controls. */
|
||||
val FIELD_ROW_LABEL_WIDTH = 180.dp
|
||||
|
||||
/** The default spacing between stacked [FieldRow]s in a section. */
|
||||
val FIELD_ROW_SPACING = 14.dp
|
||||
|
||||
/**
|
||||
* The uniform height of a compact inline form control (a NumberField, a SelectField), so a column of mixed
|
||||
* controls lines up to one height rather than each sizing to its own text metrics. A single source shared
|
||||
* by every field control keeps them exactly matched - change it here and the whole form follows.
|
||||
*/
|
||||
val FIELD_CONTROL_HEIGHT = 20.dp
|
||||
|
||||
/** The drawn size of a [FieldRow]'s optional label icon. */
|
||||
private val FIELD_ROW_ICON_SIZE = 16.dp
|
||||
|
||||
/**
|
||||
* One labelled control row: a fixed-width label on the left and its [control] on the right, so the
|
||||
* controls down a section align. The shared label:control primitive the settings sections and the
|
||||
* Properties panel build on (promoted here from the settings package so both reuse one row).
|
||||
*
|
||||
* An [icon] leads the label inside the same column, so the controls stay aligned with the rows that
|
||||
* have none. It is decorative - the label beside it is the row's name - so it carries no semantics.
|
||||
*
|
||||
* @param String label The already-localized row label.
|
||||
* @param Modifier modifier The layout modifier for the row.
|
||||
* @param Dp labelWidth The label column width (narrow it for a tight panel).
|
||||
* @param UmamoIcon? icon A glyph drawn before the label, or null for a text-only label.
|
||||
* @param Function control The control composable (a SelectField, NumberField, Checkbox, etc.).
|
||||
*/
|
||||
@Composable
|
||||
fun FieldRow(
|
||||
label: String,
|
||||
modifier: Modifier = Modifier,
|
||||
labelWidth: Dp = FIELD_ROW_LABEL_WIDTH,
|
||||
icon: UmamoIcon? = null,
|
||||
control: @Composable () -> Unit,
|
||||
) {
|
||||
val colors = LocalUmamoColors.current
|
||||
Row(modifier = modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Row(modifier = Modifier.width(labelWidth), verticalAlignment = Alignment.CenterVertically) {
|
||||
if (icon != null) {
|
||||
Canvas(modifier = Modifier.size(FIELD_ROW_ICON_SIZE)) {
|
||||
drawIcon(icon, colors.text)
|
||||
}
|
||||
Spacer(modifier = Modifier.width(6.dp))
|
||||
}
|
||||
Text(
|
||||
text = label,
|
||||
style = LocalUmamoTypography.current.bodyMedium,
|
||||
color = colors.text,
|
||||
)
|
||||
}
|
||||
Spacer(modifier = Modifier.width(12.dp))
|
||||
// The control fills the remaining width, so a fillMaxWidth field / dropdown spans the row and a
|
||||
// fixed-width control sits at the column start - both stay aligned down a section.
|
||||
Box(modifier = Modifier.weight(1f)) {
|
||||
control()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
/**
|
||||
* The hairline seam between two butted fields in a vertical [FieldStack]. The panel surface behind the
|
||||
* stack shows through this gap, so the division follows the theme (a dark seam over a dark island, a light
|
||||
* seam over a light one) rather than being a drawn border - the vertical analogue of a ButtonGroup's
|
||||
* SEGMENT_GAP, keeping both stacked runs visually consistent.
|
||||
*/
|
||||
val FIELD_STACK_SEAM = 1.dp
|
||||
|
||||
/**
|
||||
* Lays out a vertical run of butted fields as one joined group, Blender-style: the fields sit flush with a
|
||||
* [FIELD_STACK_SEAM] hairline between them, and only the run's outer corners round. Mirrors [ButtonGroup]
|
||||
* for the vertical axis - the container owns the seams and hands each row its [StackPosition] (via
|
||||
* [stackPositionOf]), so a caller stacks fields without hand-threading First / Middle / Last and can never
|
||||
* get an end wrong. Each row is a composable taking the position it should pass to its field's
|
||||
* stackPosition (so the row's own label / control layout stays the caller's concern).
|
||||
*
|
||||
* @param List rows The stacked rows in top-to-bottom order; each is given its position in the run.
|
||||
* @param Modifier modifier The layout modifier for the enclosing column.
|
||||
*/
|
||||
@Composable
|
||||
fun FieldStack(
|
||||
rows: List<@Composable (StackPosition) -> Unit>,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
Column(modifier = modifier) {
|
||||
rows.forEachIndexed { rowIndex, row ->
|
||||
if (rowIndex > 0) {
|
||||
Spacer(modifier = Modifier.height(FIELD_STACK_SEAM))
|
||||
}
|
||||
row(stackPositionOf(rowIndex, rows.size))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.draganddrop.dragAndDropTarget
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draganddrop.DragAndDropEvent
|
||||
import androidx.compose.ui.draganddrop.DragAndDropTarget
|
||||
import androidx.compose.ui.unit.dp
|
||||
import org.umamo.ui.theme.LocalUmamoColors
|
||||
import org.umamo.ui.theme.LocalUmamoShapes
|
||||
|
||||
/**
|
||||
* Whether this drag-and-drop event carries files at all - the question a drop target answers before it
|
||||
* joins a session.
|
||||
*
|
||||
* Separate from [droppedFilePaths] because of when each may be asked. A platform may not hand over the
|
||||
* payload of a drag still in flight (AWT says so explicitly: a drag event's transfer data can be
|
||||
* unavailable until the drop), while what KINDS of data the drag carries is known from the start. So this
|
||||
* inspects only the advertised shape, and the paths are read once the file has actually been let go.
|
||||
*
|
||||
* @return Boolean True when the drag advertises files this target could take.
|
||||
*/
|
||||
expect fun DragAndDropEvent.carriesFiles(): Boolean
|
||||
|
||||
/**
|
||||
* The stored paths a completed drop carries, or empty when it carries none.
|
||||
*
|
||||
* A path here is in the form the recent-files list stores - a file-system path on desktop, a `content://`
|
||||
* uri string on Android - so a caller hands one straight to the document loader.
|
||||
*
|
||||
* @return List The dropped files as stored paths, in the order the platform reported them.
|
||||
*/
|
||||
expect fun DragAndDropEvent.droppedFilePaths(): List<String>
|
||||
|
||||
/**
|
||||
* Wraps [content] in a surface that accepts files dropped on it from outside the application, framing
|
||||
* itself in the accent color while a drag it would accept is over it.
|
||||
*
|
||||
* Only a drag carrying files starts a session here ([carriesFiles]), so a text or image drag falls through
|
||||
* to whatever else in the hierarchy wants it. Nothing is read or validated beyond that: [onDrop] is handed
|
||||
* the paths and decides what each one means, because the way a file is opened is the caller's business and
|
||||
* the file's contents are the loader's.
|
||||
*
|
||||
* The frame is drawn here rather than left to the caller so the over-state and the thing it paints cannot
|
||||
* drift apart, and it is drawn as an overlaid sibling so it neither re-lays-out [content] nor takes any
|
||||
* space from it.
|
||||
*
|
||||
* @param Function onDrop Called with the dropped files' stored paths; never called with an empty list.
|
||||
* @param Function content The content the drop target covers.
|
||||
*/
|
||||
@Composable
|
||||
fun FileDropTarget(onDrop: (List<String>) -> Unit, content: @Composable () -> Unit) {
|
||||
// The target node outlives recompositions, so it reads the caller's lambda through a holder rather
|
||||
// than capturing the first composition's.
|
||||
val currentOnDrop by rememberUpdatedState(onDrop)
|
||||
var dragOver by remember { mutableStateOf(false) }
|
||||
val target =
|
||||
remember {
|
||||
object : DragAndDropTarget {
|
||||
override fun onEntered(event: DragAndDropEvent) {
|
||||
dragOver = true
|
||||
}
|
||||
|
||||
override fun onExited(event: DragAndDropEvent) {
|
||||
dragOver = false
|
||||
}
|
||||
|
||||
// Clears on the session's end as well as on exit: a drag cancelled outside the window
|
||||
// (Escape, or a release over another application) sends no exit, and the frame would stay.
|
||||
override fun onEnded(event: DragAndDropEvent) {
|
||||
dragOver = false
|
||||
}
|
||||
|
||||
override fun onDrop(event: DragAndDropEvent): Boolean {
|
||||
val paths = event.droppedFilePaths()
|
||||
if (paths.isEmpty()) {
|
||||
return false
|
||||
}
|
||||
currentOnDrop(paths)
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
Box(
|
||||
Modifier.fillMaxSize().dragAndDropTarget(
|
||||
shouldStartDragAndDrop = { startEvent -> startEvent.carriesFiles() },
|
||||
target = target,
|
||||
),
|
||||
) {
|
||||
content()
|
||||
if (dragOver) {
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(LocalUmamoColors.current.accent.copy(alpha = 0.5f), LocalUmamoShapes.current.large)
|
||||
.border(2.dp, LocalUmamoColors.current.accent, LocalUmamoShapes.current.large),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.foundation.layout.ColumnScope
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import org.umamo.ui.theme.LocalUmamoColors
|
||||
import org.umamo.ui.theme.LocalUmamoIcons
|
||||
import org.umamo.ui.theme.LocalUmamoTypography
|
||||
import org.umamo.ui.theme.UmamoIcon
|
||||
|
||||
/**
|
||||
* A header filter dropdown: the shared [PopupChip] wearing a funnel, holding a panel of view toggles.
|
||||
* The panel stays open while toggling, so several filters can be flipped in one visit, and the open
|
||||
* state stays inside the chip - a panel adds a filter menu by supplying only its toggle rows.
|
||||
*
|
||||
* @param String contentDescription The accessible label for the chip (the face is icon-only).
|
||||
* @param Modifier modifier The layout modifier.
|
||||
* @param UmamoIcon icon The chip's leading glyph; the funnel by default.
|
||||
* @param Boolean enabled When false the chip dims and clicks are inert.
|
||||
* @param Function content The toggle rows, stacked in the popup panel.
|
||||
*/
|
||||
@Composable
|
||||
fun FilterPopupChip(
|
||||
contentDescription: String,
|
||||
modifier: Modifier = Modifier,
|
||||
icon: UmamoIcon = LocalUmamoIcons.filterFiltered,
|
||||
enabled: Boolean = true,
|
||||
content: @Composable ColumnScope.() -> Unit,
|
||||
) {
|
||||
PopupChip(
|
||||
contentDescription = contentDescription,
|
||||
modifier = modifier,
|
||||
icon = icon,
|
||||
enabled = enabled,
|
||||
content = content,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* A muted caption heading one group of rows inside a [FilterPopupChip] panel. Extracted so every
|
||||
* filter panel's section headings share one type style and inset. One line, ellipsized: a heading
|
||||
* that names a document object (an artwork file) can be arbitrarily long, and it must not widen or
|
||||
* wrap the panel the rows beneath it are sized for.
|
||||
*
|
||||
* @param String text The heading text.
|
||||
* @param Modifier modifier The layout modifier.
|
||||
*/
|
||||
@Composable
|
||||
fun FilterSectionLabel(text: String, modifier: Modifier = Modifier) {
|
||||
Text(
|
||||
text = text,
|
||||
style = LocalUmamoTypography.current.labelSmall,
|
||||
color = LocalUmamoColors.current.textMuted,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = modifier.padding(horizontal = 8.dp, vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.text.BasicTextField
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
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
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.focus.onFocusChanged
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.SolidColor
|
||||
import androidx.compose.ui.input.key.Key
|
||||
import androidx.compose.ui.input.key.KeyEventType
|
||||
import androidx.compose.ui.input.key.key
|
||||
import androidx.compose.ui.input.key.onKeyEvent
|
||||
import androidx.compose.ui.input.key.type
|
||||
import androidx.compose.ui.platform.LocalFocusManager
|
||||
import androidx.compose.ui.text.TextRange
|
||||
import androidx.compose.ui.text.input.TextFieldValue
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Popup
|
||||
import androidx.compose.ui.window.PopupProperties
|
||||
import org.umamo.ui.graphics.formatHexColor
|
||||
import org.umamo.ui.graphics.parseHexColor
|
||||
import org.umamo.ui.model.KeyedFieldState
|
||||
import org.umamo.ui.model.backgroundTint
|
||||
import org.umamo.ui.model.tint
|
||||
import org.umamo.ui.theme.LocalUmamoColors
|
||||
import org.umamo.ui.theme.LocalUmamoShapes
|
||||
import org.umamo.ui.theme.LocalUmamoTypography
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/**
|
||||
* A compact hex color entry: a live swatch beside a text field accepting "#AARRGGBB" (or "#RRGGBB",
|
||||
* treated as opaque). Every keystroke that parses is committed immediately through [onValueChange] in
|
||||
* canonical form - the auto-save model the settings window uses, so the swatch and any live consumer (the
|
||||
* viewport gizmo) follow the typing with no confirm step. Text that does not parse stays local to the
|
||||
* field (the swatch holds the last good color) and is discarded on focus loss, which re-seeds the field
|
||||
* from the persisted [value]. Enter confirms by clearing focus.
|
||||
*
|
||||
* Clicking the swatch opens an RGB-slider popover for graphical picking; a slider drag commits once at its
|
||||
* end (one write per gesture, not per frame), while the text field stays the path for exact entry.
|
||||
*
|
||||
* Like [NumberField], it lends its cancel hook to [LocalInlineEditController] while focused, so the editor
|
||||
* shell's root key handler yields keystrokes to the field (hex digits are also bare-digit shortcuts) and
|
||||
* routes Escape here (clearing focus) instead.
|
||||
*
|
||||
* @param String value The persisted color as canonical "#AARRGGBB" text.
|
||||
* @param Function onValueChange Called with the canonical hex of each parseable edit.
|
||||
* @param Modifier modifier Layout modifier (the caller supplies the width).
|
||||
* @param KeyedFieldState keyState The keyform state to tint the field with (outline on the swatch, background
|
||||
* fill on the text field).
|
||||
*/
|
||||
@Composable
|
||||
fun HexColorField(
|
||||
value: String,
|
||||
onValueChange: (String) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
keyState: KeyedFieldState = KeyedFieldState.None,
|
||||
) {
|
||||
val colors = LocalUmamoColors.current
|
||||
// The SWATCH keeps the outline form of the keyed tint, because its background IS the user's own color and
|
||||
// has nothing to spare; the hex field beside it takes the tint as a fill, like every other text control.
|
||||
val swatchBorderColor = keyState.tint(colors) ?: colors.controlBorder
|
||||
val keyedFill = keyState.backgroundTint(colors) ?: Color.Transparent
|
||||
val shapes = LocalUmamoShapes.current
|
||||
val controller = LocalInlineEditController.current
|
||||
val focusManager = LocalFocusManager.current
|
||||
var focused by remember { mutableStateOf(false) }
|
||||
// A TextFieldValue rather than a String so the context menu can act on a selection.
|
||||
var text by remember { mutableStateOf(TextFieldValue(value, TextRange(value.length))) }
|
||||
var pickerOpen by remember { mutableStateOf(false) }
|
||||
|
||||
// Mirror the external value - and do it EVEN WHILE FOCUSED, because this field is not the only writer
|
||||
// of what it shows. The swatch's own picker, a parameter scrub moving a keyed channel, and undo all
|
||||
// change the value underneath it; skipping the mirror while focused pinned the field to whatever it
|
||||
// last held, and since nothing takes focus back off it, a keyed color stayed frozen on its first key
|
||||
// forever while the viewport went on blending.
|
||||
//
|
||||
// The compare is on the PARSED color, not the text, and that is what keeps this from fighting the
|
||||
// typist: the user's own keystroke round-trips out through onValueChange and comes back equal, so it
|
||||
// re-seeds nothing. Half-typed text that does not parse is left alone for the same reason.
|
||||
LaunchedEffect(value, focused) {
|
||||
val typed = parseHexColor(text.text)
|
||||
if (!focused || (typed != null && typed != parseHexColor(value))) {
|
||||
text = TextFieldValue(value, TextRange(value.length))
|
||||
}
|
||||
}
|
||||
|
||||
// Drop the lent cancel hook if the field disposes while focused (a section switch mid-edit).
|
||||
DisposableEffect(Unit) {
|
||||
onDispose {
|
||||
if (focused) {
|
||||
controller.cancel = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = modifier) {
|
||||
// The live swatch: the color being typed when parseable, else the last persisted one. Clicking it
|
||||
// opens the slider popover, anchored to this swatch (the Box wrapper is the popup's anchor bounds).
|
||||
val swatchColor = parseHexColor(text.text) ?: parseHexColor(value) ?: Color.Transparent
|
||||
Box {
|
||||
Box(
|
||||
modifier =
|
||||
Modifier
|
||||
.size(18.dp)
|
||||
.clip(shapes.small)
|
||||
.background(swatchColor)
|
||||
.border(1.dp, swatchBorderColor, shapes.small)
|
||||
// Opens only. It must NOT toggle: an outside-click dismiss fires first and closes the
|
||||
// popover, and this click would then immediately reopen it, so the swatch could never
|
||||
// be used to close. Closing is the popup's own job (click-away or Escape).
|
||||
.clickable { pickerOpen = true },
|
||||
)
|
||||
if (pickerOpen) {
|
||||
Popup(
|
||||
popupPositionProvider = BelowAnchorPositionProvider,
|
||||
onDismissRequest = { pickerOpen = false },
|
||||
// NOT focusable: a focusable popup pulls focus off the shell root, and nothing restores it
|
||||
// on dismiss - every keyboard shortcut stays dead until Tab traversal reclaims it (the
|
||||
// hazard IconButton.suppressFocus exists to avoid). The sliders are pointer-driven, so the
|
||||
// popover needs no focus of its own; dismissal still works via the outside-click handler.
|
||||
properties = PopupProperties(focusable = false),
|
||||
) {
|
||||
// The popover edits the persisted color; a slider commit round-trips through onValueChange
|
||||
// (canonical hex), which re-seeds the swatch and the text field.
|
||||
ColorSliderPopover(
|
||||
color = parseHexColor(value) ?: Color.Black,
|
||||
onColorChange = { picked -> onValueChange(formatHexColor(picked)) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer(modifier = Modifier.width(6.dp))
|
||||
TextEditContextMenuArea(
|
||||
value = text,
|
||||
onValueChange = { edited -> commitHexEdit(edited, text, onValueChange) { updated -> text = updated } },
|
||||
modifier = Modifier.weight(1f),
|
||||
) { gesture ->
|
||||
BasicTextField(
|
||||
value = text,
|
||||
onValueChange = { edited -> commitHexEdit(edited, text, onValueChange) { updated -> text = updated } },
|
||||
textStyle = LocalUmamoTypography.current.bodySmall.copy(color = colors.text),
|
||||
singleLine = true,
|
||||
cursorBrush = SolidColor(colors.text),
|
||||
modifier =
|
||||
gesture
|
||||
.textEntrySurface(controller)
|
||||
.fillMaxWidth()
|
||||
.clip(shapes.small)
|
||||
.background(colors.controlBackground)
|
||||
.background(keyedFill, shapes.small)
|
||||
.border(1.dp, colors.controlBorder, shapes.small)
|
||||
.padding(horizontal = 6.dp, vertical = 4.dp)
|
||||
.onFocusChanged { focusState ->
|
||||
// hasFocus (not isFocused): BasicTextField focuses an internal child, so this node only
|
||||
// ever sees its subtree's focus.
|
||||
if (focusState.hasFocus) {
|
||||
if (!focused) {
|
||||
focused = true
|
||||
// Escape routes here via the shell: end the edit by clearing focus (the mirror
|
||||
// effect above then re-seeds the text from the persisted value).
|
||||
controller.cancel = { focusManager.clearFocus() }
|
||||
}
|
||||
} else if (focused) {
|
||||
focused = false
|
||||
controller.cancel = null
|
||||
}
|
||||
}
|
||||
.onKeyEvent { event ->
|
||||
// Hardware Enter confirms by clearing focus (edits are already persisted live).
|
||||
if (event.type == KeyEventType.KeyDown && (event.key == Key.Enter || event.key == Key.NumPadEnter)) {
|
||||
focusManager.clearFocus()
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies one hex-field edit: shows it, and persists it when the TEXT changed and parses.
|
||||
*
|
||||
* Shared by the field and its context menu so a pasted color takes effect exactly like a typed one - the
|
||||
* menu writing only the local text would have shown a color the document never received.
|
||||
*
|
||||
* Selection-only changes are shown and not persisted. BasicTextField's TextFieldValue overload reports a
|
||||
* caret or selection move through the same callback as an edit, so persisting unconditionally re-committed
|
||||
* the stored value for merely clicking into the field, dragging a selection across it, or picking Select
|
||||
* All - and on a keyed channel that is an undo step plus an uncommitted-edit tint for a value that never
|
||||
* changed.
|
||||
*
|
||||
* @param TextFieldValue edited The value the field or menu produced.
|
||||
* @param TextFieldValue previous The value it replaces, for telling an edit from a selection move.
|
||||
* @param Function onValueChange The caller's persist callback, given canonical hex.
|
||||
* @param Function show Writes the edited value back to the field's own state.
|
||||
*/
|
||||
private fun commitHexEdit(
|
||||
edited: TextFieldValue,
|
||||
previous: TextFieldValue,
|
||||
onValueChange: (String) -> Unit,
|
||||
show: (TextFieldValue) -> Unit,
|
||||
) {
|
||||
show(edited)
|
||||
if (edited.text == previous.text) {
|
||||
return
|
||||
}
|
||||
parseHexColor(edited.text)?.let { parsed -> onValueChange(formatHexColor(parsed)) }
|
||||
}
|
||||
|
||||
/**
|
||||
* The RGB-slider popover a [HexColorField] swatch opens: a preview strip over three channel sliders. The
|
||||
* sliders drive a local draft so the preview follows every frame, but the outer [onColorChange] fires only
|
||||
* when a slider gesture ends - so a whole drag is one commit (and one undo step), not one per frame. The
|
||||
* draft re-seeds whenever the committed [color] changes externally (e.g. the text field is typed while the
|
||||
* popover is open). A slider edits only its channel, so the color's alpha (if any) is preserved.
|
||||
*
|
||||
* @param Color color The current committed color the sliders start from.
|
||||
* @param Function onColorChange Commits a picked color (fired at each slider gesture's end).
|
||||
*/
|
||||
@Composable
|
||||
private fun ColorSliderPopover(color: Color, onColorChange: (Color) -> Unit) {
|
||||
val colors = LocalUmamoColors.current
|
||||
val shapes = LocalUmamoShapes.current
|
||||
var draft by remember { mutableStateOf(color) }
|
||||
LaunchedEffect(color) {
|
||||
draft = color
|
||||
}
|
||||
Surface(color = colors.menuBackground, shape = shapes.medium) {
|
||||
Column(
|
||||
modifier = Modifier.width(184.dp).padding(8.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
Box(
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.height(22.dp)
|
||||
.clip(shapes.small)
|
||||
.background(draft)
|
||||
.border(1.dp, colors.controlBorder, shapes.small),
|
||||
)
|
||||
ColorChannelSlider("R", draft.red, { channel -> draft = draft.copy(red = channel) }, { onColorChange(draft) })
|
||||
ColorChannelSlider("G", draft.green, { channel -> draft = draft.copy(green = channel) }, { onColorChange(draft) })
|
||||
ColorChannelSlider("B", draft.blue, { channel -> draft = draft.copy(blue = channel) }, { onColorChange(draft) })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One 0..255 channel row inside [ColorSliderPopover]: a letter label, the slider, and a numeric readout.
|
||||
* The slider streams its channel value as a 0..1 fraction to [onChannel] for the live preview and calls
|
||||
* [onCommit] once when the gesture ends.
|
||||
*
|
||||
* @param String label The channel letter ("R" / "G" / "B").
|
||||
* @param Float channel The channel's current 0..1 value.
|
||||
* @param Function onChannel Called with the new 0..1 channel value on each slider frame.
|
||||
* @param Function onCommit Called once when the slider gesture ends.
|
||||
*/
|
||||
@Composable
|
||||
private fun ColorChannelSlider(label: String, channel: Float, onChannel: (Float) -> Unit, onCommit: () -> Unit) {
|
||||
val colors = LocalUmamoColors.current
|
||||
val typography = LocalUmamoTypography.current
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(text = label, style = typography.labelSmall, color = colors.textMuted, modifier = Modifier.width(12.dp))
|
||||
Slider(
|
||||
value = channel * 255f,
|
||||
onValueChange = { raw -> onChannel((raw / 255f).coerceIn(0f, 1f)) },
|
||||
modifier = Modifier.weight(1f),
|
||||
onValueChangeFinished = onCommit,
|
||||
valueRange = 0f..255f,
|
||||
)
|
||||
Spacer(modifier = Modifier.width(6.dp))
|
||||
Text(
|
||||
text = (channel * 255f).roundToInt().toString(),
|
||||
style = typography.labelSmall,
|
||||
color = colors.text,
|
||||
textAlign = TextAlign.End,
|
||||
modifier = Modifier.width(28.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.staticCompositionLocalOf
|
||||
|
||||
/**
|
||||
* A coordination seam between a transient inline text editor (today: renaming a workspace tab) and a
|
||||
* host that runs its own keyboard dispatch. A bare text field cannot defend itself here: the editor
|
||||
* lives inside the editor shell, whose root key handler previews every keystroke before the focused
|
||||
* field sees it, so the shell would claim Space (palette), letters (file commands), and Escape while the
|
||||
* user is merely typing a name. While an editor is open it parks its cancel callback here; the host
|
||||
* checks this first and, finding it non-null, routes Escape to the cancel and lets every other key fall
|
||||
* through to the field instead of running its own shortcuts. Holds null whenever no inline editor is
|
||||
* open. Only the editor should write it.
|
||||
*
|
||||
* The same seam answers the other question a host has about text entry: whether the press it is
|
||||
* watching landed on the editor itself. A press anywhere else ends text entry (the shell hands the
|
||||
* keyboard back to its root), and only the editor's own node can say that the press was meant for it.
|
||||
*
|
||||
* @property Function cancel Cancels the open inline editor, or null when none is open.
|
||||
* @property Boolean pressLandedOnTextEditor Whether the press being dispatched hit a text editor.
|
||||
*/
|
||||
class InlineEditController {
|
||||
var cancel: (() -> Unit)? by mutableStateOf(null)
|
||||
|
||||
/**
|
||||
* Whether the press currently being dispatched landed on a live text editor's own node. The host
|
||||
* clears this on the press's Initial pass (an ancestor sees that pass before any descendant), each
|
||||
* text editor sets it on its own Initial pass, and the host reads it on the Final pass, after every
|
||||
* descendant has handled the press. One synchronous dispatch on one thread, so the flag never has to
|
||||
* tell one press from the next and needs no token.
|
||||
*
|
||||
* A plain var, deliberately, where [cancel] is snapshot state: nothing displays this, and making it
|
||||
* observable would recompose the whole shell twice on every mouse press.
|
||||
*/
|
||||
var pressLandedOnTextEditor: Boolean = false
|
||||
}
|
||||
|
||||
/**
|
||||
* Supplies the [InlineEditController] a host shares with the inline editors nested under it. Defaults to
|
||||
* a standalone instance so an editor used without a coordinating host still functions (it falls back to
|
||||
* its own focus-loss commit and to the field's own key handling).
|
||||
*/
|
||||
val LocalInlineEditController = staticCompositionLocalOf { InlineEditController() }
|
||||
@@ -0,0 +1,132 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.foundation.text.BasicTextField
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.focus.onFocusChanged
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.SolidColor
|
||||
import androidx.compose.ui.input.key.Key
|
||||
import androidx.compose.ui.input.key.KeyEventType
|
||||
import androidx.compose.ui.input.key.key
|
||||
import androidx.compose.ui.input.key.onKeyEvent
|
||||
import androidx.compose.ui.input.key.type
|
||||
import androidx.compose.ui.text.TextRange
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.TextFieldValue
|
||||
|
||||
/**
|
||||
* A single-line inline rename text field, the shared core behind every in-place rename in the editor
|
||||
* (the workspace tab and the outliner row). The whole name starts selected so typing replaces it; it
|
||||
* commits on Enter or when focus leaves (clicking away), and cancels on Escape. Escape is routed in by
|
||||
* the host through [LocalInlineEditController], because the editor shell's root key handler previews
|
||||
* Escape (and every shortcut) before this field could see it. A blank name commits as a cancel, so the
|
||||
* entity keeps its old name. The caller supplies the surrounding styling (a tab fill, a tree row); this
|
||||
* owns only the field and its commit/cancel lifecycle.
|
||||
*
|
||||
* 共通のインライン名前編集フィールド(タブとアウトライナーで再利用)。Enter/フォーカス喪失で確定、
|
||||
* Escape で取消(シェル経由)。空名は取消扱い。装飾は呼び出し側が与える。
|
||||
*
|
||||
* @param String initialName The current name, pre-selected for replacement.
|
||||
* @param TextStyle textStyle The text style (the caller supplies the color to match its context).
|
||||
* @param Color cursorColor The text-cursor color.
|
||||
* @param Function onCommit Called with the trimmed new name when the edit is confirmed (never blank).
|
||||
* @param Function onCancel Called when the edit is abandoned (Escape or a blank name).
|
||||
* @param Modifier modifier The layout modifier for the field.
|
||||
*/
|
||||
@Composable
|
||||
fun InlineRenameField(
|
||||
initialName: String,
|
||||
textStyle: TextStyle,
|
||||
cursorColor: Color,
|
||||
onCommit: (String) -> Unit,
|
||||
onCancel: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val controller = LocalInlineEditController.current
|
||||
val focusRequester = remember { FocusRequester() }
|
||||
var fieldValue by remember {
|
||||
mutableStateOf(TextFieldValue(initialName, selection = TextRange(0, initialName.length)))
|
||||
}
|
||||
// Guards against resolving twice: e.g. Enter commits, then the editor's disposal fires onFocusChanged,
|
||||
// which would otherwise commit again.
|
||||
var resolved by remember { mutableStateOf(false) }
|
||||
var hasFocused by remember { mutableStateOf(false) }
|
||||
|
||||
fun commit() {
|
||||
if (resolved) {
|
||||
return
|
||||
}
|
||||
resolved = true
|
||||
val trimmed = fieldValue.text.trim()
|
||||
if (trimmed.isEmpty()) {
|
||||
onCancel()
|
||||
} else {
|
||||
onCommit(trimmed)
|
||||
}
|
||||
}
|
||||
|
||||
fun cancel() {
|
||||
if (resolved) {
|
||||
return
|
||||
}
|
||||
resolved = true
|
||||
onCancel()
|
||||
}
|
||||
|
||||
// While mounted, lend the shell this editor's cancel so it can route Escape here (it intercepts Escape
|
||||
// before the field would receive it); clear the hook on dispose.
|
||||
DisposableEffect(Unit) {
|
||||
controller.cancel = { cancel() }
|
||||
onDispose { controller.cancel = null }
|
||||
}
|
||||
LaunchedEffect(Unit) {
|
||||
focusRequester.requestFocus()
|
||||
}
|
||||
|
||||
BasicTextField(
|
||||
value = fieldValue,
|
||||
onValueChange = { newValue -> fieldValue = newValue },
|
||||
singleLine = true,
|
||||
textStyle = textStyle,
|
||||
cursorBrush = SolidColor(cursorColor),
|
||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
|
||||
keyboardActions = KeyboardActions(onDone = { commit() }),
|
||||
modifier =
|
||||
modifier
|
||||
.textEntrySurface(controller)
|
||||
.focusRequester(focusRequester)
|
||||
.onFocusChanged { focusState ->
|
||||
// hasFocus, not isFocused: BasicTextField focuses an internal child node, so this node is
|
||||
// never itself focused - only its subtree is. isFocused would never fire, and the click-away
|
||||
// commit below would never run.
|
||||
if (focusState.hasFocus) {
|
||||
hasFocused = true
|
||||
} else if (hasFocused) {
|
||||
// Clicking away commits, mirroring renaming a file in an explorer.
|
||||
commit()
|
||||
}
|
||||
}
|
||||
.onKeyEvent { event ->
|
||||
// Hardware Enter confirms (the soft-keyboard Done action is wired above). Escape is left for
|
||||
// the shell to route into cancel(), so it is deliberately not handled here.
|
||||
if (event.type == KeyEventType.KeyDown && (event.key == Key.Enter || event.key == Key.NumPadEnter)) {
|
||||
commit()
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.text.BasicTextField
|
||||
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 androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.focus.focusProperties
|
||||
import androidx.compose.ui.focus.onFocusChanged
|
||||
import androidx.compose.ui.geometry.CornerRadius
|
||||
import androidx.compose.ui.graphics.Path
|
||||
import androidx.compose.ui.graphics.SolidColor
|
||||
import androidx.compose.ui.graphics.drawscope.Stroke
|
||||
import androidx.compose.ui.platform.LocalFocusManager
|
||||
import androidx.compose.ui.text.TextRange
|
||||
import androidx.compose.ui.text.input.TextFieldValue
|
||||
import androidx.compose.ui.unit.dp
|
||||
import org.umamo.ui.model.KeyedFieldState
|
||||
import org.umamo.ui.model.tint
|
||||
import org.umamo.ui.theme.LocalUmamoColors
|
||||
import org.umamo.ui.theme.LocalUmamoShapes
|
||||
import org.umamo.ui.theme.LocalUmamoTypography
|
||||
|
||||
/**
|
||||
* A compact checkbox row: a small box (accent-filled with a checkmark when on, neutral when off) plus a
|
||||
* label, the whole row toggling [onCheckedChange]. A disabled row ignores clicks and dims - it still
|
||||
* shows its stored state, so a setting gated behind another one reads as "remembered but inert".
|
||||
*
|
||||
* @param Boolean checked Current state.
|
||||
* @param Function onCheckedChange Toggle callback.
|
||||
* @param String label The row label.
|
||||
* @param KeyedFieldState keyState The keyform state to tint the box's border with.
|
||||
* @param Boolean enabled Whether the row accepts clicks; false renders it dimmed.
|
||||
*/
|
||||
@Composable
|
||||
fun Checkbox(
|
||||
checked: Boolean,
|
||||
onCheckedChange: (Boolean) -> Unit,
|
||||
label: String,
|
||||
keyState: KeyedFieldState = KeyedFieldState.None,
|
||||
enabled: Boolean = true,
|
||||
) {
|
||||
val colors = LocalUmamoColors.current
|
||||
val interaction = remember { MutableInteractionSource() }
|
||||
val boxFill =
|
||||
when {
|
||||
checked && enabled -> colors.accent
|
||||
checked -> colors.controlBorder
|
||||
else -> colors.controlBackground
|
||||
}
|
||||
// The keyed tint replaces the box's ordinary border, the way HexColorField does it - a checkbox is
|
||||
// small enough that a second mark beside it would be the louder signal, not the quieter one.
|
||||
val boxBorder = keyState.tint(colors) ?: colors.controlBorder
|
||||
val checkColor = colors.accentText
|
||||
val labelColor = if (enabled) colors.text else colors.textDisabled
|
||||
Row(
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.height(22.dp)
|
||||
// NOT focusable, like SectionHeader: a toggle in transient chrome (the operation settings
|
||||
// strip) would otherwise carry focus out of the composition with it and strand the keyboard.
|
||||
.focusProperties { canFocus = false }
|
||||
.clickable(
|
||||
interactionSource = interaction,
|
||||
indication = null,
|
||||
enabled = enabled,
|
||||
onClick = { onCheckedChange(!checked) },
|
||||
)
|
||||
.padding(horizontal = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Canvas(modifier = Modifier.size(13.dp)) {
|
||||
val radius = CornerRadius(2.dp.toPx())
|
||||
drawRoundRect(color = boxFill, cornerRadius = radius)
|
||||
drawRoundRect(color = boxBorder, cornerRadius = radius, style = Stroke(1.dp.toPx()))
|
||||
if (checked) {
|
||||
val tick = Path()
|
||||
tick.moveTo(size.width * 0.22f, size.height * 0.52f)
|
||||
tick.lineTo(size.width * 0.42f, size.height * 0.72f)
|
||||
tick.lineTo(size.width * 0.78f, size.height * 0.28f)
|
||||
drawPath(tick, color = checkColor, style = Stroke(1.6.dp.toPx()))
|
||||
}
|
||||
}
|
||||
Spacer(modifier = Modifier.width(6.dp))
|
||||
Text(text = label, style = LocalUmamoTypography.current.labelMedium, color = labelColor)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A compact bordered text field wrapping Foundation's [BasicTextField] (which already handles cursor,
|
||||
* selection, and IME). Single line, tight padding. When [placeholder] is set it shows as dimmed hint
|
||||
* text while the field is empty.
|
||||
*
|
||||
* Like [NumberField], it lends a cancel hook to [LocalInlineEditController] while focused so the editor
|
||||
* shell's root key handler stops claiming keystrokes the field needs - notably Space (which otherwise
|
||||
* opens the command palette) and letter shortcuts - and routes Escape here (clearing focus) instead.
|
||||
*
|
||||
* @param String value The current text.
|
||||
* @param Function onValueChange Edit callback.
|
||||
* @param Modifier modifier Layout modifier.
|
||||
* @param String? placeholder Optional dimmed hint shown while the field is empty.
|
||||
* @param Function? trailing Optional control pinned inside the field's trailing edge (a clear
|
||||
* affordance, a unit label). It takes its width out of the text's, so it never overlaps the value.
|
||||
*/
|
||||
@Composable
|
||||
fun TextField(
|
||||
value: String,
|
||||
onValueChange: (String) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
placeholder: String? = null,
|
||||
trailing: (@Composable () -> Unit)? = null,
|
||||
) {
|
||||
val colors = LocalUmamoColors.current
|
||||
val shapes = LocalUmamoShapes.current
|
||||
val controller = LocalInlineEditController.current
|
||||
val focusManager = LocalFocusManager.current
|
||||
var focused by remember { mutableStateOf(false) }
|
||||
// Held as a TextFieldValue purely so the context menu can act on a selection; the public API stays
|
||||
// String-shaped, and the caret is re-pinned to the end whenever the caller replaces the text out from
|
||||
// under the field (a cleared search box, a reset).
|
||||
var fieldValue by remember { mutableStateOf(TextFieldValue(value, TextRange(value.length))) }
|
||||
if (fieldValue.text != value) {
|
||||
fieldValue = TextFieldValue(value, TextRange(value.length))
|
||||
}
|
||||
// Park the cancel hook only while focused; the shell checks it to yield Space / letters to the field
|
||||
// and to route Escape (clear focus) here. Drop it on focus loss and on dispose-while-focused.
|
||||
DisposableEffect(Unit) {
|
||||
onDispose {
|
||||
if (focused) {
|
||||
controller.cancel = null
|
||||
}
|
||||
}
|
||||
}
|
||||
val applyEdit: (TextFieldValue) -> Unit = { edited ->
|
||||
fieldValue = edited
|
||||
if (edited.text != value) {
|
||||
onValueChange(edited.text)
|
||||
}
|
||||
}
|
||||
TextEditContextMenuArea(value = fieldValue, onValueChange = applyEdit) { gesture ->
|
||||
BasicTextField(
|
||||
value = fieldValue,
|
||||
onValueChange = applyEdit,
|
||||
textStyle = LocalUmamoTypography.current.bodySmall.copy(color = colors.text),
|
||||
singleLine = true,
|
||||
cursorBrush = SolidColor(colors.text),
|
||||
modifier =
|
||||
gesture
|
||||
.then(modifier)
|
||||
.textEntrySurface(controller)
|
||||
.clip(shapes.small)
|
||||
.background(colors.controlBackground)
|
||||
.border(1.dp, colors.controlBorder, shapes.small)
|
||||
.padding(horizontal = 6.dp, vertical = 4.dp)
|
||||
.onFocusChanged { focusState ->
|
||||
// hasFocus (not isFocused): BasicTextField focuses an internal child, so this node only
|
||||
// ever sees its subtree's focus.
|
||||
if (focusState.hasFocus) {
|
||||
if (!focused) {
|
||||
focused = true
|
||||
controller.cancel = { focusManager.clearFocus() }
|
||||
}
|
||||
} else if (focused) {
|
||||
focused = false
|
||||
controller.cancel = null
|
||||
}
|
||||
},
|
||||
decorationBox = { innerTextField ->
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
// The weighted box IS the text viewport - BasicTextField scrolls the caret into THIS box - so
|
||||
// a trailing control takes its width out of the text's rather than sitting on top of it. An
|
||||
// overlaid control would hide the caret exactly when the value outgrows the field.
|
||||
Box(modifier = Modifier.weight(1f)) {
|
||||
// Overlay the placeholder behind the field's own text so it disappears as soon as the user types.
|
||||
if (placeholder != null && value.isEmpty()) {
|
||||
Text(text = placeholder, style = LocalUmamoTypography.current.bodySmall, color = colors.textMuted)
|
||||
}
|
||||
innerTextField()
|
||||
}
|
||||
if (trailing != null) {
|
||||
Spacer(modifier = Modifier.width(4.dp))
|
||||
trailing()
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.staticCompositionLocalOf
|
||||
|
||||
/**
|
||||
* A coordination seam between a control that is capturing the next key press (the keybindings editor's chord
|
||||
* chip) and a host that runs its own keyboard dispatch.
|
||||
*
|
||||
* The host's root key handler previews every key before the focused control sees it, so a capture cannot defend
|
||||
* itself: the host would take Escape for whatever overlay the control sits in and close it, where the control
|
||||
* means Escape to cancel the capture alone. This is narrower than [InlineEditController] on purpose. A text
|
||||
* field inside an overlay gives Escape to the overlay, which is what a rigger expects of a dialog; a capture is
|
||||
* an armed state that owns the WHOLE keyboard - any key may be the one being bound - so while one is live the
|
||||
* host stands aside entirely and the control's own handler decides every key, Escape included.
|
||||
*
|
||||
* A count rather than a flag: one control can end its capture in the same pass another begins, and the order
|
||||
* of those two must not leave the host thinking nothing is capturing.
|
||||
*/
|
||||
class KeyCaptureController {
|
||||
private var liveCaptures by mutableIntStateOf(0)
|
||||
|
||||
/** Whether a control is capturing key presses now. */
|
||||
val active: Boolean
|
||||
get() = liveCaptures > 0
|
||||
|
||||
/** Marks a capture as begun; pair every call with one [end]. */
|
||||
fun begin() {
|
||||
liveCaptures++
|
||||
}
|
||||
|
||||
/** Marks a capture as over, whether it bound a key or was cancelled. */
|
||||
fun end() {
|
||||
liveCaptures = (liveCaptures - 1).coerceAtLeast(0)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Supplies the [KeyCaptureController] a host shares with the capturing controls nested under it. Defaults to a
|
||||
* standalone instance, so a control used without a coordinating host still works - with no host previewing keys
|
||||
* there is nobody to stand aside.
|
||||
*/
|
||||
val LocalKeyCapture = staticCompositionLocalOf { KeyCaptureController() }
|
||||
@@ -0,0 +1,539 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.hoverable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.collectIsHoveredAsState
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.IntrinsicSize
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.compositionLocalOf
|
||||
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
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.layout.onSizeChanged
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.IntOffset
|
||||
import androidx.compose.ui.unit.IntRect
|
||||
import androidx.compose.ui.unit.IntSize
|
||||
import androidx.compose.ui.unit.LayoutDirection
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Popup
|
||||
import androidx.compose.ui.window.PopupPositionProvider
|
||||
import androidx.compose.ui.window.PopupProperties
|
||||
import kotlinx.coroutines.delay
|
||||
import org.jetbrains.compose.resources.stringResource
|
||||
import org.umamo.ui.resources.Res
|
||||
import org.umamo.ui.resources.search_hint
|
||||
import org.umamo.ui.theme.LocalUmamoColors
|
||||
import org.umamo.ui.theme.LocalUmamoShapes
|
||||
import org.umamo.ui.theme.LocalUmamoTypography
|
||||
import org.umamo.ui.theme.drawIcon
|
||||
import kotlin.math.max
|
||||
|
||||
/** How long the pointer may be off both a submenu row and its flyout before the flyout closes. */
|
||||
private const val SUBMENU_CLOSE_GRACE_MS = 180L
|
||||
|
||||
/** The guaranteed gap between a row's label and its trailing shortcut or submenu arrow. */
|
||||
private val ROW_TRAILING_GAP = 24.dp
|
||||
|
||||
/** Edge length of a row's leading icon, matching the kit's other 16.dp Canvas icons. */
|
||||
private val MENU_ICON_SIZE = 16.dp
|
||||
|
||||
/**
|
||||
* The breathing room kept between a menu and the window edge. A menu grows to the window minus this and
|
||||
* only then scrolls, so a long-but-fitting list (the blend modes) shows in full rather than being cut off.
|
||||
*/
|
||||
private val MENU_WINDOW_MARGIN = 16.dp
|
||||
|
||||
/** The shortest a menu is ever capped to, so a tiny window still shows a usable strip of rows. */
|
||||
private val MENU_MIN_HEIGHT = 96.dp
|
||||
|
||||
/** The cap used when a menu is measured unbounded (no window height to subtract from). */
|
||||
private val MENU_FALLBACK_MAX_HEIGHT = 360.dp
|
||||
|
||||
/** The inset a pinned search box keeps from the menu's edges, matching the rows' own. */
|
||||
private val MENU_SEARCH_INSET = 8.dp
|
||||
|
||||
/** The gap between a row's leading icon (or its reserved slot) and the label. */
|
||||
private val MENU_ICON_LABEL_GAP = 8.dp
|
||||
|
||||
/**
|
||||
* True while composing inside a popup that already owns the outside-click and Esc dismiss. Only one
|
||||
* popup in a tree may be focusable, so a popup opened from inside another one must not take focus and
|
||||
* fight it for the dismiss - the inner press would otherwise read as "outside" to the outer popup, which
|
||||
* would tear the inner one down mid-click. Popups that host arbitrary caller content (the overflow
|
||||
* dropdown, a filter panel) provide this so the menus and chips inside them yield automatically.
|
||||
*/
|
||||
val LocalPopupDismissOwned = compositionLocalOf { false }
|
||||
|
||||
/**
|
||||
* Notifies an ancestor submenu whether this branch still wants the parent flyout kept open. Each
|
||||
* submenu flyout is its own [Popup] window, so hovering a grandchild does not count as hovering the
|
||||
* parent's hoverable box - without this bridge a third-level flyout closes the parent after the grace
|
||||
* and tears itself down. Null at the root (nothing to notify).
|
||||
*/
|
||||
private val LocalSubmenuKeepOpen = compositionLocalOf<((Boolean) -> Unit)?> { null }
|
||||
|
||||
/**
|
||||
* A popup menu rendered from a [MenuItem] list - the one menu surface used across the menu bar, context
|
||||
* menus, and the area type selector. Styled to the kit's menu look: medium rounded corners, the dark
|
||||
* panel fill, no border, and no drop shadow. Hosted in a [Popup] so it escapes its parent's bounds,
|
||||
* positioned by [positionProvider]; a focusable root dismisses on an outside click or Esc via
|
||||
* [onDismissRequest]. Renders [MenuItem.Submenu] entries as nested flyouts that open on hover (desktop)
|
||||
* or tap (touch).
|
||||
*
|
||||
* @param List items The entries to render.
|
||||
* @param Function onDismissRequest Called to close the whole menu tree (outside click / Esc / selection).
|
||||
* @param PopupPositionProvider positionProvider Where the popup is placed relative to its anchor.
|
||||
* @param Modifier modifier Modifier for the menu's content column.
|
||||
* @param Boolean focusable Whether this popup owns focus and the dismiss - true for a root menu, false
|
||||
* for a nested submenu flyout (only one popup in the tree may be focusable, or they fight over focus).
|
||||
* Defaults to yielding whenever an enclosing popup already owns it (see [LocalPopupDismissOwned]).
|
||||
*/
|
||||
@Composable
|
||||
fun Menu(
|
||||
items: List<MenuItem>,
|
||||
onDismissRequest: () -> Unit,
|
||||
positionProvider: PopupPositionProvider,
|
||||
modifier: Modifier = Modifier,
|
||||
focusable: Boolean = !LocalPopupDismissOwned.current,
|
||||
) {
|
||||
Popup(
|
||||
popupPositionProvider = positionProvider,
|
||||
onDismissRequest = onDismissRequest,
|
||||
properties = PopupProperties(focusable = focusable),
|
||||
) {
|
||||
MenuPanel(items = items, dismissRoot = onDismissRequest, modifier = modifier)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The styled column of rows inside a [Menu]'s popup. Tracks which submenu (if any) is currently open so
|
||||
* exactly one flyout shows per level; [dismissRoot] is threaded down so selecting a leaf anywhere in the
|
||||
* tree tears the whole menu down. When any action row in this panel carries an icon, every row reserves
|
||||
* the icon slot so all labels share one column (Blender-style); each flyout is its own panel, so the
|
||||
* decision never leaks across nesting levels.
|
||||
*
|
||||
* A [MenuItem.Search] pins above the scrolling rows and fixes the panel to its width; without one the
|
||||
* panel hugs its widest row.
|
||||
*
|
||||
* @param List items The entries to render.
|
||||
* @param Function dismissRoot Closes the entire menu tree.
|
||||
* @param Modifier modifier Modifier for the column.
|
||||
*/
|
||||
@Composable
|
||||
private fun MenuPanel(items: List<MenuItem>, dismissRoot: () -> Unit, modifier: Modifier = Modifier) {
|
||||
val colors = LocalUmamoColors.current
|
||||
val density = LocalDensity.current
|
||||
var openSubmenuIndex by remember { mutableStateOf<Int?>(null) }
|
||||
val searches = items.filterIsInstance<MenuItem.Search>()
|
||||
val rows = items.filter { menuEntry -> menuEntry !is MenuItem.Search }
|
||||
val fixedWidth = searches.firstOrNull()?.width
|
||||
// A search menu caps its rows well under the window: a picker over a whole layer inventory would
|
||||
// otherwise stand as tall as the window, fit neither below nor above its chip, and open clamped to
|
||||
// the window's bottom edge - far from the chip - until a search shrank it back under the anchor.
|
||||
val searchRowsCap = searches.firstOrNull()?.maxRowsHeight
|
||||
val reserveIconSlot = rows.any { menuEntry -> menuEntry is MenuItem.Action && menuEntry.icon != null }
|
||||
val scrollState = rememberScrollState()
|
||||
// The pinned search's height, measured, so the row cap below leaves room for it: the rows' box is
|
||||
// still measured against the window height, not the height left under the search.
|
||||
var pinnedHeight by remember { mutableStateOf(0.dp) }
|
||||
Surface(color = colors.menuBackground, shape = LocalUmamoShapes.current.medium) {
|
||||
Column(modifier = if (fixedWidth != null) Modifier.width(fixedWidth) else Modifier) {
|
||||
if (searches.isNotEmpty()) {
|
||||
Column(modifier = Modifier.onSizeChanged { size -> pinnedHeight = with(density) { size.height.toDp() } }) {
|
||||
for (search in searches) {
|
||||
MenuSearchRow(search)
|
||||
}
|
||||
}
|
||||
}
|
||||
// A popup is measured against the window, so its incoming max height IS the window height: cap the
|
||||
// rows to that minus a margin and only then scroll. A long-but-fitting menu (the blend modes) shows
|
||||
// in full instead of being cut off at an arbitrary constant.
|
||||
BoxWithConstraints {
|
||||
val available = this@BoxWithConstraints.maxHeight
|
||||
val windowCap =
|
||||
if (available == Dp.Infinity) {
|
||||
MENU_FALLBACK_MAX_HEIGHT
|
||||
} else {
|
||||
(available - MENU_WINDOW_MARGIN - pinnedHeight).coerceAtLeast(MENU_MIN_HEIGHT)
|
||||
}
|
||||
val rowCap = if (searchRowsCap != null && searchRowsCap < windowCap) searchRowsCap else windowCap
|
||||
Box {
|
||||
// The cap and the scroll ride on an OUTER column so the row column below keeps measuring its
|
||||
// IntrinsicSize.Max width exactly as before - intrinsics are asked of that node, never
|
||||
// through the scrolling one. Under a search the width is the search's, and the rows fill it.
|
||||
Column(modifier = Modifier.heightIn(max = rowCap).verticalScroll(scrollState)) {
|
||||
val rowColumnWidth = if (fixedWidth != null) Modifier.fillMaxWidth() else Modifier.width(IntrinsicSize.Max)
|
||||
Column(modifier = modifier.then(rowColumnWidth).padding(vertical = 2.dp)) {
|
||||
rows.forEachIndexed { index, item ->
|
||||
when (item) {
|
||||
is MenuItem.Action ->
|
||||
MenuActionRow(
|
||||
item = item,
|
||||
reserveIconSlot = reserveIconSlot,
|
||||
onClick = {
|
||||
item.onSelect()
|
||||
dismissRoot()
|
||||
},
|
||||
)
|
||||
|
||||
is MenuItem.Separator -> MenuSeparatorRow()
|
||||
is MenuItem.Heading -> MenuHeadingRow(item)
|
||||
is MenuItem.Submenu ->
|
||||
MenuSubmenuRow(
|
||||
item = item,
|
||||
reserveIconSlot = reserveIconSlot,
|
||||
expanded = openSubmenuIndex == index,
|
||||
onRequestOpen = { openSubmenuIndex = index },
|
||||
onRequestClose = {
|
||||
if (openSubmenuIndex == index) {
|
||||
openSubmenuIndex = null
|
||||
}
|
||||
},
|
||||
dismissRoot = dismissRoot,
|
||||
)
|
||||
|
||||
is MenuItem.Search -> Unit
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// matchParentSize keeps the scrollbar a pure overlay: it fills its own box rather than the
|
||||
// popup's window-sized constraints, so it can no longer inflate the menu to full height.
|
||||
Box(modifier = Modifier.matchParentSize()) {
|
||||
VerticalScrollbarOverlay(scrollState)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The pinned search box: the kit [SearchField] at the panel's width less the row inset, focused as
|
||||
* soon as it composes so the menu opens ready to type into. Esc and a pick dismiss the menu as ever -
|
||||
* the popup owns both - and Compose hands focus back to whatever held it before the popup opened.
|
||||
*
|
||||
* @param MenuItem.Search item The search entry.
|
||||
*/
|
||||
@Composable
|
||||
private fun MenuSearchRow(item: MenuItem.Search) {
|
||||
val focusRequester = remember { FocusRequester() }
|
||||
SearchField(
|
||||
value = item.value,
|
||||
onValueChange = item.onValueChange,
|
||||
modifier = Modifier.padding(horizontal = MENU_SEARCH_INSET, vertical = 6.dp).focusRequester(focusRequester),
|
||||
width = item.width - MENU_SEARCH_INSET * 2,
|
||||
placeholder = item.placeholder ?: stringResource(Res.string.search_hint),
|
||||
)
|
||||
LaunchedEffect(focusRequester) {
|
||||
focusRequester.requestFocus()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A section heading: the same muted caption a filter panel heads its groups with, so a menu's file
|
||||
* names and a panel's section titles read as one thing. Inert, and outside the icon column.
|
||||
*
|
||||
* @param MenuItem.Heading item The heading entry.
|
||||
*/
|
||||
@Composable
|
||||
private fun MenuHeadingRow(item: MenuItem.Heading) {
|
||||
FilterSectionLabel(text = item.label)
|
||||
}
|
||||
|
||||
/**
|
||||
* One selectable menu row: an optional leading icon, the label, an optional shortcut hint right-aligned.
|
||||
* A disabled row is dimmed (icon included) and neither hovers nor clicks. An icon-less row in a panel
|
||||
* that reserves the slot indents its label to the shared column.
|
||||
*
|
||||
* @param MenuItem.Action item The row to render.
|
||||
* @param Boolean reserveIconSlot Whether icon-less rows indent to the panel's shared label column.
|
||||
* @param Function onClick Invoked when an enabled row is chosen.
|
||||
*/
|
||||
@Composable
|
||||
private fun MenuActionRow(item: MenuItem.Action, reserveIconSlot: Boolean, onClick: () -> Unit) {
|
||||
val colors = LocalUmamoColors.current
|
||||
val typography = LocalUmamoTypography.current
|
||||
val interaction = remember { MutableInteractionSource() }
|
||||
val hovered by interaction.collectIsHoveredAsState()
|
||||
val rowModifier =
|
||||
if (item.enabled) {
|
||||
Modifier.clickable(interactionSource = interaction, indication = null, onClick = onClick)
|
||||
} else {
|
||||
Modifier
|
||||
}
|
||||
Row(
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 4.dp, vertical = 1.dp)
|
||||
.then(rowModifier)
|
||||
.background(
|
||||
when {
|
||||
hovered && item.enabled -> colors.rowHover
|
||||
else -> Color.Transparent
|
||||
},
|
||||
shape = LocalUmamoShapes.current.small,
|
||||
)
|
||||
.padding(horizontal = 4.dp, vertical = 2.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
if (item.icon != null) {
|
||||
val iconTint = if (item.enabled) colors.text else colors.textMuted
|
||||
Canvas(modifier = Modifier.size(MENU_ICON_SIZE)) {
|
||||
drawIcon(item.icon, iconTint)
|
||||
}
|
||||
Spacer(modifier = Modifier.width(MENU_ICON_LABEL_GAP))
|
||||
} else if (reserveIconSlot) {
|
||||
Spacer(modifier = Modifier.width(MENU_ICON_SIZE + MENU_ICON_LABEL_GAP))
|
||||
}
|
||||
// One line, ellipsized, and the row's slack is the label's: a fixed-width menu (one with a search
|
||||
// box) must never wrap a long layer name, and the shortcut stays at the row's end. A hugging menu
|
||||
// is as wide as its widest row, so nothing changes there.
|
||||
Text(
|
||||
text = item.label,
|
||||
style = typography.labelMedium,
|
||||
color = if (item.enabled) colors.text else colors.textMuted,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
if (item.shortcut != null) {
|
||||
Spacer(modifier = Modifier.width(ROW_TRAILING_GAP))
|
||||
Text(text = item.shortcut, style = typography.labelSmall, color = colors.textMuted)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A separator rule between groups of rows, inset so it does not touch the menu's rounded corners. */
|
||||
@Composable
|
||||
private fun MenuSeparatorRow() {
|
||||
val colors = LocalUmamoColors.current
|
||||
Divider(modifier = Modifier.padding(horizontal = 8.dp, vertical = 2.dp), color = colors.guideLine)
|
||||
}
|
||||
|
||||
/**
|
||||
* A submenu row: label, a trailing arrow, and a nested flyout that opens to its right. On desktop the
|
||||
* flyout opens on hover and closes after a short grace once the pointer leaves the row, the flyout, and
|
||||
* every nested descendant flyout (so a diagonal move across the gap does not snap it shut, and a
|
||||
* third-level flyout does not tear its parent down - each flyout is its own popup window, so grandchild
|
||||
* hover is reported up via [LocalSubmenuKeepOpen]); on a touch screen, with no hover, tapping the row
|
||||
* toggles it. The flyout popup is non-focusable so the focusable root menu stays the sole owner of the
|
||||
* outside-click / Esc dismiss for the whole tree.
|
||||
*
|
||||
* @param MenuItem.Submenu item The submenu row.
|
||||
* @param Boolean reserveIconSlot Whether this row indents its label to the panel's shared label column.
|
||||
* @param Boolean expanded Whether this row's flyout is currently shown.
|
||||
* @param Function onRequestOpen Asks the panel to open this row's flyout (closing any sibling's).
|
||||
* @param Function onRequestClose Asks the panel to close this row's flyout.
|
||||
* @param Function dismissRoot Closes the entire menu tree (forwarded to the flyout).
|
||||
*/
|
||||
@Composable
|
||||
private fun MenuSubmenuRow(
|
||||
item: MenuItem.Submenu,
|
||||
reserveIconSlot: Boolean,
|
||||
expanded: Boolean,
|
||||
onRequestOpen: () -> Unit,
|
||||
onRequestClose: () -> Unit,
|
||||
dismissRoot: () -> Unit,
|
||||
) {
|
||||
val colors = LocalUmamoColors.current
|
||||
val typography = LocalUmamoTypography.current
|
||||
val rowInteraction = remember { MutableInteractionSource() }
|
||||
val rowHovered by rowInteraction.collectIsHoveredAsState()
|
||||
val flyoutInteraction = remember { MutableInteractionSource() }
|
||||
val flyoutHovered by flyoutInteraction.collectIsHoveredAsState()
|
||||
// A nested flyout is a separate Popup, so its hover never reaches [flyoutHovered]; descendants report
|
||||
// through LocalSubmenuKeepOpen so this row stays open while the pointer is in a grandchild.
|
||||
var descendantKeepOpen by remember { mutableStateOf(false) }
|
||||
val reportKeepOpenToParent = LocalSubmenuKeepOpen.current
|
||||
val keepOpen = rowHovered || flyoutHovered || descendantKeepOpen
|
||||
|
||||
// Open on hover (desktop only - touch never reports hover, so the row's clickable carries that there).
|
||||
LaunchedEffect(rowHovered) {
|
||||
if (rowHovered && item.enabled) {
|
||||
onRequestOpen()
|
||||
}
|
||||
}
|
||||
// Tell the ancestor whether this branch still wants it open (row, own flyout, or a nested flyout).
|
||||
LaunchedEffect(keepOpen) {
|
||||
reportKeepOpenToParent?.invoke(keepOpen)
|
||||
}
|
||||
DisposableEffect(reportKeepOpenToParent) {
|
||||
onDispose { reportKeepOpenToParent?.invoke(false) }
|
||||
}
|
||||
LaunchedEffect(expanded) {
|
||||
if (!expanded) {
|
||||
descendantKeepOpen = false
|
||||
}
|
||||
}
|
||||
// Close after a grace once neither the row, the flyout, nor any nested descendant is hovered,
|
||||
// re-checking after the delay so a diagonal move across the gap (or into a grandchild) keeps it open.
|
||||
LaunchedEffect(rowHovered, flyoutHovered, descendantKeepOpen) {
|
||||
if (!rowHovered && !flyoutHovered && !descendantKeepOpen) {
|
||||
delay(SUBMENU_CLOSE_GRACE_MS)
|
||||
if (!rowHovered && !flyoutHovered && !descendantKeepOpen) {
|
||||
onRequestClose()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// clickable feeds hover into rowInteraction (so rowHovered tracks the desktop pointer) and toggles the
|
||||
// flyout on tap (the touch path, where hover never fires).
|
||||
val rowModifier =
|
||||
if (item.enabled) {
|
||||
Modifier.clickable(indication = null, interactionSource = rowInteraction) {
|
||||
if (expanded) {
|
||||
onRequestClose()
|
||||
} else {
|
||||
onRequestOpen()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Modifier
|
||||
}
|
||||
Box {
|
||||
Row(
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 4.dp, vertical = 1.dp)
|
||||
.then(rowModifier)
|
||||
.background(
|
||||
when {
|
||||
((rowHovered || expanded) && item.enabled) -> colors.rowHover
|
||||
else -> Color.Transparent
|
||||
},
|
||||
shape = LocalUmamoShapes.current.small,
|
||||
)
|
||||
.padding(horizontal = 4.dp, vertical = 2.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
if (reserveIconSlot) {
|
||||
Spacer(modifier = Modifier.width(MENU_ICON_SIZE + MENU_ICON_LABEL_GAP))
|
||||
}
|
||||
Text(
|
||||
text = item.label,
|
||||
style = typography.labelMedium,
|
||||
color = if (item.enabled) colors.text else colors.textMuted,
|
||||
)
|
||||
Spacer(modifier = Modifier.weight(1f))
|
||||
Spacer(modifier = Modifier.width(ROW_TRAILING_GAP))
|
||||
Text(text = "▸", style = typography.labelMedium, color = colors.textMuted)
|
||||
}
|
||||
if (expanded) {
|
||||
Popup(
|
||||
popupPositionProvider = SubmenuPositionProvider,
|
||||
onDismissRequest = dismissRoot,
|
||||
properties = PopupProperties(focusable = false),
|
||||
) {
|
||||
// Descendants call this so hovering a nested flyout counts as keeping THIS flyout open.
|
||||
CompositionLocalProvider(
|
||||
LocalSubmenuKeepOpen provides { active -> descendantKeepOpen = active },
|
||||
) {
|
||||
Box(modifier = Modifier.hoverable(flyoutInteraction)) {
|
||||
MenuPanel(items = item.items, dismissRoot = dismissRoot)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Positions a popup at its anchor's bottom-left - a menu dropping straight down from its trigger (the
|
||||
* menu-bar label or the area type selector) - kept on screen: the left edge is clamped into the window,
|
||||
* and a menu that would overflow the bottom flips ABOVE its anchor instead, falling back to a clamped
|
||||
* position when it fits neither way (a menu taller than the window then starts at the top edge and
|
||||
* scrolls). Without this a long dropdown simply ran off the bottom and its tail was unreachable.
|
||||
*/
|
||||
internal object BelowAnchorPositionProvider : PopupPositionProvider {
|
||||
override fun calculatePosition(
|
||||
anchorBounds: IntRect,
|
||||
windowSize: IntSize,
|
||||
layoutDirection: LayoutDirection,
|
||||
popupContentSize: IntSize,
|
||||
): IntOffset {
|
||||
val left = anchorBounds.left.coerceIn(0, max(0, windowSize.width - popupContentSize.width))
|
||||
val fitsBelow = anchorBounds.bottom + popupContentSize.height <= windowSize.height
|
||||
val above = anchorBounds.top - popupContentSize.height
|
||||
val top =
|
||||
when {
|
||||
fitsBelow -> anchorBounds.bottom
|
||||
above >= 0 -> above
|
||||
else -> windowSize.height - popupContentSize.height
|
||||
}
|
||||
return IntOffset(left, top.coerceIn(0, max(0, windowSize.height - popupContentSize.height)))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Positions a submenu flyout flush to the right of its parent row, aligned with the row's top, flipping
|
||||
* to the row's left when a right-side flyout would overflow the window, and clamping the top so a tall
|
||||
* flyout near the window bottom stays on screen.
|
||||
*/
|
||||
private object SubmenuPositionProvider : PopupPositionProvider {
|
||||
override fun calculatePosition(
|
||||
anchorBounds: IntRect,
|
||||
windowSize: IntSize,
|
||||
layoutDirection: LayoutDirection,
|
||||
popupContentSize: IntSize,
|
||||
): IntOffset {
|
||||
val fitsRight = anchorBounds.right + popupContentSize.width <= windowSize.width
|
||||
val left =
|
||||
if (fitsRight) {
|
||||
anchorBounds.right
|
||||
} else {
|
||||
max(0, anchorBounds.left - popupContentSize.width)
|
||||
}
|
||||
val top = anchorBounds.top.coerceIn(0, max(0, windowSize.height - popupContentSize.height))
|
||||
return IntOffset(left, top)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Positions a popup at a point [localOffset] inside its anchor (the context-menu host), so the menu opens
|
||||
* at the cursor. The point is offset by the anchor's window origin and then clamped to keep the whole
|
||||
* menu on screen.
|
||||
*
|
||||
* @property IntOffset localOffset The cursor point relative to the anchor's top-left.
|
||||
*/
|
||||
internal class AtPointPositionProvider(private val localOffset: IntOffset) : PopupPositionProvider {
|
||||
override fun calculatePosition(
|
||||
anchorBounds: IntRect,
|
||||
windowSize: IntSize,
|
||||
layoutDirection: LayoutDirection,
|
||||
popupContentSize: IntSize,
|
||||
): IntOffset {
|
||||
val x = (anchorBounds.left + localOffset.x).coerceIn(0, max(0, windowSize.width - popupContentSize.width))
|
||||
val y = (anchorBounds.top + localOffset.y).coerceIn(0, max(0, windowSize.height - popupContentSize.height))
|
||||
return IntOffset(x, y)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.focusable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.collectIsHoveredAsState
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.staticCompositionLocalOf
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.input.key.Key
|
||||
import androidx.compose.ui.input.key.KeyEventType
|
||||
import androidx.compose.ui.input.key.key
|
||||
import androidx.compose.ui.input.key.onPreviewKeyEvent
|
||||
import androidx.compose.ui.input.key.type
|
||||
import androidx.compose.ui.unit.dp
|
||||
import org.umamo.ui.theme.LocalUmamoColors
|
||||
import org.umamo.ui.theme.LocalUmamoShapes
|
||||
import org.umamo.ui.theme.LocalUmamoTypography
|
||||
|
||||
/**
|
||||
* A tiny coordination seam between a [MenuBar] and a host that runs its own keyboard dispatch. While a
|
||||
* menu-bar menu is open the bar parks a close callback here; a host whose key handler would otherwise
|
||||
* claim Escape first (the editor shell's root onPreviewKeyEvent, where Escape is bound to a command)
|
||||
* pulls this and dismisses the menu before its own shortcut for that key fires. Holds null whenever no
|
||||
* menu-bar menu is open. Only a [MenuBar] should write it.
|
||||
*
|
||||
* MenuBar とホスト側のキー処理をつなぐ小さな仲介。メニューが開いている間だけ閉じる関数を預ける。
|
||||
*
|
||||
* @property Function closeOpenMenu Closes the currently open menu, or null when none is open.
|
||||
*/
|
||||
class MenuBarController {
|
||||
var closeOpenMenu: (() -> Unit)? by mutableStateOf(null)
|
||||
}
|
||||
|
||||
/**
|
||||
* Supplies the [MenuBarController] a host shares with its [MenuBar]. Defaults to a standalone instance
|
||||
* so a bar used without a coordinating host still works: it falls back to its own focus-based Escape
|
||||
* handling and to pointer dismissal (outside click / selection).
|
||||
*/
|
||||
val LocalMenuBarController = staticCompositionLocalOf { MenuBarController() }
|
||||
|
||||
/**
|
||||
* A horizontal strip of top-level menu labels (File, Help, …), each opening its [TopLevelMenu] as a
|
||||
* [Menu] dropped beneath it. Clicking a label toggles its menu; while any menu is open, hovering a
|
||||
* different label switches to it (the standard menu-bar behavior), so a user can sweep across the bar
|
||||
* without re-clicking. Built from kit [Menu]s, so it shares the menu look and works on desktop and
|
||||
* tablet alike - an in-window bar rather than a host-OS menu strip.
|
||||
*
|
||||
* The dropdowns open non-focusable so the host window keeps focus while a menu is open - a focusable
|
||||
* popup steals focus and the labels (which live in that now-unfocused window) stop receiving hover, so
|
||||
* the sweep-to-switch would silently never fire. That trade-off moves the keyboard dismiss onto the bar
|
||||
* itself: opening a menu pulls focus to the bar and Escape closes it (a host with its own key dispatch
|
||||
* coordinates through [LocalMenuBarController] instead); pointer dismissal (outside click / selection)
|
||||
* works regardless.
|
||||
*
|
||||
* 最上位メニューラベルの横帯。クリックで開閉、開いている間は他ラベルへのホバーで切り替わる。
|
||||
* ドロップダウンは非フォーカスで開き(フォーカスを奪うとラベルのホバーが効かなくなるため)、Esc は
|
||||
* バー自身が処理する。
|
||||
*
|
||||
* @param List menus The top-level menus in bar order.
|
||||
* @param Modifier modifier The layout modifier.
|
||||
*/
|
||||
@Composable
|
||||
fun MenuBar(menus: List<TopLevelMenu>, modifier: Modifier = Modifier) {
|
||||
var openIndex by remember { mutableStateOf<Int?>(null) }
|
||||
val focusRequester = remember { FocusRequester() }
|
||||
val closeMenu = remember { { openIndex = null } }
|
||||
val controller = LocalMenuBarController.current
|
||||
|
||||
// Opening a menu pulls keyboard focus to the bar so Escape can dismiss it: the dropdowns are
|
||||
// non-focusable (keeping the window focused so the labels keep receiving hover for the sweep below),
|
||||
// which leaves the bar itself to own the keyboard dismiss. Keyed on the open/closed transition, not
|
||||
// the index, so sweeping between menus does not re-request focus on every label change.
|
||||
LaunchedEffect(openIndex != null) {
|
||||
if (openIndex != null) {
|
||||
focusRequester.requestFocus()
|
||||
}
|
||||
}
|
||||
// While open, park the close callback on the shared controller so a host that dispatches keys ahead
|
||||
// of this bar (the editor shell claims Escape at its root before it ever reaches here) can dismiss
|
||||
// the menu first. Cleared on close and on disposal so a stale closer never lingers.
|
||||
DisposableEffect(openIndex, controller) {
|
||||
controller.closeOpenMenu = if (openIndex == null) null else closeMenu
|
||||
onDispose { controller.closeOpenMenu = null }
|
||||
}
|
||||
|
||||
Row(
|
||||
modifier =
|
||||
modifier
|
||||
.focusRequester(focusRequester)
|
||||
.focusable()
|
||||
.onPreviewKeyEvent { keyEvent ->
|
||||
if (openIndex != null && keyEvent.type == KeyEventType.KeyDown && keyEvent.key == Key.Escape) {
|
||||
closeMenu()
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
},
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
menus.forEachIndexed { index, menu ->
|
||||
MenuBarLabel(
|
||||
menu = menu,
|
||||
menuOpen = openIndex == index,
|
||||
anyMenuOpen = openIndex != null,
|
||||
onToggle = { openIndex = if (openIndex == index) null else index },
|
||||
onHoverSwitch = { openIndex = index },
|
||||
onDismiss = closeMenu,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One menu-bar label and the [Menu] it anchors. The popup is a child of this label's [Box], so Compose
|
||||
* hands the label's bounds to the below-anchor position provider and the menu drops under the label with
|
||||
* no manual coordinate capture. While a menu is already open elsewhere on the bar, hovering this label
|
||||
* switches the open menu to it.
|
||||
*
|
||||
* メニューバーの 1 ラベルとそれが開くメニュー。ポップアップはラベルの子なので真下に開く。
|
||||
*
|
||||
* @param TopLevelMenu menu The menu this label opens.
|
||||
* @param Boolean menuOpen Whether this label's menu is currently open.
|
||||
* @param Boolean anyMenuOpen Whether some label on the bar is open (enables hover-to-switch).
|
||||
* @param Function onToggle Toggles this label's menu open/closed (on click).
|
||||
* @param Function onHoverSwitch Switches the open menu to this label (on hover while another is open).
|
||||
* @param Function onDismiss Closes the open menu (outside click / Esc / selection).
|
||||
*/
|
||||
@Composable
|
||||
private fun MenuBarLabel(
|
||||
menu: TopLevelMenu,
|
||||
menuOpen: Boolean,
|
||||
anyMenuOpen: Boolean,
|
||||
onToggle: () -> Unit,
|
||||
onHoverSwitch: () -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
val colors = LocalUmamoColors.current
|
||||
val interaction = remember { MutableInteractionSource() }
|
||||
val hovered by interaction.collectIsHoveredAsState()
|
||||
// Sweeping the bar: once one menu is open, moving the pointer over another label opens that one.
|
||||
LaunchedEffect(hovered) {
|
||||
if (hovered && anyMenuOpen && !menuOpen) {
|
||||
onHoverSwitch()
|
||||
}
|
||||
}
|
||||
Box {
|
||||
Row(
|
||||
modifier =
|
||||
Modifier
|
||||
.clickable(interactionSource = interaction, indication = null, onClick = onToggle)
|
||||
.background(
|
||||
color = if (menuOpen || hovered) colors.accent else Color.Transparent,
|
||||
shape = LocalUmamoShapes.current.medium,
|
||||
)
|
||||
.padding(horizontal = 10.dp, vertical = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
text = menu.label,
|
||||
style = LocalUmamoTypography.current.labelMedium,
|
||||
color = if (menuOpen || hovered) colors.accentText else colors.text,
|
||||
)
|
||||
}
|
||||
if (menuOpen) {
|
||||
// Non-focusable so the host window keeps focus and the bar keeps receiving hover (the
|
||||
// sweep-to-switch above): a focusable popup would starve the labels of hover events. The
|
||||
// keyboard dismiss is owned by the bar / its host instead; outside-click dismissal still
|
||||
// routes through onDismissRequest regardless of focusability.
|
||||
Menu(
|
||||
items = menu.items,
|
||||
onDismissRequest = onDismiss,
|
||||
positionProvider = BelowAnchorPositionProvider,
|
||||
focusable = false,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import org.umamo.ui.theme.UmamoIcon
|
||||
|
||||
/**
|
||||
* How tall a search menu's rows grow before they scroll, unless its [MenuItem.Search] says otherwise.
|
||||
* A picker over a document's whole layer inventory would otherwise take the general rule - rows up to
|
||||
* the window's height - and a menu that tall fits neither below nor above its chip, so the popup is
|
||||
* clamped to the window's bottom edge and opens far from the chip until a search shrinks it.
|
||||
*/
|
||||
val MENU_SEARCH_ROWS_MAX_HEIGHT: Dp = 320.dp
|
||||
|
||||
/**
|
||||
* One entry in a [Menu]: a clickable action, a nested submenu, a separator, a section heading, or a
|
||||
* search box. This is a data model, not a Compose slot DSL - a caller builds a List<MenuItem>
|
||||
* (resolving localized chrome via stringResource at the call site and passing user data such as file
|
||||
* names verbatim) and one renderer draws every menu identically across the menu bar, context menus,
|
||||
* the area type selector, and the searchable pickers.
|
||||
*
|
||||
* The label is a plain String rather than a StringResource because menus mix localized chrome ("Open")
|
||||
* with user data (a recent-file name, a space title) that has no StringResource; the call site resolves
|
||||
* the chrome and supplies the data. An [Action] carries an onSelect lambda rather than a command id
|
||||
* because not every item is command-bound (the area selector emits an AreaCommand, a recent-file row
|
||||
* calls open(path), Exit calls onExit); command binding layers on top via commandMenuItem(...).
|
||||
*
|
||||
* メニュー 1 項目。アクション・入れ子サブメニュー・区切りのいずれか。スロット DSL ではなくデータ。
|
||||
*/
|
||||
sealed interface MenuItem {
|
||||
/**
|
||||
* A selectable row: an optional leading [icon], the [label], an optional [shortcut] accelerator
|
||||
* right-aligned, running [onSelect] on click. A disabled row renders dimmed and neither hovers nor
|
||||
* responds to a click. When any sibling row in the same panel carries an icon, icon-less rows indent
|
||||
* their label to the same column so labels stay aligned.
|
||||
*
|
||||
* 選択可能な行。任意の先頭アイコン、ラベル、右に任意のショートカット、クリックで onSelect を実行する。
|
||||
*
|
||||
* @property String label The display text (already-resolved chrome or user data).
|
||||
* @property Function onSelect Invoked when the row is chosen.
|
||||
* @property String? shortcut The right-aligned accelerator hint (e.g. "Ctrl+O"), or null for none.
|
||||
* @property Boolean enabled Whether the row is interactive.
|
||||
* @property UmamoIcon? icon The leading glyph, or null for a text-only row.
|
||||
*/
|
||||
data class Action(
|
||||
val label: String,
|
||||
val onSelect: () -> Unit,
|
||||
val shortcut: String? = null,
|
||||
val enabled: Boolean = true,
|
||||
val icon: UmamoIcon? = null,
|
||||
) : MenuItem
|
||||
|
||||
/**
|
||||
* A row that opens a nested flyout of [items], marked with a trailing arrow. On desktop the flyout
|
||||
* opens on hover; on a touch screen (no hover) it opens on tap. A disabled submenu cannot open.
|
||||
*
|
||||
* ホバー(デスクトップ)またはタップ(タッチ)で入れ子フライアウトを開く行。矢印付き。
|
||||
*
|
||||
* @property String label The display text.
|
||||
* @property List items The submenu entries.
|
||||
* @property Boolean enabled Whether the submenu can be opened.
|
||||
*/
|
||||
data class Submenu(
|
||||
val label: String,
|
||||
val items: List<MenuItem>,
|
||||
val enabled: Boolean = true,
|
||||
) : MenuItem
|
||||
|
||||
/** A horizontal rule separating groups of rows. */
|
||||
data object Separator : MenuItem
|
||||
|
||||
/**
|
||||
* A muted caption over the rows that follow it - a file name over its layers, a group's title over
|
||||
* its entries. Inert: it neither hovers nor clicks nor dismisses, and it ignores the icon column the
|
||||
* action rows share. One line, ellipsized, because a heading naming a document object (an artwork
|
||||
* file) can be arbitrarily long and must not widen the menu the rows beneath it are sized for.
|
||||
*
|
||||
* @property String label The heading text.
|
||||
*/
|
||||
data class Heading(
|
||||
val label: String,
|
||||
) : MenuItem
|
||||
|
||||
/**
|
||||
* A search box pinned above the rows, taking focus when the menu opens so typing starts at once.
|
||||
* The menu does no filtering: the caller keeps the query, filters the rows it passes, and hands the
|
||||
* query back here - the model stays a plain list, and the ranking rule (a name match, a whole file
|
||||
* when the file name matches, the palette's ranker) stays where the data is. One per menu, listed
|
||||
* first; the panel pins every Search item above the rows whatever its position.
|
||||
*
|
||||
* The menu takes [width] as its own, fixed: a search menu that re-hugged its widest surviving row
|
||||
* would resize under the user's hands on every keystroke. Its rows scroll past [maxRowsHeight], a
|
||||
* cap well under the window so the menu stays anchored under its chip however long the unfiltered
|
||||
* list is (see [MENU_SEARCH_ROWS_MAX_HEIGHT]).
|
||||
*
|
||||
* @property String value The current query.
|
||||
* @property Function onValueChange Takes the edited query; the clear affordance reports an empty string.
|
||||
* @property Dp width The menu's width, which the box fills less the row inset.
|
||||
* @property String? placeholder The dimmed hint while the query is empty, or null for the kit's default.
|
||||
* @property Dp maxRowsHeight How tall the rows grow before they scroll.
|
||||
*/
|
||||
data class Search(
|
||||
val value: String,
|
||||
val onValueChange: (String) -> Unit,
|
||||
val width: Dp,
|
||||
val placeholder: String? = null,
|
||||
val maxRowsHeight: Dp = MENU_SEARCH_ROWS_MAX_HEIGHT,
|
||||
) : MenuItem
|
||||
}
|
||||
|
||||
/**
|
||||
* One top-level menu-bar entry: a [label] (File, Help, …) that opens [items] as a [Menu] dropped
|
||||
* beneath it.
|
||||
*
|
||||
* メニューバーの最上位項目。ラベルをクリックすると items を真下にメニューとして開く。
|
||||
*
|
||||
* @property String label The menu-bar label.
|
||||
* @property List items The menu opened beneath the label.
|
||||
*/
|
||||
data class TopLevelMenu(
|
||||
val label: String,
|
||||
val items: List<MenuItem>,
|
||||
)
|
||||
@@ -0,0 +1,69 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import org.jetbrains.compose.resources.stringResource
|
||||
import org.umamo.ui.kit.button.Button
|
||||
import org.umamo.ui.resources.Res
|
||||
import org.umamo.ui.resources.dialog_okay
|
||||
import org.umamo.ui.theme.LocalUmamoColors
|
||||
import org.umamo.ui.theme.LocalUmamoShapes
|
||||
import org.umamo.ui.theme.LocalUmamoTypography
|
||||
|
||||
/**
|
||||
* A minimal modal message dialog: a scrim over the whole shell with a small centered card carrying the
|
||||
* [message] and a single OK button - [ConfirmDialog]'s one-button sibling for alerts that only inform
|
||||
* (a failed file open, a rejected import). Presentation-only and shell-agnostic: the caller owns the
|
||||
* visible state and supplies [onDismiss]. Clicking the scrim, like OK, dismisses; the card swallows
|
||||
* clicks so a press inside it does not count as a scrim dismissal.
|
||||
*
|
||||
* @param String message The already-localized message shown in the card.
|
||||
* @param Function onDismiss Called when the user dismisses (OK button or scrim click).
|
||||
* @param Modifier modifier Layout modifier for the scrim.
|
||||
*/
|
||||
@Composable
|
||||
fun MessageDialog(
|
||||
message: String,
|
||||
onDismiss: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val colors = LocalUmamoColors.current
|
||||
Box(
|
||||
// indication = null (the kit convention): a bare clickable renders the default hover/press
|
||||
// indication across the whole scrim, a stray dimming layer that toggles on pointer enter/leave.
|
||||
modifier =
|
||||
modifier
|
||||
.fillMaxSize()
|
||||
.background(colors.overlayScrim)
|
||||
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = onDismiss),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Surface(
|
||||
// The card swallows clicks (enabled = false) so a press on it is not read as a scrim dismissal.
|
||||
modifier = Modifier.widthIn(min = 180.dp, max = 420.dp).clickable(enabled = false, onClick = {}),
|
||||
color = colors.panelBackground,
|
||||
shape = LocalUmamoShapes.current.medium,
|
||||
border = BorderStroke(1.dp, colors.panelBorder),
|
||||
shadowElevation = 8.dp,
|
||||
) {
|
||||
Column(modifier = Modifier.padding(20.dp)) {
|
||||
Text(text = message, style = LocalUmamoTypography.current.bodyMedium)
|
||||
Box(modifier = Modifier.padding(top = 20.dp).align(Alignment.End)) {
|
||||
Button(label = stringResource(Res.string.dialog_okay), onClick = onDismiss, primary = true)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,633 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
|
||||
import androidx.compose.foundation.gestures.detectTapGestures
|
||||
import androidx.compose.foundation.hoverable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.collectIsHoveredAsState
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.text.BasicTextField
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.focus.onFocusChanged
|
||||
import androidx.compose.ui.geometry.Size
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.Shape
|
||||
import androidx.compose.ui.graphics.SolidColor
|
||||
import androidx.compose.ui.input.key.Key
|
||||
import androidx.compose.ui.input.key.KeyEventType
|
||||
import androidx.compose.ui.input.key.key
|
||||
import androidx.compose.ui.input.key.onKeyEvent
|
||||
import androidx.compose.ui.input.key.type
|
||||
import androidx.compose.ui.input.pointer.PointerIcon
|
||||
import androidx.compose.ui.input.pointer.pointerHoverIcon
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.platform.LocalFocusManager
|
||||
import androidx.compose.ui.text.TextRange
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.TextFieldValue
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import org.umamo.ui.model.KeyedFieldState
|
||||
import org.umamo.ui.model.backgroundTint
|
||||
import org.umamo.ui.theme.LocalUmamoColors
|
||||
import org.umamo.ui.theme.LocalUmamoCursors
|
||||
import org.umamo.ui.theme.LocalUmamoIcons
|
||||
import org.umamo.ui.theme.LocalUmamoShapes
|
||||
import org.umamo.ui.theme.LocalUmamoTypography
|
||||
import org.umamo.ui.theme.UmamoIcon
|
||||
import org.umamo.ui.theme.drawIcon
|
||||
import org.umamo.ui.theme.umamoPointerIcon
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/** The alpha applied to the accent tint when a bounded field draws its left-to-right magnitude fill. */
|
||||
private const val NUMBER_FIELD_FILL_ALPHA = 0.30f
|
||||
|
||||
/**
|
||||
* The field's fixed height, shared with the other inline form controls via [FIELD_CONTROL_HEIGHT] so a
|
||||
* NumberField and a SelectField line up. Pinned (rather than content-driven) so the display and type-in
|
||||
* faces do not jump when swapping, and so the edge chevrons' fillMaxHeight has a bounded constraint to fill
|
||||
* - a scroll container hands children an unbounded max height, under which fillMaxHeight collapses to the
|
||||
* glyph. With no vertical padding on the inner content, the box's fixed height plus center alignment
|
||||
* position the single text line, so the glyph is never clipped by a competing content height.
|
||||
*/
|
||||
private val NUMBER_FIELD_HEIGHT = FIELD_CONTROL_HEIGHT
|
||||
|
||||
/**
|
||||
* A compact numeric field for a scalar [value], clamped to [range]. Blender-style: the field shows the
|
||||
* value while idle; a quick click enters type-in mode; a horizontal drag past the touch slop scrubs the
|
||||
* value (previewed live, committed once on release); hovering reveals decrement / increment chevrons that
|
||||
* step by [step]. When [range] is a usable finite span a left-to-right magnitude fill tracks where the
|
||||
* value sits in it. Commits (type-in confirm, chevron step, drag release) each fire [onValueChange] once
|
||||
* with the value rounded to [decimals] places and clamped to [range]; a whole scrub is one commit, so a
|
||||
* caller can treat it as one undo step.
|
||||
*
|
||||
* 数値入力欄。クリックで入力、ドラッグでスクラブ、ホバーで増減シェブロン。範囲が有限なら塗りで大きさを示す。
|
||||
*
|
||||
* @param Float value The current value, shown when not being edited.
|
||||
* @param Function onValueChange Called with the committed value (rounded to [decimals] and clamped to [range]).
|
||||
* @param ClosedFloatingPointRange range The min..max the committed value is clamped to (an infinite endpoint = unbounded, no fill).
|
||||
* @param Modifier modifier Layout modifier (the caller supplies the width).
|
||||
* @param Int decimals The fractional places shown; the stored value is rounded to the same (Float-capped).
|
||||
* @param Float step The increment for a chevron press and the scrub sensitivity.
|
||||
* @param String? unitSuffix An optional trailing unit shown in the idle field (e.g. "px", "%"); never in the edit text.
|
||||
* @param Boolean showFill Whether to draw the magnitude fill when the range is bounded (off for wide sanity clamps).
|
||||
* @param Boolean plain When true, renders a bare type-in box only (no scrub, chevrons, or fill) - the simple field.
|
||||
* @param Boolean enabled When false the value still shows but dimmed, and every edit path is inert.
|
||||
* @param StackPosition stackPosition This field's position in a vertical stack (corner rounding + seam).
|
||||
* @param KeyedFieldState keyState The keyform state to tint the field's background fill with.
|
||||
* @param Function? onPreview Called with each in-flight value while the field is being drag-scrubbed.
|
||||
*/
|
||||
@Composable
|
||||
fun NumberField(
|
||||
value: Float,
|
||||
onValueChange: (Float) -> Unit,
|
||||
range: ClosedFloatingPointRange<Float>,
|
||||
modifier: Modifier = Modifier,
|
||||
decimals: Int = 2,
|
||||
step: Float = 1f,
|
||||
unitSuffix: String? = null,
|
||||
showFill: Boolean = true,
|
||||
plain: Boolean = false,
|
||||
enabled: Boolean = true,
|
||||
stackPosition: StackPosition = StackPosition.Single,
|
||||
keyState: KeyedFieldState = KeyedFieldState.None,
|
||||
onPreview: ((Float) -> Unit)? = null,
|
||||
) {
|
||||
val bounded = showFill && range.start.isFinite() && range.endInclusive.isFinite() && range.endInclusive > range.start
|
||||
NumberFieldCore(
|
||||
keyState = keyState,
|
||||
value = value,
|
||||
range = range,
|
||||
step = step,
|
||||
bounded = bounded,
|
||||
format = { toFormat -> formatDecimals(toFormat, decimals) },
|
||||
parse = { typed -> typed.trim().toFloatOrNull() },
|
||||
onCommit = { raw -> onValueChange(roundToDecimals(raw, decimals).coerceIn(range.start, range.endInclusive)) },
|
||||
onPreview =
|
||||
onPreview?.let { preview ->
|
||||
{ raw: Float -> preview(roundToDecimals(raw, decimals).coerceIn(range.start, range.endInclusive)) }
|
||||
},
|
||||
modifier = modifier,
|
||||
unitSuffix = unitSuffix,
|
||||
plain = plain,
|
||||
enabled = enabled,
|
||||
stackPosition = stackPosition,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Integer variant of [NumberField]: shows and commits a whole number (a typed decimal or non-number is
|
||||
* rejected). Same Blender-style interaction - click to type, drag to scrub, hover chevrons - stepping by
|
||||
* [step]. The magnitude fill draws only for a genuinely bounded range: a half-open sanity clamp such as
|
||||
* `0..Int.MAX_VALUE` reads as unbounded and shows no fill.
|
||||
*
|
||||
* 整数版の数値入力欄。クリックで入力、ドラッグでスクラブ、ホバーで増減。両端が有限のときだけ塗りを描く。
|
||||
*
|
||||
* @param Int value The current value, shown when not being edited.
|
||||
* @param Function onValueChange Called with the committed value (clamped to [range]).
|
||||
* @param IntRange range The min..max the committed value is clamped to.
|
||||
* @param Modifier modifier Layout modifier (the caller supplies the width).
|
||||
* @param Int step The increment for a chevron press and the scrub sensitivity.
|
||||
* @param String? unitSuffix An optional trailing unit shown in the idle field; never in the edit text.
|
||||
* @param Boolean showFill Whether to draw the magnitude fill when the range is bounded.
|
||||
* @param Boolean plain When true, renders a bare type-in box only (the simple field).
|
||||
* @param Boolean enabled When false the value still shows but dimmed, and every edit path is inert.
|
||||
* @param StackPosition stackPosition This field's position in a vertical stack (corner rounding + seam).
|
||||
* @param KeyedFieldState keyState The keyform state to tint the field's background fill with.
|
||||
* @param Function? onPreview Called with each in-flight value while the field is being drag-scrubbed.
|
||||
*/
|
||||
@Composable
|
||||
fun NumberField(
|
||||
value: Int,
|
||||
onValueChange: (Int) -> Unit,
|
||||
range: IntRange,
|
||||
modifier: Modifier = Modifier,
|
||||
step: Int = 1,
|
||||
unitSuffix: String? = null,
|
||||
showFill: Boolean = true,
|
||||
plain: Boolean = false,
|
||||
enabled: Boolean = true,
|
||||
stackPosition: StackPosition = StackPosition.Single,
|
||||
keyState: KeyedFieldState = KeyedFieldState.None,
|
||||
onPreview: ((Int) -> Unit)? = null,
|
||||
) {
|
||||
val floatRange = range.first.toFloat()..range.last.toFloat()
|
||||
// A whole-domain endpoint means "unbounded", so a plain int clamp such as 0..Int.MAX_VALUE draws no fill.
|
||||
val bounded = showFill && range.first > Int.MIN_VALUE && range.last < Int.MAX_VALUE
|
||||
NumberFieldCore(
|
||||
keyState = keyState,
|
||||
onPreview =
|
||||
onPreview?.let { preview ->
|
||||
{ raw: Float -> preview(raw.roundToInt().coerceIn(range.first, range.last)) }
|
||||
},
|
||||
value = value.toFloat(),
|
||||
range = floatRange,
|
||||
step = step.toFloat(),
|
||||
bounded = bounded,
|
||||
format = { toFormat -> toFormat.roundToInt().toString() },
|
||||
parse = { typed -> typed.trim().toIntOrNull()?.toFloat() },
|
||||
onCommit = { raw -> onValueChange(raw.roundToInt().coerceIn(range.first, range.last)) },
|
||||
modifier = modifier,
|
||||
unitSuffix = unitSuffix,
|
||||
plain = plain,
|
||||
enabled = enabled,
|
||||
stackPosition = stackPosition,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The shared engine behind both [NumberField] overloads, working in Float and delegating type-specific
|
||||
* formatting / parsing / rounding to the overload via [format], [parse], and [onCommit]. Holds the two
|
||||
* interaction states: a display face (tap to edit, drag to scrub, hover chevrons, magnitude fill) and the
|
||||
* type-in editor swapped in while editing. A scrub previews locally (nothing commits per frame) and
|
||||
* commits once on release; [plain] skips straight to a bare type-in box.
|
||||
*
|
||||
* @param Float value The current value (the source of truth while idle).
|
||||
* @param ClosedFloatingPointRange range The clamp range.
|
||||
* @param Float step The chevron / scrub increment.
|
||||
* @param Boolean bounded Whether to draw the magnitude fill (a usable finite range).
|
||||
* @param Function format Formats a value for display and for seeding the editor.
|
||||
* @param Function parse Parses typed text to a raw value, or null when unparseable.
|
||||
* @param Function onCommit Rounds / clamps a raw value and fires the caller's callback (one committed edit).
|
||||
* @param Modifier modifier Layout modifier (the width).
|
||||
* @param String? unitSuffix The idle trailing unit, or null.
|
||||
* @param Boolean plain Whether to render the bare type-in box only.
|
||||
* @param Boolean enabled Whether the field accepts edits at all.
|
||||
* @param StackPosition stackPosition The field's position in a vertical stack.
|
||||
* @param KeyedFieldState keyState The keyform state to tint the field's background fill with.
|
||||
* @param Function? onPreview Called with each in-flight value while the field is being drag-scrubbed.
|
||||
*/
|
||||
@Composable
|
||||
private fun NumberFieldCore(
|
||||
value: Float,
|
||||
range: ClosedFloatingPointRange<Float>,
|
||||
step: Float,
|
||||
bounded: Boolean,
|
||||
format: (Float) -> String,
|
||||
parse: (String) -> Float?,
|
||||
onCommit: (Float) -> Unit,
|
||||
modifier: Modifier,
|
||||
unitSuffix: String?,
|
||||
plain: Boolean,
|
||||
enabled: Boolean,
|
||||
stackPosition: StackPosition,
|
||||
keyState: KeyedFieldState = KeyedFieldState.None,
|
||||
onPreview: ((Float) -> Unit)? = null,
|
||||
) {
|
||||
val shapes = LocalUmamoShapes.current
|
||||
val shape = stackedShape(shapes.small, stackPosition, StackAxis.Vertical)
|
||||
// Parses typed text, clamps to the range, and commits; an unparseable entry does nothing.
|
||||
val commitTyped: (String) -> Unit = { typed ->
|
||||
parse(typed)?.let { parsed -> onCommit(parsed.coerceIn(range.start, range.endInclusive)) }
|
||||
}
|
||||
|
||||
if (plain) {
|
||||
// The simple field: a bare type-in box, matching the pre-upgrade behavior (no scrub / chevrons / fill).
|
||||
// Disabled, it degrades to the same inert display face the rich field uses, so both faces read alike.
|
||||
if (enabled) {
|
||||
NumberEntryField(
|
||||
display = format(value),
|
||||
shape = shape,
|
||||
modifier = modifier,
|
||||
keyState = keyState,
|
||||
commit = commitTyped,
|
||||
)
|
||||
} else {
|
||||
NumberFieldDisplay(
|
||||
text = format(value),
|
||||
unitSuffix = unitSuffix,
|
||||
fillFraction = null,
|
||||
shape = shape,
|
||||
modifier = modifier,
|
||||
enabled = false,
|
||||
keyState = keyState,
|
||||
)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
var editing by remember { mutableStateOf(false) }
|
||||
// The live scrub value while a drag is in flight (null when idle); previews without committing per frame.
|
||||
var dragValue by remember { mutableStateOf<Float?>(null) }
|
||||
// The value the drag STARTED from. scrubValue maps a TOTAL pointer delta onto a fixed base, so the base
|
||||
// has to stay fixed: reading the live `value` instead would compound the movement, because onPreview feeds
|
||||
// each frame's value straight back in through the pending buffer, accelerating the scrub and forcing a
|
||||
// reversed drag to spend its first stretch merely unwinding the drift.
|
||||
var scrubStartValue by remember { mutableStateOf(0f) }
|
||||
|
||||
// Being disabled ENDS an in-flight edit rather than parking it: leaving `editing` set would re-open the
|
||||
// type-in box - autoFocus and all - the moment the field became editable again, stealing focus for an
|
||||
// edit the user abandoned long ago. A scrub preview is dropped for the same reason.
|
||||
if (!enabled && (editing || dragValue != null)) {
|
||||
editing = false
|
||||
dragValue = null
|
||||
}
|
||||
|
||||
if (editing && enabled) {
|
||||
NumberEntryField(
|
||||
display = format(value),
|
||||
shape = shape,
|
||||
modifier = modifier,
|
||||
autoFocus = true,
|
||||
onFocusLost = { editing = false },
|
||||
keyState = keyState,
|
||||
commit = commitTyped,
|
||||
)
|
||||
} else {
|
||||
val shown = dragValue ?: value
|
||||
NumberFieldDisplay(
|
||||
text = format(shown),
|
||||
unitSuffix = unitSuffix,
|
||||
fillFraction = if (bounded) numberFieldFillFraction(shown, range.start, range.endInclusive) else null,
|
||||
shape = shape,
|
||||
modifier = modifier,
|
||||
enabled = enabled,
|
||||
onTapToEdit = { editing = true },
|
||||
onScrubStart = {
|
||||
scrubStartValue = value
|
||||
dragValue = value
|
||||
},
|
||||
onScrub = { totalDeltaPx ->
|
||||
val scrubbed = scrubValue(scrubStartValue, totalDeltaPx, step, range)
|
||||
dragValue = scrubbed
|
||||
// Reported live so the caller can drive whatever the value affects while the drag is still
|
||||
// happening. Without it a scrub moves the number and nothing else until release, which
|
||||
// reads as the edit not working - the field is the only thing that responds.
|
||||
onPreview?.invoke(scrubbed)
|
||||
},
|
||||
onScrubEnd = {
|
||||
dragValue?.let { finalValue -> onCommit(finalValue) }
|
||||
dragValue = null
|
||||
},
|
||||
onStep = { direction -> onCommit((value + direction * step).coerceIn(range.start, range.endInclusive)) },
|
||||
// Forwarded on the RESTING face, the one every real field shows: this is the background tint that
|
||||
// warns a typed value is unkeyed and dies on the next scrub, so every enabled field must carry it,
|
||||
// not only the disabled-plain display path.
|
||||
keyState = keyState,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The idle display face of a [NumberField]: a box showing [text] (plus an optional [unitSuffix]) over a
|
||||
* left-to-right accent magnitude fill, with decrement / increment chevrons that fade in on hover.
|
||||
* A quick tap enters type-in mode ([onTapToEdit]); a horizontal drag past the touch slop scrubs
|
||||
* ([onScrubStart] / [onScrub] with the total delta from the gesture start / [onScrubEnd]). The two
|
||||
* pointer handlers are separate inputs like [Slider], and callbacks are read through
|
||||
* [rememberUpdatedState] so a reused row slot always drives the current field.
|
||||
*
|
||||
* @param String text The formatted value to show.
|
||||
* @param String? unitSuffix An optional trailing unit, or null.
|
||||
* @param Float? fillFraction The magnitude fill in 0..1, or null for no fill.
|
||||
* @param Shape shape The field's (stack-aware) corner shape.
|
||||
* @param Modifier modifier Layout modifier (the width).
|
||||
* @param Boolean enabled When false the text dims and NO edit affordance is attached - no scrub cursor, no
|
||||
* pointer handlers, no hover chevrons - so a disabled field cannot be interacted with by any route.
|
||||
* @param Function onTapToEdit Enters type-in mode (a click that did not become a drag).
|
||||
* @param Function onScrubStart Begins a scrub gesture.
|
||||
* @param Function onScrub Reports the total horizontal drag delta from the gesture start, in pixels.
|
||||
* @param Function onScrubEnd Ends the scrub (commit the previewed value).
|
||||
* @param Function onStep Steps the value by a chevron press (-1 or +1).
|
||||
* @param KeyedFieldState keyState The keyform state to tint the field's background fill with.
|
||||
*/
|
||||
@Composable
|
||||
private fun NumberFieldDisplay(
|
||||
text: String,
|
||||
unitSuffix: String?,
|
||||
fillFraction: Float?,
|
||||
shape: Shape,
|
||||
modifier: Modifier,
|
||||
enabled: Boolean = true,
|
||||
onTapToEdit: () -> Unit = {},
|
||||
onScrubStart: () -> Unit = {},
|
||||
onScrub: (Float) -> Unit = {},
|
||||
onScrubEnd: () -> Unit = {},
|
||||
onStep: (Int) -> Unit = {},
|
||||
keyState: KeyedFieldState = KeyedFieldState.None,
|
||||
) {
|
||||
val colors = LocalUmamoColors.current
|
||||
val typography = LocalUmamoTypography.current
|
||||
val interaction = remember { MutableInteractionSource() }
|
||||
val hovered by interaction.collectIsHoveredAsState()
|
||||
val currentTap by rememberUpdatedState(onTapToEdit)
|
||||
val currentScrubStart by rememberUpdatedState(onScrubStart)
|
||||
val currentScrub by rememberUpdatedState(onScrub)
|
||||
val currentScrubEnd by rememberUpdatedState(onScrubEnd)
|
||||
val fillColor = colors.accent.copy(alpha = NUMBER_FIELD_FILL_ALPHA)
|
||||
Box(
|
||||
modifier =
|
||||
modifier
|
||||
.height(NUMBER_FIELD_HEIGHT)
|
||||
.clip(shape)
|
||||
.background(if (hovered && enabled) colors.controlBackgroundHover else colors.controlBackground)
|
||||
// The keyed tint layers OVER the fill rather than replacing it, which is what keeps hover
|
||||
// working on a keyed field: the base below changes, the translucent tint above does not. An
|
||||
// unkeyed field paints nothing extra and looks exactly as it did.
|
||||
.background(keyState.backgroundTint(colors) ?: Color.Transparent, shape)
|
||||
.then(
|
||||
if (!enabled) {
|
||||
// A disabled field attaches no gesture or cursor affordance at all, so it cannot be
|
||||
// scrubbed, typed into, or stepped, and it does not advertise that it could be.
|
||||
Modifier
|
||||
} else {
|
||||
Modifier
|
||||
.hoverable(interaction)
|
||||
// The east-west arrows advertise the scrub before the user tries it - the drag is
|
||||
// otherwise invisible. Not overrideDescendants: the chevrons take back the default
|
||||
// pointer so they still read as buttons.
|
||||
.pointerHoverIcon(umamoPointerIcon(LocalUmamoCursors.ewScroll))
|
||||
.pointerInput(Unit) {
|
||||
detectTapGestures { currentTap() }
|
||||
}
|
||||
// Horizontal-only: the scrub claims left/right drags but leaves vertical drags to the
|
||||
// enclosing scroll (a scroll gesture begun on a field must still scroll the panel).
|
||||
.pointerInput(Unit) {
|
||||
var total = 0f
|
||||
detectHorizontalDragGestures(
|
||||
onDragStart = {
|
||||
total = 0f
|
||||
currentScrubStart()
|
||||
},
|
||||
onDragEnd = { currentScrubEnd() },
|
||||
onDragCancel = { currentScrubEnd() },
|
||||
) { change, dragAmount ->
|
||||
change.consume()
|
||||
total += dragAmount
|
||||
currentScrub(total)
|
||||
}
|
||||
}
|
||||
},
|
||||
),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
if (fillFraction != null) {
|
||||
// The magnitude fill sits behind the value (drawn first) and spans the fraction of the width.
|
||||
Canvas(modifier = Modifier.matchParentSize()) {
|
||||
drawRect(color = fillColor, size = Size(size.width * fillFraction, size.height))
|
||||
}
|
||||
}
|
||||
Row(
|
||||
// No vertical padding: the fixed-height box centers the single text line, so it is never clipped
|
||||
// by an inner content height that would exceed the box (the cause of a padded row overflowing).
|
||||
modifier = Modifier.padding(horizontal = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
val textColor = if (enabled) colors.text else colors.textDisabled
|
||||
Text(text = text, style = typography.bodySmall, color = textColor)
|
||||
if (unitSuffix != null) {
|
||||
Spacer(modifier = Modifier.width(2.dp))
|
||||
Text(text = unitSuffix, style = typography.bodySmall, color = textColor)
|
||||
}
|
||||
}
|
||||
if (hovered && enabled) {
|
||||
StepChevron(
|
||||
icon = LocalUmamoIcons.chevronLeft,
|
||||
onClick = { onStep(-1) },
|
||||
modifier = Modifier.align(Alignment.CenterStart),
|
||||
keyState = keyState,
|
||||
)
|
||||
StepChevron(
|
||||
icon = LocalUmamoIcons.chevronRight,
|
||||
onClick = { onStep(1) },
|
||||
modifier = Modifier.align(Alignment.CenterEnd),
|
||||
keyState = keyState,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A decrement / increment chevron shown on the idle field's edge while hovered: a full-height edge button
|
||||
* with its own control-fill background (brightening on hover) so the glyph stays legible over the value
|
||||
* text and the magnitude fill behind it. Its square outer corners are clipped to the field's rounded
|
||||
* shape by the parent. A pointer convenience over the field's type-in, so it carries no accessibility
|
||||
* label of its own.
|
||||
*
|
||||
* @param UmamoIcon icon The chevron glyph (left = decrement, right = increment).
|
||||
* @param Function onClick Steps the value one increment.
|
||||
* @param Modifier modifier Layout modifier (the caller aligns it to an edge).
|
||||
* @param KeyedFieldState keyState The field's keyed state, tinted over this button's own opaque fill so a
|
||||
* keyed field does not lose the signal at both ends exactly when the chevrons appear.
|
||||
*/
|
||||
@Composable
|
||||
private fun StepChevron(icon: UmamoIcon, onClick: () -> Unit, modifier: Modifier, keyState: KeyedFieldState) {
|
||||
val colors = LocalUmamoColors.current
|
||||
val interaction = remember { MutableInteractionSource() }
|
||||
val hovered by interaction.collectIsHoveredAsState()
|
||||
Box(
|
||||
modifier =
|
||||
modifier
|
||||
.fillMaxHeight()
|
||||
.width(16.dp)
|
||||
// Takes back the plain pointer from the field's scrub cursor: this edge is a click target, not
|
||||
// a drag zone, and the innermost hover icon wins.
|
||||
.pointerHoverIcon(PointerIcon.Default)
|
||||
.background(if (hovered) colors.buttonHover else colors.controlBackground)
|
||||
// Opaque fills over the field's own, and the chevrons show exactly WHEN the field is hovered -
|
||||
// so without the tint here a keyed field loses 32dp of its signal at both ends on hover.
|
||||
.background(keyState.backgroundTint(colors) ?: Color.Transparent)
|
||||
.clickable(interactionSource = interaction, indication = null, onClick = onClick),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Canvas(modifier = Modifier.size(12.dp)) {
|
||||
drawIcon(icon, colors.text)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The single-line type-in editor: a [BasicTextField] showing [display] while idle and letting the user
|
||||
* type a replacement, committing the raw text to [commit] on Enter or focus loss and discarding on Escape.
|
||||
* When [autoFocus] is set it grabs focus on first composition (the field just swapped into edit mode) and
|
||||
* calls [onFocusLost] when focus leaves, so the host can swap the display face back in. It lends its
|
||||
* cancel hook to [LocalInlineEditController] while focused so the shell routes Escape here and yields
|
||||
* shortcut keys (Space, digits, minus) to the field.
|
||||
*
|
||||
* @param String display The formatted external value, shown while idle.
|
||||
* @param Shape shape The field's (stack-aware) corner shape.
|
||||
* @param Modifier modifier Layout modifier (the width).
|
||||
* @param Boolean autoFocus When true, requests focus on first composition (rich edit mode).
|
||||
* @param Function onFocusLost Called after focus leaves (rich edit mode swaps back to the display face).
|
||||
* @param KeyedFieldState keyState The field's keyed state, tinted behind the text so clicking a keyed field
|
||||
* to type does not flash the box back to the plain fill for the length of the edit.
|
||||
* @param Function commit Parses / clamps / fires the caller callback with the raw typed text.
|
||||
*/
|
||||
@Composable
|
||||
private fun NumberEntryField(
|
||||
display: String,
|
||||
shape: Shape,
|
||||
modifier: Modifier,
|
||||
autoFocus: Boolean = false,
|
||||
onFocusLost: () -> Unit = {},
|
||||
keyState: KeyedFieldState = KeyedFieldState.None,
|
||||
commit: (String) -> Unit,
|
||||
) {
|
||||
val colors = LocalUmamoColors.current
|
||||
val controller = LocalInlineEditController.current
|
||||
val focusManager = LocalFocusManager.current
|
||||
val focusRequester = remember { FocusRequester() }
|
||||
var focused by remember { mutableStateOf(false) }
|
||||
// A TextFieldValue rather than a String so the context menu can act on a selection; the caret sits at the
|
||||
// end whenever the value is (re)seeded from outside, which is where a click-to-type gesture wants it.
|
||||
var text by remember { mutableStateOf(TextFieldValue(display, TextRange(display.length))) }
|
||||
// True between an Escape (which clears focus to discard) and the resulting focus-loss, so that path
|
||||
// discards instead of committing. Plain commit paths (Enter, click-away) leave it false.
|
||||
var discarding by remember { mutableStateOf(false) }
|
||||
|
||||
if (autoFocus) {
|
||||
LaunchedEffect(Unit) {
|
||||
focusRequester.requestFocus()
|
||||
}
|
||||
}
|
||||
// A field disposed while it holds focus (its host left the composition - the operation settings strip
|
||||
// on the next edit) gets no focus-loss callback, so the cancel hook it parked would keep the shell
|
||||
// yielding the keyboard to a field that no longer exists. Release it here; the host's reclaim effect
|
||||
// then takes the keyboard back.
|
||||
DisposableEffect(Unit) {
|
||||
onDispose {
|
||||
if (focused) {
|
||||
controller.cancel = null
|
||||
}
|
||||
}
|
||||
}
|
||||
// While not editing, mirror the external value (a slider / pad drag or a reset updates the number).
|
||||
LaunchedEffect(display, focused) {
|
||||
if (!focused) {
|
||||
text = TextFieldValue(display, TextRange(display.length))
|
||||
}
|
||||
}
|
||||
|
||||
// The visual box carries the fixed height, fill, and border so it matches the display face exactly (no
|
||||
// jump on click); the inner text field wraps its own line height and the box centers it, with horizontal
|
||||
// padding only - the same "let the fixed box own the height" approach the display face uses. That
|
||||
// promise includes the KEYED tint: without it, clicking a keyed field to type flashed the whole box back
|
||||
// to the plain fill for the length of the edit.
|
||||
TextEditContextMenuArea(value = text, onValueChange = { edited -> text = edited }) { gesture ->
|
||||
Box(
|
||||
modifier =
|
||||
gesture
|
||||
.then(modifier)
|
||||
.textEntrySurface(controller)
|
||||
.height(NUMBER_FIELD_HEIGHT)
|
||||
.clip(shape)
|
||||
.background(colors.controlBackground)
|
||||
.background(keyState.backgroundTint(colors) ?: Color.Transparent, shape)
|
||||
.border(1.dp, colors.controlBorder, shape),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
BasicTextField(
|
||||
value = text,
|
||||
onValueChange = { edited -> text = edited },
|
||||
textStyle = LocalUmamoTypography.current.bodySmall.copy(color = colors.text, textAlign = TextAlign.End),
|
||||
singleLine = true,
|
||||
cursorBrush = SolidColor(colors.text),
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number, imeAction = ImeAction.Done),
|
||||
// Soft-keyboard Done: clear focus so the single commit happens on the focus-loss path below.
|
||||
keyboardActions = KeyboardActions(onDone = { focusManager.clearFocus() }),
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 4.dp)
|
||||
.focusRequester(focusRequester)
|
||||
.onFocusChanged { focusState ->
|
||||
// hasFocus (not isFocused): BasicTextField focuses an internal child, so this node only ever
|
||||
// sees its subtree's focus.
|
||||
if (focusState.hasFocus) {
|
||||
if (!focused) {
|
||||
focused = true
|
||||
controller.cancel = {
|
||||
discarding = true
|
||||
focusManager.clearFocus()
|
||||
}
|
||||
}
|
||||
} else if (focused) {
|
||||
focused = false
|
||||
controller.cancel = null
|
||||
if (discarding) {
|
||||
discarding = false
|
||||
} else {
|
||||
commit(text.text)
|
||||
}
|
||||
onFocusLost()
|
||||
}
|
||||
}
|
||||
.onKeyEvent { event ->
|
||||
// Hardware Enter confirms by clearing focus, so the commit runs once on the focus-loss path.
|
||||
if (event.type == KeyEventType.KeyDown && (event.key == Key.Enter || event.key == Key.NumPadEnter)) {
|
||||
focusManager.clearFocus()
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.pow
|
||||
import kotlin.math.round
|
||||
|
||||
/*
|
||||
* Pure, Compose-free numeric-field math: display / storage rounding, the min-max fill fraction, the
|
||||
* drag-scrub value mapping, and fixed-decimal formatting. Extracted so the field's behavior is unit
|
||||
* testable without a Compose harness (see NumberFieldMathTest).
|
||||
*/
|
||||
|
||||
/**
|
||||
* The storage-precision cap for a decimal NumberField. A Float holds roughly six to seven significant
|
||||
* decimal digits, so the requested "up to eight places" is capped here - promote the field and its model
|
||||
* slot to Double if eight-place fidelity is ever genuinely needed.
|
||||
*/
|
||||
const val NUMBER_FIELD_STORAGE_DECIMALS = 6
|
||||
|
||||
/** Pixels of horizontal drag per one [step] increment while scrubbing (the pointer-scrub sensitivity). */
|
||||
const val NUMBER_FIELD_SCRUB_PIXELS_PER_STEP = 6f
|
||||
|
||||
/**
|
||||
* The left-to-right fill fraction for a bounded field: where [value] sits in [min]..[max], clamped to
|
||||
* 0..1. Returns null when the bounds are not a usable finite range (infinite endpoint, or max <= min),
|
||||
* so an unbounded field draws no fill - the "min AND max set" rule.
|
||||
*
|
||||
* @param Float value The current value.
|
||||
* @param Float min The range minimum.
|
||||
* @param Float max The range maximum.
|
||||
* @return Float? The fill fraction in 0..1, or null when unbounded.
|
||||
*/
|
||||
fun numberFieldFillFraction(value: Float, min: Float, max: Float): Float? {
|
||||
if (!min.isFinite() || !max.isFinite() || max <= min) {
|
||||
return null
|
||||
}
|
||||
return ((value - min) / (max - min)).coerceIn(0f, 1f)
|
||||
}
|
||||
|
||||
/**
|
||||
* Rounds [value] to [decimals] fractional places (the field's storage rounding); [decimals] <= 0 rounds
|
||||
* to a whole number. Capped at [NUMBER_FIELD_STORAGE_DECIMALS] since a Float cannot faithfully hold more.
|
||||
*
|
||||
* @param Float value The value to round.
|
||||
* @param Int decimals The number of fractional places to keep.
|
||||
* @return Float The rounded value.
|
||||
*/
|
||||
fun roundToDecimals(value: Float, decimals: Int): Float {
|
||||
val places = decimals.coerceIn(0, NUMBER_FIELD_STORAGE_DECIMALS)
|
||||
if (places <= 0) {
|
||||
return round(value)
|
||||
}
|
||||
val scale = 10.0.pow(places).toFloat()
|
||||
return round(value * scale) / scale
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats [value] to exactly [decimals] fractional places for display (Blender pads a float field to a
|
||||
* fixed width, e.g. "0.500"); [decimals] <= 0 shows a whole number. Dependency-free (kotlinx / java.text
|
||||
* formatting is not available in commonMain). Capped at [NUMBER_FIELD_STORAGE_DECIMALS].
|
||||
*
|
||||
* @param Float value The value to format.
|
||||
* @param Int decimals The number of fractional places to show.
|
||||
* @return String The fixed-decimal text.
|
||||
*/
|
||||
fun formatDecimals(value: Float, decimals: Int): String {
|
||||
val places = decimals.coerceIn(0, NUMBER_FIELD_STORAGE_DECIMALS)
|
||||
if (places <= 0) {
|
||||
return round(value.toDouble()).toLong().toString()
|
||||
}
|
||||
val scale = 10.0.pow(places).toLong()
|
||||
val scaled = round(value.toDouble() * scale).toLong()
|
||||
val sign = if (scaled < 0) "-" else ""
|
||||
val magnitude = abs(scaled)
|
||||
val whole = magnitude / scale
|
||||
val fraction = (magnitude % scale).toString().padStart(places, '0')
|
||||
return "$sign$whole.$fraction"
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps a horizontal drag onto a new value: [startValue] plus one [step] per
|
||||
* [NUMBER_FIELD_SCRUB_PIXELS_PER_STEP] pixels of [deltaPx], clamped to [range]. Rightward drag
|
||||
* increases, leftward decreases (screen-x convention).
|
||||
*
|
||||
* @param Float startValue The value at the gesture's start.
|
||||
* @param Float deltaPx The total horizontal drag distance from the start, in pixels.
|
||||
* @param Float step The value increment per scrub notch.
|
||||
* @param ClosedFloatingPointRange range The clamp range.
|
||||
* @return Float The scrubbed value.
|
||||
*/
|
||||
fun scrubValue(startValue: Float, deltaPx: Float, step: Float, range: ClosedFloatingPointRange<Float>): Float {
|
||||
val raw = startValue + (deltaPx / NUMBER_FIELD_SCRUB_PIXELS_PER_STEP) * step
|
||||
return raw.coerceIn(range.start, range.endInclusive)
|
||||
}
|
||||
@@ -0,0 +1,333 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.layout.Layout
|
||||
import androidx.compose.ui.layout.Measurable
|
||||
import androidx.compose.ui.layout.Placeable
|
||||
import androidx.compose.ui.layout.SubcomposeLayout
|
||||
import androidx.compose.ui.unit.Constraints
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.constrainHeight
|
||||
import androidx.compose.ui.unit.constrainWidth
|
||||
import androidx.compose.ui.unit.dp
|
||||
import org.jetbrains.compose.resources.stringResource
|
||||
import org.umamo.ui.resources.*
|
||||
import org.umamo.ui.theme.LocalUmamoIcons
|
||||
|
||||
/** The inset around one collapsed control inside the overflow panel. */
|
||||
private val OVERFLOW_MENU_ROW_PADDING_HORIZONTAL = 8.dp
|
||||
|
||||
/** The gap between two stacked controls inside the overflow panel. */
|
||||
private val OVERFLOW_MENU_ROW_PADDING_VERTICAL = 2.dp
|
||||
|
||||
/**
|
||||
* The separation a flexible gap keeps once its leftover is gone - the same 8.dp the strip puts between
|
||||
* two adjacent controls, so a fully squeezed gap reads as ordinary spacing rather than as a seam.
|
||||
*/
|
||||
val FLEXIBLE_SPACE_MIN_WIDTH = 8.dp
|
||||
|
||||
/**
|
||||
* Declares the controls on an [OverflowRow]. Deliberately NOT a composable scope: the row has to hold
|
||||
* each control's body as a value so the overflow panel can render exactly the collapsed subset, and a
|
||||
* composable collector would let one inner restartable scope re-append to a list the outer scope never
|
||||
* rebuilt. This is [androidx.compose.foundation.lazy.LazyListScope]'s shape, for the same reason.
|
||||
*
|
||||
* The consequence is worth stating plainly: CompositionLocals may only be read inside an item body,
|
||||
* never in the builder that declares the items.
|
||||
*
|
||||
* It is also not a RowScope, so Modifier.weight inside an item is a compile error - weight distribution
|
||||
* belongs to [flexibleSpace], which the packer understands.
|
||||
*/
|
||||
interface OverflowRowScope {
|
||||
/**
|
||||
* A control that collapses into the overflow dropdown when the strip runs out of room. Collapsing
|
||||
* happens from the end: the last declared item goes first.
|
||||
*
|
||||
* Pass [minWidth] for a control that can usefully give up width before it gives up entirely - a search
|
||||
* box is the obvious one - and it is measured against the room actually left, compressing down to that
|
||||
* floor and only collapsing below it. Left unspecified the control is placed at its natural width or
|
||||
* not at all, which is what a chip or a button wants.
|
||||
*
|
||||
* @param Any? key A stable identity for the slot, so its state survives a sibling appearing or
|
||||
* disappearing. Defaults to the declaration index, which is only safe when the item list is fixed.
|
||||
* @param Dp minWidth The narrowest this control may be squeezed to; unspecified to never compress.
|
||||
* @param Function content The control.
|
||||
*/
|
||||
fun item(key: Any? = null, minWidth: Dp = Dp.Unspecified, content: @Composable () -> Unit)
|
||||
|
||||
/**
|
||||
* A control that is always placed, even when placing it overflows the strip. Reserve this for the
|
||||
* one control a strip is about - a header that hides its own subject is worse than one that clips.
|
||||
*
|
||||
* @param Any? key A stable identity for the slot; see [item].
|
||||
* @param Function content The control.
|
||||
*/
|
||||
fun pinnedItem(key: Any? = null, content: @Composable () -> Unit)
|
||||
|
||||
/**
|
||||
* A weighted gap that absorbs leftover width - the replacement for Spacer(Modifier.weight(w)). It
|
||||
* carries no spacing of its own on either side, since it IS the separation.
|
||||
*
|
||||
* [minWidth] is the separation the gap never closes below, reserved before the controls around it are
|
||||
* admitted rather than shared out of what happens to be left. Without it a starved strip resolves the
|
||||
* gap to nothing and the controls either side butt together, which reads as a rendering fault.
|
||||
*
|
||||
* @param Float weight This gap's share of the leftover width.
|
||||
* @param Dp minWidth The separation this gap keeps even with no leftover to share.
|
||||
*/
|
||||
fun flexibleSpace(weight: Float = 1f, minWidth: Dp = FLEXIBLE_SPACE_MIN_WIDTH)
|
||||
}
|
||||
|
||||
/**
|
||||
* One declared slot: its identity, how it behaves when width runs short, and its body.
|
||||
*
|
||||
* @property Any key The slot's stable identity, also its subcomposition slot id.
|
||||
* @property OverflowSlotKind kind How the slot behaves when width runs short.
|
||||
* @property Float weight The share of leftover width, for a Flexible slot.
|
||||
* @property Dp minWidth A control's squeeze floor, or a gap's minimum separation.
|
||||
* @property Function? content The control, or null for a Flexible gap.
|
||||
*/
|
||||
private class OverflowSlot(
|
||||
val key: Any,
|
||||
val kind: OverflowSlotKind,
|
||||
val weight: Float,
|
||||
val minWidth: Dp,
|
||||
val content: (@Composable () -> Unit)?,
|
||||
)
|
||||
|
||||
/** Subcomposition slot ids, wrapped so a caller's item key can never collide with the overflow chip's. */
|
||||
private sealed interface OverflowSlotId {
|
||||
data class Item(val key: Any) : OverflowSlotId
|
||||
|
||||
data object OverflowButton : OverflowSlotId
|
||||
}
|
||||
|
||||
/** Collects the declared slots into a plain list; rebuilt on every recomposition, never remembered. */
|
||||
private class OverflowRowCollector : OverflowRowScope {
|
||||
val slots = mutableListOf<OverflowSlot>()
|
||||
|
||||
override fun item(key: Any?, minWidth: Dp, content: @Composable () -> Unit) {
|
||||
add(key, OverflowSlotKind.Collapsible, weight = 0f, minWidth = minWidth, content = content)
|
||||
}
|
||||
|
||||
override fun pinnedItem(key: Any?, content: @Composable () -> Unit) {
|
||||
add(key, OverflowSlotKind.Pinned, weight = 0f, minWidth = Dp.Unspecified, content = content)
|
||||
}
|
||||
|
||||
override fun flexibleSpace(weight: Float, minWidth: Dp) {
|
||||
add(key = null, kind = OverflowSlotKind.Flexible, weight = weight, minWidth = minWidth, content = null)
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends one slot, defaulting its key to the declaration index and rejecting duplicates.
|
||||
*
|
||||
* @param Any? key The caller's key, or null to key by declaration index.
|
||||
* @param OverflowSlotKind kind How the slot behaves when width runs short.
|
||||
* @param Float weight The share of leftover width, for a Flexible gap.
|
||||
* @param Dp minWidth The narrowest the control may be squeezed to, or unspecified.
|
||||
* @param Function? content The control, or null for a Flexible gap.
|
||||
*/
|
||||
private fun add(key: Any?, kind: OverflowSlotKind, weight: Float, minWidth: Dp, content: (@Composable () -> Unit)?) {
|
||||
val slotKey = key ?: slots.size
|
||||
// A duplicate key silently merges two slots' subcompositions, so their state would swap under the
|
||||
// user. That is a programming error, not a runtime branch - same posture as SpaceRegistry.
|
||||
require(slots.none { existing -> existing.key == slotKey }) { "duplicate OverflowRow slot key: $slotKey" }
|
||||
slots.add(OverflowSlot(key = slotKey, kind = kind, weight = weight, minWidth = minWidth, content = content))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A horizontal strip whose controls collapse into a trailing overflow dropdown instead of being crushed
|
||||
* when the strip runs out of room. A plain Row measures each un-weighted child against whatever width
|
||||
* is left, so a narrowing strip squeezes its controls to nothing in place; this measures every control
|
||||
* at its natural width and simply stops placing the ones that do not fit, handing them to the chip.
|
||||
*
|
||||
* Each item is measured with an unbounded width and the strip's own height, so an item must be
|
||||
* intrinsically sized - Modifier.fillMaxWidth at an item root resolves to zero against an infinite
|
||||
* maximum and the item is dropped. An item that renders nothing costs nothing: it measures zero and is
|
||||
* skipped, spacing and all, which is how a mode-gated control disappears cleanly.
|
||||
*
|
||||
* Note for future adopters: this is a SubcomposeLayout, whose intrinsic measurements are expensive and
|
||||
* lossy. It is fine under a fixed height (an area header), but do not drop it into a parent that asks
|
||||
* for intrinsics - Modifier.height(IntrinsicSize.Min), say - without checking first.
|
||||
*
|
||||
* @param Modifier modifier The layout modifier.
|
||||
* @param Dp horizontalSpacing The gap between adjacent controls.
|
||||
* @param Alignment verticalAlignment How controls align across the strip's height.
|
||||
* @param String overflowContentDescription The overflow chip's accessible label and tooltip.
|
||||
* @param Function content Declares the controls; see [OverflowRowScope].
|
||||
*/
|
||||
@Composable
|
||||
fun OverflowRow(
|
||||
modifier: Modifier = Modifier,
|
||||
horizontalSpacing: Dp = 8.dp,
|
||||
verticalAlignment: Alignment.Vertical = Alignment.CenterVertically,
|
||||
overflowContentDescription: String = stringResource(Res.string.header_more),
|
||||
content: OverflowRowScope.() -> Unit,
|
||||
) {
|
||||
val collector = OverflowRowCollector()
|
||||
collector.content()
|
||||
val slots = collector.slots
|
||||
var overflowExpanded by remember { mutableStateOf(false) }
|
||||
// Keys rather than slots: keys compare cheaply and correctly, while a slot holds a lambda that is a
|
||||
// fresh instance every recomposition and so would never compare equal.
|
||||
val collapsedKeys = remember { mutableStateOf<List<Any>>(emptyList()) }
|
||||
// What the verdict in collapsedKeys was computed against. Reusing it while the strip and its slot list
|
||||
// are unchanged is what lets the second pass DROP the slot whose measurement decided the collapse -
|
||||
// deciding it costs one composition, and without this that composition would linger unplaced, showing up
|
||||
// in the semantics tree and duplicating the copy the panel renders.
|
||||
val lastPackKey = remember { mutableStateOf<Pair<Int, List<Any>>?>(null) }
|
||||
// Remembered rather than measured up front: the chip is composed ONLY when something collapsed (an
|
||||
// always-composed chip is an unplaced node in the tree), yet its width has to be reserved on every pass
|
||||
// or the strip oscillates. Reserving the last measured width keeps both true.
|
||||
val overflowButtonWidthPx = remember { mutableStateOf(0) }
|
||||
|
||||
SubcomposeLayout(modifier = modifier) { constraints ->
|
||||
val slotConstraints = Constraints(maxHeight = constraints.maxHeight)
|
||||
val spacingPx = horizontalSpacing.roundToPx()
|
||||
val slotKeys = slots.map { slot -> slot.key }
|
||||
val packKey = constraints.maxWidth to slotKeys
|
||||
// A changed width or slot list re-evaluates from scratch, so a widened strip can re-admit what it
|
||||
// collapsed; an unchanged one honors the previous verdict and leaves the decided slots uncomposed.
|
||||
val preCollapsed =
|
||||
if (lastPackKey.value == packKey) {
|
||||
slots.indices.filterTo(mutableSetOf()) { slotIndex -> slotKeys[slotIndex] in collapsedKeys.value }
|
||||
} else {
|
||||
emptySet()
|
||||
}
|
||||
|
||||
// Each slot is composed once (subcompose may not be called twice with one id in a pass) and the
|
||||
// packer reads its width through INTRINSICS, never measure(): the strip is walked up to twice, a
|
||||
// compressible slot is offered a different bound on each walk and again when a tail is costed, and
|
||||
// Compose forbids measuring one Measurable twice in a pass. Intrinsics answer any number of times
|
||||
// (a control that shrinks to its bound is min(natural, bound) wide), and every PLACED slot is then
|
||||
// measured exactly once, at the width the packer settled on.
|
||||
val measurables = HashMap<Int, Measurable>(slots.size)
|
||||
val naturalWidthPx = HashMap<Int, Int>(slots.size)
|
||||
|
||||
fun measurableFor(slotIndex: Int): Measurable =
|
||||
measurables.getOrPut(slotIndex) {
|
||||
val slot = slots[slotIndex]
|
||||
subcompose(OverflowSlotId.Item(slot.key)) {
|
||||
// One wrapper Row per item, so a multi-control item is one indivisible group whose
|
||||
// internal spacing matches the strip's, and subcompose always yields one measurable.
|
||||
Row(verticalAlignment = verticalAlignment, horizontalArrangement = Arrangement.spacedBy(horizontalSpacing)) {
|
||||
slot.content?.invoke()
|
||||
}
|
||||
}.first()
|
||||
}
|
||||
val packing =
|
||||
packOverflowRow(
|
||||
slots =
|
||||
slots.map { slot ->
|
||||
OverflowSlotSpec(
|
||||
kind = slot.kind,
|
||||
weight = slot.weight,
|
||||
minWidthPx = if (slot.minWidth == Dp.Unspecified) 0 else slot.minWidth.roundToPx(),
|
||||
)
|
||||
},
|
||||
availableWidthPx = constraints.maxWidth,
|
||||
boundedWidth = constraints.hasBoundedWidth,
|
||||
spacingPx = spacingPx,
|
||||
overflowButtonWidthPx = overflowButtonWidthPx.value,
|
||||
preCollapsedSlotIndices = preCollapsed,
|
||||
) { slotIndex, maxWidthPx ->
|
||||
val natural = naturalWidthPx.getOrPut(slotIndex) { measurableFor(slotIndex).maxIntrinsicWidth(constraints.maxHeight) }
|
||||
if (maxWidthPx == OVERFLOW_WIDTH_UNBOUNDED) natural else minOf(natural, maxWidthPx.coerceAtLeast(0))
|
||||
}
|
||||
val placeables = HashMap<Int, Placeable>(packing.placements.size)
|
||||
for (placement in packing.placements) {
|
||||
if (slots[placement.slotIndex].kind == OverflowSlotKind.Flexible) {
|
||||
continue
|
||||
}
|
||||
placeables[placement.slotIndex] = measurableFor(placement.slotIndex).measure(slotConstraints.copy(maxWidth = placement.widthPx))
|
||||
}
|
||||
|
||||
val collapsed = packing.collapsedSlotIndices.map { slotIndex -> slotKeys[slotIndex] }
|
||||
if (collapsedKeys.value != collapsed) {
|
||||
collapsedKeys.value = collapsed
|
||||
}
|
||||
if (lastPackKey.value != packKey) {
|
||||
lastPackKey.value = packKey
|
||||
}
|
||||
|
||||
val overflowPlaceable =
|
||||
if (collapsed.isEmpty()) {
|
||||
null
|
||||
} else {
|
||||
subcompose(OverflowSlotId.OverflowButton) {
|
||||
val collapsedSlots = slots.filter { slot -> slot.key in collapsed }
|
||||
PopupChip(
|
||||
contentDescription = overflowContentDescription,
|
||||
icon = LocalUmamoIcons.dots,
|
||||
expanded = overflowExpanded,
|
||||
onExpandedChange = { next -> overflowExpanded = next },
|
||||
) {
|
||||
collapsedSlots.forEach { slot ->
|
||||
key(slot.key) {
|
||||
OverflowMenuRow { slot.content?.invoke() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}.first().measure(slotConstraints)
|
||||
}
|
||||
if (overflowPlaceable != null && overflowButtonWidthPx.value != overflowPlaceable.width) {
|
||||
// The first strip to overflow reserved nothing, so it packed one chip too generously. Recording
|
||||
// the real width re-measures once and settles; from then on the reserve is a constant.
|
||||
overflowButtonWidthPx.value = overflowPlaceable.width
|
||||
}
|
||||
// The chip is gone, so an open panel would be anchored to nothing. It cannot be OPENED while
|
||||
// unplaced (an absent node takes no clicks), but it can be open when the strip widens under it.
|
||||
if (collapsed.isEmpty() && overflowExpanded) {
|
||||
overflowExpanded = false
|
||||
}
|
||||
|
||||
// The chip counts toward the strip's height too - it is placed, so a strip sized to the items alone
|
||||
// would clip it whenever it is the tallest thing on the row.
|
||||
val contentHeight = maxOf(placeables.values.maxOfOrNull { it.height } ?: 0, overflowPlaceable?.height ?: 0)
|
||||
val height = constraints.constrainHeight(contentHeight)
|
||||
layout(constraints.constrainWidth(packing.contentWidthPx), height) {
|
||||
packing.placements.forEach { placement ->
|
||||
val placeable = placeables[placement.slotIndex] ?: return@forEach
|
||||
placeable.place(x = placement.xPx, y = verticalAlignment.align(placeable.height, height))
|
||||
}
|
||||
val buttonXPx = packing.overflowButtonXPx
|
||||
if (overflowPlaceable != null && buttonXPx != null) {
|
||||
overflowPlaceable.place(x = buttonXPx, y = verticalAlignment.align(overflowPlaceable.height, height))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One control's row inside the overflow panel: the control at its natural size, inset from the panel
|
||||
* edges. Collapses to nothing when the control renders nothing, so a mode-gated item that ended up past
|
||||
* the collapse point leaves an empty sliver rather than a visible gap.
|
||||
*
|
||||
* @param Function content The collapsed control.
|
||||
*/
|
||||
@Composable
|
||||
private fun OverflowMenuRow(content: @Composable () -> Unit) {
|
||||
Layout(content = content) { measurables, constraints ->
|
||||
val horizontalPaddingPx = OVERFLOW_MENU_ROW_PADDING_HORIZONTAL.roundToPx()
|
||||
val verticalPaddingPx = OVERFLOW_MENU_ROW_PADDING_VERTICAL.roundToPx()
|
||||
val placeables = measurables.map { measurable -> measurable.measure(constraints) }
|
||||
val contentWidth = placeables.maxOfOrNull { placeable -> placeable.width } ?: 0
|
||||
if (contentWidth == 0) {
|
||||
return@Layout layout(0, 0) {}
|
||||
}
|
||||
val contentHeight = placeables.maxOf { placeable -> placeable.height }
|
||||
layout(contentWidth + horizontalPaddingPx * 2, contentHeight + verticalPaddingPx * 2) {
|
||||
placeables.forEach { placeable -> placeable.place(horizontalPaddingPx, verticalPaddingPx) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,410 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
/**
|
||||
* What one declared slot is, from the packer's point of view. The composable content is deliberately
|
||||
* absent - this file decides geometry only, so it stays a pure function the layout tests can drive
|
||||
* without a composition.
|
||||
*/
|
||||
internal enum class OverflowSlotKind {
|
||||
/** Collapses into the overflow dropdown when the strip runs out of room. */
|
||||
Collapsible,
|
||||
|
||||
/** Always placed, even when that overflows the strip. */
|
||||
Pinned,
|
||||
|
||||
/** A weighted gap that absorbs leftover width; never collapses and never carries spacing. */
|
||||
Flexible,
|
||||
}
|
||||
|
||||
/**
|
||||
* Sentinel [OverflowSlotSpec.minWidthPx] and measure bound meaning "no limit" - a slot that is measured at
|
||||
* whatever width it asks for, and collapses whole rather than compressing.
|
||||
*/
|
||||
internal const val OVERFLOW_WIDTH_UNBOUNDED = Int.MAX_VALUE
|
||||
|
||||
/**
|
||||
* One declared slot, stripped of its content.
|
||||
*
|
||||
* @property OverflowSlotKind kind How the slot behaves when width runs short.
|
||||
* @property Float weight The share of leftover width, for [OverflowSlotKind.Flexible] only.
|
||||
* @property Int minWidthPx For a Collapsible slot, the narrowest it may be squeezed to before
|
||||
* it collapses instead; for a Flexible gap, the separation it never closes below. 0 means a control is
|
||||
* placed at its natural width or not at all, and a gap may close completely.
|
||||
*/
|
||||
internal data class OverflowSlotSpec(
|
||||
val kind: OverflowSlotKind,
|
||||
val weight: Float = 0f,
|
||||
val minWidthPx: Int = 0,
|
||||
)
|
||||
|
||||
/**
|
||||
* One slot that made it onto the strip, at its resolved position.
|
||||
*
|
||||
* @property Int slotIndex The slot's index in the declared list.
|
||||
* @property Int xPx The slot's left edge, relative to the strip.
|
||||
* @property Int widthPx The slot's resolved width; for a Flexible gap, its floor plus its share of the
|
||||
* leftover.
|
||||
*/
|
||||
internal data class OverflowPlacement(
|
||||
val slotIndex: Int,
|
||||
val xPx: Int,
|
||||
val widthPx: Int,
|
||||
)
|
||||
|
||||
/**
|
||||
* The resolved strip: what is placed and where, what collapsed, and where the overflow chip goes.
|
||||
*
|
||||
* @property List placements The placed slots in declaration order.
|
||||
* @property List collapsedSlotIndices The slots that did not fit, in declaration order - the dropdown's contents.
|
||||
* @property Int? overflowButtonXPx The chip's left edge, or null when nothing collapsed (it is measured
|
||||
* but not placed).
|
||||
* @property Int contentWidthPx The extent the strip actually occupies.
|
||||
*/
|
||||
internal data class OverflowRowPacking(
|
||||
val placements: List<OverflowPlacement>,
|
||||
val collapsedSlotIndices: List<Int>,
|
||||
val overflowButtonXPx: Int?,
|
||||
val contentWidthPx: Int,
|
||||
)
|
||||
|
||||
/**
|
||||
* Decides which slots fit on the strip, at which x, and how wide each flexible gap resolves to.
|
||||
*
|
||||
* The strip is walked up to twice. The first walk charges nothing for the overflow chip, because a
|
||||
* strip whose controls all fit does not show one; if that walk collapses nothing it is the answer. Only
|
||||
* when something genuinely does not fit is the chip certain to exist, and the second walk charges for it.
|
||||
* That ordering is what keeps the two walks from disagreeing - once a control has missed at the full
|
||||
* width, reserving the chip can only push more out, never restore "everything fits" - so the strip
|
||||
* settles rather than oscillating on a one-pixel resize.
|
||||
*
|
||||
* Widths are pulled through [slotWidthPx] rather than passed in so the caller can compose lazily: every
|
||||
* Pinned slot is measured up front (they are always placed, so their width must be reserved before any
|
||||
* earlier Collapsible slot is admitted), Collapsible slots are measured in declaration order until one
|
||||
* does not fit, and nothing after that is measured at all. A slot measuring zero is dropped entirely -
|
||||
* no spacing, not collapsed, absent from the dropdown - which is how a mode-gated control that renders
|
||||
* nothing costs nothing.
|
||||
*
|
||||
* @param List slots The declared slots, in declaration order.
|
||||
* @param Int availableWidthPx The strip's width; ignored for collapsing when [boundedWidth] is false.
|
||||
* @param Boolean boundedWidth Whether the strip has a real width. When false nothing collapses and
|
||||
* every flexible gap sits at its floor, since there is no leftover to share out.
|
||||
* @param Int spacingPx The gap between two adjacent placed slots.
|
||||
* @param Int overflowButtonWidthPx The measured width of the trailing overflow chip.
|
||||
* @param Set preCollapsedSlotIndices Collapsible slots an earlier pass already ruled out, collapsed
|
||||
* again without being measured. Deciding the FIRST slot that does not fit costs one measurement, so
|
||||
* that slot is composed; feeding the verdict back lets the caller drop it on the next pass instead of
|
||||
* leaving it composed-but-unplaced. Empty re-evaluates every slot from scratch.
|
||||
* @param Function slotWidthPx Reports one slot's width at a given maximum, on demand. A slot
|
||||
* declaring [OverflowSlotSpec.minWidthPx] can be asked twice with different bounds (once per walk) and
|
||||
* again when a tail is costed, so the answer must be repeatable and side-effect free - an intrinsic
|
||||
* width, never a measure(), which Compose allows once per slot per pass.
|
||||
* @return OverflowRowPacking The resolved strip.
|
||||
*/
|
||||
internal fun packOverflowRow(
|
||||
slots: List<OverflowSlotSpec>,
|
||||
availableWidthPx: Int,
|
||||
boundedWidth: Boolean,
|
||||
spacingPx: Int,
|
||||
overflowButtonWidthPx: Int,
|
||||
preCollapsedSlotIndices: Set<Int> = emptySet(),
|
||||
slotWidthPx: (slotIndex: Int, maxWidthPx: Int) -> Int,
|
||||
): OverflowRowPacking {
|
||||
// Pinned slots are always placed, so a pinned slot LATER in the strip still has to be reserved for
|
||||
// before an earlier collapsible one is admitted. Measuring them up front is what makes that
|
||||
// reservation possible without measuring the collapsible tail.
|
||||
val pinnedWidths = HashMap<Int, Int>(slots.size)
|
||||
slots.forEachIndexed { slotIndex, slot ->
|
||||
if (slot.kind == OverflowSlotKind.Pinned) {
|
||||
pinnedWidths[slotIndex] = slotWidthPx(slotIndex, OVERFLOW_WIDTH_UNBOUNDED)
|
||||
}
|
||||
}
|
||||
// What every slot from here on is already owed: a pinned slot's measured width (it is always placed),
|
||||
// and a flexible gap's floor (it never closes below it). Charged against each admission so an earlier
|
||||
// control cannot take room its successors have a claim on. One spacing per pinned slot over-reserves
|
||||
// by at most a single gap - an exact figure would need the placed set, which is what this decides.
|
||||
val reservedWidthAfter = IntArray(slots.size + 1)
|
||||
for (slotIndex in slots.indices.reversed()) {
|
||||
val slot = slots[slotIndex]
|
||||
val pinnedWidth = pinnedWidths[slotIndex] ?: 0
|
||||
val ownReserve =
|
||||
when {
|
||||
slot.kind == OverflowSlotKind.Flexible -> slot.minWidthPx
|
||||
pinnedWidth > 0 -> pinnedWidth + spacingPx
|
||||
else -> 0
|
||||
}
|
||||
reservedWidthAfter[slotIndex] = reservedWidthAfter[slotIndex + 1] + ownReserve
|
||||
}
|
||||
|
||||
// Walked twice at most. The first walk reserves NOTHING for the overflow chip, because a strip whose
|
||||
// controls all fit shows no chip and must not be charged for one - reserving unconditionally collapsed
|
||||
// the last control roughly a chip early, with visible slack still in the flexible gaps. If that walk
|
||||
// collapses nothing, it is the answer. If it collapses something, the chip is needed for certain, so
|
||||
// the second walk charges for it; that can only push MORE out, never bring the set back to "everything
|
||||
// fits", so the two walks cannot disagree about whether a chip exists and the strip cannot oscillate.
|
||||
val withoutChip = walkStrip(slots, availableWidthPx, boundedWidth, spacingPx, 0, preCollapsedSlotIndices, reservedWidthAfter, pinnedWidths, slotWidthPx)
|
||||
val walk =
|
||||
if (withoutChip.collapsedSlotIndices.isEmpty() || overflowButtonWidthPx == 0) {
|
||||
withoutChip
|
||||
} else {
|
||||
walkStrip(
|
||||
slots,
|
||||
availableWidthPx,
|
||||
boundedWidth,
|
||||
spacingPx,
|
||||
overflowButtonWidthPx,
|
||||
preCollapsedSlotIndices,
|
||||
reservedWidthAfter,
|
||||
pinnedWidths,
|
||||
slotWidthPx,
|
||||
)
|
||||
}
|
||||
|
||||
val placedIndices = walk.placedIndices
|
||||
val placedWidths = walk.placedWidths
|
||||
val collapsedSlotIndices = walk.collapsedSlotIndices
|
||||
// The reserved chip width returns to the flexible gaps whenever nothing actually collapsed.
|
||||
val overflowReservePx =
|
||||
if (collapsedSlotIndices.isEmpty()) {
|
||||
0
|
||||
} else {
|
||||
overflowButtonWidthPx + spacingPx
|
||||
}
|
||||
val leftoverPx =
|
||||
if (boundedWidth) {
|
||||
(availableWidthPx - walk.usedPx - overflowReservePx).coerceAtLeast(0)
|
||||
} else {
|
||||
0
|
||||
}
|
||||
distributeFlexibleWidths(slots, placedIndices, placedWidths, leftoverPx)
|
||||
|
||||
val placements = mutableListOf<OverflowPlacement>()
|
||||
var xPx = 0
|
||||
var previousPlacedWasFlexible = false
|
||||
placedIndices.forEachIndexed { placedIndex, slotIndex ->
|
||||
val isFlexible = slots[slotIndex].kind == OverflowSlotKind.Flexible
|
||||
if (placedIndex > 0 && !previousPlacedWasFlexible && !isFlexible) {
|
||||
xPx += spacingPx
|
||||
}
|
||||
placements.add(OverflowPlacement(slotIndex = slotIndex, xPx = xPx, widthPx = placedWidths[placedIndex]))
|
||||
xPx += placedWidths[placedIndex]
|
||||
previousPlacedWasFlexible = isFlexible
|
||||
}
|
||||
|
||||
val overflowButtonXPx =
|
||||
if (collapsedSlotIndices.isEmpty()) {
|
||||
null
|
||||
} else {
|
||||
(availableWidthPx - overflowButtonWidthPx).coerceAtLeast(0)
|
||||
}
|
||||
val contentWidthPx = maxOf(xPx, overflowButtonXPx?.plus(overflowButtonWidthPx) ?: 0)
|
||||
return OverflowRowPacking(
|
||||
placements = placements,
|
||||
collapsedSlotIndices = collapsedSlotIndices,
|
||||
overflowButtonXPx = overflowButtonXPx,
|
||||
contentWidthPx = contentWidthPx,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* One walk's outcome, before the flexible gaps are sized and the slots are positioned.
|
||||
*
|
||||
* @property MutableList placedIndices The placed slots, in declaration order.
|
||||
* @property MutableList placedWidths Each placed slot's width, parallel to [placedIndices].
|
||||
* @property MutableList collapsedSlotIndices The slots that did not fit.
|
||||
* @property Int usedPx The width the placed slots and their spacing consumed.
|
||||
*/
|
||||
private class StripWalk(
|
||||
val placedIndices: MutableList<Int>,
|
||||
val placedWidths: MutableList<Int>,
|
||||
val collapsedSlotIndices: MutableList<Int>,
|
||||
val usedPx: Int,
|
||||
)
|
||||
|
||||
/**
|
||||
* Admits slots left to right against a budget, collapsing from the first one that does not fit.
|
||||
*
|
||||
* A slot declaring [OverflowSlotSpec.minWidthPx] is offered the room actually left rather than measured
|
||||
* unbounded, so it compresses toward its floor instead of collapsing the moment its natural width stops
|
||||
* fitting - a 160.dp search box has most of its width to give up before vanishing is the right answer.
|
||||
* Below the floor it collapses like anything else.
|
||||
*
|
||||
* @param List slots The declared slots, in declaration order.
|
||||
* @param Int availableWidthPx The strip's width.
|
||||
* @param Boolean boundedWidth False when the strip has no real width, so nothing collapses.
|
||||
* @param Int spacingPx The gap between two adjacent placed slots.
|
||||
* @param Int reservedForChipPx Width held back for the trailing overflow chip.
|
||||
* @param Set preCollapsedSlotIndices Collapsible slots an earlier pass already ruled out.
|
||||
* @param IntArray reservedWidthAfter Width already owed at or after each index - pinned slots' widths
|
||||
* and flexible gaps' floors - so an earlier control cannot take room its successors have a claim on.
|
||||
* @param Map pinnedWidths The pinned slots' already-measured widths.
|
||||
* @param Function slotWidthPx Measures one slot at a given maximum width.
|
||||
* @return StripWalk What was placed, what collapsed, and how much width it took.
|
||||
*/
|
||||
private fun walkStrip(
|
||||
slots: List<OverflowSlotSpec>,
|
||||
availableWidthPx: Int,
|
||||
boundedWidth: Boolean,
|
||||
spacingPx: Int,
|
||||
reservedForChipPx: Int,
|
||||
preCollapsedSlotIndices: Set<Int>,
|
||||
reservedWidthAfter: IntArray,
|
||||
pinnedWidths: Map<Int, Int>,
|
||||
slotWidthPx: (slotIndex: Int, maxWidthPx: Int) -> Int,
|
||||
): StripWalk {
|
||||
val budgetPx = (availableWidthPx - reservedForChipPx).coerceAtLeast(0)
|
||||
val placedIndices = mutableListOf<Int>()
|
||||
val placedWidths = mutableListOf<Int>()
|
||||
val collapsedSlotIndices = mutableListOf<Int>()
|
||||
var usedPx = 0
|
||||
var previousWasFlexible = false
|
||||
var anythingPlaced = false
|
||||
var collapsing = false
|
||||
|
||||
slots.forEachIndexed { slotIndex, slot ->
|
||||
if (slot.kind == OverflowSlotKind.Flexible) {
|
||||
// Placed at its floor, not at zero: the floor is the gap's guaranteed separation, so it has to be
|
||||
// spent here where it counts against what the controls beside it may take. Any leftover is added
|
||||
// on top afterwards. A zero-floor gap behaves exactly as before.
|
||||
placedIndices.add(slotIndex)
|
||||
placedWidths.add(slot.minWidthPx)
|
||||
usedPx += slot.minWidthPx
|
||||
previousWasFlexible = true
|
||||
anythingPlaced = true
|
||||
return@forEachIndexed
|
||||
}
|
||||
// Past the collapse point no further COLLAPSIBLE slot is even measured: composing a control only to
|
||||
// hide it is the cost this packer exists to avoid. A pinned slot still goes through - the latch
|
||||
// governs what may be dropped, and a pinned slot may not.
|
||||
if (slot.kind == OverflowSlotKind.Collapsible && (collapsing || slotIndex in preCollapsedSlotIndices)) {
|
||||
collapsing = true
|
||||
collapsedSlotIndices.add(slotIndex)
|
||||
return@forEachIndexed
|
||||
}
|
||||
// A flexible gap IS the separation, so it suppresses spacing on both sides.
|
||||
val leadingSpacingPx =
|
||||
if (anythingPlaced && !previousWasFlexible) {
|
||||
spacingPx
|
||||
} else {
|
||||
0
|
||||
}
|
||||
val roomPx = budgetPx - usedPx - leadingSpacingPx - reservedWidthAfter[slotIndex + 1]
|
||||
val compressible = slot.kind == OverflowSlotKind.Collapsible && boundedWidth && slot.minWidthPx > 0
|
||||
if (compressible && roomPx < slot.minWidthPx) {
|
||||
collapsing = true
|
||||
collapsedSlotIndices.add(slotIndex)
|
||||
return@forEachIndexed
|
||||
}
|
||||
// A compressible slot is offered the room left AFTER the controls behind it, so it gives up width to
|
||||
// keep them on the strip rather than taking its natural width and pushing them into the dropdown - a
|
||||
// search box narrowing is a far better trade than a filter chip vanishing. It never yields below its
|
||||
// own floor; past that the tail collapses as usual. Costing the tail means measuring it early, which
|
||||
// is the one place this packer gives up laziness - bounded by the handful of controls a strip carries.
|
||||
val measureMaxPx =
|
||||
if (compressible) {
|
||||
maxOf(slot.minWidthPx, roomPx - collapsibleTailWidthPx(slots, slotIndex, spacingPx, preCollapsedSlotIndices, slotWidthPx))
|
||||
} else {
|
||||
OVERFLOW_WIDTH_UNBOUNDED
|
||||
}
|
||||
val width = pinnedWidths[slotIndex] ?: slotWidthPx(slotIndex, measureMaxPx)
|
||||
if (width == 0) {
|
||||
return@forEachIndexed
|
||||
}
|
||||
if (slot.kind == OverflowSlotKind.Collapsible && boundedWidth && !compressible && width > roomPx) {
|
||||
collapsing = true
|
||||
collapsedSlotIndices.add(slotIndex)
|
||||
return@forEachIndexed
|
||||
}
|
||||
placedIndices.add(slotIndex)
|
||||
placedWidths.add(width)
|
||||
usedPx += leadingSpacingPx + width
|
||||
previousWasFlexible = false
|
||||
anythingPlaced = true
|
||||
}
|
||||
return StripWalk(placedIndices, placedWidths, collapsedSlotIndices, usedPx)
|
||||
}
|
||||
|
||||
/**
|
||||
* The width the collapsible controls declared AFTER [slotIndex] need, so a compressible slot can leave
|
||||
* room for them instead of taking its natural width and pushing them off the strip.
|
||||
*
|
||||
* Only non-compressible slots count: a second compressible slot could give up width of its own, so
|
||||
* charging its natural width here would make the first one yield more than it has to.
|
||||
*
|
||||
* @param List slots The declared slots, in declaration order.
|
||||
* @param Int slotIndex The compressible slot the tail is being costed for.
|
||||
* @param Int spacingPx The gap between two adjacent placed slots.
|
||||
* @param Set preCollapsedSlotIndices Slots an earlier pass already ruled out; they cost nothing.
|
||||
* @param Function slotWidthPx Measures one slot at a given maximum width.
|
||||
* @return Int The tail's width including the gap in front of each entry.
|
||||
*/
|
||||
private fun collapsibleTailWidthPx(
|
||||
slots: List<OverflowSlotSpec>,
|
||||
slotIndex: Int,
|
||||
spacingPx: Int,
|
||||
preCollapsedSlotIndices: Set<Int>,
|
||||
slotWidthPx: (slotIndex: Int, maxWidthPx: Int) -> Int,
|
||||
): Int {
|
||||
var tailPx = 0
|
||||
for (laterIndex in slotIndex + 1 until slots.size) {
|
||||
val later = slots[laterIndex]
|
||||
if (later.kind != OverflowSlotKind.Collapsible || later.minWidthPx > 0 || laterIndex in preCollapsedSlotIndices) {
|
||||
continue
|
||||
}
|
||||
val laterWidth = slotWidthPx(laterIndex, OVERFLOW_WIDTH_UNBOUNDED)
|
||||
if (laterWidth > 0) {
|
||||
tailPx += laterWidth + spacingPx
|
||||
}
|
||||
}
|
||||
return tailPx
|
||||
}
|
||||
|
||||
/**
|
||||
* Shares [leftoverPx] out across the placed flexible gaps in proportion to their weights, writing the
|
||||
* results back into [placedWidths]. Largest-remainder rather than plain rounding, so the parts sum to
|
||||
* exactly the leftover and the strip's right edge lands where the caller expects it to.
|
||||
*
|
||||
* @param List slots The declared slots, for their kinds and weights.
|
||||
* @param List placedIndices The slot index behind each entry of [placedWidths].
|
||||
* @param MutableList placedWidths The resolved widths, mutated in place.
|
||||
* @param Int leftoverPx The width to share out.
|
||||
*/
|
||||
private fun distributeFlexibleWidths(
|
||||
slots: List<OverflowSlotSpec>,
|
||||
placedIndices: List<Int>,
|
||||
placedWidths: MutableList<Int>,
|
||||
leftoverPx: Int,
|
||||
) {
|
||||
if (leftoverPx <= 0) {
|
||||
return
|
||||
}
|
||||
val flexiblePositions =
|
||||
placedIndices.indices.filter { position ->
|
||||
val slot = slots[placedIndices[position]]
|
||||
slot.kind == OverflowSlotKind.Flexible && slot.weight > 0f
|
||||
}
|
||||
if (flexiblePositions.isEmpty()) {
|
||||
return
|
||||
}
|
||||
val totalWeight = flexiblePositions.sumOf { position -> slots[placedIndices[position]].weight.toDouble() }
|
||||
var assignedPx = 0
|
||||
val fractions = DoubleArray(flexiblePositions.size)
|
||||
flexiblePositions.forEachIndexed { flexibleIndex, position ->
|
||||
val exact = leftoverPx * slots[placedIndices[position]].weight / totalWeight
|
||||
val whole = exact.toInt()
|
||||
// Added to the floor the walk already spent, not written over it - the leftover is what is free
|
||||
// BEYOND the floors, so overwriting would hand the floor's own pixels out a second time.
|
||||
placedWidths[position] = placedWidths[position] + whole
|
||||
fractions[flexibleIndex] = exact - whole
|
||||
assignedPx += whole
|
||||
}
|
||||
// Hand the rounding remainder to the largest fractional parts, earliest gap first on a tie.
|
||||
val byLargestFraction = flexiblePositions.indices.sortedWith(compareByDescending<Int> { fractions[it] }.thenBy { it })
|
||||
var remainderPx = leftoverPx - assignedPx
|
||||
var cursor = 0
|
||||
while (remainderPx > 0 && byLargestFraction.isNotEmpty()) {
|
||||
val position = flexiblePositions[byLargestFraction[cursor % byLargestFraction.size]]
|
||||
placedWidths[position] = placedWidths[position] + 1
|
||||
remainderPx -= 1
|
||||
cursor += 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.gestures.detectDragGestures
|
||||
import androidx.compose.foundation.gestures.detectTapGestures
|
||||
import androidx.compose.foundation.layout.aspectRatio
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.geometry.Size
|
||||
import androidx.compose.ui.graphics.drawscope.Stroke
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.unit.dp
|
||||
import org.umamo.ui.theme.LocalUmamoColors
|
||||
|
||||
/**
|
||||
* A flat, draggable 2D pad for a LINKED ("combined") parameter pair: a recessed square drawing a
|
||||
* nine-point reference grid plus a single handle, set by tap or drag anywhere on the control. The X axis
|
||||
* runs left to right over [xRange]; the Y axis runs bottom to top over [yRange] - screen-top is the
|
||||
* maximum, matching how Cubism orients its combined-parameter pad. The control is sized entirely by
|
||||
* [modifier]: supply both a width and a bounded height (e.g.
|
||||
* `Modifier.fillMaxWidth().heightIn(max = 200.dp)`), because a Canvas otherwise expands to fill all the
|
||||
* space offered - inside a scrolling column that would overrun the rows beneath it. The grid and handle
|
||||
* scale to whatever rectangle results, so a non-square pad is fine (each axis maps independently).
|
||||
*
|
||||
* 2D パッド(リンクパラメータ対用)。X は左右、Y は下上(上端が最大)。大きさは [modifier] で指定(幅と高さの上限)。
|
||||
*
|
||||
* [onChange] streams the live (X, Y) for every tap / drag frame; [onChangeFinished] fires once at the
|
||||
* gesture boundary (tap, drag release, or cancel), so a whole drag can be committed as one gesture.
|
||||
*
|
||||
* @param Float xValue The current X-axis value.
|
||||
* @param Float yValue The current Y-axis value.
|
||||
* @param Function onChange Called with (newX, newY) on each tap / drag frame (the preview).
|
||||
* @param Modifier modifier Layout modifier (supply the width and a bounded height).
|
||||
* @param Function onChangeFinished Called once when the gesture ends (tap, drag release, or cancel).
|
||||
* @param ClosedFloatingPointRange xRange The X-axis min..max range.
|
||||
* @param ClosedFloatingPointRange yRange The Y-axis min..max range.
|
||||
*/
|
||||
@Composable
|
||||
fun Pad2D(
|
||||
xValue: Float,
|
||||
yValue: Float,
|
||||
onChange: (Float, Float) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
onChangeFinished: () -> Unit = {},
|
||||
xRange: ClosedFloatingPointRange<Float> = 0f..1f,
|
||||
yRange: ClosedFloatingPointRange<Float> = 0f..1f,
|
||||
) {
|
||||
val colors = LocalUmamoColors.current
|
||||
val xSpan = (xRange.endInclusive - xRange.start).takeIf { it != 0f } ?: 1f
|
||||
val ySpan = (yRange.endInclusive - yRange.start).takeIf { it != 0f } ?: 1f
|
||||
val xFraction = ((xValue - xRange.start) / xSpan).coerceIn(0f, 1f)
|
||||
// Y is inverted: the maximum sits at the top, so a value fraction of 1 maps to screen y = 0.
|
||||
val yFractionFromTop = 1f - ((yValue - yRange.start) / ySpan).coerceIn(0f, 1f)
|
||||
val trackColor = colors.sliderTrack
|
||||
val borderColor = colors.controlBorder
|
||||
val gridColor = colors.guideLine
|
||||
val crossColor = colors.divider
|
||||
val handleColor = colors.sliderThumb
|
||||
val handleRingColor = colors.accent
|
||||
// pointerInput is keyed only on the ranges, so it does not restart when a recomposition hands in a new
|
||||
// onChange (a reused list slot binding to a different pair). Read the latest through this so a drag
|
||||
// always drives the current pair, never the one that first occupied the slot.
|
||||
val currentOnChange by rememberUpdatedState(onChange)
|
||||
val currentOnChangeFinished by rememberUpdatedState(onChangeFinished)
|
||||
Canvas(
|
||||
modifier =
|
||||
modifier
|
||||
.aspectRatio(1.5f)
|
||||
.pointerInput(xRange, yRange) {
|
||||
detectTapGestures { offset ->
|
||||
currentOnChange(
|
||||
valueAt(offset.x, size.width.toFloat(), xRange, invert = false),
|
||||
valueAt(offset.y, size.height.toFloat(), yRange, invert = true),
|
||||
)
|
||||
currentOnChangeFinished()
|
||||
}
|
||||
}
|
||||
.pointerInput(xRange, yRange) {
|
||||
detectDragGestures(
|
||||
onDragEnd = { currentOnChangeFinished() },
|
||||
onDragCancel = { currentOnChangeFinished() },
|
||||
) { change, _ ->
|
||||
change.consume()
|
||||
currentOnChange(
|
||||
valueAt(change.position.x, size.width.toFloat(), xRange, invert = false),
|
||||
valueAt(change.position.y, size.height.toFloat(), yRange, invert = true),
|
||||
)
|
||||
}
|
||||
},
|
||||
) {
|
||||
val padWidth = size.width
|
||||
val padHeight = size.height
|
||||
drawRect(color = trackColor, size = Size(padWidth, padHeight))
|
||||
drawRect(color = borderColor, size = Size(padWidth, padHeight), style = Stroke(width = 1.dp.toPx()))
|
||||
// A faint center cross for orientation; the thirds would over-clutter, so the center is enough.
|
||||
drawLine(crossColor, Offset(padWidth / 2f, 0f), Offset(padWidth / 2f, padHeight), strokeWidth = 1.dp.toPx())
|
||||
drawLine(crossColor, Offset(0f, padHeight / 2f), Offset(padWidth, padHeight / 2f), strokeWidth = 1.dp.toPx())
|
||||
// Nine reference dots at the 0 / 0.5 / 1 grid intersections on each axis.
|
||||
val dotRadius = 1.5.dp.toPx()
|
||||
for (gridRow in 0..2) {
|
||||
for (gridColumn in 0..2) {
|
||||
val center = Offset(padWidth * gridColumn / 2f, padHeight * gridRow / 2f)
|
||||
drawCircle(color = gridColor, radius = dotRadius, center = center)
|
||||
}
|
||||
}
|
||||
// The handle at the current value (X across, Y measured from the top).
|
||||
val handleCenter =
|
||||
Offset(
|
||||
(padWidth * xFraction).coerceIn(0f, padWidth),
|
||||
(padHeight * yFractionFromTop).coerceIn(0f, padHeight),
|
||||
)
|
||||
drawCircle(color = handleColor, radius = 5.dp.toPx(), center = handleCenter)
|
||||
drawCircle(
|
||||
color = handleRingColor,
|
||||
radius = 5.dp.toPx(),
|
||||
center = handleCenter,
|
||||
style = Stroke(width = 1.5.dp.toPx()),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps a pointer coordinate within [extent] onto [range], clamped to the ends. When [invert] is set the
|
||||
* axis is flipped so coordinate 0 (the top of a Canvas) becomes the range maximum - used for the Y axis,
|
||||
* where screen-top should read as the highest value.
|
||||
*
|
||||
* @param Float coordinate The pointer position along the axis (x or y).
|
||||
* @param Float extent The axis length in pixels (width or height).
|
||||
* @param ClosedFloatingPointRange range The min..max value range.
|
||||
* @param Boolean invert When true, flip so coordinate 0 maps to the range maximum.
|
||||
* @return Float The clamped value for that coordinate.
|
||||
*/
|
||||
private fun valueAt(
|
||||
coordinate: Float,
|
||||
extent: Float,
|
||||
range: ClosedFloatingPointRange<Float>,
|
||||
invert: Boolean,
|
||||
): Float {
|
||||
val safeExtent = extent.takeIf { it > 0f } ?: 1f
|
||||
val rawFraction = (coordinate / safeExtent).coerceIn(0f, 1f)
|
||||
val fraction =
|
||||
if (invert) {
|
||||
1f - rawFraction
|
||||
} else {
|
||||
rawFraction
|
||||
}
|
||||
return range.start + fraction * (range.endInclusive - range.start)
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.collectIsHoveredAsState
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ColumnScope
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.focusProperties
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.unit.dp
|
||||
import org.umamo.ui.theme.LocalUmamoColors
|
||||
import org.umamo.ui.theme.LocalUmamoTypography
|
||||
|
||||
/**
|
||||
* A thin-bordered panel with a header bar (title on the left, an optional [headerAction] on the right) over a
|
||||
* tight content column.
|
||||
*
|
||||
* @param String title The header title.
|
||||
* @param Modifier modifier Layout modifier.
|
||||
* @param Function headerAction Optional trailing header content (e.g. a [Button]).
|
||||
* @param Function content The panel body.
|
||||
*/
|
||||
@Composable
|
||||
fun Panel(
|
||||
title: String,
|
||||
modifier: Modifier = Modifier,
|
||||
headerAction: (@Composable () -> Unit)? = null,
|
||||
content: @Composable ColumnScope.() -> Unit,
|
||||
) {
|
||||
val colors = LocalUmamoColors.current
|
||||
Column(modifier = modifier.border(1.dp, colors.panelBorder).background(colors.panelBackground)) {
|
||||
Row(
|
||||
modifier =
|
||||
Modifier.fillMaxWidth().background(colors.headerBackground)
|
||||
.padding(horizontal = 6.dp, vertical = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(text = title, style = LocalUmamoTypography.current.labelLarge)
|
||||
Spacer(modifier = Modifier.weight(1f))
|
||||
headerAction?.invoke()
|
||||
}
|
||||
Column(modifier = Modifier.padding(6.dp), content = content)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A disclosure row: a small chevron (right when collapsed, down when expanded) plus a label, the whole row
|
||||
* clickable to [onToggle], with a hover highlight.
|
||||
*
|
||||
* @param String label The section label.
|
||||
* @param Boolean expanded Whether the section is open.
|
||||
* @param Function onToggle Toggle callback.
|
||||
* @param Modifier modifier Layout modifier (e.g. a leading indent for a nested section).
|
||||
*/
|
||||
@Composable
|
||||
fun SectionHeader(label: String, expanded: Boolean, onToggle: () -> Unit, modifier: Modifier = Modifier) {
|
||||
val colors = LocalUmamoColors.current
|
||||
val interaction = remember { MutableInteractionSource() }
|
||||
val hovered by interaction.collectIsHoveredAsState()
|
||||
Row(
|
||||
modifier =
|
||||
modifier
|
||||
.fillMaxWidth()
|
||||
.height(22.dp)
|
||||
.background(if (hovered) colors.rowHover else Color.Transparent)
|
||||
// NOT focusable: a header can sit in chrome that leaves the composition on the next edit (the
|
||||
// operation settings strip, a Properties section that hides when its rows go), and Compose
|
||||
// leaves focus null when the focused node is disposed - every keyboard shortcut then dies
|
||||
// until something focusable is clicked again. The keyboard belongs to the shell root.
|
||||
.focusProperties { canFocus = false }
|
||||
.clickable(interactionSource = interaction, indication = null, onClick = onToggle)
|
||||
.padding(horizontal = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
DisclosureChevron(expanded = expanded, tint = colors.text, glyphSize = 10.dp)
|
||||
Spacer(modifier = Modifier.width(5.dp))
|
||||
Text(text = label, style = LocalUmamoTypography.current.labelMedium)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,354 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.alpha
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.geometry.Size
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.input.pointer.PointerEventType
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.layout.layout
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.unit.dp
|
||||
import org.jetbrains.compose.resources.StringResource
|
||||
import org.jetbrains.compose.resources.stringResource
|
||||
import org.umamo.ui.action.LocalCommands
|
||||
import org.umamo.ui.theme.LocalUmamoColors
|
||||
import org.umamo.ui.theme.LocalUmamoShapes
|
||||
import org.umamo.ui.theme.LocalUmamoTypography
|
||||
import org.umamo.ui.theme.UmamoIcon
|
||||
import org.umamo.ui.theme.drawIcon
|
||||
import kotlin.math.PI
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.atan2
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.roundToInt
|
||||
import kotlin.math.sin
|
||||
|
||||
/**
|
||||
* One radial pie-menu entry. Entries dispatch through the command registry (the action-registry
|
||||
* guardrail - the pie never hardcodes a handler), so a rebind or palette invocation of the same
|
||||
* command behaves identically.
|
||||
*
|
||||
* パイメニューの1項目。コマンドレジストリ経由で実行される。
|
||||
*
|
||||
* @property String commandId The command to invoke when picked.
|
||||
* @property StringResource label The entry's localized label.
|
||||
* @property Any? argument Optional argument forwarded to the command handler.
|
||||
* @property Boolean enabled False renders the entry dimmed and refuses the pick.
|
||||
* @property UmamoIcon? icon The entry's leading icon; null renders the bright-pink placeholder
|
||||
* square, a deliberately loud reminder that the entry still needs an authored icon.
|
||||
*/
|
||||
data class PieMenuEntry(
|
||||
val commandId: String,
|
||||
val label: StringResource,
|
||||
val argument: Any? = null,
|
||||
val enabled: Boolean = true,
|
||||
val icon: UmamoIcon? = null,
|
||||
)
|
||||
|
||||
// Blender's slot order for up to eight pie entries: W, E, S, N, NW, NE, SW, SE - the first entries
|
||||
// land on the cardinal directions, so a four-entry pie reads as a clean compass. Angles are radians
|
||||
// in screen space (y down).
|
||||
private val PIE_SLOT_ANGLES =
|
||||
floatArrayOf(
|
||||
PI.toFloat(), // W
|
||||
0f, // E
|
||||
(PI / 2).toFloat(), // S
|
||||
(-PI / 2).toFloat(), // N
|
||||
(-3 * PI / 4).toFloat(), // NW
|
||||
(-PI / 4).toFloat(), // NE
|
||||
(3 * PI / 4).toFloat(), // SW
|
||||
(PI / 4).toFloat(), // SE
|
||||
)
|
||||
|
||||
/** The ring radius the entry chips sit on. */
|
||||
private val PIE_RADIUS = 96.dp
|
||||
|
||||
/** How far past the chip ring the wedge background disc extends. */
|
||||
private val PIE_DISC_OVERSHOOT = 40.dp
|
||||
|
||||
/** The entry chips' leading icon size (the pink placeholder square shares it). */
|
||||
private val PIE_ICON_SIZE = 12.dp
|
||||
|
||||
/**
|
||||
* The horizontal half-extent reserved for a West / East chip when clamping the pie center: the chips
|
||||
* sit centered ON the ring, so the ring radius plus this covers the widest labels. Conservative - a
|
||||
* pathological label still has the per-chip coercion as its safety net.
|
||||
*/
|
||||
private val PIE_CHIP_MAX_HALF_WIDTH = 120.dp
|
||||
|
||||
/** Pointer travel (px) from the pie center below which a release dismisses instead of picking. */
|
||||
private const val PIE_DEAD_ZONE_PX = 24f
|
||||
|
||||
/** The placeholder tint for an entry with no authored icon yet - deliberately loud (see PieMenuEntry.icon). */
|
||||
private val PIE_ICON_PLACEHOLDER = Color(0xFFFF2BD6)
|
||||
|
||||
/**
|
||||
* A Blender-style radial pie menu centered at [center]: up to eight entries on a ring, picked by
|
||||
* DIRECTION from the center (not chip bounds), so a coarse flick works as well as a precise click -
|
||||
* and the same gesture works for press-drag-release (pen-friendly; the future pen radial menu reuses
|
||||
* this component). A click (or release) inside the dead zone, or on a disabled entry's direction,
|
||||
* dismisses without invoking. Escape is the shell's to route (it closes the pie via the session
|
||||
* latch), and so are the 1..N instant digit picks; this composable only handles pointer input.
|
||||
*
|
||||
* The wedge background disc makes the direction mapping readable: each entry's sector is the exact
|
||||
* angular region the pick function resolves to it (the angular Voronoi of the used slot directions),
|
||||
* with the hovered sector highlighted; the dead zone renders as the center disc, holding [title].
|
||||
*
|
||||
* The center is CLAMPED so the full ring fits inside the overlay's bounds (Blender constrains its
|
||||
* pies to the screen the same way): the whole pie shifts inward rather than squishing chips at an
|
||||
* edge. The clamp lives here - not in the host - because the direction pick, the wedges, the title,
|
||||
* and the chips must all share the one effective center or the pick math desyncs from the drawing.
|
||||
*
|
||||
* Blender 風の放射状パイメニュー。方向で選択するため、クリックでもドラッグ&リリースでも使える。
|
||||
* 扇形の背景が方向と項目の対応を示し、中央の円にタイトルが乗る。中心はリング全体が収まるよう
|
||||
* オーバーレイ境界内にクランプされる。
|
||||
*
|
||||
* @param List<PieMenuEntry> entries The entries, in Blender slot order (W, E, S, N, NW, NE, SW, SE).
|
||||
* @param Offset center The requested pie center in the host's local pixels (frozen at open by the
|
||||
* host); the rendered center is this clamped inside the overlay so the ring never clips.
|
||||
* @param Function onDismiss Called after an invocation or a dismissing click.
|
||||
* @param StringResource? title The pie's name, rendered at the center (null for none).
|
||||
* @param Modifier modifier The layout modifier (the host passes a stack fill).
|
||||
*/
|
||||
@Composable
|
||||
fun PieMenuOverlay(
|
||||
entries: List<PieMenuEntry>,
|
||||
center: Offset,
|
||||
onDismiss: () -> Unit,
|
||||
title: StringResource? = null,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val commands = LocalCommands.current
|
||||
val colors = LocalUmamoColors.current
|
||||
val shapes = LocalUmamoShapes.current
|
||||
val density = LocalDensity.current
|
||||
val liveEntries = rememberUpdatedState(entries)
|
||||
var hoveredSlot by remember { mutableStateOf(-1) }
|
||||
|
||||
BoxWithConstraints(modifier = modifier.fillMaxSize()) {
|
||||
// The center everything draws and picks from: [center] shifted so the full ring - disc
|
||||
// vertically, ring plus the widest chip horizontally - fits inside these bounds. An overlay
|
||||
// too small to fit the pie at all centers it instead (coerceIn would throw on min > max).
|
||||
val effectiveCenter =
|
||||
with(density) {
|
||||
val horizontalMargin = PIE_RADIUS.toPx() + PIE_CHIP_MAX_HALF_WIDTH.toPx()
|
||||
val verticalMargin = PIE_RADIUS.toPx() + PIE_DISC_OVERSHOOT.toPx()
|
||||
val boundsWidth = constraints.maxWidth.toFloat()
|
||||
val boundsHeight = constraints.maxHeight.toFloat()
|
||||
Offset(
|
||||
if (boundsWidth >= 2f * horizontalMargin) center.x.coerceIn(horizontalMargin, boundsWidth - horizontalMargin) else boundsWidth / 2f,
|
||||
if (boundsHeight >= 2f * verticalMargin) center.y.coerceIn(verticalMargin, boundsHeight - verticalMargin) else boundsHeight / 2f,
|
||||
)
|
||||
}
|
||||
// The pointer loop below outlives recompositions (pointerInput(Unit)), so it must read the
|
||||
// center through a live reference - a window resize while the pie is open moves the clamp.
|
||||
val liveCenter = rememberUpdatedState(effectiveCenter)
|
||||
|
||||
/**
|
||||
* Picks the entry slot whose direction is nearest the pointer's direction from the center.
|
||||
*
|
||||
* @param Offset position The pointer position in the overlay's coordinates.
|
||||
* @return Int The nearest slot index, or -1 inside the dead zone.
|
||||
*/
|
||||
fun slotAt(position: Offset): Int {
|
||||
val delta = position - liveCenter.value
|
||||
if (delta.getDistance() < PIE_DEAD_ZONE_PX) {
|
||||
return -1
|
||||
}
|
||||
val pointerAngle = atan2(delta.y, delta.x)
|
||||
var best = -1
|
||||
var bestDifference = Float.MAX_VALUE
|
||||
for (slotIndex in liveEntries.value.indices) {
|
||||
var difference = abs(pointerAngle - PIE_SLOT_ANGLES[slotIndex])
|
||||
if (difference > PI.toFloat()) {
|
||||
difference = 2 * PI.toFloat() - difference
|
||||
}
|
||||
if (difference < bestDifference) {
|
||||
bestDifference = difference
|
||||
best = slotIndex
|
||||
}
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
Box(
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.pointerInput(Unit) {
|
||||
awaitPointerEventScope {
|
||||
while (true) {
|
||||
val event = awaitPointerEvent()
|
||||
val change = event.changes.firstOrNull() ?: continue
|
||||
when (event.type) {
|
||||
PointerEventType.Move -> hoveredSlot = slotAt(change.position)
|
||||
|
||||
PointerEventType.Release -> {
|
||||
// Only the release picks: a click and a press-drag-release both end in exactly
|
||||
// one Release, so one gesture invokes the command exactly once - picking on
|
||||
// Press as well would double-invoke non-idempotent commands like merge.
|
||||
// A dead-zone or disabled-direction release dismisses without invoking.
|
||||
val slotIndex = slotAt(change.position)
|
||||
val entry = liveEntries.value.getOrNull(slotIndex)
|
||||
if (entry != null && entry.enabled) {
|
||||
commands.invoke(entry.commandId, entry.argument)
|
||||
}
|
||||
onDismiss()
|
||||
}
|
||||
|
||||
// A press only anchors the gesture (and is consumed below); its release decides.
|
||||
PointerEventType.Press -> {}
|
||||
|
||||
else -> {}
|
||||
}
|
||||
change.consume()
|
||||
}
|
||||
}
|
||||
},
|
||||
) {
|
||||
// The wedge background: each used slot's sector spans the midpoints to its angular neighbors -
|
||||
// exactly the region slotAt() resolves to it - with the hovered sector highlighted and the dead
|
||||
// zone drawn as the center disc. Drawn beneath the chips so labels stay crisp.
|
||||
Canvas(modifier = Modifier.fillMaxSize()) {
|
||||
val outerRadius = PIE_RADIUS.toPx() + PIE_DISC_OVERSHOOT.toPx()
|
||||
val discTopLeft = Offset(effectiveCenter.x - outerRadius, effectiveCenter.y - outerRadius)
|
||||
val discSize = Size(outerRadius * 2, outerRadius * 2)
|
||||
val sortedSlots = entries.indices.sortedBy { slotIndex -> PIE_SLOT_ANGLES[slotIndex] }
|
||||
for ((sortedPosition, slotIndex) in sortedSlots.withIndex()) {
|
||||
val slotAngle = PIE_SLOT_ANGLES[slotIndex]
|
||||
val startDeg: Float
|
||||
val sweepDeg: Float
|
||||
if (sortedSlots.size == 1) {
|
||||
startDeg = 0f
|
||||
sweepDeg = 360f
|
||||
} else {
|
||||
val previousAngle = PIE_SLOT_ANGLES[sortedSlots[(sortedPosition - 1 + sortedSlots.size) % sortedSlots.size]]
|
||||
val nextAngle = PIE_SLOT_ANGLES[sortedSlots[(sortedPosition + 1) % sortedSlots.size]]
|
||||
var gapBefore = slotAngle - previousAngle
|
||||
if (gapBefore <= 0f) {
|
||||
gapBefore += 2f * PI.toFloat()
|
||||
}
|
||||
var gapAfter = nextAngle - slotAngle
|
||||
if (gapAfter <= 0f) {
|
||||
gapAfter += 2f * PI.toFloat()
|
||||
}
|
||||
startDeg = (slotAngle - gapBefore / 2f) * 180f / PI.toFloat()
|
||||
sweepDeg = (gapBefore + gapAfter) / 2f * 180f / PI.toFloat()
|
||||
}
|
||||
val hovered = slotIndex == hoveredSlot && entries[slotIndex].enabled
|
||||
drawArc(
|
||||
color = if (hovered) colors.accent.copy(alpha = 0.25f) else colors.viewportBadgeBackground,
|
||||
startAngle = startDeg,
|
||||
sweepAngle = sweepDeg,
|
||||
useCenter = true,
|
||||
topLeft = discTopLeft,
|
||||
size = discSize,
|
||||
)
|
||||
}
|
||||
// Sector separators, then the dead-zone disc (the dismiss region reads as "no pick").
|
||||
if (sortedSlots.size > 1) {
|
||||
for ((sortedPosition, slotIndex) in sortedSlots.withIndex()) {
|
||||
val nextAngle = PIE_SLOT_ANGLES[sortedSlots[(sortedPosition + 1) % sortedSlots.size]]
|
||||
var gapAfter = nextAngle - PIE_SLOT_ANGLES[slotIndex]
|
||||
if (gapAfter <= 0f) {
|
||||
gapAfter += 2f * PI.toFloat()
|
||||
}
|
||||
val boundary = PIE_SLOT_ANGLES[slotIndex] + gapAfter / 2f
|
||||
drawLine(
|
||||
color = colors.panelBorder,
|
||||
start = effectiveCenter,
|
||||
end = Offset(effectiveCenter.x + cos(boundary) * outerRadius, effectiveCenter.y + sin(boundary) * outerRadius),
|
||||
strokeWidth = 1f,
|
||||
)
|
||||
}
|
||||
}
|
||||
drawCircle(color = colors.panelBackground, radius = PIE_DEAD_ZONE_PX * 1.6f, center = effectiveCenter)
|
||||
}
|
||||
if (title != null) {
|
||||
Text(
|
||||
text = stringResource(title),
|
||||
style = LocalUmamoTypography.current.labelSmall,
|
||||
color = colors.textMuted,
|
||||
modifier =
|
||||
Modifier.layout { measurable, constraints ->
|
||||
val placeable = measurable.measure(constraints.copy(minWidth = 0, minHeight = 0))
|
||||
layout(constraints.maxWidth, constraints.maxHeight) {
|
||||
placeable.place(
|
||||
(effectiveCenter.x - placeable.width / 2f).roundToInt().coerceIn(0, (constraints.maxWidth - placeable.width).coerceAtLeast(0)),
|
||||
(effectiveCenter.y - placeable.height / 2f).roundToInt().coerceIn(0, (constraints.maxHeight - placeable.height).coerceAtLeast(0)),
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
entries.forEachIndexed { slotIndex, entry ->
|
||||
val angle = PIE_SLOT_ANGLES[slotIndex]
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier =
|
||||
Modifier
|
||||
.layout { measurable, constraints ->
|
||||
val placeable = measurable.measure(constraints.copy(minWidth = 0, minHeight = 0))
|
||||
layout(constraints.maxWidth, constraints.maxHeight) {
|
||||
val radiusPx = PIE_RADIUS.toPx()
|
||||
val slotX = (effectiveCenter.x + cos(angle) * radiusPx - placeable.width / 2f).roundToInt()
|
||||
val slotY = (effectiveCenter.y + sin(angle) * radiusPx - placeable.height / 2f).roundToInt()
|
||||
placeable.place(
|
||||
slotX.coerceIn(0, (constraints.maxWidth - placeable.width).coerceAtLeast(0)),
|
||||
slotY.coerceIn(0, (constraints.maxHeight - placeable.height).coerceAtLeast(0)),
|
||||
)
|
||||
}
|
||||
}
|
||||
.background(
|
||||
if (slotIndex == hoveredSlot && entry.enabled) colors.accent.copy(alpha = 0.25f) else colors.viewportBadgeBackground,
|
||||
shapes.small,
|
||||
)
|
||||
.alpha(if (entry.enabled) 1f else 0.4f)
|
||||
.padding(horizontal = 10.dp, vertical = 5.dp),
|
||||
) {
|
||||
// The leading icon; a missing one renders the loud placeholder square (an authoring reminder).
|
||||
val entryIcon = entry.icon
|
||||
Canvas(modifier = Modifier.size(PIE_ICON_SIZE)) {
|
||||
if (entryIcon != null) {
|
||||
drawIcon(entryIcon, colors.controlGlyph)
|
||||
} else {
|
||||
drawRect(color = PIE_ICON_PLACEHOLDER)
|
||||
}
|
||||
}
|
||||
Spacer(modifier = Modifier.width(6.dp))
|
||||
// The instant digit shortcut (the shell's pie key branch maps 1..N to the entry order).
|
||||
Text(
|
||||
text = "${slotIndex + 1}",
|
||||
style = LocalUmamoTypography.current.labelSmall,
|
||||
color = colors.textMuted,
|
||||
)
|
||||
Spacer(modifier = Modifier.width(6.dp))
|
||||
Text(
|
||||
text = stringResource(entry.label),
|
||||
style = LocalUmamoTypography.current.labelMedium,
|
||||
color = if (slotIndex == hoveredSlot && entry.enabled) colors.text else colors.textMuted,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ColumnScope
|
||||
import androidx.compose.foundation.layout.IntrinsicSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Popup
|
||||
import androidx.compose.ui.window.PopupProperties
|
||||
import org.umamo.ui.theme.LocalUmamoColors
|
||||
import org.umamo.ui.theme.LocalUmamoShapes
|
||||
import org.umamo.ui.theme.UmamoIcon
|
||||
|
||||
/**
|
||||
* A [DropdownChip] over a stay-open panel of arbitrary content: only an outside click or Esc dismisses
|
||||
* it, so several controls can be driven in one visit. That is the whole reason this is a raw [Popup]
|
||||
* rather than the kit [Menu], which dismisses per click - and the reason [DropdownChip] leaves its
|
||||
* dropdown a slot in the first place.
|
||||
*
|
||||
* The panel provides [LocalPopupDismissOwned], so a [Menu] or nested chip composed inside the content
|
||||
* yields the dismiss to this popup instead of fighting it for focus.
|
||||
*
|
||||
* Open state is optionally hoistable: leave [expanded] null and the chip owns it (the common case), or
|
||||
* pass it with [onExpandedChange] when the caller has to force the panel shut - the overflow row does,
|
||||
* since a strip that widens while the panel is open would otherwise leave it anchored to nothing.
|
||||
*
|
||||
* @param String contentDescription The accessible label for the chip (the face is icon-only).
|
||||
* @param Modifier modifier The layout modifier.
|
||||
* @param UmamoIcon icon The chip's leading glyph, or null for a chevron-only face.
|
||||
* @param Boolean? expanded The open state when hoisted; null to let the chip own it.
|
||||
* @param Function? onExpandedChange Open-state sink, required when [expanded] is hoisted.
|
||||
* @param Boolean enabled When false the chip dims and clicks are inert.
|
||||
* @param DropdownChipStyle style The face's role: Header chrome by default, Compact for a list row.
|
||||
* @param Color? iconTint A status color for the glyph at rest, or null for the chip's own content color.
|
||||
* @param Function content The panel's rows.
|
||||
*/
|
||||
@Composable
|
||||
fun PopupChip(
|
||||
contentDescription: String,
|
||||
modifier: Modifier = Modifier,
|
||||
icon: UmamoIcon? = null,
|
||||
expanded: Boolean? = null,
|
||||
onExpandedChange: ((Boolean) -> Unit)? = null,
|
||||
enabled: Boolean = true,
|
||||
style: DropdownChipStyle = DropdownChipStyle.Header,
|
||||
iconTint: Color? = null,
|
||||
content: @Composable ColumnScope.() -> Unit,
|
||||
) {
|
||||
var selfOpen by remember { mutableStateOf(false) }
|
||||
val open = expanded ?: selfOpen
|
||||
val setOpen: (Boolean) -> Unit = { next ->
|
||||
if (onExpandedChange != null) {
|
||||
onExpandedChange(next)
|
||||
} else {
|
||||
selfOpen = next
|
||||
}
|
||||
}
|
||||
DropdownChip(
|
||||
expanded = open,
|
||||
onExpandRequest = { setOpen(true) },
|
||||
contentDescription = contentDescription,
|
||||
modifier = modifier,
|
||||
icon = icon,
|
||||
enabled = enabled,
|
||||
style = style,
|
||||
iconTint = iconTint,
|
||||
) {
|
||||
PopupPanel(onDismissRequest = { setOpen(false) }, content = content)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The stay-open panel a [PopupChip] drops: a raw [Popup] below its anchor, styled like the kit [Menu]
|
||||
* (the dark panel fill, medium corners) but dismissed only by an outside click or Esc, so several
|
||||
* controls can be driven in one visit. Composable on its own inside a [DropdownChip] slot, for a chip
|
||||
* that shows a [Menu] on one visit and a panel on the next (a review chip's relink-by-hand list).
|
||||
*
|
||||
* The panel provides [LocalPopupDismissOwned], so a [Menu] or nested chip composed inside the content
|
||||
* yields the dismiss to this popup instead of fighting it for focus.
|
||||
*
|
||||
* @param Function onDismissRequest Called on an outside click or Esc.
|
||||
* @param Function content The panel's rows.
|
||||
*/
|
||||
@Composable
|
||||
fun PopupPanel(onDismissRequest: () -> Unit, content: @Composable ColumnScope.() -> Unit) {
|
||||
val colors = LocalUmamoColors.current
|
||||
Popup(
|
||||
popupPositionProvider = BelowAnchorPositionProvider,
|
||||
onDismissRequest = onDismissRequest,
|
||||
properties = PopupProperties(focusable = true),
|
||||
) {
|
||||
CompositionLocalProvider(LocalPopupDismissOwned provides true) {
|
||||
Surface(color = colors.menuBackground, shape = LocalUmamoShapes.current.medium) {
|
||||
// Intrinsic width so the panel hugs its widest row rather than needing a magic dp.
|
||||
Column(modifier = Modifier.width(IntrinsicSize.Max).padding(vertical = 4.dp), content = content)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.itemsIndexed
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.foundation.text.BasicTextField
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
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
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.focus.focusProperties
|
||||
import androidx.compose.ui.focus.onFocusChanged
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.SolidColor
|
||||
import androidx.compose.ui.input.key.Key
|
||||
import androidx.compose.ui.input.key.KeyEventType
|
||||
import androidx.compose.ui.input.key.key
|
||||
import androidx.compose.ui.input.key.onPreviewKeyEvent
|
||||
import androidx.compose.ui.input.key.type
|
||||
import androidx.compose.ui.layout.onSizeChanged
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.platform.LocalFocusManager
|
||||
import androidx.compose.ui.unit.DpSize
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Popup
|
||||
import androidx.compose.ui.window.PopupProperties
|
||||
import org.umamo.ui.kit.button.IconButton
|
||||
import org.umamo.ui.theme.LocalUmamoColors
|
||||
import org.umamo.ui.theme.LocalUmamoIcons
|
||||
import org.umamo.ui.theme.LocalUmamoShapes
|
||||
import org.umamo.ui.theme.LocalUmamoTypography
|
||||
import org.umamo.ui.theme.UmamoIcon
|
||||
import org.umamo.ui.theme.drawIcon
|
||||
|
||||
/** Edge length of the leading type glyph and the trailing affordances inside a relation field. */
|
||||
private val RELATION_GLYPH_SIZE = 14.dp
|
||||
|
||||
/** How tall the candidate dropdown may grow before it scrolls. */
|
||||
private val RELATION_DROPDOWN_MAX_HEIGHT = 260.dp
|
||||
|
||||
/** The narrowest the dropdown may be, so it stays readable before the anchor has been measured. */
|
||||
private val RELATION_DROPDOWN_MIN_WIDTH = 140.dp
|
||||
|
||||
/**
|
||||
* A Blender-style single relation picker: one box that shows the bound entity and, once focused, doubles
|
||||
* as the search field for rebinding it. A leading glyph carries the bound entity's type, a trailing "x"
|
||||
* clears the binding, and a trailing eyedropper (when [onPick] is supplied) hands the pick to the viewport
|
||||
* or the outliner instead of the list.
|
||||
*
|
||||
* `[type glyph] [current relation, or the typed query] [x] [eyedropper]`
|
||||
*
|
||||
* Focusing the field swaps its text for an empty query and opens the candidate list; blurring restores the
|
||||
* bound entity's name. The dropdown is deliberately NON-focusable and its rows decline focus, so clicking
|
||||
* a row cannot blur the field out from under the click (the classic combo-box race); it closes on commit,
|
||||
* Escape, or the field losing focus. Up / Down / Enter are intercepted ahead of the field so they navigate
|
||||
* the list while ordinary typing still reaches it.
|
||||
*
|
||||
* Like [NumberField] and [HexColorField] it lends its cancel hook to [LocalInlineEditController] while
|
||||
* focused, so the shell's root key handler yields keystrokes to the field instead of firing shortcuts.
|
||||
*
|
||||
* @param T The candidate entity type.
|
||||
* @param Object? selected The currently bound entity, or null when unbound.
|
||||
* @param List candidates Every entity that may be bound, in menu order.
|
||||
* @param Function label The display name of an entity (also what the search matches).
|
||||
* @param Function icon The type glyph of an entity.
|
||||
* @param Function onSelect Binds an entity, or null to clear the binding.
|
||||
* @param Modifier modifier The layout modifier (the caller supplies the width).
|
||||
* @param Function? onPick Arms an eyedropper pick, or null to omit the eyedropper.
|
||||
* @param Boolean picking Whether a pick armed by THIS field is in flight (lights the eyedropper).
|
||||
* @param String placeholder The muted text shown when nothing is bound.
|
||||
* @param String clearDescription The accessible label of the clear button (NOT the placeholder - that
|
||||
* would announce the search prompt as the button's name).
|
||||
* @param String pickDescription The accessible label of the eyedropper button.
|
||||
*/
|
||||
@Composable
|
||||
fun <T> RelationField(
|
||||
selected: T?,
|
||||
candidates: List<T>,
|
||||
label: (T) -> String,
|
||||
icon: (T) -> UmamoIcon,
|
||||
onSelect: (T?) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
onPick: (() -> Unit)? = null,
|
||||
picking: Boolean = false,
|
||||
placeholder: String = "",
|
||||
clearDescription: String = "",
|
||||
pickDescription: String = "",
|
||||
) {
|
||||
val colors = LocalUmamoColors.current
|
||||
val shapes = LocalUmamoShapes.current
|
||||
val typography = LocalUmamoTypography.current
|
||||
val controller = LocalInlineEditController.current
|
||||
val focusManager = LocalFocusManager.current
|
||||
val density = LocalDensity.current
|
||||
val listState = rememberLazyListState()
|
||||
|
||||
var focused by remember { mutableStateOf(false) }
|
||||
var query by remember { mutableStateOf("") }
|
||||
var highlighted by remember { mutableStateOf(0) }
|
||||
var anchorWidthPx by remember { mutableStateOf(0) }
|
||||
|
||||
val selectedLabel = selected?.let(label) ?: ""
|
||||
// The field is a search box while focused and a read-out of the binding otherwise.
|
||||
val fieldText = if (focused) query else selectedLabel
|
||||
val filtered =
|
||||
if (query.isBlank()) {
|
||||
candidates
|
||||
} else {
|
||||
candidates.filter { candidate -> label(candidate).contains(query.trim(), ignoreCase = true) }
|
||||
}
|
||||
// Filtering can shrink the list under the highlight, so clamp at read rather than on every edit.
|
||||
val safeIndex = highlighted.coerceIn(0, maxOf(0, filtered.size - 1))
|
||||
val open = focused
|
||||
|
||||
LaunchedEffect(query) {
|
||||
highlighted = 0
|
||||
}
|
||||
LaunchedEffect(safeIndex, open, filtered.size) {
|
||||
if (open && filtered.isNotEmpty()) {
|
||||
listState.scrollToItem(safeIndex)
|
||||
}
|
||||
}
|
||||
// Drop the lent cancel hook if the field disposes while focused (a section switch mid-edit).
|
||||
DisposableEffect(Unit) {
|
||||
onDispose {
|
||||
if (focused) {
|
||||
controller.cancel = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val commit: (T?) -> Unit = { value ->
|
||||
onSelect(value)
|
||||
query = ""
|
||||
// ONLY when this field actually holds focus. The clear "x" is shown while unfocused, and clearing
|
||||
// focus from there would null the shell root's focus owner - killing every keyboard shortcut until
|
||||
// Tab traversal reclaims it (the same hazard IconButton.suppressFocus exists to avoid). Blurring a
|
||||
// focused field is safe: dropping the lent inline-edit hook triggers the shell's focus-reclaim.
|
||||
if (focused) {
|
||||
focusManager.clearFocus()
|
||||
}
|
||||
}
|
||||
|
||||
Box(
|
||||
modifier =
|
||||
modifier
|
||||
.onSizeChanged { size -> anchorWidthPx = size.width }
|
||||
// Navigation keys are claimed ahead of the focused field; ordinary typing falls through to it.
|
||||
.onPreviewKeyEvent { event ->
|
||||
if (!open || event.type != KeyEventType.KeyDown) {
|
||||
return@onPreviewKeyEvent false
|
||||
}
|
||||
when (event.key) {
|
||||
Key.DirectionDown -> {
|
||||
if (filtered.isNotEmpty()) {
|
||||
highlighted = (safeIndex + 1) % filtered.size
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
Key.DirectionUp -> {
|
||||
if (filtered.isNotEmpty()) {
|
||||
highlighted = (safeIndex - 1 + filtered.size) % filtered.size
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
Key.Enter, Key.NumPadEnter -> {
|
||||
filtered.getOrNull(safeIndex)?.let { candidate -> commit(candidate) }
|
||||
true
|
||||
}
|
||||
|
||||
Key.Escape -> {
|
||||
query = ""
|
||||
focusManager.clearFocus()
|
||||
true
|
||||
}
|
||||
|
||||
else -> false
|
||||
}
|
||||
},
|
||||
) {
|
||||
Row(
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.height(FIELD_CONTROL_HEIGHT)
|
||||
.clip(shapes.small)
|
||||
.background(colors.tabBackground)
|
||||
.border(1.dp, colors.controlBorder, shapes.small)
|
||||
.padding(horizontal = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
val leadingGlyph = selected?.let(icon)
|
||||
if (leadingGlyph != null) {
|
||||
Canvas(modifier = Modifier.size(RELATION_GLYPH_SIZE)) {
|
||||
drawIcon(leadingGlyph, colors.textMuted)
|
||||
}
|
||||
Spacer(modifier = Modifier.width(4.dp))
|
||||
}
|
||||
BasicTextField(
|
||||
value = fieldText,
|
||||
onValueChange = { newText -> query = newText },
|
||||
textStyle = typography.bodySmall.copy(color = colors.text),
|
||||
singleLine = true,
|
||||
cursorBrush = SolidColor(colors.text),
|
||||
modifier =
|
||||
Modifier
|
||||
.weight(1f)
|
||||
.textEntrySurface(controller)
|
||||
.onFocusChanged { focusState ->
|
||||
// hasFocus (not isFocused): BasicTextField focuses an internal child.
|
||||
if (focusState.hasFocus) {
|
||||
if (!focused) {
|
||||
focused = true
|
||||
query = ""
|
||||
controller.cancel = { focusManager.clearFocus() }
|
||||
}
|
||||
} else if (focused) {
|
||||
focused = false
|
||||
query = ""
|
||||
controller.cancel = null
|
||||
}
|
||||
},
|
||||
decorationBox = { inner ->
|
||||
Box(contentAlignment = Alignment.CenterStart) {
|
||||
if (fieldText.isEmpty()) {
|
||||
Text(
|
||||
text = placeholder,
|
||||
style = typography.bodySmall,
|
||||
color = colors.textMuted,
|
||||
maxLines = 1,
|
||||
)
|
||||
}
|
||||
inner()
|
||||
}
|
||||
},
|
||||
)
|
||||
if (selected != null && !focused) {
|
||||
IconButton(
|
||||
icon = LocalUmamoIcons.close,
|
||||
onClick = { commit(null) },
|
||||
contentDescription = clearDescription,
|
||||
size = DpSize(16.dp, 16.dp),
|
||||
glyphSize = 12.dp,
|
||||
)
|
||||
}
|
||||
if (onPick != null) {
|
||||
IconButton(
|
||||
icon = LocalUmamoIcons.eyedropper,
|
||||
onClick = onPick,
|
||||
contentDescription = pickDescription,
|
||||
size = DpSize(16.dp, 16.dp),
|
||||
glyphSize = 12.dp,
|
||||
active = picking,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (open) {
|
||||
val anchorWidth = with(density) { anchorWidthPx.toDp() }
|
||||
Popup(
|
||||
popupPositionProvider = BelowAnchorPositionProvider,
|
||||
onDismissRequest = { focusManager.clearFocus() },
|
||||
// NOT focusable: a focusable popup would blur the search field the moment it opened.
|
||||
properties = PopupProperties(focusable = false),
|
||||
) {
|
||||
Surface(color = colors.menuBackground, shape = shapes.medium) {
|
||||
Box {
|
||||
// Pinned to the field's own width: a LazyColumn fills whatever max width it is handed,
|
||||
// and inside a popup that is the whole window, so an unbounded one spans the screen.
|
||||
LazyColumn(
|
||||
state = listState,
|
||||
modifier =
|
||||
Modifier
|
||||
.width(anchorWidth.coerceAtLeast(RELATION_DROPDOWN_MIN_WIDTH))
|
||||
.heightIn(max = RELATION_DROPDOWN_MAX_HEIGHT)
|
||||
.padding(vertical = 2.dp),
|
||||
) {
|
||||
itemsIndexed(filtered) { index, candidate ->
|
||||
RelationCandidateRow(
|
||||
label = label(candidate),
|
||||
icon = icon(candidate),
|
||||
highlighted = index == safeIndex,
|
||||
onClick = { commit(candidate) },
|
||||
)
|
||||
}
|
||||
}
|
||||
// matchParentSize keeps the scrollbar a pure overlay - it fills this box rather than the
|
||||
// popup's window-sized constraints, so it cannot inflate the dropdown to full height.
|
||||
Box(modifier = Modifier.matchParentSize()) {
|
||||
VerticalScrollbarOverlay(listState)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One candidate row in a [RelationField]'s dropdown: the entity's type glyph and name, lit when it is the
|
||||
* keyboard highlight. The row declines focus so clicking it cannot blur the search field out from under
|
||||
* the click, which would tear the popup down before the click resolved.
|
||||
*
|
||||
* @param String label The entity's display name.
|
||||
* @param UmamoIcon icon The entity's type glyph.
|
||||
* @param Boolean highlighted Whether this row is the current keyboard highlight.
|
||||
* @param Function onClick Binds this candidate.
|
||||
*/
|
||||
@Composable
|
||||
private fun RelationCandidateRow(label: String, icon: UmamoIcon, highlighted: Boolean, onClick: () -> Unit) {
|
||||
val colors = LocalUmamoColors.current
|
||||
Row(
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 4.dp, vertical = 1.dp)
|
||||
.focusProperties { canFocus = false }
|
||||
.clickable(onClick = onClick)
|
||||
.background(
|
||||
color = if (highlighted) colors.rowHover else Color.Transparent,
|
||||
shape = LocalUmamoShapes.current.small,
|
||||
)
|
||||
.padding(horizontal = 4.dp, vertical = 3.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Canvas(modifier = Modifier.size(RELATION_GLYPH_SIZE)) {
|
||||
drawIcon(icon, colors.textMuted)
|
||||
}
|
||||
Spacer(modifier = Modifier.width(6.dp))
|
||||
Text(
|
||||
text = label,
|
||||
style = LocalUmamoTypography.current.bodySmall,
|
||||
color = colors.text,
|
||||
maxLines = 1,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.gestures.DraggableState
|
||||
import androidx.compose.foundation.gestures.Orientation
|
||||
import androidx.compose.foundation.gestures.draggable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.input.pointer.PointerIcon
|
||||
import androidx.compose.ui.input.pointer.pointerHoverIcon
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.DpSize
|
||||
import androidx.compose.ui.unit.dp
|
||||
import org.umamo.ui.kit.button.IconButton
|
||||
import org.umamo.ui.theme.LocalUmamoColors
|
||||
import org.umamo.ui.theme.LocalUmamoIcons
|
||||
import org.umamo.ui.theme.LocalUmamoShapes
|
||||
import org.umamo.ui.theme.LocalUmamoTypography
|
||||
import org.umamo.ui.theme.UmamoIcon
|
||||
import org.umamo.ui.theme.drawIcon
|
||||
|
||||
/** Edge length of a bound row's type glyph, matching [RelationField]'s. */
|
||||
private val RELATION_ROW_GLYPH_SIZE = 14.dp
|
||||
|
||||
/** The bound-list height a relation list opens at. */
|
||||
private val RELATION_LIST_DEFAULT_HEIGHT = 76.dp
|
||||
|
||||
/** The shortest the bound list may be dragged (about two rows). */
|
||||
private val RELATION_LIST_MIN_HEIGHT = 44.dp
|
||||
|
||||
/** The tallest the bound list may be dragged. */
|
||||
private val RELATION_LIST_MAX_HEIGHT = 320.dp
|
||||
|
||||
/** The grab handle's strip height at the bottom of the bound list. */
|
||||
private val RELATION_GRIP_HEIGHT = 10.dp
|
||||
|
||||
/**
|
||||
* The multi-value sibling of [RelationField]: a scrollable list of bound entities, each row carrying its
|
||||
* type glyph, its name, and a remove button, over an add field that searches the remaining candidates and
|
||||
* offers the same eyedropper. A grab handle under the list drags its height, so a long list can be given
|
||||
* room without the whole panel growing.
|
||||
*
|
||||
* The bound list is a set, not a sequence - for clip masks the order does not affect coverage - so rows are
|
||||
* not reorderable.
|
||||
*
|
||||
* @param T The bound entity type.
|
||||
* @param List entries The currently bound entities, in display order.
|
||||
* @param List candidates The entities the add field offers (the caller excludes those already bound).
|
||||
* @param Function label The display name of an entity (also what the add field's search matches).
|
||||
* @param Function keyOf The entity's STABLE identity, used to key its row. Not the label: a display name
|
||||
* comes from the source art and is not unique (a PSD routinely holds several "Layer 1"), so keying on it
|
||||
* would let two rows share one key and reuse each other's per-row state.
|
||||
* @param Function icon The type glyph of an entity.
|
||||
* @param Function onAdd Binds an entity.
|
||||
* @param Function onRemove Unbinds an entity.
|
||||
* @param Modifier modifier The layout modifier.
|
||||
* @param Function? onPick Arms an eyedropper pick, or null to omit the eyedropper.
|
||||
* @param Boolean picking Whether a pick armed by THIS field is in flight.
|
||||
* @param String addPlaceholder The muted text shown in the empty add field.
|
||||
* @param String emptyLabel The muted text shown when nothing is bound.
|
||||
* @param String removeDescription The accessible label of a row's remove button.
|
||||
* @param String pickDescription The accessible label of the add field's eyedropper.
|
||||
* @param Dp? height The list's height when the caller holds it, or null for the list to hold its own. The list
|
||||
* leaves the composition whenever its row does (a tab change, a folded section, another selection), so only a
|
||||
* caller-held height survives that.
|
||||
* @param Function? onHeightChange Receives each dragged height, for a caller that holds it.
|
||||
*/
|
||||
@Composable
|
||||
fun <T> RelationListField(
|
||||
entries: List<T>,
|
||||
candidates: List<T>,
|
||||
label: (T) -> String,
|
||||
keyOf: (T) -> Any,
|
||||
icon: (T) -> UmamoIcon,
|
||||
onAdd: (T) -> Unit,
|
||||
onRemove: (T) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
onPick: (() -> Unit)? = null,
|
||||
picking: Boolean = false,
|
||||
addPlaceholder: String = "",
|
||||
emptyLabel: String = "",
|
||||
removeDescription: String = "",
|
||||
pickDescription: String = "",
|
||||
height: Dp? = null,
|
||||
onHeightChange: ((Dp) -> Unit)? = null,
|
||||
) {
|
||||
val colors = LocalUmamoColors.current
|
||||
val shapes = LocalUmamoShapes.current
|
||||
val typography = LocalUmamoTypography.current
|
||||
val density = LocalDensity.current
|
||||
val scrollState = rememberScrollState()
|
||||
var ownHeight by remember { mutableStateOf(RELATION_LIST_DEFAULT_HEIGHT) }
|
||||
val listHeight = (height ?: ownHeight).coerceIn(RELATION_LIST_MIN_HEIGHT, RELATION_LIST_MAX_HEIGHT)
|
||||
// The drag state is built once, so it reads the height and the callback through these rather than capturing
|
||||
// the first composition's.
|
||||
val latestHeight by rememberUpdatedState(listHeight)
|
||||
val latestOnHeightChange by rememberUpdatedState(onHeightChange)
|
||||
// The grip drags the list's own height; the panel around it is untouched (this is not an area splitter).
|
||||
val dragState =
|
||||
remember {
|
||||
DraggableState { deltaPx ->
|
||||
val delta = with(density) { deltaPx.toDp() }
|
||||
val dragged = (latestHeight + delta).coerceIn(RELATION_LIST_MIN_HEIGHT, RELATION_LIST_MAX_HEIGHT)
|
||||
ownHeight = dragged
|
||||
latestOnHeightChange?.invoke(dragged)
|
||||
}
|
||||
}
|
||||
|
||||
Column(modifier = modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
RelationField(
|
||||
selected = null,
|
||||
candidates = candidates,
|
||||
label = label,
|
||||
icon = icon,
|
||||
onSelect = { candidate -> candidate?.let(onAdd) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
onPick = onPick,
|
||||
picking = picking,
|
||||
placeholder = addPlaceholder,
|
||||
pickDescription = pickDescription,
|
||||
)
|
||||
Box(
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.height(listHeight)
|
||||
.clip(shapes.small)
|
||||
.background(colors.tabBackground)
|
||||
.border(1.dp, colors.controlBorder, shapes.small),
|
||||
) {
|
||||
Column(modifier = Modifier.fillMaxWidth().verticalScroll(scrollState).padding(2.dp)) {
|
||||
if (entries.isEmpty()) {
|
||||
Text(
|
||||
text = emptyLabel,
|
||||
style = typography.bodySmall,
|
||||
color = colors.textDisabled,
|
||||
maxLines = 1,
|
||||
modifier = Modifier.padding(horizontal = 4.dp, vertical = 2.dp),
|
||||
)
|
||||
} else {
|
||||
for (entry in entries) {
|
||||
key(keyOf(entry)) {
|
||||
RelationBoundRow(
|
||||
label = label(entry),
|
||||
icon = icon(entry),
|
||||
removeDescription = removeDescription,
|
||||
onRemove = { onRemove(entry) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
VerticalScrollbarOverlay(scrollState)
|
||||
}
|
||||
// The resize grab handle: Blender puts it under the list, centerd.
|
||||
Box(
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.height(RELATION_GRIP_HEIGHT)
|
||||
.pointerHoverIcon(PointerIcon.Hand)
|
||||
.draggable(state = dragState, orientation = Orientation.Vertical),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Canvas(modifier = Modifier.size(RELATION_ROW_GLYPH_SIZE)) {
|
||||
drawIcon(LocalUmamoIcons.gripHorizontal, colors.textMuted)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One bound row inside a [RelationListField]: the entity's type glyph and name, with a trailing remove.
|
||||
*
|
||||
* @param String label The entity's display name.
|
||||
* @param UmamoIcon icon The entity's type glyph.
|
||||
* @param String removeDescription The accessible label of the remove button.
|
||||
* @param Function onRemove Unbinds this entity.
|
||||
*/
|
||||
@Composable
|
||||
private fun RelationBoundRow(label: String, icon: UmamoIcon, removeDescription: String, onRemove: () -> Unit) {
|
||||
val colors = LocalUmamoColors.current
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 2.dp, vertical = 1.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Canvas(modifier = Modifier.size(RELATION_ROW_GLYPH_SIZE)) {
|
||||
drawIcon(icon, colors.textMuted)
|
||||
}
|
||||
Spacer(modifier = Modifier.width(6.dp))
|
||||
Text(
|
||||
text = label,
|
||||
style = LocalUmamoTypography.current.bodySmall,
|
||||
color = colors.text,
|
||||
maxLines = 1,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
IconButton(
|
||||
icon = LocalUmamoIcons.close,
|
||||
onClick = onRemove,
|
||||
contentDescription = removeDescription,
|
||||
size = DpSize(16.dp, 16.dp),
|
||||
glyphSize = 12.dp,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.foundation.ScrollState
|
||||
import androidx.compose.foundation.layout.BoxScope
|
||||
import androidx.compose.foundation.lazy.LazyListState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
/**
|
||||
* The thickness every scrollbar in the editor draws at.
|
||||
*
|
||||
* Shared rather than restated per bar: a scrollbar is a pointer target before it is a decoration, and one
|
||||
* that is thinner than the others is measurably harder to hit for no reason the user can see.
|
||||
*/
|
||||
val SCROLLBAR_THICKNESS: Dp = 8.dp
|
||||
|
||||
/** The shortest a scrollbar thumb may draw, so a long scroll still leaves something to grab. */
|
||||
val SCROLLBAR_MIN_THUMB: Dp = 24.dp
|
||||
|
||||
/** The scrollbar thumb's corner radius - a full round on [SCROLLBAR_THICKNESS]. */
|
||||
val SCROLLBAR_CORNER_RADIUS: Dp = 4.dp
|
||||
|
||||
/**
|
||||
* A draggable vertical scrollbar pinned to the right edge of the hosting Box, shown only while the
|
||||
* [scrollState] can actually scroll (its content overflows the viewport). Overlay sibling of the
|
||||
* scrolling content; call it after the content inside a Box so it draws on top.
|
||||
*
|
||||
* Platform-split: desktop draws Foundation's draggable VerticalScrollbar (those APIs are Compose-Desktop
|
||||
* only), while Android scrolls by touch with its own overscroll affordance, so the Android actual is a
|
||||
* deliberate no-op - keeping this overlay callable from shared UI without leaking a desktop-only API.
|
||||
*
|
||||
* 右端に固定する縦スクロールバー。デスクトップは Foundation のバー、Android はタッチ操作のため何もしない。
|
||||
*
|
||||
* @param ScrollState scrollState The scroll state of the verticalScroll content to drive and gate on.
|
||||
*/
|
||||
@Composable
|
||||
expect fun BoxScope.VerticalScrollbarOverlay(scrollState: ScrollState)
|
||||
|
||||
/**
|
||||
* A draggable vertical scrollbar pinned to the right edge of the hosting Box, shown only while the
|
||||
* [listState] can actually scroll in either direction. Overlay sibling of a LazyColumn; call it after
|
||||
* the list inside a Box so it draws on top. Platform-split like the [ScrollState] overload: a real bar on
|
||||
* desktop, a no-op on touch-driven Android.
|
||||
*
|
||||
* LazyColumn 用の縦スクロールバー。デスクトップのみ描画、Android はタッチ操作のため何もしない。
|
||||
*
|
||||
* @param LazyListState listState The LazyColumn's state to drive and gate on.
|
||||
*/
|
||||
@Composable
|
||||
expect fun BoxScope.VerticalScrollbarOverlay(listState: LazyListState)
|
||||
@@ -0,0 +1,70 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.DpSize
|
||||
import androidx.compose.ui.unit.dp
|
||||
import org.jetbrains.compose.resources.stringResource
|
||||
import org.umamo.ui.kit.button.IconButton
|
||||
import org.umamo.ui.resources.*
|
||||
import org.umamo.ui.theme.LocalUmamoIcons
|
||||
|
||||
/**
|
||||
* The standard width of a header search box - wide enough for a name, narrow enough to leave the rest
|
||||
* of the strip room in a tight area.
|
||||
*/
|
||||
val SEARCH_FIELD_WIDTH = 160.dp
|
||||
|
||||
/**
|
||||
* The narrowest a header search box is worth squeezing to: still wide enough to read a few characters and
|
||||
* the clear affordance beside them. Below this it is better off in the overflow dropdown at full width.
|
||||
*/
|
||||
val SEARCH_FIELD_MIN_WIDTH = 72.dp
|
||||
|
||||
/**
|
||||
* A filter box: a [TextField] with a clear affordance pinned inside its trailing edge, shown only while
|
||||
* there is text to clear. The X rides the field's trailing slot rather than being overlaid on it, so
|
||||
* the value and the caret can never run underneath it.
|
||||
*
|
||||
* Every panel that filters a list mounts this one component - the outliner and the properties panel both
|
||||
* did their own copy of the field-plus-X, which is exactly the drift the kit exists to prevent.
|
||||
*
|
||||
* @param String value The current query.
|
||||
* @param Function onValueChange Edit callback; the clear affordance reports an empty string.
|
||||
* @param Modifier modifier The layout modifier.
|
||||
* @param Dp width The box's width; [SEARCH_FIELD_WIDTH] unless a caller needs otherwise.
|
||||
* @param String placeholder The dimmed hint shown while the query is empty.
|
||||
* @param String clearContentDescription The clear affordance's accessible label and hover tooltip.
|
||||
*/
|
||||
@Composable
|
||||
fun SearchField(
|
||||
value: String,
|
||||
onValueChange: (String) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
width: Dp = SEARCH_FIELD_WIDTH,
|
||||
placeholder: String = stringResource(Res.string.search_hint),
|
||||
clearContentDescription: String = stringResource(Res.string.search_clear),
|
||||
) {
|
||||
TextField(
|
||||
value = value,
|
||||
onValueChange = onValueChange,
|
||||
modifier = modifier.width(width),
|
||||
placeholder = placeholder,
|
||||
trailing =
|
||||
if (value.isEmpty()) {
|
||||
null
|
||||
} else {
|
||||
{
|
||||
IconButton(
|
||||
icon = LocalUmamoIcons.close,
|
||||
onClick = { onValueChange("") },
|
||||
contentDescription = clearContentDescription,
|
||||
size = DpSize(16.dp, 16.dp),
|
||||
glyphSize = 16.dp,
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.layout.onSizeChanged
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.unit.dp
|
||||
import org.umamo.ui.theme.UmamoIcon
|
||||
|
||||
/**
|
||||
* A single-choice form dropdown: the current selection's (optional) icon and label shown in a [DropdownChip]
|
||||
* styled as a field, opening a [Menu] of the options beneath it. The one reusable select control for forms
|
||||
* - settings rows and the Properties panel share it; the header chips are the same [DropdownChip] in its
|
||||
* [DropdownChipStyle.Header] role, so there is one chip anatomy, not two.
|
||||
*
|
||||
* The popup is forced to at least the chip's own width (measured via [onSizeChanged]) so the option list
|
||||
* never opens narrower than the field - a value picked near the field's trailing edge stays under the
|
||||
* pointer instead of requiring an awkward reach. The menu owns its outside-click / Escape dismissal.
|
||||
*
|
||||
* @param T selected The currently selected option.
|
||||
* @param List options The options to choose from, in display order.
|
||||
* @param Function label Resolves an option to its display string (localized chrome or verbatim data).
|
||||
* @param Function onSelect Called with the chosen option (a no-op selection of the current value is fine).
|
||||
* @param Modifier modifier Layout modifier for the field (pass fillMaxWidth to span a form column).
|
||||
* @param Function? icon Optional per-option leading glyph (e.g. a blend-mode icon), or null for none.
|
||||
*/
|
||||
@Composable
|
||||
fun <T> SelectField(
|
||||
selected: T,
|
||||
options: List<T>,
|
||||
label: (T) -> String,
|
||||
onSelect: (T) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
icon: ((T) -> UmamoIcon?)? = null,
|
||||
) {
|
||||
var expanded by remember { mutableStateOf(false) }
|
||||
var anchorWidth by remember { mutableStateOf(0.dp) }
|
||||
val density = LocalDensity.current
|
||||
DropdownChip(
|
||||
expanded = expanded,
|
||||
onExpandRequest = { expanded = !expanded },
|
||||
contentDescription = label(selected),
|
||||
modifier = modifier.onSizeChanged { size -> anchorWidth = with(density) { size.width.toDp() } },
|
||||
icon = icon?.invoke(selected),
|
||||
label = label(selected),
|
||||
style = DropdownChipStyle.Field,
|
||||
) {
|
||||
Menu(
|
||||
items =
|
||||
options.map { option ->
|
||||
MenuItem.Action(
|
||||
label = label(option),
|
||||
icon = icon?.invoke(option),
|
||||
onSelect = { onSelect(option) },
|
||||
)
|
||||
},
|
||||
onDismissRequest = { expanded = false },
|
||||
positionProvider = BelowAnchorPositionProvider,
|
||||
modifier = Modifier.widthIn(min = anchorWidth),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.gestures.detectDragGestures
|
||||
import androidx.compose.foundation.gestures.detectTapGestures
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.geometry.CornerRadius
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.geometry.Size
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.drawscope.DrawScope
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.unit.dp
|
||||
import org.umamo.ui.theme.LocalUmamoColors
|
||||
|
||||
/** The thumb dot's radius; the thumb travels inset by this from each end so it never spills past the control. */
|
||||
private val SLIDER_THUMB_RADIUS = 5.dp
|
||||
|
||||
/** A per-key marker's half-extent; kept under the thumb radius so the current-value thumb stays dominant. */
|
||||
private val SLIDER_KEY_MARK_RADIUS = 3.5.dp
|
||||
|
||||
/**
|
||||
* The shape a slider draws for its thumb and for a per-key marker. A circle marks a key-form (grid) point;
|
||||
* a square marks a blend-shape point - the parameter-cockpit distinction between the two control-point
|
||||
* kinds (see ParameterKind: circle points drive keyform interpolation, square points drive additive
|
||||
* blend-shape deltas).
|
||||
*/
|
||||
enum class SliderKeyShape {
|
||||
Circle,
|
||||
Square,
|
||||
}
|
||||
|
||||
/**
|
||||
* A parameter key to mark on the slider track: its value and the shape that encodes its kind.
|
||||
*
|
||||
* @param Float value The parameter value the key sits at.
|
||||
* @param SliderKeyShape shape The marker shape (Circle = grid key, Square = blend-shape key).
|
||||
*/
|
||||
data class SliderKeyMark(
|
||||
val value: Float,
|
||||
val shape: SliderKeyShape,
|
||||
)
|
||||
|
||||
/**
|
||||
* A flat, draggable slider: a thin track + fill + small thumb on a [Canvas], set by tap or drag anywhere on
|
||||
* the control. Replaces Material's Slider (no large thumb, no ripple). A fixed-height control; pass a width
|
||||
* via [modifier] (e.g. `Modifier.fillMaxWidth()`).
|
||||
*
|
||||
* [onValueChange] streams the live value for every frame of a tap or drag; [onValueChangeFinished] fires
|
||||
* once at the gesture boundary (the tap, or the drag's release / cancel). This lets a caller treat a whole
|
||||
* continuous drag as a single committed gesture (e.g. one undo step) while still previewing each frame.
|
||||
*
|
||||
* @param Float value The current value.
|
||||
* @param Function onValueChange Called with the new value on each tap / drag frame (the preview).
|
||||
* @param Modifier modifier Layout modifier (supply the width).
|
||||
* @param Function onValueChangeFinished Called once when the gesture ends (tap, drag release, or cancel).
|
||||
* @param ClosedFloatingPointRange valueRange The min..max range.
|
||||
* @param List keyMarks Parameter keys to mark on the track, each with its shape (circle grid key / square
|
||||
* blend-shape key), so the user can see and scrub onto a key. Empty by default.
|
||||
* @param SliderKeyShape thumbShape The thumb's shape (Circle for a key-form parameter, Square for a
|
||||
* blend-shape parameter); defaults to Circle.
|
||||
*/
|
||||
@Composable
|
||||
fun Slider(
|
||||
value: Float,
|
||||
onValueChange: (Float) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
onValueChangeFinished: () -> Unit = {},
|
||||
valueRange: ClosedFloatingPointRange<Float> = 0f..1f,
|
||||
keyMarks: List<SliderKeyMark> = emptyList(),
|
||||
thumbShape: SliderKeyShape = SliderKeyShape.Circle,
|
||||
) {
|
||||
val colors = LocalUmamoColors.current
|
||||
val span = (valueRange.endInclusive - valueRange.start).takeIf { it != 0f } ?: 1f
|
||||
val fraction = ((value - valueRange.start) / span).coerceIn(0f, 1f)
|
||||
val trackColor = colors.sliderTrack
|
||||
val fillColor = colors.accent
|
||||
val thumbColor = colors.sliderThumb
|
||||
val tickColor = colors.guideLine
|
||||
// pointerInput is keyed only on valueRange, so it does not restart when a recomposition hands in a new
|
||||
// onValueChange (a reused list slot binding to a different row). Read the latest through these so a drag
|
||||
// always drives the current row, never the one that first occupied the slot.
|
||||
val currentOnValueChange by rememberUpdatedState(onValueChange)
|
||||
val currentOnValueChangeFinished by rememberUpdatedState(onValueChangeFinished)
|
||||
Canvas(
|
||||
modifier =
|
||||
modifier
|
||||
.height(18.dp)
|
||||
.pointerInput(valueRange) {
|
||||
val thumbRadius = SLIDER_THUMB_RADIUS.toPx()
|
||||
detectTapGestures { offset ->
|
||||
currentOnValueChange(valueAt(offset.x, size.width.toFloat(), thumbRadius, valueRange))
|
||||
currentOnValueChangeFinished()
|
||||
}
|
||||
}
|
||||
.pointerInput(valueRange) {
|
||||
val thumbRadius = SLIDER_THUMB_RADIUS.toPx()
|
||||
detectDragGestures(
|
||||
onDragEnd = { currentOnValueChangeFinished() },
|
||||
onDragCancel = { currentOnValueChangeFinished() },
|
||||
) { change, _ ->
|
||||
change.consume()
|
||||
currentOnValueChange(valueAt(change.position.x, size.width.toFloat(), thumbRadius, valueRange))
|
||||
}
|
||||
},
|
||||
) {
|
||||
val trackHeight = 4.dp.toPx()
|
||||
val thumbRadius = SLIDER_THUMB_RADIUS.toPx()
|
||||
val centerY = size.height / 2f
|
||||
val corner = CornerRadius(trackHeight / 2f)
|
||||
val top = Offset(0f, centerY - trackHeight / 2f)
|
||||
// The thumb center travels within [thumbRadius, width - thumbRadius] so the whole dot stays inside the
|
||||
// control's hit area at both ends; otherwise the outer half of the thumb would hang into the
|
||||
// non-interactive padding at the track start, and a click there would miss the slider. The track fills
|
||||
// the full width for the end caps.
|
||||
val usableWidth = (size.width - 2f * thumbRadius).coerceAtLeast(0f)
|
||||
val thumbCenterX = thumbRadius + fraction * usableWidth
|
||||
drawRoundRect(color = trackColor, topLeft = top, size = Size(size.width, trackHeight), cornerRadius = corner)
|
||||
drawRoundRect(
|
||||
color = fillColor,
|
||||
topLeft = top,
|
||||
size = Size(thumbCenterX, trackHeight),
|
||||
cornerRadius = corner,
|
||||
)
|
||||
// Key markers: a small dot at each key value so the user can see and scrub onto a key. Shape
|
||||
// encodes the key's kind - a circle for a key-form (grid) key, a square for a blend-shape key.
|
||||
val markRadius = SLIDER_KEY_MARK_RADIUS.toPx()
|
||||
for (mark in keyMarks) {
|
||||
val keyFraction = ((mark.value - valueRange.start) / span).coerceIn(0f, 1f)
|
||||
val markX = (thumbRadius + keyFraction * usableWidth).coerceIn(0f, size.width)
|
||||
drawSliderShape(mark.shape, tickColor, markX, centerY, markRadius)
|
||||
}
|
||||
drawSliderShape(thumbShape, thumbColor, thumbCenterX, centerY, thumbRadius)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws one slider marker (thumb or key mark) centered at ([centerX], [centerY]): a filled circle of
|
||||
* [radius], or a square of the same half-extent with slightly rounded corners to match the flat look.
|
||||
*
|
||||
* @param SliderKeyShape shape The marker shape.
|
||||
* @param Color color The fill color.
|
||||
* @param Float centerX The marker center x.
|
||||
* @param Float centerY The marker center y.
|
||||
* @param Float radius The circle radius, or the square's half-side.
|
||||
*/
|
||||
private fun DrawScope.drawSliderShape(shape: SliderKeyShape, color: Color, centerX: Float, centerY: Float, radius: Float) {
|
||||
when (shape) {
|
||||
SliderKeyShape.Circle -> {
|
||||
drawCircle(color = color, radius = radius, center = Offset(centerX, centerY))
|
||||
}
|
||||
|
||||
SliderKeyShape.Square -> {
|
||||
drawRoundRect(
|
||||
color = color,
|
||||
topLeft = Offset(centerX - radius, centerY - radius),
|
||||
size = Size(radius * 2f, radius * 2f),
|
||||
cornerRadius = CornerRadius(radius * 0.35f),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps a pointer x onto [range] over the thumb's travel band, which is inset [inset] from each end so the
|
||||
* track ends map to the range ends and the whole thumb stays inside the control. Clamped to that band.
|
||||
*
|
||||
* @param Float x The pointer x within the control.
|
||||
* @param Float width The control's full width.
|
||||
* @param Float inset The thumb radius the travel band is inset by at each end.
|
||||
* @param ClosedFloatingPointRange range The value range to map onto.
|
||||
* @return Float The value at [x].
|
||||
*/
|
||||
private fun valueAt(x: Float, width: Float, inset: Float, range: ClosedFloatingPointRange<Float>): Float {
|
||||
val usableWidth = (width - 2f * inset).takeIf { it > 0f } ?: 1f
|
||||
val fraction = ((x - inset) / usableWidth).coerceIn(0f, 1f)
|
||||
return range.start + fraction * (range.endInclusive - range.start)
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.foundation.shape.CornerBasedShape
|
||||
import androidx.compose.foundation.shape.ZeroCornerSize
|
||||
import androidx.compose.ui.graphics.RectangleShape
|
||||
import androidx.compose.ui.graphics.Shape
|
||||
|
||||
/**
|
||||
* A control's position within a butted run of stacked controls, driving which corners it rounds and which
|
||||
* it squares against a neighbour. [Single] is a standalone control (all corners rounded).
|
||||
*/
|
||||
enum class StackPosition {
|
||||
Single,
|
||||
First,
|
||||
Middle,
|
||||
Last,
|
||||
}
|
||||
|
||||
/** The axis a butted run of controls is laid along: a horizontal Row or a vertical Column. */
|
||||
enum class StackAxis {
|
||||
Horizontal,
|
||||
Vertical,
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves an item's [StackPosition] from its index within a run of [count] items: the sole item is
|
||||
* [StackPosition.Single], the ends are First / Last, and the interior is Middle.
|
||||
*
|
||||
* @param Int index The item's position in the run.
|
||||
* @param Int count The number of items in the run.
|
||||
* @return StackPosition The item's position role.
|
||||
*/
|
||||
fun stackPositionOf(index: Int, count: Int): StackPosition =
|
||||
when {
|
||||
count <= 1 -> StackPosition.Single
|
||||
index <= 0 -> StackPosition.First
|
||||
index >= count - 1 -> StackPosition.Last
|
||||
else -> StackPosition.Middle
|
||||
}
|
||||
|
||||
/**
|
||||
* Shapes one control in a butted run so the run reads as a single control with hairline seams: the run's
|
||||
* outer corners keep [groupShape]'s rounding while the corners shared with a neighbour are squared. A
|
||||
* horizontal run (ButtonGroup) squares the leading / trailing edges; a vertical run (a stacked numeric
|
||||
* field group) squares the top / bottom edges. RoundedCornerShape's start / end corners already mirror
|
||||
* under RTL, so the first item stays the visual leading end either way.
|
||||
*
|
||||
* @param CornerBasedShape groupShape The rounding applied to the run's outer corners.
|
||||
* @param StackPosition position The item's position role in the run.
|
||||
* @param StackAxis axis The run's layout axis.
|
||||
* @return Shape The item's corner shape.
|
||||
*/
|
||||
fun stackedShape(groupShape: CornerBasedShape, position: StackPosition, axis: StackAxis): Shape =
|
||||
when (position) {
|
||||
StackPosition.Single -> groupShape
|
||||
StackPosition.Middle -> RectangleShape
|
||||
StackPosition.First ->
|
||||
when (axis) {
|
||||
StackAxis.Horizontal -> groupShape.copy(topEnd = ZeroCornerSize, bottomEnd = ZeroCornerSize)
|
||||
StackAxis.Vertical -> groupShape.copy(bottomStart = ZeroCornerSize, bottomEnd = ZeroCornerSize)
|
||||
}
|
||||
StackPosition.Last ->
|
||||
when (axis) {
|
||||
StackAxis.Horizontal -> groupShape.copy(topStart = ZeroCornerSize, bottomStart = ZeroCornerSize)
|
||||
StackAxis.Vertical -> groupShape.copy(topStart = ZeroCornerSize, topEnd = ZeroCornerSize)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.draw.shadow
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.RectangleShape
|
||||
import androidx.compose.ui.graphics.Shape
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import org.umamo.ui.theme.LocalUmamoColors
|
||||
|
||||
/**
|
||||
* A background container: a [Box] with a fill [color], an optional [shape] clip, an optional [border], and an
|
||||
* optional drop [shadowElevation]. Replaces Material's Surface (its tonal-elevation tinting is intentionally
|
||||
* dropped - pick an explicit [color] instead).
|
||||
*
|
||||
* @param Modifier modifier Layout modifier.
|
||||
* @param Color color Background fill (defaults to the panel color).
|
||||
* @param Shape shape Clip + border + shadow shape.
|
||||
* @param BorderStroke? border Optional border.
|
||||
* @param Dp shadowElevation Drop-shadow elevation (0 = none).
|
||||
* @param Function content The surface content.
|
||||
*/
|
||||
@Composable
|
||||
fun Surface(
|
||||
modifier: Modifier = Modifier,
|
||||
color: Color = LocalUmamoColors.current.panelBackground,
|
||||
shape: Shape = RectangleShape,
|
||||
border: BorderStroke? = null,
|
||||
shadowElevation: Dp = 0.dp,
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
var surfaceModifier = modifier
|
||||
if (shadowElevation > 0.dp) {
|
||||
surfaceModifier = surfaceModifier.shadow(shadowElevation, shape)
|
||||
}
|
||||
surfaceModifier = surfaceModifier.clip(shape).background(color)
|
||||
if (border != null) {
|
||||
surfaceModifier = surfaceModifier.border(border, shape)
|
||||
}
|
||||
Box(modifier = surfaceModifier) { content() }
|
||||
}
|
||||
|
||||
/**
|
||||
* A thin horizontal divider line.
|
||||
*
|
||||
* @param Modifier modifier Layout modifier.
|
||||
* @param Dp thickness Line thickness.
|
||||
* @param Color color Line color (defaults to the divider color).
|
||||
*/
|
||||
@Composable
|
||||
fun Divider(modifier: Modifier = Modifier, thickness: Dp = 1.dp, color: Color = LocalUmamoColors.current.divider) {
|
||||
Box(modifier = modifier.fillMaxWidth().height(thickness).background(color))
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.collectIsHoveredAsState
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.RowScope
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import org.umamo.ui.theme.LocalUmamoColors
|
||||
import org.umamo.ui.theme.LocalUmamoShapes
|
||||
|
||||
/**
|
||||
* A flat tab strip - a [Row] over the header background, hosting [Tab]s. No animated indicator (the active
|
||||
* tab is shown by its fill); replaces Material's TabRow.
|
||||
*
|
||||
* @param Modifier modifier Layout modifier.
|
||||
* @param Function content The [Tab]s.
|
||||
*/
|
||||
@Composable
|
||||
fun TabRow(modifier: Modifier = Modifier, content: @Composable RowScope.() -> Unit) {
|
||||
Row(modifier = modifier.fillMaxWidth(), content = content)
|
||||
}
|
||||
|
||||
/**
|
||||
* One tab: a clickable cell that takes the panel color when [selected] and a hover highlight otherwise.
|
||||
*
|
||||
* @param Boolean selected Whether this tab is active.
|
||||
* @param Function onClick Selection callback.
|
||||
* @param Modifier modifier Layout modifier.
|
||||
* @param Function label The tab's label content.
|
||||
*/
|
||||
@Composable
|
||||
fun Tab(selected: Boolean, onClick: () -> Unit, modifier: Modifier = Modifier, label: @Composable () -> Unit) {
|
||||
val colors = LocalUmamoColors.current
|
||||
val shapes = LocalUmamoShapes.current
|
||||
val interaction = remember { MutableInteractionSource() }
|
||||
val hovered by interaction.collectIsHoveredAsState()
|
||||
val fill =
|
||||
when {
|
||||
selected -> colors.headerBackground
|
||||
hovered -> colors.rowHover
|
||||
else -> colors.tabBackground
|
||||
}
|
||||
Box(
|
||||
modifier =
|
||||
modifier
|
||||
.padding(horizontal = 2.dp)
|
||||
.clickable(interactionSource = interaction, indication = null, onClick = onClick)
|
||||
.background(fill, shape = shapes.medium)
|
||||
.padding(horizontal = 10.dp, vertical = 4.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
label()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.foundation.text.BasicText
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.takeOrElse
|
||||
import androidx.compose.ui.text.TextLayoutResult
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import org.umamo.ui.theme.LocalUmamoColors
|
||||
import org.umamo.ui.theme.LocalUmamoTypography
|
||||
|
||||
/*
|
||||
* The custom design system (org.umamo.ui.kit): small, flat, hover-driven widgets on Compose Foundation, with
|
||||
* no Material. Names are unprefixed and read the theme tokens (LocalUmamoColors / LocalUmamoTypography /
|
||||
* LocalUmamoShapes) directly. There is no ripple - interaction feedback is hover-highlight throughout.
|
||||
*
|
||||
* 独自デザイン系。Material を使わない平坦な Foundation 製ウィジェット群。
|
||||
*/
|
||||
|
||||
/**
|
||||
* Renders text. Wraps Foundation's [BasicText] with the kit's type scale and color: the [style] defaults to
|
||||
* the body style, and the color resolves to [color] → the style's own color → the theme's text color.
|
||||
*
|
||||
* @param String text The text to render.
|
||||
* @param Modifier modifier Layout modifier.
|
||||
* @param TextStyle style The text style (defaults to the body scale).
|
||||
* @param Color color Explicit color, or Unspecified to inherit from the style/theme.
|
||||
* @param TextAlign? textAlign Optional horizontal alignment override.
|
||||
* @param Int maxLines Maximum line count before truncation.
|
||||
* @param TextOverflow overflow How overflowing text is handled.
|
||||
* @param Function? onTextLayout Called with the measured layout result, or null to skip it.
|
||||
*/
|
||||
@Composable
|
||||
fun Text(
|
||||
text: String,
|
||||
modifier: Modifier = Modifier,
|
||||
style: TextStyle = LocalUmamoTypography.current.bodyMedium,
|
||||
color: Color = Color.Unspecified,
|
||||
textAlign: TextAlign? = null,
|
||||
maxLines: Int = Int.MAX_VALUE,
|
||||
overflow: TextOverflow = TextOverflow.Clip,
|
||||
onTextLayout: ((TextLayoutResult) -> Unit)? = null,
|
||||
) {
|
||||
val resolvedColor = color.takeOrElse { style.color.takeOrElse { LocalUmamoColors.current.text } }
|
||||
val resolvedStyle = style.copy(color = resolvedColor, textAlign = textAlign ?: style.textAlign)
|
||||
BasicText(
|
||||
text = text,
|
||||
modifier = modifier,
|
||||
style = resolvedStyle,
|
||||
// Reported so a caller can react to the MEASURED result - the only way to know a label was actually
|
||||
// ellipsized, which is what decides whether a "show the full name" tooltip is noise or necessary.
|
||||
onTextLayout = onTextLayout,
|
||||
maxLines = maxLines,
|
||||
overflow = overflow,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalClipboardManager
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.TextRange
|
||||
import androidx.compose.ui.text.input.TextFieldValue
|
||||
import androidx.compose.ui.unit.IntOffset
|
||||
import org.jetbrains.compose.resources.stringResource
|
||||
import org.umamo.ui.resources.Res
|
||||
import org.umamo.ui.resources.text_menu_copy
|
||||
import org.umamo.ui.resources.text_menu_cut
|
||||
import org.umamo.ui.resources.text_menu_paste
|
||||
import org.umamo.ui.resources.text_menu_select_all
|
||||
|
||||
/*
|
||||
* The context menu for the kit's text fields.
|
||||
*
|
||||
* Compose's own text fields carry a built-in Cut / Copy / Paste / Select All menu, and because that menu is
|
||||
* installed on the innermost node it wins the right-click outright - so a Properties row's Insert / Remove
|
||||
* Keyframe menu and a panel header's area menu were both unreachable over any field. Rather than suppress
|
||||
* the built-in menu and lose the clipboard entries, this replaces it with ONE menu drawn in the kit's own
|
||||
* chrome: whatever the enclosing ContextMenuArea offers, a rule, then the four clipboard actions.
|
||||
*
|
||||
* The clipboard actions are re-implemented here rather than delegated back to the built-in menu, which is
|
||||
* why the fields that use this hold a TextFieldValue rather than a String - Cut, Copy and Select All are all
|
||||
* statements about a selection range, and the String-shaped BasicTextField overload does not expose one.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Wraps a text field so a context-menu request opens the kit menu instead of Compose's built-in one.
|
||||
*
|
||||
* [content] receives the gesture modifier rather than having it applied to a wrapper, and must chain it AHEAD
|
||||
* of its own: the caller's modifier carries focus requesters and layout that belong to the FIELD, and a
|
||||
* wrapper that swallowed them would silently break things like the command palette's auto-focus. [modifier]
|
||||
* is for the few things that must sit on the wrapper instead - a Row weight, which only a direct child of
|
||||
* the row can carry.
|
||||
*
|
||||
* @param TextFieldValue value The field's current text and selection.
|
||||
* @param Function onValueChange Applies a clipboard action's result back to the field.
|
||||
* @param Modifier modifier Layout for the wrapping box, where the field itself cannot carry it.
|
||||
* @param Function content The text field, given the modifier that opens the menu.
|
||||
*/
|
||||
@Composable
|
||||
internal fun TextEditContextMenuArea(
|
||||
value: TextFieldValue,
|
||||
onValueChange: (TextFieldValue) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
content: @Composable (Modifier) -> Unit,
|
||||
) {
|
||||
var open by remember { mutableStateOf(false) }
|
||||
var anchorOffset by remember { mutableStateOf(IntOffset.Zero) }
|
||||
val gesture =
|
||||
Modifier.textEditContextMenuGesture { localOffset ->
|
||||
anchorOffset = localOffset
|
||||
open = true
|
||||
}
|
||||
Box(modifier = modifier) {
|
||||
// The field must NOT inherit the ambient items a second time through some nested area of its own:
|
||||
// they are already the head of this menu, and a doubled list reads as a bug rather than as emphasis.
|
||||
CompositionLocalProvider(LocalContextMenuItems provides emptyList()) {
|
||||
content(gesture)
|
||||
}
|
||||
if (open) {
|
||||
// Built only while the menu is up. Every kit text field mounts one of these, the entries depend
|
||||
// on the CLIPBOARD (a cross-process read on desktop), and LocalContextMenuItems hands down a list
|
||||
// rebuilt by its area every recomposition - so building them unconditionally read the system
|
||||
// clipboard once per field per frame of any neighbouring scrub. Reading the ambient items here
|
||||
// is still correct: this sits outside the provider that blanks them for `content`.
|
||||
val surroundingItems = LocalContextMenuItems.current
|
||||
val clipboardItems = textEditMenuItems(value, onValueChange)
|
||||
Menu(
|
||||
items =
|
||||
if (surroundingItems.isEmpty()) {
|
||||
clipboardItems
|
||||
} else {
|
||||
surroundingItems + MenuItem.Separator + clipboardItems
|
||||
},
|
||||
onDismissRequest = { open = false },
|
||||
positionProvider = AtPointPositionProvider(anchorOffset),
|
||||
focusable = true,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The four clipboard entries, each disabled when it would do nothing.
|
||||
*
|
||||
* Cut and Copy need a non-collapsed selection, Paste needs something on the clipboard, and Select All needs
|
||||
* text to select. Showing them greyed rather than hiding them keeps the menu's shape stable, so the entry a
|
||||
* user is reaching for does not move between right-clicks.
|
||||
*
|
||||
* @param TextFieldValue value The field's current text and selection.
|
||||
* @param Function onValueChange Applies the result back to the field.
|
||||
* @return List<MenuItem> The clipboard entries.
|
||||
*/
|
||||
@Composable
|
||||
private fun textEditMenuItems(value: TextFieldValue, onValueChange: (TextFieldValue) -> Unit): List<MenuItem> {
|
||||
@Suppress("DEPRECATION")
|
||||
val clipboard = LocalClipboardManager.current
|
||||
val hasSelection = !value.selection.collapsed
|
||||
// One clipboard read for both the Paste entry's enablement and its action; the caller only builds this
|
||||
// while the menu is opening, so the cross-process query happens once per right-click.
|
||||
val hasClipboardText = clipboard.hasText()
|
||||
return listOf(
|
||||
MenuItem.Action(
|
||||
label = stringResource(Res.string.text_menu_cut),
|
||||
onSelect = {
|
||||
clipboard.setText(AnnotatedString(value.selectedText()))
|
||||
onValueChange(value.withSelectionReplaced(""))
|
||||
},
|
||||
enabled = hasSelection,
|
||||
),
|
||||
MenuItem.Action(
|
||||
label = stringResource(Res.string.text_menu_copy),
|
||||
onSelect = { clipboard.setText(AnnotatedString(value.selectedText())) },
|
||||
enabled = hasSelection,
|
||||
),
|
||||
MenuItem.Action(
|
||||
label = stringResource(Res.string.text_menu_paste),
|
||||
onSelect = { onValueChange(value.withSelectionReplaced(clipboard.getText()?.text.orEmpty())) },
|
||||
enabled = hasClipboardText,
|
||||
),
|
||||
MenuItem.Action(
|
||||
label = stringResource(Res.string.text_menu_select_all),
|
||||
onSelect = { onValueChange(value.copy(selection = TextRange(0, value.text.length))) },
|
||||
enabled = value.text.isNotEmpty(),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/** The text covered by this value's selection, or "" when the selection is a bare caret. */
|
||||
internal fun TextFieldValue.selectedText(): String = text.substring(selection.min, selection.max)
|
||||
|
||||
/**
|
||||
* This value with its selection replaced by [replacement], the caret left after the inserted text.
|
||||
*
|
||||
* @param String replacement The text to put in the selection's place.
|
||||
* @return TextFieldValue The edited value.
|
||||
*/
|
||||
internal fun TextFieldValue.withSelectionReplaced(replacement: String): TextFieldValue {
|
||||
val edited = text.replaceRange(selection.min, selection.max, replacement)
|
||||
val caret = selection.min + replacement.length
|
||||
return copy(text = edited, selection = TextRange(caret))
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.input.pointer.PointerEventPass
|
||||
import androidx.compose.ui.input.pointer.PointerEventType
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
|
||||
/**
|
||||
* Marks a node as a text editor's own surface, so a host watching the window can tell a press ON the
|
||||
* editor from a press anywhere else.
|
||||
*
|
||||
* @param InlineEditController controller The seam this editor shares with its host.
|
||||
* @return Modifier The node, carrying the editor's press claim.
|
||||
*/
|
||||
fun Modifier.textEntrySurface(controller: InlineEditController): Modifier =
|
||||
this.pointerInput(controller) {
|
||||
awaitPointerEventScope {
|
||||
while (true) {
|
||||
if (awaitPointerEvent(PointerEventPass.Initial).type == PointerEventType.Press) {
|
||||
controller.pressLandedOnTextEditor = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.draw.drawBehind
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.geometry.Size
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import org.umamo.ui.theme.LocalUmamoColors
|
||||
import org.umamo.ui.theme.LocalUmamoShapes
|
||||
import kotlin.math.ceil
|
||||
|
||||
/** The default square edge of a thumbnail slot (the overlap picker's compact preview). */
|
||||
val DefaultThumbnailSize = 44.dp
|
||||
|
||||
/** The cell edge of the transparency checker drawn behind a thumbnail. */
|
||||
private val ThumbnailCheckerCell = 6.dp
|
||||
|
||||
/**
|
||||
* A square art-mesh preview slot, shared by the overlap picker and the Outliner hover preview. When
|
||||
* [thumbnail] is present it is drawn over a small transparency checker (the themed viewport checker colors)
|
||||
* so the layer's silhouette reads against the surface; when it is null the slot is an empty box of the same
|
||||
* size, keeping label-only rows aligned with thumbnailed ones.
|
||||
*
|
||||
* @param ImageBitmap? thumbnail The layer-art preview, or null for an untextured drawable.
|
||||
* @param Dp size The square edge of the slot.
|
||||
*/
|
||||
@Composable
|
||||
fun ThumbnailSlot(thumbnail: ImageBitmap?, size: Dp = DefaultThumbnailSize) {
|
||||
val slotModifier = Modifier.size(size)
|
||||
if (thumbnail == null) {
|
||||
Box(modifier = slotModifier)
|
||||
return
|
||||
}
|
||||
val colors = LocalUmamoColors.current
|
||||
val checkerLight = colors.transparencyCheckerLight
|
||||
val checkerDark = colors.transparencyCheckerDark
|
||||
Box(
|
||||
modifier =
|
||||
slotModifier
|
||||
.clip(LocalUmamoShapes.current.small)
|
||||
.drawBehind {
|
||||
val cell = ThumbnailCheckerCell.toPx()
|
||||
val columns = ceil(this.size.width / cell).toInt()
|
||||
val rows = ceil(this.size.height / cell).toInt()
|
||||
var rowIndex = 0
|
||||
while (rowIndex < rows) {
|
||||
var columnIndex = 0
|
||||
while (columnIndex < columns) {
|
||||
val isDarkCell = (rowIndex + columnIndex) % 2 == 1
|
||||
drawRect(
|
||||
color = if (isDarkCell) checkerDark else checkerLight,
|
||||
topLeft = Offset(columnIndex * cell, rowIndex * cell),
|
||||
size = Size(cell, cell),
|
||||
)
|
||||
columnIndex += 1
|
||||
}
|
||||
rowIndex += 1
|
||||
}
|
||||
},
|
||||
) {
|
||||
Image(
|
||||
bitmap = thumbnail,
|
||||
contentDescription = null,
|
||||
contentScale = ContentScale.Fit,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package org.umamo.ui.kit
|
||||
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import org.umamo.ui.theme.LocalUmamoColors
|
||||
import org.umamo.ui.theme.LocalUmamoShapes
|
||||
import org.umamo.ui.theme.LocalUmamoTypography
|
||||
|
||||
/**
|
||||
* The widest a tooltip's label runs before it wraps. A control's name never reaches it; a row's
|
||||
* description is a sentence or two, and without the cap it would draw as one line across the window.
|
||||
*/
|
||||
private val TOOLTIP_MAX_WIDTH = 280.dp
|
||||
|
||||
/**
|
||||
* Wraps [content] with a hover tooltip showing [text]. Desktop reveals the tooltip after a short
|
||||
* mouse-dwell over the content; touch platforms have no hover, so the content renders unchanged there (a
|
||||
* long-press tooltip awaits the Android target). The caller's layout [modifier] rides on the wrapper
|
||||
* (the outermost node) so alignment and weight still resolve against the parent.
|
||||
*
|
||||
* The label is meant to double as the control's accessible description - passing the same string to both
|
||||
* the tooltip and semantics keeps the on-screen hint and the a11y name in lockstep. A blank [text]
|
||||
* attaches no tooltip, so callers can pass an unconditional label.
|
||||
*
|
||||
* ホバー時にツールチップを表示する。デスクトップはマウス静止で表示、タッチはホバーが無いのでそのまま描画
|
||||
* (長押しツールチップは Android ターゲットで対応)。ラベルはアクセシビリティ名を兼ねる。
|
||||
*
|
||||
* @param String text The tooltip label; blank attaches no tooltip.
|
||||
* @param Modifier modifier The layout modifier, applied to the wrapper.
|
||||
* @param Function content The control the tooltip describes.
|
||||
*/
|
||||
@Composable
|
||||
expect fun Tooltip(text: String, modifier: Modifier = Modifier, content: @Composable () -> Unit)
|
||||
|
||||
/**
|
||||
* The tooltip's floating card: a small rounded popover reading like the kit's menus (menu fill, a
|
||||
* hairline border, a soft drop shadow) with the label in the primary text color. Shared by every
|
||||
* platform's [Tooltip] so the chrome stays identical, and by any other transient label that should read
|
||||
* as a tooltip - the relation-pick badge positions one at the cursor through [modifier]. Keeping the
|
||||
* chrome here is the point: a second hand-rolled card would drift out of step with this one.
|
||||
*
|
||||
* ツールチップの浮動カード。メニューと同じ見た目(塗り・枠線・影)でラベルを表示する。
|
||||
*
|
||||
* @param String text The tooltip label.
|
||||
* @param Modifier modifier The layout modifier, applied to the card (a caller may position it).
|
||||
*/
|
||||
@Composable
|
||||
internal fun TooltipCard(text: String, modifier: Modifier = Modifier) {
|
||||
val colors = LocalUmamoColors.current
|
||||
Surface(
|
||||
modifier = modifier,
|
||||
color = colors.menuBackground,
|
||||
shape = LocalUmamoShapes.current.small,
|
||||
border = BorderStroke(1.dp, colors.panelBorder),
|
||||
shadowElevation = 4.dp,
|
||||
) {
|
||||
Text(
|
||||
text = text,
|
||||
style = LocalUmamoTypography.current.labelMedium,
|
||||
color = colors.text,
|
||||
modifier = Modifier.widthIn(max = TOOLTIP_MAX_WIDTH).padding(horizontal = 8.dp, vertical = 4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package org.umamo.ui.kit.button
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.collectIsHoveredAsState
|
||||
import androidx.compose.foundation.interaction.collectIsPressedAsState
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.unit.dp
|
||||
import org.umamo.ui.kit.Text
|
||||
import org.umamo.ui.theme.LocalUmamoColors
|
||||
import org.umamo.ui.theme.LocalUmamoShapes
|
||||
import org.umamo.ui.theme.LocalUmamoTypography
|
||||
|
||||
/**
|
||||
* A small flat button: tight padding, small corners, hover-highlight and a darker fill while held (no
|
||||
* ripple). [primary] fills with the accent; otherwise a neutral control fill.
|
||||
*
|
||||
* @param String label The button text.
|
||||
* @param Function onClick Click callback.
|
||||
* @param Modifier modifier Layout modifier.
|
||||
* @param Boolean primary Accent fill when true, neutral when false.
|
||||
* @param Boolean enabled When false the button rests on the neutral fill with a disabled label, shows no
|
||||
* hover or press, and ignores clicks.
|
||||
*/
|
||||
@Composable
|
||||
fun Button(label: String, onClick: () -> Unit, modifier: Modifier = Modifier, primary: Boolean = true, enabled: Boolean = true) {
|
||||
val colors = LocalUmamoColors.current
|
||||
val shapes = LocalUmamoShapes.current
|
||||
val interaction = remember { MutableInteractionSource() }
|
||||
val hovered by interaction.collectIsHoveredAsState()
|
||||
val pressed by interaction.collectIsPressedAsState()
|
||||
// The same ramp the filled icon buttons and button-group segments use (accentControlFill), except that
|
||||
// a secondary button's hover stays the softer rowHover it has always drawn; a press outranks a hover, and
|
||||
// a disabled button outranks both, showing no feedback, as a disabled IconButton does.
|
||||
val fill =
|
||||
when {
|
||||
!enabled -> colors.controlBackground
|
||||
primary && pressed -> colors.accentPressed
|
||||
primary && hovered -> colors.accentHover
|
||||
primary -> colors.accent
|
||||
pressed -> colors.buttonPressed
|
||||
hovered -> colors.rowHover
|
||||
else -> colors.controlBackground
|
||||
}
|
||||
val labelColor =
|
||||
when {
|
||||
!enabled -> colors.textDisabled
|
||||
primary -> colors.accentText
|
||||
else -> colors.text
|
||||
}
|
||||
Box(
|
||||
modifier =
|
||||
modifier
|
||||
.clip(shapes.small)
|
||||
.background(fill)
|
||||
.clickable(interactionSource = interaction, indication = null, enabled = enabled, onClick = onClick)
|
||||
.padding(horizontal = 8.dp, vertical = 3.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(
|
||||
text = label,
|
||||
style = LocalUmamoTypography.current.labelMedium,
|
||||
color = labelColor,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package org.umamo.ui.kit.button
|
||||
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.collectIsHoveredAsState
|
||||
import androidx.compose.foundation.interaction.collectIsPressedAsState
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.CornerBasedShape
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Shape
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.unit.dp
|
||||
import org.umamo.ui.kit.StackAxis
|
||||
import org.umamo.ui.kit.Tooltip
|
||||
import org.umamo.ui.kit.stackPositionOf
|
||||
import org.umamo.ui.kit.stackedShape
|
||||
import org.umamo.ui.theme.LocalUmamoColors
|
||||
import org.umamo.ui.theme.LocalUmamoShapes
|
||||
import org.umamo.ui.theme.UmamoIcon
|
||||
import org.umamo.ui.theme.drawIcon
|
||||
|
||||
/** One segment's face - wider than tall, like Blender's aligned toggle buttons. */
|
||||
private val SEGMENT_WIDTH = 26.dp
|
||||
private val SEGMENT_HEIGHT = 20.dp
|
||||
|
||||
/** Icon size inside a segment. */
|
||||
private val SEGMENT_ICON_SIZE = 16.dp
|
||||
|
||||
/** The hairline seam between adjacent segments (the surface behind shows through). */
|
||||
private val SEGMENT_GAP = 1.dp
|
||||
|
||||
/**
|
||||
* One segment of a [ButtonGroup]: an icon toggle that lights with the accent while [selected]. This is
|
||||
* a data model rather than a slot DSL (same reasoning as [MenuItem]) - the group must know each
|
||||
* segment's position to shape its corners, so callers hand over a list and one renderer draws it.
|
||||
*
|
||||
* ButtonGroup の 1 セグメント。selected の間アクセント色で点灯するアイコントグル。
|
||||
*
|
||||
* @property UmamoIcon icon The segment's glyph.
|
||||
* @property Boolean selected Whether the segment is lit (the caller owns the toggle state).
|
||||
* @property Function onClick Invoked on tap; the caller flips its own state.
|
||||
* @property String contentDescription The accessible label, doubling as the segment's hover label.
|
||||
* Required: a segment's face is only a glyph, so an absent label would leave it nameless to a screen
|
||||
* reader and silent on hover at once.
|
||||
*/
|
||||
data class ButtonGroupItem(
|
||||
val icon: UmamoIcon,
|
||||
val selected: Boolean,
|
||||
val onClick: () -> Unit,
|
||||
val contentDescription: String,
|
||||
)
|
||||
|
||||
/**
|
||||
* A Blender-style run of butted icon toggles: the segments sit flush against each other separated by a
|
||||
* hairline seam, with the group's outer corners rounded and every shared edge square - one pill-shaped
|
||||
* control rather than a row of isolated chips. Each segment carries its own selected state, so the
|
||||
* group serves both independent toggles (the outliner's restriction columns) and radio-style sets (the
|
||||
* viewport's mesh select modes) - the caller decides the semantics in its onClick handlers.
|
||||
*
|
||||
* Blender 式の連結トグル列。両端だけ角丸で、隣接辺は直角。各セグメントが自分の選択状態を持つ。
|
||||
*
|
||||
* @param List items The segments, in display order.
|
||||
* @param Modifier modifier The layout modifier.
|
||||
*/
|
||||
@Composable
|
||||
fun ButtonGroup(items: List<ButtonGroupItem>, modifier: Modifier = Modifier) {
|
||||
val shapes = LocalUmamoShapes.current
|
||||
Row(modifier = modifier, verticalAlignment = Alignment.CenterVertically) {
|
||||
items.forEachIndexed { segmentIndex, item ->
|
||||
if (segmentIndex > 0) {
|
||||
Spacer(modifier = Modifier.width(SEGMENT_GAP))
|
||||
}
|
||||
ButtonGroupSegment(
|
||||
item = item,
|
||||
shape = segmentShape(shapes.small, segmentIndex, items.size),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Shapes one segment by its position in the (horizontal) group, delegating to the shared [stackedShape]
|
||||
* helper that the vertical numeric-field stack also uses: outer corners take the group's rounding,
|
||||
* corners shared with a neighbour are squared.
|
||||
*
|
||||
* @param CornerBasedShape groupShape The rounding applied to the group's outer corners.
|
||||
* @param Int segmentIndex This segment's position.
|
||||
* @param Int segmentCount The number of segments in the group.
|
||||
* @return Shape The segment's corner shape.
|
||||
*/
|
||||
private fun segmentShape(groupShape: CornerBasedShape, segmentIndex: Int, segmentCount: Int): Shape =
|
||||
stackedShape(groupShape, stackPositionOf(segmentIndex, segmentCount), StackAxis.Horizontal)
|
||||
|
||||
/**
|
||||
* One rendered segment: a full-bleed fill (accent while selected, neutral control fill otherwise, both
|
||||
* brightening on hover) under a centered icon. Flat like the rest of the kit - the default indication
|
||||
* is suppressed and the fill carries the hover feedback. The fill and glyph share [accentControlFill] /
|
||||
* [accentControlGlyph] with the filled [IconButton], so header controls and segments read as one family.
|
||||
*
|
||||
* @param ButtonGroupItem item The segment to draw.
|
||||
* @param Shape shape The position-dependent corner shape from [segmentShape].
|
||||
*/
|
||||
@Composable
|
||||
private fun ButtonGroupSegment(item: ButtonGroupItem, shape: Shape) {
|
||||
val colors = LocalUmamoColors.current
|
||||
val interaction = remember { MutableInteractionSource() }
|
||||
val hovered by interaction.collectIsHoveredAsState()
|
||||
val pressed by interaction.collectIsPressedAsState()
|
||||
val fill = accentControlFill(colors, item.selected, hovered, pressed)
|
||||
val iconTint = accentControlGlyph(colors, item.selected)
|
||||
// The label doubles as the hover text, as it does on IconButton - it is the human name of the segment
|
||||
// either way.
|
||||
Tooltip(text = item.contentDescription) {
|
||||
Box(
|
||||
modifier =
|
||||
Modifier
|
||||
.size(width = SEGMENT_WIDTH, height = SEGMENT_HEIGHT)
|
||||
.clip(shape)
|
||||
.background(fill)
|
||||
.clickable(interactionSource = interaction, indication = null, onClick = item.onClick)
|
||||
.semantics { contentDescription = item.contentDescription },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Canvas(modifier = Modifier.size(SEGMENT_ICON_SIZE)) {
|
||||
drawIcon(item.icon, iconTint)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package org.umamo.ui.kit.button
|
||||
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.unit.DpSize
|
||||
import androidx.compose.ui.unit.dp
|
||||
import org.umamo.ui.theme.LocalUmamoIcons
|
||||
import org.umamo.ui.theme.LocalUmamoShapes
|
||||
|
||||
/**
|
||||
* A modal-card header close button: a flat "✕" glyph that brightens from muted to full text color on
|
||||
* hover, matching the kit's other icon controls. Shared by the settings window and the Help dialogs;
|
||||
* needed for keyboardless tablets where Escape is unavailable. A thin preset of [IconButton] - it fixes
|
||||
* the close glyph at a larger 20dp and, sitting in stable dialog chrome, keeps keyboard focus.
|
||||
*
|
||||
* モーダルヘッダの閉じるボタン。ホバーで明るくなる「✕」。Esc が使えないタブレット向け。
|
||||
*
|
||||
* @param Function onClick Click callback (closes the window).
|
||||
* @param String contentDescription The accessible label (the face is only a glyph).
|
||||
*/
|
||||
@Composable
|
||||
internal fun CloseButton(onClick: () -> Unit, contentDescription: String) {
|
||||
IconButton(
|
||||
icon = LocalUmamoIcons.close,
|
||||
onClick = onClick,
|
||||
contentDescription = contentDescription,
|
||||
size = DpSize(20.dp, 20.dp),
|
||||
glyphSize = 20.dp,
|
||||
suppressFocus = false,
|
||||
appearance = IconButtonAppearance.Filled(LocalUmamoShapes.current.small),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
package org.umamo.ui.kit.button
|
||||
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.collectIsHoveredAsState
|
||||
import androidx.compose.foundation.interaction.collectIsPressedAsState
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.requiredSize
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.CornerBasedShape
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.focus.focusProperties
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.DpSize
|
||||
import androidx.compose.ui.unit.dp
|
||||
import org.umamo.ui.kit.Tooltip
|
||||
import org.umamo.ui.theme.LocalUmamoColors
|
||||
import org.umamo.ui.theme.UmamoColors
|
||||
import org.umamo.ui.theme.UmamoIcon
|
||||
import org.umamo.ui.theme.drawIcon
|
||||
|
||||
/**
|
||||
* A small flat or elevation-filled icon button: a themed glyph over an optional control-fill chip, flat
|
||||
* (no ripple) with hover feedback. Consolidates the kit's icon buttons - the reset and close affordances
|
||||
* are this control with a preset icon and size.
|
||||
*
|
||||
* The default suppresses keyboard focus because these buttons live inside the shell tree, where a click
|
||||
* that removes or restructures the button's own row would otherwise leave the focus owner null and the
|
||||
* shell root's onPreviewKeyEvent (all keyboard dispatch) dead until Tab traversal reclaims focus. A
|
||||
* button anchored in stable chrome (a dialog header) can opt back in with [suppressFocus] = false.
|
||||
*
|
||||
* @param UmamoIcon icon The glyph to draw.
|
||||
* @param Function onClick Click callback.
|
||||
* @param String contentDescription The accessible label (the face is only a glyph).
|
||||
* @param Modifier modifier Layout modifier.
|
||||
* @param IconButtonAppearance appearance Flat glyph, or a Filled elevation chip (background plus corners).
|
||||
* @param DpSize size The button's box, square by default; 26x20 for header controls.
|
||||
* @param Dp glyphSize The drawn glyph size, honored even when it exceeds [size]
|
||||
* (the glyph then overhangs its box rather than being capped).
|
||||
* @param Boolean active A lit toggle state (accent glyph when Flat, accent fill when Filled).
|
||||
* @param Boolean enabled When false the glyph dims to the disabled tint and clicks are inert
|
||||
* (no-document chrome renders its controls this way rather than hiding them).
|
||||
* @param Boolean suppressFocus When true the click never pulls keyboard focus off the shell root.
|
||||
*/
|
||||
@Composable
|
||||
fun IconButton(
|
||||
icon: UmamoIcon,
|
||||
onClick: () -> Unit,
|
||||
contentDescription: String,
|
||||
modifier: Modifier = Modifier,
|
||||
appearance: IconButtonAppearance = IconButtonAppearance.Flat,
|
||||
size: DpSize = DpSize(20.dp, 20.dp),
|
||||
glyphSize: Dp = 16.dp,
|
||||
active: Boolean = false,
|
||||
enabled: Boolean = true,
|
||||
suppressFocus: Boolean = true,
|
||||
) {
|
||||
val colors = LocalUmamoColors.current
|
||||
val interaction = remember { MutableInteractionSource() }
|
||||
val hoveredLive by interaction.collectIsHoveredAsState()
|
||||
val pressedLive by interaction.collectIsPressedAsState()
|
||||
// A disabled button shows no hover or press feedback (the fill and border stay at rest).
|
||||
val hovered = hoveredLive && enabled
|
||||
val pressed = pressedLive && enabled
|
||||
val glyphColor =
|
||||
when {
|
||||
!enabled -> colors.textDisabled
|
||||
appearance is IconButtonAppearance.Filled -> accentControlGlyph(colors, active)
|
||||
active -> colors.accent
|
||||
hovered -> colors.text
|
||||
else -> colors.textMuted
|
||||
}
|
||||
var faceModifier = Modifier.size(size)
|
||||
if (appearance is IconButtonAppearance.Filled) {
|
||||
// Elevation is the inline clip + background idiom, not kit Surface: the fill must ramp on hover,
|
||||
// which a Surface's static color cannot do.
|
||||
faceModifier =
|
||||
faceModifier
|
||||
.clip(appearance.shape)
|
||||
.background(accentControlFill(colors, active && enabled, hovered, pressed))
|
||||
.border(
|
||||
width = 1.dp,
|
||||
color =
|
||||
when {
|
||||
hovered -> colors.panelBorderHover
|
||||
else -> colors.controlBorder
|
||||
},
|
||||
shape = appearance.shape,
|
||||
)
|
||||
}
|
||||
if (suppressFocus) {
|
||||
faceModifier = faceModifier.focusProperties { canFocus = false }
|
||||
}
|
||||
faceModifier =
|
||||
faceModifier
|
||||
.clickable(interactionSource = interaction, indication = null, enabled = enabled, onClick = onClick)
|
||||
.semantics { this.contentDescription = contentDescription }
|
||||
// The caller's layout modifier rides on the tooltip wrapper (the outermost node) so alignment and
|
||||
// weight still resolve against the parent; the fixed-size face sits inside it. contentDescription
|
||||
// doubles as the hover label - it is the human name of the control either way.
|
||||
Tooltip(text = contentDescription, modifier = modifier) {
|
||||
Box(modifier = faceModifier, contentAlignment = Alignment.Center) {
|
||||
// requiredSize, not size: size coerces to the box's constraints, which silently caps glyphSize at
|
||||
// the smaller of the two and lets a starved parent shrink the glyph away entirely.
|
||||
Canvas(modifier = Modifier.requiredSize(glyphSize)) {
|
||||
drawIcon(icon, glyphColor)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* How an [IconButton]'s face is painted: a bare glyph, or a filled elevation chip.
|
||||
*
|
||||
* エリアヘッダのような塗り付きボタンと、ダイアログの✕のような塗りなしボタンを一つの型で表す。
|
||||
*/
|
||||
sealed interface IconButtonAppearance {
|
||||
/** Flat: no fill; the glyph itself carries hover and active feedback. */
|
||||
data object Flat : IconButtonAppearance
|
||||
|
||||
/**
|
||||
* Filled: a control-fill elevation chip (a background plus corner rounding) sits under the glyph, the
|
||||
* fill brightening on hover and switching to the accent while active. This is the treatment that lets
|
||||
* any icon button read as a raised button at rest.
|
||||
*
|
||||
* @property CornerBasedShape shape The corner rounding of the elevation fill.
|
||||
*/
|
||||
data class Filled(val shape: CornerBasedShape) : IconButtonAppearance
|
||||
}
|
||||
|
||||
/**
|
||||
* The fill behind a filled icon button or button-group segment: the neutral control fill at rest, the
|
||||
* accent while selected, brightening one step on hover and darkening one while held. Shared so the
|
||||
* header's filled buttons and a [ButtonGroup]'s segments stay one visual family rather than two copies of
|
||||
* the same ramp; [Button] restates it only because its secondary hover is the softer rowHover.
|
||||
*
|
||||
* A press outranks a hover because the pointer is necessarily over a control it is pressing.
|
||||
*
|
||||
* @param UmamoColors colors The active color scheme.
|
||||
* @param Boolean selected Whether the control is lit (accent) rather than neutral.
|
||||
* @param Boolean hovered Whether the pointer is over the control.
|
||||
* @param Boolean pressed Whether the control is held down.
|
||||
* @return Color The resolved fill color.
|
||||
*/
|
||||
internal fun accentControlFill(colors: UmamoColors, selected: Boolean, hovered: Boolean, pressed: Boolean): Color =
|
||||
when {
|
||||
selected && pressed -> colors.accentPressed
|
||||
selected && hovered -> colors.accentHover
|
||||
selected -> colors.accent
|
||||
pressed -> colors.buttonPressed
|
||||
hovered -> colors.buttonHover
|
||||
else -> colors.controlBackground
|
||||
}
|
||||
|
||||
/**
|
||||
* The glyph tint on a filled icon button or button-group segment: on-accent text while selected, the
|
||||
* neutral control glyph otherwise. Paired with [accentControlFill].
|
||||
*
|
||||
* @param UmamoColors colors The active color scheme.
|
||||
* @param Boolean selected Whether the control is lit.
|
||||
* @return Color The resolved glyph color.
|
||||
*/
|
||||
internal fun accentControlGlyph(colors: UmamoColors, selected: Boolean): Color =
|
||||
if (selected) colors.accentText else colors.controlGlyph
|
||||
@@ -0,0 +1,66 @@
|
||||
package org.umamo.ui.kit.button
|
||||
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.DpSize
|
||||
import androidx.compose.ui.unit.dp
|
||||
import org.umamo.ui.kit.Tooltip
|
||||
import org.umamo.ui.theme.UmamoIcon
|
||||
import org.umamo.ui.theme.drawIcon
|
||||
|
||||
/**
|
||||
* A labelled glyph whose gesture the caller owns: a themed icon centered in a fixed-size box, carrying the
|
||||
* accessible name and (by default) the matching hover tooltip. This is [IconButton]'s sibling for the
|
||||
* slots that cannot be an [IconButton] - a tree row's eye, its selectable pointer, a disclosure chevron -
|
||||
* because they consume their own press so the whole-row selection handler skips them, and they must not
|
||||
* take keyboard focus off a row the very edit beside them can dispose.
|
||||
*
|
||||
* Both live here so the kit's label contract has one neighborhood rather than two: a control's accessible
|
||||
* name doubles as its hover label, and passing one string to both keeps them in lockstep.
|
||||
*
|
||||
* @param UmamoIcon icon The glyph to draw.
|
||||
* @param String contentDescription The accessible name (the face is only a glyph).
|
||||
* @param Color tint The glyph color, resolved by the caller against its own row state.
|
||||
* @param Modifier modifier Applied to the sized face, so the caller's gesture covers the whole slot.
|
||||
* @param DpSize slotSize The hit box; set it equal to [glyphSize] for a bare inline glyph.
|
||||
* @param Dp glyphSize The drawn glyph size inside the box.
|
||||
* @param String hoverLabel The tooltip text, defaulting to [contentDescription]. A slot sitting
|
||||
* beside its own visible text passes "" to keep the accessible name without a hover card that only
|
||||
* repeats what is already on screen.
|
||||
*/
|
||||
@Composable
|
||||
fun IconSlot(
|
||||
icon: UmamoIcon,
|
||||
contentDescription: String,
|
||||
tint: Color,
|
||||
modifier: Modifier = Modifier,
|
||||
slotSize: DpSize = DpSize(20.dp, 20.dp),
|
||||
glyphSize: Dp = 16.dp,
|
||||
hoverLabel: String = contentDescription,
|
||||
) {
|
||||
// Unlike IconButton, the caller's modifier rides on the FACE rather than the tooltip wrapper: here it
|
||||
// carries the gesture, which has to cover the slot's hit box exactly. The wrapper sizes to the face,
|
||||
// so the hover region matches either way.
|
||||
Tooltip(text = hoverLabel) {
|
||||
Box(
|
||||
modifier =
|
||||
Modifier
|
||||
.size(slotSize)
|
||||
.then(modifier)
|
||||
.semantics { this.contentDescription = contentDescription },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Canvas(modifier = Modifier.size(glyphSize)) {
|
||||
drawIcon(icon, tint)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package org.umamo.ui.l10n
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.State
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.produceState
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.staticCompositionLocalOf
|
||||
import org.umamo.settings.Settings
|
||||
|
||||
/**
|
||||
* The active UI language tag (BCP-47, e.g. "en" / "ja" / "ko") for the composition, driven by the
|
||||
* localization.locale setting rather than the OS locale. Descendants that need the raw tag read
|
||||
* `LocalAppLocale.current`; most code just calls stringResource() and lets the catalogs resolve.
|
||||
*/
|
||||
val LocalAppLocale = staticCompositionLocalOf { "en" }
|
||||
|
||||
/** The settings key holding the UI language tag. */
|
||||
const val LOCALE_SETTINGS_KEY: String = "localization.locale"
|
||||
|
||||
/** The language the UI falls back to when the setting holds none, and when no system language has a catalog. */
|
||||
const val FALLBACK_LOCALE_TAG: String = "en"
|
||||
|
||||
/**
|
||||
* The UI languages Umamo ships, in display order: one entry per composeResources/values-<tag>/ catalog, keyed
|
||||
* by the BCP-47 tag written to localization.locale (which applyAppLocale feeds to the resource environment).
|
||||
*
|
||||
* The values are endonyms ("English" / "日本語" / "한국어"), shown verbatim whatever the active UI language: a
|
||||
* language's own name is identity, not chrome to translate, and it is what a rigger who cannot read the
|
||||
* current language looks for.
|
||||
*/
|
||||
val UI_LANGUAGE_ENDONYMS: Map<String, String> = linkedMapOf("en" to "English", "ja" to "日本語", "ko" to "한국어")
|
||||
|
||||
/**
|
||||
* The operating system's preferred UI languages as BCP-47 tags, most preferred first; empty when the platform
|
||||
* reports none. Reads the system's own preference, never the process default [applyAppLocale] overrides, so
|
||||
* the answer is the same before and after the app applies its language.
|
||||
*
|
||||
* @return List<String> The preferred language tags.
|
||||
*/
|
||||
expect fun systemLanguageTags(): List<String>
|
||||
|
||||
/**
|
||||
* Picks the UI language for a list of preferred language tags: the first preferred tag with a catalog wins.
|
||||
* Each tag is tried at its most specific first - the whole tag, then language-region, then the language alone -
|
||||
* so a region catalog ("zh-CN") is matched before a bare language one would be. `_` separators (the JVM and
|
||||
* POSIX spelling) read as `-`, and case does not matter.
|
||||
*
|
||||
* @param List preferredTags The preferred language tags, most preferred first.
|
||||
* @param Collection supported The tags that have a catalog.
|
||||
* @return String The matched supported tag, or [FALLBACK_LOCALE_TAG] when none matches.
|
||||
*/
|
||||
fun matchUiLanguage(preferredTags: List<String>, supported: Collection<String>): String {
|
||||
val supportedByLowercase = supported.associateBy { tag -> tag.lowercase() }
|
||||
for (preferredTag in preferredTags) {
|
||||
val subtags = preferredTag.replace('_', '-').lowercase().split('-').filter { subtag -> subtag.isNotEmpty() }
|
||||
val language = subtags.firstOrNull() ?: continue
|
||||
// A region is the two-letter or three-digit subtag after the language (and any four-letter script).
|
||||
val region = subtags.drop(1).firstOrNull { subtag -> subtag.length == 2 || (subtag.length == 3 && subtag.all(Char::isDigit)) }
|
||||
val candidates = listOfNotNull(subtags.joinToString("-"), region?.let { "$language-$it" }, language)
|
||||
for (candidate in candidates) {
|
||||
supportedByLowercase[candidate]?.let { matched -> return matched }
|
||||
}
|
||||
}
|
||||
return FALLBACK_LOCALE_TAG
|
||||
}
|
||||
|
||||
/**
|
||||
* The UI language tag as live state: read from the localization.locale setting and updated when it
|
||||
* changes, so whatever is keyed on it re-localizes on a runtime language switch.
|
||||
*
|
||||
* @param Settings settings The settings store to read and follow.
|
||||
* @return State The live BCP-47 language tag.
|
||||
*/
|
||||
@Composable
|
||||
fun rememberLocaleTag(settings: Settings): State<String> =
|
||||
produceState(initialValue = settings.getString(LOCALE_SETTINGS_KEY) ?: FALLBACK_LOCALE_TAG, settings) {
|
||||
settings.changes.collect { changedKey ->
|
||||
if (changedKey == LOCALE_SETTINGS_KEY) {
|
||||
value = settings.getString(LOCALE_SETTINGS_KEY) ?: FALLBACK_LOCALE_TAG
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies [languageTag] as the process resource locale on the current platform. Compose
|
||||
* Multiplatform has no first-party "override the resource locale at runtime" API yet (JetBrains issue
|
||||
* #4197), so the portable lever is the JVM default locale, which the desktop/Android resource
|
||||
* environment derives from. expect/actual keeps java.util.Locale out of commonMain (absent there).
|
||||
*
|
||||
* @param String languageTag The BCP-47 language tag to apply.
|
||||
*/
|
||||
expect fun applyAppLocale(languageTag: String)
|
||||
|
||||
/**
|
||||
* Provides [languageTag] to the subtree and makes stringResource() resolve against it. Two effects:
|
||||
* [applyAppLocale] sets the platform locale before children compose (via remember keyed on the tag,
|
||||
* so it re-runs only when the language actually changes), and `key(languageTag)` forces the subtree -
|
||||
* including Compose's cached resource environment - to recompose on a switch so the new catalog is read.
|
||||
*
|
||||
* @param String languageTag The BCP-47 language tag to make active.
|
||||
* @param Function content The subtree to render under this locale.
|
||||
*/
|
||||
@Composable
|
||||
fun ProvideAppLocale(languageTag: String, content: @Composable () -> Unit) {
|
||||
// remember(key) runs once per distinct tag - applies the locale before the keyed content composes.
|
||||
remember(languageTag) {
|
||||
applyAppLocale(languageTag)
|
||||
languageTag
|
||||
}
|
||||
CompositionLocalProvider(LocalAppLocale provides languageTag) {
|
||||
key(languageTag) {
|
||||
content()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
package org.umamo.ui.menu
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import org.jetbrains.compose.resources.stringResource
|
||||
import org.umamo.ui.action.Keymap
|
||||
import org.umamo.ui.action.formatAccelerator
|
||||
import org.umamo.ui.document.fileDisplayName
|
||||
import org.umamo.ui.kit.MenuItem
|
||||
import org.umamo.ui.kit.TopLevelMenu
|
||||
import org.umamo.ui.resources.Res
|
||||
import org.umamo.ui.resources.cmd_workspace_next
|
||||
import org.umamo.ui.resources.cmd_workspace_prev
|
||||
import org.umamo.ui.resources.menu_about
|
||||
import org.umamo.ui.resources.menu_credits
|
||||
import org.umamo.ui.resources.menu_documentation
|
||||
import org.umamo.ui.resources.menu_edit
|
||||
import org.umamo.ui.resources.menu_exit
|
||||
import org.umamo.ui.resources.menu_export
|
||||
import org.umamo.ui.resources.menu_export_cmo3
|
||||
import org.umamo.ui.resources.menu_export_image
|
||||
import org.umamo.ui.resources.menu_export_moc3
|
||||
import org.umamo.ui.resources.menu_file
|
||||
import org.umamo.ui.resources.menu_file_new
|
||||
import org.umamo.ui.resources.menu_file_open
|
||||
import org.umamo.ui.resources.menu_file_save
|
||||
import org.umamo.ui.resources.menu_file_save_as
|
||||
import org.umamo.ui.resources.menu_help
|
||||
import org.umamo.ui.resources.menu_import
|
||||
import org.umamo.ui.resources.menu_import_artwork
|
||||
import org.umamo.ui.resources.menu_import_cmo3
|
||||
import org.umamo.ui.resources.menu_import_moc3
|
||||
import org.umamo.ui.resources.menu_open_recent
|
||||
import org.umamo.ui.resources.menu_preferences
|
||||
import org.umamo.ui.resources.menu_quick_setup
|
||||
import org.umamo.ui.resources.menu_redo
|
||||
import org.umamo.ui.resources.menu_source_code
|
||||
import org.umamo.ui.resources.menu_undo
|
||||
import org.umamo.ui.resources.menu_web_site
|
||||
import org.umamo.ui.resources.menu_workspace
|
||||
import org.umamo.ui.resources.menu_workspace_export_all
|
||||
import org.umamo.ui.resources.menu_workspace_export_this
|
||||
import org.umamo.ui.resources.menu_workspace_import
|
||||
import org.umamo.ui.resources.menu_workspace_reset
|
||||
import org.umamo.ui.resources.workspace_new
|
||||
|
||||
/**
|
||||
* Runs a command by id through the action registry, with the argument an argument-only command takes (a
|
||||
* recent file's path) or null. The one thing a menu row does.
|
||||
*/
|
||||
typealias MenuDispatch = (commandId: String, argument: Any?) -> Unit
|
||||
|
||||
/**
|
||||
* One menu row that stands for a command. The row is built from the command's id ALONE: selecting it
|
||||
* dispatches that id, and its accelerator hint is whatever chord the keymap binds to that same id. Naming
|
||||
* the id once is the point - a row that dispatched one id and looked its hint up under another would show
|
||||
* no chord, or the wrong one, and nothing would say so.
|
||||
*
|
||||
* @param String label The localized row label.
|
||||
* @param String commandId The command the row stands for.
|
||||
* @param Keymap keymap The keymap the accelerator hint is resolved against.
|
||||
* @param MenuDispatch dispatch Runs a command by id.
|
||||
* @param Boolean enabled Whether the row can be selected.
|
||||
* @return MenuItem.Action The row.
|
||||
*/
|
||||
private fun commandRow(
|
||||
label: String,
|
||||
commandId: String,
|
||||
keymap: Keymap,
|
||||
dispatch: MenuDispatch,
|
||||
enabled: Boolean = true,
|
||||
): MenuItem.Action =
|
||||
MenuItem.Action(
|
||||
label = label,
|
||||
onSelect = { dispatch(commandId, null) },
|
||||
shortcut = keymap.chordFor(commandId)?.let { chord -> formatAccelerator(chord) },
|
||||
enabled = enabled,
|
||||
)
|
||||
|
||||
/**
|
||||
* Builds the File menu shared by every platform's menu bar. Open, Save, and Save As mean the native
|
||||
* `.uma` document; artwork, CMO3, and MOC3 come in through the Import submenu (artwork first: it is the
|
||||
* headline workflow's entry), and CMO3 / MOC3 are interop boundaries that leave through Export. Every
|
||||
* row dispatches its file.* command, so the menu, the keyboard, and the palette share one path. Both
|
||||
* Save rows are gated on [canSave] (a puppet document that did not open read-only), the CMO3 and MOC3
|
||||
* Export rows on [canExport] (a puppet document is open; the CMO3 export reconciles onto a CMO3-origin
|
||||
* document's retained graph and synthesizes a fresh one otherwise), and Export Image on [canExportImage]
|
||||
* (a puppet document is open on a platform with a puppet renderer to draw it); Open Recent labels each stored path via
|
||||
* fileDisplayName, disables itself when the list is empty, and hands the path to file.openPath, which
|
||||
* opens or imports by what the file is.
|
||||
*
|
||||
* @param Keymap keymap The keymap the accelerator hints are resolved against.
|
||||
* @param List recentFiles The recent file paths for the Open Recent submenu, most-recent first.
|
||||
* @param Boolean canExport Whether an exportable puppet document is open (gates the CMO3 and MOC3 rows).
|
||||
* @param Boolean canExportImage Whether the open document can be rendered to an image (gates Export Image).
|
||||
* @param Boolean canSave Whether the open document can be saved (gates both Save rows).
|
||||
* @param MenuDispatch dispatch Runs a command by id.
|
||||
* @return TopLevelMenu The File menu.
|
||||
*/
|
||||
@Composable
|
||||
fun fileMenu(
|
||||
keymap: Keymap,
|
||||
recentFiles: List<String>,
|
||||
canExport: Boolean,
|
||||
canExportImage: Boolean,
|
||||
canSave: Boolean,
|
||||
dispatch: MenuDispatch,
|
||||
): TopLevelMenu =
|
||||
TopLevelMenu(
|
||||
label = stringResource(Res.string.menu_file),
|
||||
items =
|
||||
listOf(
|
||||
commandRow(stringResource(Res.string.menu_file_new), "file.new", keymap, dispatch),
|
||||
commandRow(stringResource(Res.string.menu_file_open), "file.open", keymap, dispatch),
|
||||
MenuItem.Submenu(
|
||||
label = stringResource(Res.string.menu_open_recent),
|
||||
// A recent file is a row per path rather than a command per path, so these carry their
|
||||
// argument and show no chord.
|
||||
items = recentFiles.map { recent -> MenuItem.Action(fileDisplayName(recent), onSelect = { dispatch("file.openPath", recent) }) },
|
||||
enabled = recentFiles.isNotEmpty(),
|
||||
),
|
||||
commandRow(stringResource(Res.string.menu_file_save), "file.save", keymap, dispatch, enabled = canSave),
|
||||
commandRow(stringResource(Res.string.menu_file_save_as), "file.saveAs", keymap, dispatch, enabled = canSave),
|
||||
MenuItem.Submenu(
|
||||
label = stringResource(Res.string.menu_import),
|
||||
items =
|
||||
listOf(
|
||||
commandRow(stringResource(Res.string.menu_import_artwork), "file.importArtwork", keymap, dispatch),
|
||||
commandRow(stringResource(Res.string.menu_import_cmo3), "file.importCmo3", keymap, dispatch),
|
||||
commandRow(stringResource(Res.string.menu_import_moc3), "file.importMoc3", keymap, dispatch),
|
||||
),
|
||||
),
|
||||
MenuItem.Submenu(
|
||||
label = stringResource(Res.string.menu_export),
|
||||
items =
|
||||
listOf(
|
||||
commandRow(stringResource(Res.string.menu_export_cmo3), "file.exportCmo3", keymap, dispatch, enabled = canExport),
|
||||
commandRow(stringResource(Res.string.menu_export_moc3), "file.exportMoc3", keymap, dispatch, enabled = canExport),
|
||||
commandRow(stringResource(Res.string.menu_export_image), "file.exportImage", keymap, dispatch, enabled = canExportImage),
|
||||
),
|
||||
),
|
||||
MenuItem.Separator,
|
||||
commandRow(stringResource(Res.string.menu_exit), "file.exit", keymap, dispatch),
|
||||
),
|
||||
)
|
||||
|
||||
/**
|
||||
* Builds the Edit menu shared by every platform's menu bar, so desktop and the keyboardless tablet reach
|
||||
* the same entries from one source (the "one shared interface" guardrail). Undo and Redo dispatch
|
||||
* edit.undo / edit.redo and are enabled per [canUndo] / [canRedo]; Preferences dispatches
|
||||
* edit.preferences, whose overlay the shell owns.
|
||||
*
|
||||
* @param Keymap keymap The keymap the accelerator hints are resolved against.
|
||||
* @param Boolean canUndo Whether an undo step is available (gates the Undo row).
|
||||
* @param Boolean canRedo Whether a redo step is available (gates the Redo row).
|
||||
* @param MenuDispatch dispatch Runs a command by id.
|
||||
* @return TopLevelMenu The Edit menu.
|
||||
*/
|
||||
@Composable
|
||||
fun editMenu(
|
||||
keymap: Keymap,
|
||||
canUndo: Boolean,
|
||||
canRedo: Boolean,
|
||||
dispatch: MenuDispatch,
|
||||
): TopLevelMenu =
|
||||
TopLevelMenu(
|
||||
label = stringResource(Res.string.menu_edit),
|
||||
items =
|
||||
listOf(
|
||||
commandRow(stringResource(Res.string.menu_undo), "edit.undo", keymap, dispatch, enabled = canUndo),
|
||||
commandRow(stringResource(Res.string.menu_redo), "edit.redo", keymap, dispatch, enabled = canRedo),
|
||||
MenuItem.Separator,
|
||||
commandRow(stringResource(Res.string.menu_preferences), "edit.preferences", keymap, dispatch),
|
||||
),
|
||||
)
|
||||
|
||||
/**
|
||||
* Builds the Workspace menu shared by every platform's menu bar: Previous / Next (the same tab shift the
|
||||
* strip's context menu and primary+PageUp / PageDown reach), then New (the same create path as the tab
|
||||
* strip's "+"), Reset (the shell confirms first), and the layout's trips to and from a file. Every row
|
||||
* dispatches its workspace.* command.
|
||||
*
|
||||
* @param Keymap keymap The keymap the accelerator hints are resolved against.
|
||||
* @param MenuDispatch dispatch Runs a command by id.
|
||||
* @return TopLevelMenu The Workspace menu.
|
||||
*/
|
||||
@Composable
|
||||
fun workspaceMenu(
|
||||
keymap: Keymap,
|
||||
dispatch: MenuDispatch,
|
||||
): TopLevelMenu =
|
||||
TopLevelMenu(
|
||||
label = stringResource(Res.string.menu_workspace),
|
||||
items =
|
||||
listOf(
|
||||
commandRow(stringResource(Res.string.cmd_workspace_prev), "workspace.prev", keymap, dispatch),
|
||||
commandRow(stringResource(Res.string.cmd_workspace_next), "workspace.next", keymap, dispatch),
|
||||
MenuItem.Separator,
|
||||
commandRow(stringResource(Res.string.workspace_new), "workspace.new", keymap, dispatch),
|
||||
commandRow(stringResource(Res.string.menu_workspace_reset), "workspace.reset", keymap, dispatch),
|
||||
MenuItem.Separator,
|
||||
commandRow(stringResource(Res.string.menu_workspace_import), "workspace.import", keymap, dispatch),
|
||||
commandRow(stringResource(Res.string.menu_workspace_export_this), "workspace.exportThis", keymap, dispatch),
|
||||
commandRow(stringResource(Res.string.menu_workspace_export_all), "workspace.exportAll", keymap, dispatch),
|
||||
),
|
||||
)
|
||||
|
||||
/**
|
||||
* Builds the Help menu shared by every platform's menu bar: the project links, then Quick Setup, then
|
||||
* Credits and About. Every row dispatches its help.* command - the links open through the shell's handler
|
||||
* and the three dialogs through the overlay state the shell owns - so the palette reaches all six as well.
|
||||
*
|
||||
* @param Keymap keymap The keymap the accelerator hints are resolved against.
|
||||
* @param MenuDispatch dispatch Runs a command by id.
|
||||
* @return TopLevelMenu The Help menu.
|
||||
*/
|
||||
@Composable
|
||||
fun helpMenu(
|
||||
keymap: Keymap,
|
||||
dispatch: MenuDispatch,
|
||||
): TopLevelMenu =
|
||||
TopLevelMenu(
|
||||
label = stringResource(Res.string.menu_help),
|
||||
items =
|
||||
listOf(
|
||||
commandRow(stringResource(Res.string.menu_source_code), "help.sourceCode", keymap, dispatch),
|
||||
commandRow(stringResource(Res.string.menu_web_site), "help.webSite", keymap, dispatch),
|
||||
commandRow(stringResource(Res.string.menu_documentation), "help.documentation", keymap, dispatch),
|
||||
MenuItem.Separator,
|
||||
commandRow(stringResource(Res.string.menu_quick_setup), "help.quickSetup", keymap, dispatch),
|
||||
MenuItem.Separator,
|
||||
commandRow(stringResource(Res.string.menu_credits), "help.credits", keymap, dispatch),
|
||||
commandRow(stringResource(Res.string.menu_about), "help.about", keymap, dispatch),
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,79 @@
|
||||
package org.umamo.ui.menu
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.produceState
|
||||
import androidx.compose.runtime.remember
|
||||
import org.umamo.edit.EditorSession
|
||||
import org.umamo.settings.Settings
|
||||
import org.umamo.ui.action.rememberLiveKeymap
|
||||
import org.umamo.ui.document.recentFiles
|
||||
import org.umamo.ui.kit.TopLevelMenu
|
||||
import org.umamo.ui.l10n.applyAppLocale
|
||||
import org.umamo.ui.l10n.rememberLocaleTag
|
||||
|
||||
/**
|
||||
* Builds the in-window menu bar from the shared per-menu builders, and keeps it live: the accelerators
|
||||
* follow the keymap settings (so a row shows the chord the keyboard uses after a preset switch or a
|
||||
* rebind), Open Recent follows the recent-files list, the Edit rows follow the session's undo and redo
|
||||
* availability, and the labels follow the UI language.
|
||||
*
|
||||
* The bar is built outside the shell's own ProvideAppLocale scope, so it re-localizes itself: the
|
||||
* key on the locale re-resolves the builders' stringResource() calls against the new catalog, and the
|
||||
* remember applies the platform locale that resolution reads before the builders run. That is scoped
|
||||
* to the menu alone, so a language switch re-localizes the bar without re-mounting the viewport or the
|
||||
* shell underneath.
|
||||
*
|
||||
* @param Settings settings The settings the keymap, the recent files, and the locale are read from.
|
||||
* @param EditorSession? session The open document's session, or null; gates the Undo and Redo rows.
|
||||
* @param Boolean canSave Whether the open document can be saved (gates both Save rows).
|
||||
* @param Boolean canExport Whether an exportable puppet document is open (gates the CMO3 and MOC3 rows).
|
||||
* @param Boolean canExportImage Whether the open document can be rendered to an image (gates Export Image).
|
||||
* @param MenuDispatch dispatch Runs a command by id; every row of the bar stands for a command, so this is
|
||||
* all the bar needs from its host, and a rebind reaches the menu, the keyboard, and the palette alike.
|
||||
* @return List The top-level menus.
|
||||
*/
|
||||
@Composable
|
||||
internal fun buildAppMenu(
|
||||
settings: Settings,
|
||||
session: EditorSession?,
|
||||
canSave: Boolean,
|
||||
canExport: Boolean,
|
||||
canExportImage: Boolean,
|
||||
dispatch: MenuDispatch,
|
||||
): List<TopLevelMenu> {
|
||||
// produceState runs unconditionally (the session may be null with no document) and re-collects when
|
||||
// the session swaps.
|
||||
val canUndo by produceState(false, session) {
|
||||
val activeSession = session
|
||||
if (activeSession == null) {
|
||||
value = false
|
||||
} else {
|
||||
activeSession.canUndo.collect { value = it }
|
||||
}
|
||||
}
|
||||
val canRedo by produceState(false, session) {
|
||||
val activeSession = session
|
||||
if (activeSession == null) {
|
||||
value = false
|
||||
} else {
|
||||
activeSession.canRedo.collect { value = it }
|
||||
}
|
||||
}
|
||||
val keymap by rememberLiveKeymap(settings)
|
||||
// Re-read on any settings change, so the Open Recent menu stays current after an open or a save.
|
||||
val recentFiles by produceState(initialValue = settings.recentFiles(), settings) {
|
||||
settings.changes.collect { value = settings.recentFiles() }
|
||||
}
|
||||
val locale by rememberLocaleTag(settings)
|
||||
return key(locale) {
|
||||
remember(locale) { applyAppLocale(locale) }
|
||||
listOf(
|
||||
fileMenu(keymap = keymap, recentFiles = recentFiles, canExport = canExport, canExportImage = canExportImage, canSave = canSave, dispatch = dispatch),
|
||||
editMenu(keymap = keymap, canUndo = canUndo, canRedo = canRedo, dispatch = dispatch),
|
||||
workspaceMenu(keymap = keymap, dispatch = dispatch),
|
||||
helpMenu(keymap = keymap, dispatch = dispatch),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,443 @@
|
||||
package org.umamo.ui.model
|
||||
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.umamo.edit.AdjustableOperation
|
||||
import org.umamo.edit.NoticePlacement
|
||||
import org.umamo.edit.OperatorParameter
|
||||
import org.umamo.edit.ParameterChoice
|
||||
import org.umamo.edit.ParameterUnit
|
||||
import org.umamo.edit.choiceValue
|
||||
import org.umamo.edit.commitArtworkAdded
|
||||
import org.umamo.edit.intValue
|
||||
import org.umamo.edit.withArtworkAdded
|
||||
import org.umamo.edit.withAtlasRepack
|
||||
import org.umamo.format.art.LayerRaster
|
||||
import org.umamo.format.art.SourceArt
|
||||
import org.umamo.format.atlas.AtlasPackOptions
|
||||
import org.umamo.format.atlas.AtlasPackSkipReason
|
||||
import org.umamo.format.atlas.packAtlas
|
||||
import org.umamo.interop.art.ArtSourceDescriptor
|
||||
import org.umamo.interop.art.ArtworkAnchor
|
||||
import org.umamo.interop.art.SourceArtAdditions
|
||||
import org.umamo.interop.art.SourceArtImport
|
||||
import org.umamo.interop.art.SourceArtImportNotice
|
||||
import org.umamo.interop.art.SourceArtImportOptions
|
||||
import org.umamo.interop.art.placedBy
|
||||
import org.umamo.render.DecodedImage
|
||||
import org.umamo.render.PuppetTextures
|
||||
import org.umamo.render.SourceArtRasters
|
||||
import org.umamo.render.generatedPuppetTextures
|
||||
import org.umamo.runtime.model.AtlasTileId
|
||||
import org.umamo.runtime.model.PuppetModel
|
||||
import org.umamo.storage.UmamoLog
|
||||
|
||||
/*
|
||||
* Adding an artwork file to an OPEN document: the bridge's additions appended to the live model, the
|
||||
* new tiles packed into the gaps around the art already on the pages, committed as one undo step and
|
||||
* registered on the operation settings strip. The repack's shape throughout - the same pack
|
||||
* primitive, the same supersede checks, the same amend-in-place adjustment - so a second artwork
|
||||
* file lands the way a repack does rather than through a second pipeline.
|
||||
*/
|
||||
|
||||
/** The parameter keys the add-artwork rows carry (the strip maps their label keys to strings). */
|
||||
internal object ImportParameterKeys {
|
||||
const val ALIGN = "import.align"
|
||||
const val OFFSET_X = "import.offsetX"
|
||||
const val OFFSET_Z = "import.offsetZ"
|
||||
const val ALPHA_THRESHOLD = "import.alphaThreshold"
|
||||
const val MARGIN = "import.margin"
|
||||
|
||||
/** The prefix an Align entry's label key carries in front of its [ArtworkAnchor.key]. */
|
||||
const val ANCHOR_CHOICE_PREFIX = "import.anchor."
|
||||
}
|
||||
|
||||
/** The widest birth-mesh margin the strip offers, in source pixels. */
|
||||
internal const val IMPORT_MAX_MARGIN = 64
|
||||
|
||||
/** How far the Offset rows reach either way, in source pixels: past any page the pack can hold. */
|
||||
internal const val IMPORT_MAX_OFFSET = 8192
|
||||
|
||||
/**
|
||||
* One artwork file to add to the open document, as read from disk.
|
||||
*
|
||||
* Holds the parsed art for the strip's adjustments (a re-run re-derives the additions from the same
|
||||
* layers) and the decoded wrapper of every layer raster, minted once: a re-run hands the raster store
|
||||
* the same instances again, and the renderer's texture cache keys on that identity.
|
||||
*
|
||||
* @property SourceArt art The parsed source art.
|
||||
* @property ArtSourceDescriptor descriptor What the model records about the file.
|
||||
* @property SourceArtImportOptions options The threshold and margin the first run uses.
|
||||
*/
|
||||
class AddArtworkRequest(
|
||||
val art: SourceArt,
|
||||
val descriptor: ArtSourceDescriptor,
|
||||
val options: SourceArtImportOptions,
|
||||
) {
|
||||
private val decoded = DecodedLayerRasters(art.layers)
|
||||
|
||||
/**
|
||||
* The decoded wrapper of one of this file's layer rasters.
|
||||
*
|
||||
* @param LayerRaster raster The layer's pixels.
|
||||
* @return DecodedImage The wrapper, the same instance on every call.
|
||||
*/
|
||||
internal fun decodedFor(raster: LayerRaster): DecodedImage = decoded.decodedFor(raster)
|
||||
}
|
||||
|
||||
/** What one add-artwork pass produced, or why it produced nothing. */
|
||||
private sealed interface AddArtworkOutcome {
|
||||
/** The file has no layer with art to add. */
|
||||
data object NothingToAdd : AddArtworkOutcome
|
||||
|
||||
/**
|
||||
* The pack could not keep some of the document's OWN art where it is - a placed tile the packer
|
||||
* would not hold fixed - so nothing was applied; the refusals name the tiles.
|
||||
*
|
||||
* @property List refusals The document's tiles the pack could not keep.
|
||||
*/
|
||||
class Refused(val refusals: List<AtlasRepackRefusal>) : AddArtworkOutcome
|
||||
|
||||
/**
|
||||
* The additions appended and packed.
|
||||
*
|
||||
* @property SourceArtAdditions added The bridge's delta, pixels, and notes.
|
||||
* @property PuppetModel model The base with the additions appended and packed.
|
||||
* @property PuppetTextures textures The pages the pack composed, index-parallel to the model's.
|
||||
* @property List notices The bridge's notes plus every added tile the pack left unplaced.
|
||||
*/
|
||||
class Added(
|
||||
val added: SourceArtAdditions,
|
||||
val model: PuppetModel,
|
||||
val textures: PuppetTextures,
|
||||
val notices: List<SourceArtImportNotice>,
|
||||
) : AddArtworkOutcome
|
||||
}
|
||||
|
||||
/**
|
||||
* The strip's rows for an add-artwork operation: Align and Offset X / Z for a file placed within the
|
||||
* rig's canvas, then Alpha Threshold and Birth Mesh Margin. A rig's first artwork sets the canvas
|
||||
* rather than landing within it, so its step carries no placement rows.
|
||||
*
|
||||
* The Offset rows are in the viewport's world axes (X right, Z up, like the transform rows' Move Z),
|
||||
* the same axes the options' nudge and the record's offset use, so a positive Offset Z moves the art
|
||||
* up on screen; the placement negates z into canvas y where the canvas math is.
|
||||
*
|
||||
* @param SourceArtImportOptions options The options the rows show.
|
||||
* @param Boolean placed Whether the file was placed within an existing canvas.
|
||||
* @return List The rows.
|
||||
*/
|
||||
internal fun addArtworkParameters(options: SourceArtImportOptions, placed: Boolean): List<OperatorParameter> {
|
||||
val rows = ArrayList<OperatorParameter>()
|
||||
if (placed) {
|
||||
rows.add(
|
||||
OperatorParameter.ChoiceParameter(
|
||||
ImportParameterKeys.ALIGN,
|
||||
ImportParameterKeys.ALIGN,
|
||||
options.anchor.key,
|
||||
ArtworkAnchor.entries.map { anchor -> ParameterChoice(anchor.key, ImportParameterKeys.ANCHOR_CHOICE_PREFIX + anchor.key) },
|
||||
),
|
||||
)
|
||||
rows.add(OperatorParameter.IntParameter(ImportParameterKeys.OFFSET_X, ImportParameterKeys.OFFSET_X, options.nudgeX, -IMPORT_MAX_OFFSET, IMPORT_MAX_OFFSET, unit = ParameterUnit.Pixels))
|
||||
rows.add(OperatorParameter.IntParameter(ImportParameterKeys.OFFSET_Z, ImportParameterKeys.OFFSET_Z, options.nudgeZ, -IMPORT_MAX_OFFSET, IMPORT_MAX_OFFSET, unit = ParameterUnit.Pixels))
|
||||
}
|
||||
rows.add(OperatorParameter.IntParameter(ImportParameterKeys.ALPHA_THRESHOLD, ImportParameterKeys.ALPHA_THRESHOLD, options.alphaThreshold, 1, 255))
|
||||
rows.add(OperatorParameter.IntParameter(ImportParameterKeys.MARGIN, ImportParameterKeys.MARGIN, options.birthMeshMargin, 0, IMPORT_MAX_MARGIN, unit = ParameterUnit.Pixels))
|
||||
return rows
|
||||
}
|
||||
|
||||
/**
|
||||
* The options [parameters] describe, over [fallback] for the seed parameters the rows do not carry
|
||||
* (and for the placement, when the step had no placement rows).
|
||||
*
|
||||
* @param List parameters The strip's rows.
|
||||
* @param SourceArtImportOptions fallback The options the first run used.
|
||||
* @return SourceArtImportOptions The adjusted options.
|
||||
*/
|
||||
internal fun addArtworkOptionsOf(parameters: List<OperatorParameter>, fallback: SourceArtImportOptions): SourceArtImportOptions =
|
||||
SourceArtImportOptions(
|
||||
parameters = fallback.parameters,
|
||||
alphaThreshold = parameters.intValue(ImportParameterKeys.ALPHA_THRESHOLD, fallback.alphaThreshold).coerceIn(1, 255),
|
||||
birthMeshMargin = parameters.intValue(ImportParameterKeys.MARGIN, fallback.birthMeshMargin).coerceIn(0, IMPORT_MAX_MARGIN),
|
||||
anchor = ArtworkAnchor.fromKey(parameters.choiceValue(ImportParameterKeys.ALIGN, fallback.anchor.key)),
|
||||
nudgeX = parameters.intValue(ImportParameterKeys.OFFSET_X, fallback.nudgeX).coerceIn(-IMPORT_MAX_OFFSET, IMPORT_MAX_OFFSET),
|
||||
nudgeZ = parameters.intValue(ImportParameterKeys.OFFSET_Z, fallback.nudgeZ).coerceIn(-IMPORT_MAX_OFFSET, IMPORT_MAX_OFFSET),
|
||||
)
|
||||
|
||||
/**
|
||||
* Appends [request]'s art to [base] and packs the new tiles into the gaps: every tile already on a
|
||||
* page is handed to the packer fixed (pinned or not), the additions pack around them at the
|
||||
* document's own page size (once more at [MAX_IMPORT_PAGE_SIZE] if a layer does not fit), and the
|
||||
* result re-derives through [withAtlasRepack] under the document's current composition so the pages
|
||||
* the existing art sits on compose exactly as they did. A new tile the pack cannot carry stays
|
||||
* unplaced and is a note; the source-layer display still draws it.
|
||||
*
|
||||
* A file joining a rig that already has art is first placed on the rig's canvas by the options'
|
||||
* anchor and nudge ([SourceArtImport.offsetFor]), and its record keeps that offset so every later
|
||||
* read of the file lands the same way. The request's own art stays unplaced: an adjustment places
|
||||
* it again from its rows.
|
||||
*
|
||||
* The new rasters are added to [artRasters] here, before the pack reads them; the store is
|
||||
* document-lifetime, so an adjustment finds them already present. The pack itself is
|
||||
* [packNewTilesAround], shared with the reload, relink, and match flows.
|
||||
*
|
||||
* @param PuppetModel base The model the additions join.
|
||||
* @param AddArtworkRequest request The file.
|
||||
* @param SourceArtImportOptions options The placement, threshold, and margin to import with.
|
||||
* @param SourceArtRasters artRasters The document's raster store.
|
||||
* @param Boolean premultipliedAlpha The document's texture-convention flag.
|
||||
* @return AddArtworkOutcome? The outcome, or null when the file has no layer with art to add.
|
||||
*/
|
||||
private fun addArtworkOutcome(
|
||||
base: PuppetModel,
|
||||
request: AddArtworkRequest,
|
||||
options: SourceArtImportOptions,
|
||||
artRasters: SourceArtRasters,
|
||||
premultipliedAlpha: Boolean,
|
||||
): AddArtworkOutcome {
|
||||
val offset = SourceArtImport.offsetFor(base, request.art, options)
|
||||
val added = SourceArtImport.additionsFor(request.art.placedBy(offset), request.descriptor, options, base, offset = offset)
|
||||
if (added.additions.drawables.isEmpty()) {
|
||||
return AddArtworkOutcome.NothingToAdd
|
||||
}
|
||||
val withArt = base.withArtworkAdded(added.additions)
|
||||
if (withArt === base) {
|
||||
UmamoLog.error("add artwork: the additions for '${request.descriptor.name}' collide with the document's ids; nothing was applied")
|
||||
return AddArtworkOutcome.NothingToAdd
|
||||
}
|
||||
// A rig with no art of its own takes its frame from the file that arrives - the new document starts
|
||||
// on a placeholder canvas, and the first artwork is what says how big the rig really is. A rig that
|
||||
// already has art keeps its canvas: a second file is placed within that frame, not around it.
|
||||
val framed = if (SourceArtImport.isFirstArtwork(base)) SourceArtImport.withFirstArtworkState(withArt, request.art) else withArt
|
||||
// The parameter template seeds a rig that has none, which is what makes importing art into a new
|
||||
// document behave like opening that art did. Authored axes are never replaced.
|
||||
val seeded = if (framed.parameters.isEmpty()) SourceArtImport.withSeedParameters(framed, options.parameters) else framed
|
||||
val decodedByTile = added.rasterByTile.mapValues { (_, raster) -> request.decodedFor(raster) }
|
||||
artRasters.addDecoded(decodedByTile)
|
||||
val decode: (AtlasTileId) -> DecodedImage? = { tileId -> decodedByTile[tileId] ?: artRasters.decodeRaster(tileId) }
|
||||
return when (val packed = packNewTilesAround(seeded, added.additions.tiles.mapTo(HashSet()) { tile -> tile.id }, decode, premultipliedAlpha, added.notices)) {
|
||||
is PackAroundOutcome.Refused -> AddArtworkOutcome.Refused(packed.refusals)
|
||||
is PackAroundOutcome.Packed -> AddArtworkOutcome.Added(added, packed.model, packed.textures, packed.notices)
|
||||
}
|
||||
}
|
||||
|
||||
/** What packing new tiles around the document's art produced, or why nothing was applied. */
|
||||
internal sealed interface PackAroundOutcome {
|
||||
/**
|
||||
* The pack could not keep some of the document's OWN art where it is - a placed tile the packer
|
||||
* would not hold fixed - so nothing was applied; the refusals name the tiles.
|
||||
*
|
||||
* @property List refusals The document's tiles the pack could not keep.
|
||||
*/
|
||||
class Refused(val refusals: List<AtlasRepackRefusal>) : PackAroundOutcome
|
||||
|
||||
/**
|
||||
* The new tiles packed and the model re-derived over the pages.
|
||||
*
|
||||
* @property PuppetModel model The model with the pack applied.
|
||||
* @property PuppetTextures textures The pages the pack composed, index-parallel to the model's.
|
||||
* @property List notices The caller's notes plus every new tile the pack left unplaced.
|
||||
*/
|
||||
class Packed(
|
||||
val model: PuppetModel,
|
||||
val textures: PuppetTextures,
|
||||
val notices: List<SourceArtImportNotice>,
|
||||
) : PackAroundOutcome
|
||||
}
|
||||
|
||||
/**
|
||||
* Packs the tiles [model] gained into the gaps around the art already on its pages: every tile with a
|
||||
* placement is handed to the packer fixed (pinned or not), the new tiles pack around them at the
|
||||
* document's own page size (once more at [MAX_IMPORT_PAGE_SIZE] if one does not fit), and the result
|
||||
* re-derives through [withAtlasRepack] under the document's current composition so the pages the
|
||||
* existing art sits on compose exactly as they did. Shared by Add Artwork, Reload, relink, Match
|
||||
* Automatically, and Replace Artwork, which differ only in how the new tiles came to be.
|
||||
*
|
||||
* A refusal over the document's OWN art refuses the whole pack: the lowering would pack that tile
|
||||
* out, and the document's art must not move for tiles being added. A refusal over a NEW tile is a
|
||||
* note - it stays unplaced and the source-layer display still draws it.
|
||||
*
|
||||
* @param PuppetModel model The model carrying the new, unplaced tiles.
|
||||
* @param Set newTileIds Which tiles are the new ones.
|
||||
* @param Function decode The pixels of any tile, the new ones included.
|
||||
* @param Boolean premultipliedAlpha The document's texture-convention flag.
|
||||
* @param List notices The notes gathered so far, carried through.
|
||||
* @return PackAroundOutcome The packed model and pages, or the refusal.
|
||||
*/
|
||||
internal fun packNewTilesAround(
|
||||
model: PuppetModel,
|
||||
newTileIds: Set<AtlasTileId>,
|
||||
decode: (AtlasTileId) -> DecodedImage?,
|
||||
premultipliedAlpha: Boolean,
|
||||
notices: List<SourceArtImportNotice>,
|
||||
): PackAroundOutcome {
|
||||
// The document's composition governs the pack, so the fixed tiles compose as they already do; the
|
||||
// gutter grows to hold the extrusion when a repack widened it past the default.
|
||||
val composition = model.atlas.composition
|
||||
val defaults = AtlasPackOptions()
|
||||
var packOptions =
|
||||
AtlasPackOptions(
|
||||
maxPageSize = repackPageSizeOf(model),
|
||||
gutter = maxOf(defaults.gutter, composition.extrude),
|
||||
extrude = composition.extrude,
|
||||
alphaThreshold = composition.alphaThreshold,
|
||||
)
|
||||
var packed = packAtlasOf(model, decode, packOptions, keepPinned = true, fixPlaced = true)
|
||||
if (packOptions.maxPageSize < MAX_IMPORT_PAGE_SIZE && packed.result.skipped.any { skip -> skip.reason == AtlasPackSkipReason.LargerThanPage }) {
|
||||
packOptions = packOptions.copy(maxPageSize = MAX_IMPORT_PAGE_SIZE)
|
||||
packed = PackedAtlas(packed.input, packAtlas(packed.input.itemsFor(keepPinned = true, fixPlaced = true), packOptions))
|
||||
}
|
||||
val newTileNames = model.atlas.tiles.filter { tile -> tile.id in newTileIds }.mapTo(HashSet()) { tile -> tile.name }
|
||||
val refusals = repackRefusals(model, packed.result.skipped, packed.input.undecodableTileIds)
|
||||
val skippedKeys = packed.result.skipped.mapTo(HashSet()) { skip -> skip.key }
|
||||
val existingRefusals =
|
||||
refusals.filter { refusal ->
|
||||
model.atlas.tiles.any { tile -> tile.name == refusal.tileName && tile.id !in newTileIds && (tile.id.raw in skippedKeys || tile.id in packed.input.undecodableTileIds) }
|
||||
}
|
||||
if (existingRefusals.isNotEmpty()) {
|
||||
return PackAroundOutcome.Refused(existingRefusals)
|
||||
}
|
||||
val allNotices = ArrayList(notices)
|
||||
for (refusal in refusals) {
|
||||
if (refusal.tileName !in newTileNames) {
|
||||
continue
|
||||
}
|
||||
allNotices.add(
|
||||
when (refusal.reason) {
|
||||
AtlasRepackRefusalReason.LargerThanPage -> SourceArtImportNotice.LayerLargerThanPage(refusal.tileName)
|
||||
else -> SourceArtImportNotice.LayerNotPacked(refusal.tileName, refusal.reason.name)
|
||||
},
|
||||
)
|
||||
}
|
||||
val lowered = lowerPack(model.atlas, packed.result)
|
||||
val repacked = model.withAtlasRepack(lowered.pages, lowered.placementsByTile, composition)
|
||||
logPack(packed.result, lowered, packOptions)
|
||||
return PackAroundOutcome.Packed(repacked, generatedPuppetTextures(packed.result.pages, repacked, premultipliedAlpha), allNotices)
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an artwork file to the open document as ONE undo step, packed beside the art already there,
|
||||
* and registers the step on the operation settings strip (Alpha Threshold, Birth Mesh Margin).
|
||||
*
|
||||
* Runs on the UI thread; the bridge and the pack hop to the default dispatcher. The additions are
|
||||
* minted against the model current at the start, so ANY edit landing while they were built
|
||||
* supersedes them - stricter than the repack, whose pack only depends on the atlas and the reaches.
|
||||
*
|
||||
* @param AtlasRepackHost host The session, art, resolver, scope, and shell callbacks.
|
||||
* @param AddArtworkRequest request The file to add.
|
||||
* @param String? areaId The area the command was dispatched over, or null - where the strip shows.
|
||||
* @return Boolean Whether the artwork was added.
|
||||
*/
|
||||
suspend fun runAddArtwork(host: AtlasRepackHost, request: AddArtworkRequest, areaId: String?): Boolean {
|
||||
val session = host.session
|
||||
val modelAtStart = session.model.value
|
||||
val outcome =
|
||||
withContext(Dispatchers.Default) {
|
||||
addArtworkOutcome(modelAtStart, request, request.options, host.artRasters, host.premultipliedAlpha)
|
||||
}
|
||||
when (outcome) {
|
||||
AddArtworkOutcome.NothingToAdd -> {
|
||||
UmamoLog.warn("add artwork: '${request.descriptor.name}' has no layer with pixels to add; nothing was applied")
|
||||
session.emitNotice("notice.import.noArtLayers", NoticePlacement.StatusBar)
|
||||
return false
|
||||
}
|
||||
is AddArtworkOutcome.Refused -> {
|
||||
for (refusal in outcome.refusals) {
|
||||
UmamoLog.warn("add artwork: the document's tile '${refusal.tileName}' could not be kept in place (${refusal.reason}); nothing was applied")
|
||||
}
|
||||
host.report(AtlasRepackReport(outcome.refusals))
|
||||
return false
|
||||
}
|
||||
is AddArtworkOutcome.Added -> Unit
|
||||
}
|
||||
if (session.model.value !== modelAtStart) {
|
||||
UmamoLog.warn("add artwork: the document changed while '${request.descriptor.name}' was being added; nothing was applied")
|
||||
session.emitNotice("notice.import.artworkSuperseded", NoticePlacement.StatusBar)
|
||||
return false
|
||||
}
|
||||
val drawableCount = outcome.added.additions.drawables.size
|
||||
val committed = session.commitArtworkAdded(request.descriptor.name, drawableCount, outcome.model)
|
||||
host.sessionAtlasPages?.prewarm(committed.atlas, outcome.textures)
|
||||
reportAddArtwork(request, outcome, committed)
|
||||
session.emitNotice(if (outcome.notices.isEmpty()) "notice.import.artworkAdded" else "notice.import.artworkNotes", NoticePlacement.StatusBar)
|
||||
session.registerAdjustableOperation(committed, areaId, addArtworkParameters(request.options, placed = !SourceArtImport.isFirstArtwork(modelAtStart))) { record ->
|
||||
host.scope.launch { adjustAddArtwork(host, record, request) }
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-derives the additions for an adjustment of the strip: the record's rows become the options, the
|
||||
* SAME parsed art is imported again over the record's base model, packed, and landed over the
|
||||
* operation's own step. A record cleared while the pass ran makes [org.umamo.edit.EditorSession.amendLastCommit]
|
||||
* drop the result rather than commit over what the rigger did since.
|
||||
*
|
||||
* @param AtlasRepackHost host The session, resolver, and shell callbacks the first run had.
|
||||
* @param AdjustableOperation record The record with the adjusted parameters.
|
||||
* @param AddArtworkRequest request The first run's file.
|
||||
*/
|
||||
internal suspend fun adjustAddArtwork(host: AtlasRepackHost, record: AdjustableOperation, request: AddArtworkRequest) {
|
||||
val base = record.baseSnapshot.model
|
||||
val options = addArtworkOptionsOf(record.parameters, request.options)
|
||||
val outcome =
|
||||
withContext(Dispatchers.Default) {
|
||||
addArtworkOutcome(base, request, options, host.artRasters, host.premultipliedAlpha)
|
||||
}
|
||||
when (outcome) {
|
||||
AddArtworkOutcome.NothingToAdd -> {
|
||||
UmamoLog.warn("add artwork: under the adjusted options '${request.descriptor.name}' has nothing to add; the previous result stands")
|
||||
return
|
||||
}
|
||||
is AddArtworkOutcome.Refused -> {
|
||||
host.report(AtlasRepackReport(outcome.refusals))
|
||||
return
|
||||
}
|
||||
is AddArtworkOutcome.Added -> Unit
|
||||
}
|
||||
host.sessionAtlasPages?.prewarm(outcome.model.atlas, outcome.textures)
|
||||
if (!host.session.amendLastCommit(record, outcome.model)) {
|
||||
UmamoLog.info("add artwork: the adjustment was superseded before it landed; nothing was applied")
|
||||
return
|
||||
}
|
||||
reportAddArtwork(request, outcome, outcome.model)
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs one add-artwork pass the way the first run and an adjustment both report it.
|
||||
*
|
||||
* @param AddArtworkRequest request The file.
|
||||
* @param AddArtworkOutcome outcome What the pass produced.
|
||||
* @param PuppetModel committed The model that landed.
|
||||
*/
|
||||
private fun reportAddArtwork(request: AddArtworkRequest, outcome: AddArtworkOutcome.Added, committed: PuppetModel) {
|
||||
for (notice in outcome.notices) {
|
||||
UmamoLog.warn("add artwork: ${describeImportNotice(notice)}")
|
||||
}
|
||||
val additions = outcome.added.additions
|
||||
UmamoLog.info(
|
||||
"add artwork: ${request.descriptor.name} -> ${additions.drawables.size} drawable(s), ${additions.parts.size} part(s)," +
|
||||
" now ${committed.atlas.pages.size} page(s); ${outcome.notices.size} note(s)",
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* One import notice as a log line: plain English naming the layer and what happened to it, the same
|
||||
* shape the export notices log in. Shared by the open (an artwork-origin document) and the add.
|
||||
*
|
||||
* @param SourceArtImportNotice notice The notice.
|
||||
* @return String The log text.
|
||||
*/
|
||||
fun describeImportNotice(notice: SourceArtImportNotice): String =
|
||||
when (notice) {
|
||||
is SourceArtImportNotice.NonRasterLayer -> "layer '${notice.layerName}' is a ${notice.kind.name.lowercase()} layer with no pixels; skipped"
|
||||
is SourceArtImportNotice.EmptyLayer -> "layer '${notice.layerName}' has no opaque pixels; skipped"
|
||||
is SourceArtImportNotice.BlendUnsupported -> "layer '${notice.layerName}' blends with ${notice.blend.name}, which has no equivalent; imported as Normal"
|
||||
is SourceArtImportNotice.BlendApproximated -> "layer '${notice.layerName}' blends with ${notice.blend.name}; imported as the nearest mode, ${notice.mappedTo.name}"
|
||||
is SourceArtImportNotice.ClipBaseMissing -> "layer '${notice.layerName}' clips to the layer below but has none in its folder; imported unclipped"
|
||||
is SourceArtImportNotice.ChannelMaskDropped -> "layer '${notice.layerName}' writes only some color channels; imported writing all of them"
|
||||
is SourceArtImportNotice.FolderBlendUnsupported -> "folder '${notice.groupPath}' blends with ${notice.blend.name}, which has no equivalent; its part composites as Normal"
|
||||
is SourceArtImportNotice.FolderClipDropped -> "folder '${notice.groupPath}' clips to the layer below; its part imports unclipped"
|
||||
is SourceArtImportNotice.LayerLargerThanPage -> "layer '${notice.layerName}' is larger than the largest atlas page; left unpacked"
|
||||
is SourceArtImportNotice.LayerNotPacked -> "layer '${notice.layerName}' could not be packed (${notice.reason}); left unpacked"
|
||||
}
|
||||
@@ -0,0 +1,560 @@
|
||||
package org.umamo.ui.model
|
||||
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.umamo.edit.AdjustableOperation
|
||||
import org.umamo.edit.EditorSession
|
||||
import org.umamo.edit.NoticePlacement
|
||||
import org.umamo.edit.commitAtlasRepack
|
||||
import org.umamo.edit.withAtlasRepack
|
||||
import org.umamo.format.atlas.AtlasPackFixed
|
||||
import org.umamo.format.atlas.AtlasPackItem
|
||||
import org.umamo.format.atlas.AtlasPackOptions
|
||||
import org.umamo.format.atlas.AtlasPackReserve
|
||||
import org.umamo.format.atlas.AtlasPackResult
|
||||
import org.umamo.format.atlas.AtlasPackSkip
|
||||
import org.umamo.format.atlas.AtlasPackSkipReason
|
||||
import org.umamo.format.atlas.packAtlas
|
||||
import org.umamo.render.DecodedImage
|
||||
import org.umamo.render.PuppetTextures
|
||||
import org.umamo.render.SourceArtRasters
|
||||
import org.umamo.render.atlasCompositionOf
|
||||
import org.umamo.render.atlasPlacementFromPack
|
||||
import org.umamo.render.generatedPuppetTextures
|
||||
import org.umamo.render.meshReserveByTile
|
||||
import org.umamo.runtime.model.AtlasPage
|
||||
import org.umamo.runtime.model.AtlasPlacement
|
||||
import org.umamo.runtime.model.AtlasTileId
|
||||
import org.umamo.runtime.model.PuppetAtlas
|
||||
import org.umamo.runtime.model.PuppetModel
|
||||
import org.umamo.runtime.model.invertUvAffine
|
||||
import org.umamo.runtime.model.placementAffine
|
||||
import org.umamo.runtime.model.storedToArtAffineForTile
|
||||
import org.umamo.storage.UmamoLog
|
||||
|
||||
/** The maximum page size a repack packs against when the document has no pages to take one from. */
|
||||
const val DEFAULT_REPACK_PAGE_SIZE: Int = 4096
|
||||
|
||||
/**
|
||||
* The page size an artwork import retries at when a layer's trimmed art does not fit the default page
|
||||
* - the largest page the official editor's own atlas settings offer, and what desktop GL 3.3 and GLES
|
||||
* 3.0 both guarantee. Art that does not fit even this stays unpacked and is named in the import notes.
|
||||
*/
|
||||
const val MAX_IMPORT_PAGE_SIZE: Int = 8192
|
||||
|
||||
/** Why one tile kept the whole repack from running. */
|
||||
enum class AtlasRepackRefusalReason {
|
||||
/** The tile's trimmed art plus its gutter does not fit a page even alone. */
|
||||
LargerThanPage,
|
||||
|
||||
/** Nothing in the tile's art meets the alpha threshold, so the pack has nothing to place. */
|
||||
NoOpaquePixels,
|
||||
|
||||
/** The tile's art has opaque pixels but fewer than the pack's configured minimum. */
|
||||
BelowMinimumCoverage,
|
||||
|
||||
/** The tile's art would not decode, or decodes to a size that disagrees with the tile. */
|
||||
Undecodable,
|
||||
|
||||
/** The tile's current placement has no invertible mapping, so its coordinates cannot follow. */
|
||||
DegeneratePlacement,
|
||||
|
||||
/** The tile is pinned at a spot that does not fit inside the maximum page size, so it cannot be kept. */
|
||||
PinnedOffPage,
|
||||
}
|
||||
|
||||
/**
|
||||
* One tile the repack refused over.
|
||||
*
|
||||
* @property String tileName The tile's display name - document data, shown verbatim.
|
||||
* @property AtlasRepackRefusalReason reason Why it could not come along.
|
||||
*/
|
||||
class AtlasRepackRefusal(
|
||||
val tileName: String,
|
||||
val reason: AtlasRepackRefusalReason,
|
||||
)
|
||||
|
||||
/**
|
||||
* The repack abort report: every BOUND tile the pack could not carry. A repack is all or nothing -
|
||||
* a tile with drawables that came out of the pack unplaced would leave those drawables without a
|
||||
* page, so one refusal aborts the whole operation and this names each one.
|
||||
*
|
||||
* @property List refusals The refused tiles, in document tile order.
|
||||
*/
|
||||
class AtlasRepackReport(
|
||||
val refusals: List<AtlasRepackRefusal>,
|
||||
)
|
||||
|
||||
/**
|
||||
* What one repack feeds the packer.
|
||||
*
|
||||
* The items are every tile as a FREE item; the placed tiles' placements sit beside them in the
|
||||
* packer's fixed form so one decoded input serves a pack that keeps the pins, a pack that ignores
|
||||
* them, and a pack that holds EVERY placed tile still (art added to an open document packs into the
|
||||
* gaps) - the strip's Keep Pinned Tiles row flips between the first two without re-decoding.
|
||||
*
|
||||
* @property List items The tiles' pixels plus their mesh reserves, all free.
|
||||
* @property Map fixedByKey The pinned placed tiles' placements as the packer's fixed form, by key.
|
||||
* @property Map placedByKey EVERY placed tile's placement as the packer's fixed form, by key.
|
||||
* @property Set undecodableTileIds Tiles whose art would not decode or disagrees with its tile.
|
||||
* @property Map reserveByTile The mesh reserves the items were built with, kept so the commit
|
||||
* can tell whether a mesh edit during the pack staled them.
|
||||
*/
|
||||
internal class RepackPackInput(
|
||||
val items: List<AtlasPackItem>,
|
||||
val fixedByKey: Map<String, AtlasPackFixed>,
|
||||
val placedByKey: Map<String, AtlasPackFixed>,
|
||||
val undecodableTileIds: Set<AtlasTileId>,
|
||||
val reserveByTile: Map<AtlasTileId, AtlasPackReserve>,
|
||||
) {
|
||||
/**
|
||||
* The items to pack: every placed tile fixed where it is when [fixPlaced], else the pinned tiles
|
||||
* fixed when [keepPinned], else every tile free. Items hold their pixels by reference, so the
|
||||
* fixed copies cost nothing.
|
||||
*
|
||||
* @param Boolean keepPinned Whether the pinned tiles stay put.
|
||||
* @param Boolean fixPlaced Whether every placed tile stays put, pinned or not.
|
||||
* @return List The pack items.
|
||||
*/
|
||||
fun itemsFor(keepPinned: Boolean, fixPlaced: Boolean = false): List<AtlasPackItem> {
|
||||
val fixedForms =
|
||||
when {
|
||||
fixPlaced -> placedByKey
|
||||
keepPinned -> fixedByKey
|
||||
else -> emptyMap()
|
||||
}
|
||||
if (fixedForms.isEmpty()) {
|
||||
return items
|
||||
}
|
||||
return items.map { item ->
|
||||
val fixed = fixedForms[item.key] ?: return@map item
|
||||
AtlasPackItem(item.key, item.width, item.height, item.rgba, item.reserve, fixed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the pack input for [model]: every tile that is used OR already packed, with its pixels and
|
||||
* its mesh reserve.
|
||||
*
|
||||
* A placed tile nobody samples keeps its spot on the pages (the file's own image entries describe it
|
||||
* there), while never-packed unbound art stays out. One function shared by the live repack and the
|
||||
* corpus gate, so what the gate proves disjoint is exactly what the command packs.
|
||||
*
|
||||
* Thread-safe given a thread-safe [decodeRaster]; the live flow runs it on the default dispatcher.
|
||||
*
|
||||
* @param PuppetModel model The model to pack.
|
||||
* @param Function decodeRaster Yields a tile's decoded pixels, or null.
|
||||
* @return RepackPackInput The pack items and the tiles that would not decode.
|
||||
*/
|
||||
internal fun buildRepackPackInput(
|
||||
model: PuppetModel,
|
||||
decodeRaster: (AtlasTileId) -> DecodedImage?,
|
||||
): RepackPackInput {
|
||||
val boundTileIds = model.drawables.mapNotNullTo(HashSet()) { drawable -> drawable.atlasTileId }
|
||||
val reserveByTile = meshReserveByTile(model)
|
||||
val items = ArrayList<AtlasPackItem>()
|
||||
val fixedByKey = HashMap<String, AtlasPackFixed>()
|
||||
val placedByKey = HashMap<String, AtlasPackFixed>()
|
||||
val undecodable = HashSet<AtlasTileId>()
|
||||
for (tile in model.atlas.tiles) {
|
||||
if (tile.id !in boundTileIds && tile.placement == null) {
|
||||
continue
|
||||
}
|
||||
val raster = decodeRaster(tile.id)
|
||||
if (raster == null || raster.width != tile.width || raster.height != tile.height) {
|
||||
undecodable.add(tile.id)
|
||||
} else {
|
||||
items.add(AtlasPackItem(tile.id.raw, raster.width, raster.height, raster.rgba, reserveByTile[tile.id]))
|
||||
val placement = tile.placement
|
||||
if (placement != null) {
|
||||
val fixed = AtlasPackFixed(placement.pageIndex, placementAffine(placement))
|
||||
placedByKey[tile.id.raw] = fixed
|
||||
if (tile.pinned) {
|
||||
fixedByKey[tile.id.raw] = fixed
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return RepackPackInput(items, fixedByKey, placedByKey, undecodable, reserveByTile)
|
||||
}
|
||||
|
||||
/**
|
||||
* The refusals a pack outcome implies for [model]: bound tiles the packer skipped, bound tiles whose
|
||||
* art would not decode, and bound tiles whose CURRENT placement has no invertible mapping (the UV
|
||||
* re-derivation reads through it, so a degenerate one strands the coordinates). Unbound tiles never
|
||||
* refuse - with no drawables over them there is nothing to strand.
|
||||
*
|
||||
* @param PuppetModel model The model the repack would apply to.
|
||||
* @param List packSkips What the packer left out, keyed by tile id.
|
||||
* @param Set undecodableTileIds Bound tiles whose art would not decode.
|
||||
* @return List The refusals, empty when the repack may proceed.
|
||||
*/
|
||||
internal fun repackRefusals(
|
||||
model: PuppetModel,
|
||||
packSkips: List<AtlasPackSkip>,
|
||||
undecodableTileIds: Set<AtlasTileId>,
|
||||
): List<AtlasRepackRefusal> {
|
||||
val boundTileIds = model.drawables.mapNotNullTo(HashSet()) { drawable -> drawable.atlasTileId }
|
||||
val skipReasonByTileId = packSkips.associateBy({ skip -> AtlasTileId(skip.key) }, { skip -> skip.reason })
|
||||
val refusals = ArrayList<AtlasRepackRefusal>()
|
||||
for (tile in model.atlas.tiles) {
|
||||
if (tile.id !in boundTileIds) {
|
||||
continue
|
||||
}
|
||||
if (tile.id in undecodableTileIds) {
|
||||
refusals.add(AtlasRepackRefusal(tile.name, AtlasRepackRefusalReason.Undecodable))
|
||||
continue
|
||||
}
|
||||
val skipReason = skipReasonByTileId[tile.id]
|
||||
if (skipReason != null) {
|
||||
val reason =
|
||||
when (skipReason) {
|
||||
AtlasPackSkipReason.LargerThanPage -> AtlasRepackRefusalReason.LargerThanPage
|
||||
AtlasPackSkipReason.NoOpaquePixels -> AtlasRepackRefusalReason.NoOpaquePixels
|
||||
AtlasPackSkipReason.BelowMinimumCoverage -> AtlasRepackRefusalReason.BelowMinimumCoverage
|
||||
AtlasPackSkipReason.FixedOutsidePage -> AtlasRepackRefusalReason.PinnedOffPage
|
||||
}
|
||||
refusals.add(AtlasRepackRefusal(tile.name, reason))
|
||||
continue
|
||||
}
|
||||
if (tile.placement != null) {
|
||||
// The same mapping the re-derivation reads: the placement plus the page it names. A page
|
||||
// the model does not have counts as degenerate too - the mapping cannot be formed at all.
|
||||
val storedToArt = model.atlas.storedToArtAffineForTile(tile.id)
|
||||
if (storedToArt == null || invertUvAffine(storedToArt) == null) {
|
||||
refusals.add(AtlasRepackRefusal(tile.name, AtlasRepackRefusalReason.DegeneratePlacement))
|
||||
}
|
||||
}
|
||||
}
|
||||
return refusals
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything a repack needs from the shell besides its options: the session to commit into, the art
|
||||
* to pack, the page resolver to pre-warm, the texture convention, the scope an adjustment re-runs on,
|
||||
* and the two shell callbacks - the refusal report and the sticky-options record. Built once per
|
||||
* document by the shell and handed to [runAtlasRepack]; the adjustment closure keeps it.
|
||||
*
|
||||
* @property EditorSession session The session to commit into.
|
||||
* @property SourceArtRasters artRasters The source-art pixels to pack.
|
||||
* @property SessionAtlasPages? sessionAtlasPages The session's page resolver, pre-warmed on success.
|
||||
* @property Boolean premultipliedAlpha The document's texture-convention flag, carried onto the new set.
|
||||
* @property CoroutineScope scope Where an adjustment's re-pack launches (the shell's scope).
|
||||
* @property Function report Receives the abort report when a pack refuses.
|
||||
* @property Function rememberOptions Receives the options and the keep-pinned choice every
|
||||
* successful pack ran with.
|
||||
*/
|
||||
class AtlasRepackHost(
|
||||
val session: EditorSession,
|
||||
val artRasters: SourceArtRasters,
|
||||
val sessionAtlasPages: SessionAtlasPages?,
|
||||
val premultipliedAlpha: Boolean,
|
||||
val scope: CoroutineScope,
|
||||
val report: (AtlasRepackReport) -> Unit,
|
||||
val rememberOptions: (AtlasPackOptions, Boolean) -> Unit,
|
||||
)
|
||||
|
||||
/**
|
||||
* The maximum page size [model]'s repack packs against by default: its largest page's side, or
|
||||
* [DEFAULT_REPACK_PAGE_SIZE] when it has none.
|
||||
*
|
||||
* @param PuppetModel model The document.
|
||||
* @return Int The page size in pixels.
|
||||
*/
|
||||
fun repackPageSizeOf(model: PuppetModel): Int = model.atlas.pages.maxOfOrNull { page -> maxOf(page.width, page.height) } ?: DEFAULT_REPACK_PAGE_SIZE
|
||||
|
||||
/**
|
||||
* One pack before anything is committed: the decoded input and what the packer made of it. Shared
|
||||
* by the repack command, the pack an artwork import runs at open, and the pack-around that lands new
|
||||
* tiles in an open document, so all of them pack the same way.
|
||||
*
|
||||
* @property RepackPackInput input The decoded tiles and their reserves.
|
||||
* @property AtlasPackResult result The packer's placements, pages, and skips.
|
||||
*/
|
||||
internal class PackedAtlas(
|
||||
val input: RepackPackInput,
|
||||
val result: AtlasPackResult,
|
||||
)
|
||||
|
||||
/**
|
||||
* Decodes and packs [model]'s atlas under [options]. Pure and thread-agnostic given a thread-safe
|
||||
* [decodeRaster]: the repack command and the artwork flows run it on the default dispatcher, the
|
||||
* import at open runs it inline.
|
||||
*
|
||||
* @param PuppetModel model The model to pack.
|
||||
* @param Function decodeRaster Yields a tile's decoded pixels, or null.
|
||||
* @param AtlasPackOptions options The packing policy.
|
||||
* @param Boolean keepPinned Whether pinned tiles stay where they are.
|
||||
* @param Boolean fixPlaced Whether every placed tile stays where it is (added art packs
|
||||
* into the gaps).
|
||||
* @return PackedAtlas The input and the result, not yet lowered or committed.
|
||||
*/
|
||||
internal fun packAtlasOf(
|
||||
model: PuppetModel,
|
||||
decodeRaster: (AtlasTileId) -> DecodedImage?,
|
||||
options: AtlasPackOptions,
|
||||
keepPinned: Boolean = true,
|
||||
fixPlaced: Boolean = false,
|
||||
): PackedAtlas {
|
||||
val input = buildRepackPackInput(model, decodeRaster)
|
||||
return PackedAtlas(input, packAtlas(input.itemsFor(keepPinned, fixPlaced), options))
|
||||
}
|
||||
|
||||
/**
|
||||
* What one pack produced for the model: the new pages and every tile's lowered placement.
|
||||
*
|
||||
* @property List pages The new page inventory.
|
||||
* @property Map placementsByTile Every tile's new placement, null for one packed out.
|
||||
* @property Int packedOutCount Placed-but-unbound tiles the pack could not carry, now unpacked.
|
||||
*/
|
||||
internal class LoweredPack(
|
||||
val pages: List<AtlasPage>,
|
||||
val placementsByTile: Map<AtlasTileId, AtlasPlacement?>,
|
||||
val packedOutCount: Int,
|
||||
)
|
||||
|
||||
/**
|
||||
* Lowers a pack result onto [atlas]'s tiles: every packed tile gets its placement, every tile the
|
||||
* pack kept fixed restates the placement it already has, and every other tile is restated unpacked.
|
||||
* A placed-but-unbound tile the pack could not carry (empty, oversized, undecodable) leaves the
|
||||
* pages rather than blocking the repack over art nothing samples; each is logged and counted.
|
||||
*
|
||||
* @param PuppetAtlas atlas The atlas being repacked.
|
||||
* @param AtlasPackResult packResult What the packer produced.
|
||||
* @return LoweredPack The pages and placements to commit.
|
||||
*/
|
||||
internal fun lowerPack(atlas: PuppetAtlas, packResult: AtlasPackResult): LoweredPack {
|
||||
val pages = packResult.pages.map { page -> AtlasPage(page.width, page.height) }
|
||||
val packedByKey = packResult.placements.associateBy { placement -> placement.key }
|
||||
val keptKeys = packResult.fixed.mapTo(HashSet()) { kept -> kept.key }
|
||||
val placementsByTile = HashMap<AtlasTileId, AtlasPlacement?>()
|
||||
var packedOut = 0
|
||||
for (tile in atlas.tiles) {
|
||||
if (tile.id.raw in keptKeys) {
|
||||
placementsByTile[tile.id] = tile.placement
|
||||
continue
|
||||
}
|
||||
val packed = packedByKey[tile.id.raw]
|
||||
placementsByTile[tile.id] = packed?.let { placement -> atlasPlacementFromPack(placement) }
|
||||
if (packed == null && tile.placement != null) {
|
||||
UmamoLog.warn("repack: unbound tile '${tile.name}' could not be packed and leaves the pages")
|
||||
packedOut++
|
||||
}
|
||||
}
|
||||
return LoweredPack(pages, placementsByTile, packedOut)
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs one pack's outcome the way both the first run and an adjustment report it.
|
||||
*
|
||||
* @param AtlasPackResult packResult The pack.
|
||||
* @param LoweredPack lowered Its lowering.
|
||||
* @param AtlasPackOptions options The options it ran with.
|
||||
*/
|
||||
internal fun logPack(packResult: AtlasPackResult, lowered: LoweredPack, options: AtlasPackOptions) {
|
||||
val occupancy =
|
||||
packResult.pages.indices.joinToString(separator = ", ") { pageIndex ->
|
||||
"${(packResult.pageOccupancy(pageIndex) * 100f).toInt()}%"
|
||||
}
|
||||
UmamoLog.info(
|
||||
"repack: ${packResult.placements.size} tile(s) onto ${lowered.pages.size} page(s) at ${options.maxPageSize} px" +
|
||||
" (occupancy $occupancy; gutter ${options.gutter}, extrude ${options.extrude}, rotation ${options.allowRotation});" +
|
||||
" ${packResult.fixed.size} pinned tile(s) kept, ${lowered.packedOutCount} unbound tile(s) packed out",
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Repacks the document's atlas: decodes every bound tile's art, runs the shared deterministic packer
|
||||
* under [options], and commits the new pages + placements + re-derived coordinates as ONE undo step,
|
||||
* pre-warming the session's page resolver with the pages the pack already composed so nothing
|
||||
* composes twice. The viewport and every UV editor follow the MODEL - the resolver publishes the
|
||||
* pages and the engine swaps them - so this function ends at the commit and the registration.
|
||||
*
|
||||
* The commit registers itself as the session's adjustable operation (the operation settings strip):
|
||||
* its rows are the pack options, and editing one re-packs the SAME decoded input from the model the
|
||||
* repack ran on and lands over the repack's own history step ([EditorSession.amendLastCommit]) - one
|
||||
* pack per adjustment, no decode, nothing replayed. See [adjustAtlasRepack].
|
||||
*
|
||||
* All or nothing: any bound tile the pack cannot carry aborts the whole repack into the host's
|
||||
* report (the modal report surface - a lost tile must not be a four-second toast). Unbound tiles
|
||||
* are packed out (placement null) with a log line; art nobody samples does not spend page space.
|
||||
*
|
||||
* Pinned tiles stay exactly where they are while [keepPinned] (the packer seeds their footprints
|
||||
* and paints them through their own placements), and pack like any other tile when it is off - the
|
||||
* pin itself survives either way, so the next repack honors it again.
|
||||
*
|
||||
* Runs on the UI thread; the decode + pack hop to the default dispatcher. The commit applies to the
|
||||
* model CURRENT at completion, so non-mesh edits made while packing survive. Two things abort as
|
||||
* superseded rather than applying a stale pack: the atlas itself changing (an undo across a repack,
|
||||
* say), and a mesh or coordinate edit that changes a tile's reach - the pack was spaced by the
|
||||
* reserves it started with, so it no longer proves the current meshes disjoint.
|
||||
*
|
||||
* @param AtlasRepackHost host The session, art, resolver, scope, and shell callbacks.
|
||||
* @param AtlasPackOptions options The options to pack with (the strip's rows start from them).
|
||||
* @param String? areaId The area the command was dispatched over, or null - where the strip shows.
|
||||
* @param Boolean keepPinned Whether pinned tiles stay where they are.
|
||||
*/
|
||||
suspend fun runAtlasRepack(
|
||||
host: AtlasRepackHost,
|
||||
options: AtlasPackOptions,
|
||||
areaId: String?,
|
||||
keepPinned: Boolean = true,
|
||||
) {
|
||||
val session = host.session
|
||||
val modelAtStart = session.model.value
|
||||
val atlas = modelAtStart.atlas
|
||||
if (atlas.tiles.isEmpty() || !atlas.storedUvsAddressPages) {
|
||||
// The command's availability gates both; a race between the check and the dispatch just no-ops.
|
||||
return
|
||||
}
|
||||
|
||||
// Only a BOUND failure refuses the repack; a placed-unbound tile that cannot come along packs out
|
||||
// instead, logged in the lowering.
|
||||
val packed =
|
||||
withContext(Dispatchers.Default) {
|
||||
packAtlasOf(modelAtStart, { tileId -> host.artRasters.decodeRaster(tileId) }, options, keepPinned)
|
||||
}
|
||||
val packInput = packed.input
|
||||
val packResult = packed.result
|
||||
|
||||
val refusals = repackRefusals(modelAtStart, packResult.skipped, packInput.undecodableTileIds)
|
||||
if (refusals.isNotEmpty()) {
|
||||
for (refusal in refusals) {
|
||||
UmamoLog.warn("repack: tile '${refusal.tileName}' refused (${refusal.reason}); nothing was applied")
|
||||
}
|
||||
host.report(AtlasRepackReport(refusals))
|
||||
return
|
||||
}
|
||||
val lowered = lowerPack(atlas, packResult)
|
||||
|
||||
// Back on the UI thread, synchronously to the commit: a pack computed against one atlas value must
|
||||
// not apply over another (an undo across a repack landing mid-pack, say).
|
||||
val modelAtCommit = session.model.value
|
||||
if (modelAtCommit.atlas !== modelAtStart.atlas) {
|
||||
UmamoLog.warn("repack: the atlas changed while packing; nothing was applied")
|
||||
session.emitNotice("notice.atlas.repackSuperseded", NoticePlacement.NearCursor)
|
||||
return
|
||||
}
|
||||
// Same rule for the reserves: the pack is only proof of disjointness for the meshes it was spaced
|
||||
// by, so a mesh edit that moved a tile's reach while packing makes it stale.
|
||||
val reservesAtCommit = meshReserveByTile(modelAtCommit)
|
||||
if (reservesAtCommit != packInput.reserveByTile) {
|
||||
val changedTileIds = (reservesAtCommit.keys + packInput.reserveByTile.keys).filter { tileId -> reservesAtCommit[tileId] != packInput.reserveByTile[tileId] }
|
||||
UmamoLog.warn(
|
||||
"repack: a mesh edit changed ${changedTileIds.size} tile reach(es) while packing (${changedTileIds.take(3).joinToString { tileId -> tileId.raw }}); nothing was applied",
|
||||
)
|
||||
session.emitNotice("notice.atlas.repackSuperseded", NoticePlacement.NearCursor)
|
||||
return
|
||||
}
|
||||
val committed = session.commitAtlasRepack(lowered.pages, lowered.placementsByTile, atlasCompositionOf(options))
|
||||
if (committed == null) {
|
||||
UmamoLog.info("repack: the pack reproduced the current placements exactly; nothing to change")
|
||||
session.emitNotice("notice.atlas.repackUnchanged", NoticePlacement.NearCursor)
|
||||
return
|
||||
}
|
||||
// Pre-warm BEFORE the resolver's collector resumes (it is queued behind this dispatch), so the
|
||||
// commit resolves its pages by cache hit instead of composing the same pages a second time.
|
||||
host.sessionAtlasPages?.prewarm(committed.atlas, generatedPuppetTextures(packResult.pages, committed, host.premultipliedAlpha))
|
||||
host.rememberOptions(options, keepPinned)
|
||||
logPack(packResult, lowered, options)
|
||||
session.emitNotice("notice.atlas.repacked", NoticePlacement.NearCursor)
|
||||
|
||||
// The decoded input is what an adjustment keeps: a re-pack costs the pack alone. The record's
|
||||
// base is the model this pack ran on, so the reserves the input was spaced by are its reserves.
|
||||
session.registerAdjustableOperation(committed, areaId, repackParameters(options, keepPinned)) { record ->
|
||||
host.scope.launch { adjustAtlasRepack(host, record, packInput) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-packs for an adjustment of the strip: the record's parameters become the options, the SAME
|
||||
* decoded [packInput] packs again off-thread, and the result lands over the repack's own step from
|
||||
* the record's base model. A refusal reports like the first run's and leaves the previous result
|
||||
* standing; a record cleared while the pack ran (any other edit, an undo, a document swap) makes
|
||||
* [EditorSession.amendLastCommit] drop the result rather than commit over what the rigger did.
|
||||
*
|
||||
* @param AtlasRepackHost host The session, resolver, and shell callbacks the first run had.
|
||||
* @param AdjustableOperation record The record with the adjusted parameters.
|
||||
* @param RepackPackInput packInput The first run's decoded input, packed again as it is.
|
||||
*/
|
||||
internal suspend fun adjustAtlasRepack(
|
||||
host: AtlasRepackHost,
|
||||
record: AdjustableOperation,
|
||||
packInput: RepackPackInput,
|
||||
) {
|
||||
val base = record.baseSnapshot.model
|
||||
val options = repackOptionsOf(record.parameters, fallback = AtlasPackOptions(maxPageSize = repackPageSizeOf(base)))
|
||||
val keepPinned = repackKeepPinnedOf(record.parameters)
|
||||
val packResult =
|
||||
try {
|
||||
withContext(Dispatchers.Default) { packAtlas(packInput.itemsFor(keepPinned), options) }
|
||||
} catch (exception: IllegalArgumentException) {
|
||||
// The rows keep every value inside the packer's contract, so this is a bug, not a rigger's
|
||||
// mistake - but a bug in an adjustment must not take the shell's scope down with it.
|
||||
UmamoLog.error("repack: the adjusted options were refused by the packer (${exception.message}); the previous result stands")
|
||||
return
|
||||
}
|
||||
val refusals = repackRefusals(base, packResult.skipped, packInput.undecodableTileIds)
|
||||
if (refusals.isNotEmpty()) {
|
||||
for (refusal in refusals) {
|
||||
UmamoLog.warn("repack: tile '${refusal.tileName}' refused under the adjusted options (${refusal.reason}); the previous result stands")
|
||||
}
|
||||
host.report(AtlasRepackReport(refusals))
|
||||
return
|
||||
}
|
||||
val lowered = lowerPack(base.atlas, packResult)
|
||||
val repacked = base.withAtlasRepack(lowered.pages, lowered.placementsByTile, atlasCompositionOf(options))
|
||||
host.sessionAtlasPages?.prewarm(repacked.atlas, generatedPuppetTextures(packResult.pages, repacked, host.premultipliedAlpha))
|
||||
if (!host.session.amendLastCommit(record, repacked)) {
|
||||
UmamoLog.info("repack: the adjustment was superseded before it landed; nothing was applied")
|
||||
return
|
||||
}
|
||||
host.rememberOptions(options, keepPinned)
|
||||
logPack(packResult, lowered, options)
|
||||
}
|
||||
|
||||
/**
|
||||
* An artwork-origin document as it opens: the model with its pages packed, the pages themselves, and
|
||||
* whatever the pack could not carry.
|
||||
*
|
||||
* @property PuppetModel model The packed model.
|
||||
* @property PuppetTextures textures The composed pages, index-parallel to the model's page list.
|
||||
* @property List refusals Bound tiles the pack left unplaced, each with the packer's reason.
|
||||
*/
|
||||
class PackedAtOpen(
|
||||
val model: PuppetModel,
|
||||
val textures: PuppetTextures,
|
||||
val refusals: List<AtlasRepackRefusal>,
|
||||
)
|
||||
|
||||
/**
|
||||
* Packs an UNPACKED model's atlas as an artwork import opens it: every tile unplaced, every drawable's
|
||||
* coordinates addressing its own art, which is exactly the state the repack's re-derivation moves onto
|
||||
* pages through the identity mapping. Packs at [DEFAULT_REPACK_PAGE_SIZE] first and once more at
|
||||
* [MAX_IMPORT_PAGE_SIZE] if any tile did not fit, then commits through [withAtlasRepack] under the
|
||||
* packer's default composition.
|
||||
*
|
||||
* Unlike the repack command, a refusal is NOT fatal: a document is still worth opening with one layer
|
||||
* unpacked, so a tile the pack cannot carry stays unplaced (its coordinates keep addressing the art,
|
||||
* which the source-layer display still draws) and is reported, never dropped.
|
||||
*
|
||||
* @param PuppetModel model The unpacked model.
|
||||
* @param Function decodeRaster Yields a tile's decoded pixels, or null.
|
||||
* @return PackedAtOpen The packed model, its pages, and the refusals.
|
||||
*/
|
||||
fun packModelAtOpen(model: PuppetModel, decodeRaster: (AtlasTileId) -> DecodedImage?): PackedAtOpen {
|
||||
var options = AtlasPackOptions(maxPageSize = DEFAULT_REPACK_PAGE_SIZE)
|
||||
var packed = packAtlasOf(model, decodeRaster, options, keepPinned = false)
|
||||
if (packed.result.skipped.any { skip -> skip.reason == AtlasPackSkipReason.LargerThanPage }) {
|
||||
options = options.copy(maxPageSize = MAX_IMPORT_PAGE_SIZE)
|
||||
packed = PackedAtlas(packed.input, packAtlas(packed.input.itemsFor(keepPinned = false), options))
|
||||
}
|
||||
val refusals = repackRefusals(model, packed.result.skipped, packed.input.undecodableTileIds)
|
||||
val lowered = lowerPack(model.atlas, packed.result)
|
||||
val repacked = model.withAtlasRepack(lowered.pages, lowered.placementsByTile, atlasCompositionOf(options))
|
||||
logPack(packed.result, lowered, options)
|
||||
return PackedAtOpen(repacked, generatedPuppetTextures(packed.result.pages, repacked, premultipliedAlpha = false), refusals)
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package org.umamo.ui.model
|
||||
|
||||
import org.umamo.edit.EditorSession
|
||||
import org.umamo.edit.OperatorParameter
|
||||
import org.umamo.edit.ParameterChoice
|
||||
import org.umamo.edit.ParameterUnit
|
||||
import org.umamo.edit.booleanValue
|
||||
import org.umamo.edit.choiceValue
|
||||
import org.umamo.edit.intValue
|
||||
import org.umamo.format.atlas.AtlasPackOptions
|
||||
|
||||
/*
|
||||
* The repack's face on the operation settings strip: its pack options as the strip's typed rows, and
|
||||
* back, plus the session memory the next repack starts from. This file is the repack's whole
|
||||
* contribution to the strip - a later operation's rows are a sibling of this file, not an edit to
|
||||
* the strip.
|
||||
*/
|
||||
|
||||
/** The parameter keys the repack's rows carry (the strip maps their label keys to strings). */
|
||||
internal object RepackParameterKeys {
|
||||
const val PAGE_SIZE = "repack.pageSize"
|
||||
const val GUTTER = "repack.gutter"
|
||||
const val EXTRUDE = "repack.extrude"
|
||||
const val ALLOW_ROTATION = "repack.allowRotation"
|
||||
const val KEEP_PINNED = "repack.keepPinned"
|
||||
const val POWER_OF_TWO = "repack.powerOfTwo"
|
||||
const val SQUARE_PAGES = "repack.squarePages"
|
||||
const val SHRINK_PAGES = "repack.shrinkPages"
|
||||
const val ALPHA_THRESHOLD = "repack.alphaThreshold"
|
||||
}
|
||||
|
||||
/** The maximum page sizes the strip offers; the document's own size joins the list when it is none of these. */
|
||||
internal val REPACK_PAGE_SIZE_CHOICES: List<Int> = listOf(1024, 2048, 4096, 8192, 16384)
|
||||
|
||||
/** The widest gutter the strip offers, in pixels. */
|
||||
internal const val REPACK_MAX_GUTTER = 64
|
||||
|
||||
/**
|
||||
* The strip's rows for [options], in display order.
|
||||
*
|
||||
* The extrusion's range follows the gutter: the packer requires extrude in 0..gutter, so the row can
|
||||
* never offer a value the packer refuses. The page size is a choice over the common sizes because a
|
||||
* free integer would invite sizes no GPU wants; the document's current size is offered even when it
|
||||
* is not one of them, so an imported document's own size is always one click away. It is the
|
||||
* MAXIMUM page size, and the row says so: with Shrink Pages on (the default) the packer settles on
|
||||
* the smallest power-of-two side that needs no more pages than this one would, so a larger choice
|
||||
* changes nothing until the art needs the room or Shrink Pages is off. Keep Pinned Tiles is the
|
||||
* one row that is not a packer option: it decides whether the pinned tiles are handed to the packer
|
||||
* fixed or free.
|
||||
*
|
||||
* @param AtlasPackOptions options The options the rows show.
|
||||
* @param Boolean keepPinned Whether the pinned tiles stay where they are.
|
||||
* @return List The rows.
|
||||
*/
|
||||
internal fun repackParameters(options: AtlasPackOptions, keepPinned: Boolean = true): List<OperatorParameter> {
|
||||
val pageSides = (REPACK_PAGE_SIZE_CHOICES + options.maxPageSize).distinct().sorted()
|
||||
return listOf(
|
||||
OperatorParameter.ChoiceParameter(
|
||||
RepackParameterKeys.PAGE_SIZE,
|
||||
RepackParameterKeys.PAGE_SIZE,
|
||||
options.maxPageSize.toString(),
|
||||
pageSides.map { side -> ParameterChoice(side.toString()) },
|
||||
),
|
||||
OperatorParameter.IntParameter(RepackParameterKeys.GUTTER, RepackParameterKeys.GUTTER, options.gutter, 0, REPACK_MAX_GUTTER, unit = ParameterUnit.Pixels),
|
||||
OperatorParameter.IntParameter(RepackParameterKeys.EXTRUDE, RepackParameterKeys.EXTRUDE, options.extrude, 0, options.gutter, unit = ParameterUnit.Pixels),
|
||||
OperatorParameter.BooleanParameter(RepackParameterKeys.ALLOW_ROTATION, RepackParameterKeys.ALLOW_ROTATION, options.allowRotation),
|
||||
OperatorParameter.BooleanParameter(RepackParameterKeys.KEEP_PINNED, RepackParameterKeys.KEEP_PINNED, keepPinned),
|
||||
OperatorParameter.BooleanParameter(RepackParameterKeys.POWER_OF_TWO, RepackParameterKeys.POWER_OF_TWO, options.powerOfTwoPages),
|
||||
OperatorParameter.BooleanParameter(RepackParameterKeys.SQUARE_PAGES, RepackParameterKeys.SQUARE_PAGES, options.squarePages),
|
||||
OperatorParameter.BooleanParameter(RepackParameterKeys.SHRINK_PAGES, RepackParameterKeys.SHRINK_PAGES, options.shrinkPages),
|
||||
OperatorParameter.IntParameter(RepackParameterKeys.ALPHA_THRESHOLD, RepackParameterKeys.ALPHA_THRESHOLD, options.alphaThreshold, 1, 255),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The options [parameters] describe, over [fallback] for anything the rows do not carry.
|
||||
*
|
||||
* The extrusion is clamped to the gutter on the way back so an edit that narrowed the gutter under
|
||||
* a wider extrusion still yields options the packer accepts; the strip re-renders from the options
|
||||
* the pack actually used, so the clamp shows.
|
||||
*
|
||||
* @param List parameters The strip's rows.
|
||||
* @param AtlasPackOptions fallback The options for rows that are absent.
|
||||
* @return AtlasPackOptions The options to pack with.
|
||||
*/
|
||||
internal fun repackOptionsOf(parameters: List<OperatorParameter>, fallback: AtlasPackOptions): AtlasPackOptions {
|
||||
val gutter = parameters.intValue(RepackParameterKeys.GUTTER, fallback.gutter).coerceIn(0, REPACK_MAX_GUTTER)
|
||||
return fallback.copy(
|
||||
maxPageSize = parameters.choiceValue(RepackParameterKeys.PAGE_SIZE, fallback.maxPageSize.toString()).toIntOrNull() ?: fallback.maxPageSize,
|
||||
gutter = gutter,
|
||||
extrude = parameters.intValue(RepackParameterKeys.EXTRUDE, fallback.extrude).coerceIn(0, gutter),
|
||||
allowRotation = parameters.booleanValue(RepackParameterKeys.ALLOW_ROTATION, fallback.allowRotation),
|
||||
powerOfTwoPages = parameters.booleanValue(RepackParameterKeys.POWER_OF_TWO, fallback.powerOfTwoPages),
|
||||
squarePages = parameters.booleanValue(RepackParameterKeys.SQUARE_PAGES, fallback.squarePages),
|
||||
shrinkPages = parameters.booleanValue(RepackParameterKeys.SHRINK_PAGES, fallback.shrinkPages),
|
||||
alphaThreshold = parameters.intValue(RepackParameterKeys.ALPHA_THRESHOLD, fallback.alphaThreshold).coerceIn(1, 255),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether [parameters] keep the pinned tiles where they are; true when the row is absent.
|
||||
*
|
||||
* @param List parameters The strip's rows.
|
||||
* @return Boolean The keep-pinned choice.
|
||||
*/
|
||||
internal fun repackKeepPinnedOf(parameters: List<OperatorParameter>): Boolean = parameters.booleanValue(RepackParameterKeys.KEEP_PINNED, true)
|
||||
|
||||
/**
|
||||
* The repack's session memory: the options the last pack ran with, held for the life of the window
|
||||
* and deliberately never persisted to settings - the pattern the MOC3 export options use.
|
||||
*
|
||||
* Two lifetimes in one object. The spacing, rotation, keep-pinned, page-shape, and threshold choices
|
||||
* stick across documents - a rigger who packs with rotation wants that for the next model too. The page
|
||||
* size sticks only within one session: it is a property of one document's pages (its default is the
|
||||
* document's own side), so carrying it onto a different document would silently pack that one at
|
||||
* the previous model's size. The session is remembered by hash code, never by reference, so this
|
||||
* object retains nothing of a closed document.
|
||||
*
|
||||
* A plain class rather than Compose state on purpose: the repack copies the returned value into its
|
||||
* record, so nothing observes this between packs and it stays unit-testable.
|
||||
*/
|
||||
class AtlasRepackSessionOptions {
|
||||
private var remembered: AtlasPackOptions? = null
|
||||
private var rememberedKeepPinned: Boolean = true
|
||||
private var rememberedSessionHash: Int? = null
|
||||
|
||||
/**
|
||||
* Whether the next repack keeps the pinned tiles where they are: the last pack's choice, or true
|
||||
* before any pack.
|
||||
*
|
||||
* @return Boolean The keep-pinned choice.
|
||||
*/
|
||||
fun keepPinnedFor(): Boolean = rememberedKeepPinned
|
||||
|
||||
/**
|
||||
* The options the next repack should run with for [session], whose default maximum page size is
|
||||
* [documentPageSize].
|
||||
*
|
||||
* @param EditorSession session The document's session.
|
||||
* @param Int documentPageSize The document's own maximum page size.
|
||||
* @return AtlasPackOptions The options to pack with.
|
||||
*/
|
||||
fun optionsFor(session: EditorSession, documentPageSize: Int): AtlasPackOptions {
|
||||
val sticky = remembered ?: return AtlasPackOptions(maxPageSize = documentPageSize)
|
||||
return if (rememberedSessionHash == session.hashCode()) sticky else sticky.copy(maxPageSize = documentPageSize)
|
||||
}
|
||||
|
||||
/**
|
||||
* Records what a pack for [session] ran with, making it the seed for the next.
|
||||
*
|
||||
* @param EditorSession session The document's session.
|
||||
* @param AtlasPackOptions options The options the pack used.
|
||||
* @param Boolean keepPinned Whether the pack kept the pinned tiles where they were.
|
||||
*/
|
||||
fun record(session: EditorSession, options: AtlasPackOptions, keepPinned: Boolean = true) {
|
||||
remembered = options
|
||||
rememberedKeepPinned = keepPinned
|
||||
rememberedSessionHash = session.hashCode()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package org.umamo.ui.model
|
||||
|
||||
import org.umamo.format.art.LayerRaster
|
||||
import org.umamo.format.art.SourceLayer
|
||||
import org.umamo.render.DecodedImage
|
||||
|
||||
/**
|
||||
* The decoded wrapper of every layer raster of some read art, minted once per raster: a re-run of the
|
||||
* operation that read the art hands the raster store the same instances again, and the renderer's
|
||||
* texture cache and the viewport's freshness test key on that identity.
|
||||
*
|
||||
* LayerRaster is a plain class, so the map keys by identity - which is the point: the wrapper of one
|
||||
* raster is one object for the request's life. Built eagerly so the off-thread passes only read.
|
||||
*
|
||||
* @param List<SourceLayer> layers The layers whose rasters are wrapped.
|
||||
*/
|
||||
internal class DecodedLayerRasters(layers: List<SourceLayer>) {
|
||||
private val decodedByRaster: Map<LayerRaster, DecodedImage> =
|
||||
layers.associate { layer -> layer.raster to DecodedImage(layer.raster.rgba, layer.raster.width, layer.raster.height) }
|
||||
|
||||
/**
|
||||
* The decoded wrapper of one of the layers' rasters, or a fresh wrapper for a raster the art did
|
||||
* not carry.
|
||||
*
|
||||
* @param LayerRaster raster The layer's pixels.
|
||||
* @return DecodedImage The wrapper, the same instance on every call for a known raster.
|
||||
*/
|
||||
fun decodedFor(raster: LayerRaster): DecodedImage = decodedByRaster[raster] ?: DecodedImage(raster.rgba, raster.width, raster.height)
|
||||
}
|
||||
@@ -0,0 +1,498 @@
|
||||
package org.umamo.ui.model
|
||||
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import org.umamo.format.raster.RasterImage
|
||||
import org.umamo.render.PuppetTextures
|
||||
import org.umamo.runtime.model.Drawable
|
||||
import org.umamo.runtime.model.DrawableId
|
||||
import org.umamo.runtime.model.OrgChild
|
||||
import org.umamo.runtime.model.PartId
|
||||
import org.umamo.runtime.model.PuppetModel
|
||||
import org.umamo.runtime.model.partByDrawable
|
||||
import org.umamo.ui.graphics.RgbaAlphaType
|
||||
import org.umamo.ui.graphics.rgbaToImageBitmap
|
||||
import kotlin.math.ceil
|
||||
import kotlin.math.floor
|
||||
import kotlin.math.max
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/**
|
||||
* Longest edge (in texels) of a single art-mesh crop. The drawable's atlas crop is nearest-downsampled to
|
||||
* fit within this box so the cache stays small even for large atlas pages; the consumer then scales the
|
||||
* result to its display slot. 96px is comfortably above the slots that show it (the overlap picker's
|
||||
* ~44dp, the Outliner and Sources hovers' ~120dp) at any reasonable display density, so the preview stays crisp.
|
||||
*/
|
||||
private const val CROP_MAX_DIMENSION = 96
|
||||
|
||||
/**
|
||||
* Longest edge (in pixels) of a combined part-folder or whole-model preview. A touch larger than a single
|
||||
* crop because it packs several layers; a part's composite is built once and cached.
|
||||
*/
|
||||
private const val PART_COMPOSITE_MAX_DIMENSION = 128
|
||||
|
||||
/**
|
||||
* Crops small art-mesh previews from the loaded model's atlas pages, the shared source for the viewport's
|
||||
* overlap picker and the Outliner's and Sources space's hover previews (per-drawable [thumbnailFor] and combined
|
||||
* [partThumbnailFor]), and for the model icon a CMO3 export writes ([modelRasterFor]). Pure CPU over the
|
||||
* immutable decoded atlas bytes ([PuppetTextures.atlases]) and the drawables' mesh data - no GL, no
|
||||
* render-thread hand-off - so it is safe to call straight from the Compose UI thread. Results are memoized;
|
||||
* [updateModel] refreshes the model-derived inputs after every committed
|
||||
* edit and evicts exactly the entries the edit staled, and [setTextures] swaps the page pixels when the
|
||||
* session repacks, evicting every pixel-derived entry wholesale.
|
||||
*
|
||||
* Rasterises to a Compose [ImageBitmap] through the rgbaToImageBitmap platform seam (Skiko on desktop,
|
||||
* android.graphics.Bitmap on Android), so one implementation serves both apps. The per-drawable crop
|
||||
* covers every drawable carrying mesh UVs (not just the currently visible ones), so a hidden layer
|
||||
* previews too.
|
||||
*
|
||||
* @property PuppetModel puppet The rig whose drawables are previewed.
|
||||
* @property PuppetTextures textures The decoded atlas page(s) + per-drawable page index.
|
||||
*/
|
||||
class DrawableThumbnailer(
|
||||
private val puppet: PuppetModel,
|
||||
// var: a repack swaps the page set mid-session; setTextures re-points this and evicts the caches.
|
||||
private var textures: PuppetTextures,
|
||||
) : DrawableThumbnailProvider {
|
||||
/** A cropped art region as raw straight-alpha RGBA (top row first), reused by both the per-drawable and part previews. */
|
||||
private class RawCrop(val rgba: ByteArray, val width: Int, val height: Int)
|
||||
|
||||
/** A drawable's rest-pose model-space axis-aligned bounds, the rectangle its crop is placed into when compositing. */
|
||||
private class ModelBounds(val minX: Float, val minY: Float, val maxX: Float, val maxY: Float) {
|
||||
val width: Float get() = maxX - minX
|
||||
val height: Float get() = maxY - minY
|
||||
}
|
||||
|
||||
// Drawable id -> drawable, over the CURRENT model - refreshed by [updateModel] so a session-created
|
||||
// drawable (a duplicate's fresh ".001" id) resolves for crops and bounds.
|
||||
private var drawableById = puppet.drawables.associateBy { it.id }
|
||||
|
||||
// Per-drawable UVs (full-atlas [0,1]), over every drawable carrying mesh UVs - the hover preview should
|
||||
// work on hidden layers too, so this is not restricted to the visible/pickable set. Refreshed by
|
||||
// [updateModel] alongside [drawableById].
|
||||
private var uvsByDrawable: Map<DrawableId, FloatArray> = uvsFor(puppet.drawables)
|
||||
|
||||
// Drawable membership + paint order and the part hierarchy a part composite is built from, over the
|
||||
// CURRENT model - [updateModel] refreshes them with the rest of the model-derived inputs. UI-thread
|
||||
// only (the same thread the previews are requested on).
|
||||
private var currentDrawables = puppet.drawables
|
||||
private var currentPartChildren: Map<PartId, List<PartId>> =
|
||||
puppet.parts.associate { part -> part.id to part.children.filterIsInstance<OrgChild.Part>().map { it.id } }
|
||||
|
||||
// Drawable -> owning part, derived from the org tree (membership lives only there now).
|
||||
private var currentDrawableOwner: Map<DrawableId, PartId?> = puppet.partByDrawable()
|
||||
|
||||
// Memoized derivations. The per-drawable caches are keyed by immutable geometry / UV data; [updateModel]
|
||||
// evicts an entry only when its drawable's mesh data was replaced or the drawable was removed. The part
|
||||
// composites depend on membership / order and are cleared wholesale.
|
||||
private val cropCache = mutableMapOf<DrawableId, RawCrop?>()
|
||||
private val boundsCache = mutableMapOf<DrawableId, ModelBounds?>()
|
||||
private val thumbnailCache = mutableMapOf<DrawableId, ImageBitmap?>()
|
||||
private val partThumbnailCache = mutableMapOf<PartId, ImageBitmap?>()
|
||||
|
||||
/**
|
||||
* Swaps the atlas page set after a repack (or its undo) and evicts every cache that read pixels or
|
||||
* page indices out of the old one. Wholesale rather than per-entry: a repack moves every placed
|
||||
* tile, so there is nothing selective to keep.
|
||||
*
|
||||
* @param PuppetTextures next The new page set.
|
||||
*/
|
||||
fun setTextures(next: PuppetTextures) {
|
||||
if (next === textures) {
|
||||
return
|
||||
}
|
||||
textures = next
|
||||
cropCache.clear()
|
||||
boundsCache.clear()
|
||||
thumbnailCache.clear()
|
||||
partThumbnailCache.clear()
|
||||
}
|
||||
|
||||
/**
|
||||
* Refreshes every model-derived input after an edit and evicts exactly the caches the edit staled:
|
||||
* the part composites always (membership / order may have changed), and the geometry-keyed
|
||||
* per-drawable entries only where the mesh data was actually copy-on-write replaced (a remesh swaps
|
||||
* uvs, a vertex move swaps positions) or the drawable was removed (a later redo may recreate the id
|
||||
* with different geometry). A session-added drawable - a duplicate's fresh ".001" id - needs no
|
||||
* eviction; its entries fill lazily on first request now that the lookups see it.
|
||||
*
|
||||
* @param PuppetModel model The current model.
|
||||
*/
|
||||
fun updateModel(model: PuppetModel) {
|
||||
val previousById = drawableById
|
||||
val newById = model.drawables.associateBy { it.id }
|
||||
for (drawable in model.drawables) {
|
||||
val previous = previousById[drawable.id] ?: continue
|
||||
if (drawable.mesh?.uvs !== previous.mesh?.uvs) {
|
||||
cropCache.remove(drawable.id)
|
||||
thumbnailCache.remove(drawable.id)
|
||||
}
|
||||
if (drawable.mesh?.positions !== previous.mesh?.positions) {
|
||||
boundsCache.remove(drawable.id)
|
||||
}
|
||||
}
|
||||
for (removedId in previousById.keys) {
|
||||
if (removedId !in newById) {
|
||||
cropCache.remove(removedId)
|
||||
thumbnailCache.remove(removedId)
|
||||
boundsCache.remove(removedId)
|
||||
}
|
||||
}
|
||||
drawableById = newById
|
||||
uvsByDrawable = uvsFor(model.drawables)
|
||||
currentDrawables = model.drawables
|
||||
currentPartChildren = model.parts.associate { part -> part.id to part.children.filterIsInstance<OrgChild.Part>().map { it.id } }
|
||||
currentDrawableOwner = model.partByDrawable()
|
||||
partThumbnailCache.clear()
|
||||
}
|
||||
|
||||
/**
|
||||
* The per-drawable full-atlas UVs over every drawable carrying mesh UVs.
|
||||
*
|
||||
* @param List<Drawable> drawables The model's drawables.
|
||||
* @return Map<DrawableId, FloatArray> Drawable id to its mesh UVs.
|
||||
*/
|
||||
private fun uvsFor(drawables: List<Drawable>): Map<DrawableId, FloatArray> =
|
||||
drawables
|
||||
.mapNotNull { drawable -> drawable.mesh?.uvs?.takeIf { it.isNotEmpty() }?.let { drawable.id to it } }
|
||||
.toMap()
|
||||
|
||||
/**
|
||||
* The cropped art preview for a drawable, or null when it is untextured, mesh-less, or unknown. Memoized.
|
||||
*
|
||||
* @param DrawableId id The drawable to preview.
|
||||
* @return ImageBitmap? The cropped preview, or null when none is available.
|
||||
*/
|
||||
override fun thumbnailFor(id: DrawableId): ImageBitmap? = thumbnailCache.getOrPut(id) { croppedFor(id)?.let(::rawToImage) }
|
||||
|
||||
/**
|
||||
* A combined preview of every art mesh under [id] (its own drawables and its sub-parts'), placed by each
|
||||
* drawable's rest-pose model bounds and composited back-to-front, or null when the part holds no textured
|
||||
* drawable. Reuses the cached per-drawable crops; only the bounding-box placement and the alpha-over blit
|
||||
* are new work, so it stays cheap. Memoized.
|
||||
*
|
||||
* @param PartId id The part to preview.
|
||||
* @return ImageBitmap? The composited preview, or null when the part has no previewable art.
|
||||
*/
|
||||
override fun partThumbnailFor(id: PartId): ImageBitmap? = partThumbnailCache.getOrPut(id) { partRasterFor(id)?.let { raster -> rawToImage(RawCrop(raster.rgba, raster.width, raster.height)) } }
|
||||
|
||||
/**
|
||||
* The combined part preview of [partThumbnailFor] as a neutral raster: every art mesh under [id]
|
||||
* placed by its rest-pose model bounds and composited back-to-front. Not memoized; the bitmap
|
||||
* wrapper is.
|
||||
*
|
||||
* @param PartId id The part to preview.
|
||||
* @return RasterImage? The composite, straight alpha, or null when the part has no previewable art.
|
||||
*/
|
||||
fun partRasterFor(id: PartId): RasterImage? {
|
||||
val subtree = partSubtree(id)
|
||||
val members = ArrayList<Pair<RawCrop, ModelBounds>>()
|
||||
for (drawable in currentDrawables) {
|
||||
val owningPartId = currentDrawableOwner[drawable.id] ?: continue
|
||||
if (owningPartId !in subtree) {
|
||||
continue
|
||||
}
|
||||
val crop = croppedFor(drawable.id) ?: continue
|
||||
val bounds = modelBoundsOf(drawable.id) ?: continue
|
||||
members += crop to bounds
|
||||
}
|
||||
return compositeOf(members)?.let { composite -> RasterImage(composite.width, composite.height, composite.rgba) }
|
||||
}
|
||||
|
||||
/**
|
||||
* The whole model's rest-pose preview: every VISIBLE drawable with a crop and bounds, root-level
|
||||
* ones included, composited back-to-front by the same rule as a part. This is the thumbnail a
|
||||
* CMO3 export writes for the model, so the official editor shows the character the file holds
|
||||
* rather than a blank tile; hidden drawables (alternate expressions, guides) stay out of it the
|
||||
* way they stay out of the viewport.
|
||||
*
|
||||
* @return RasterImage? The composite, straight alpha, or null when no visible drawable has a crop.
|
||||
*/
|
||||
fun modelRasterFor(): RasterImage? {
|
||||
val members = ArrayList<Pair<RawCrop, ModelBounds>>()
|
||||
for (drawable in currentDrawables) {
|
||||
if (!drawable.isVisible) {
|
||||
continue
|
||||
}
|
||||
val crop = croppedFor(drawable.id) ?: continue
|
||||
val bounds = modelBoundsOf(drawable.id) ?: continue
|
||||
members += crop to bounds
|
||||
}
|
||||
return compositeOf(members)?.let { composite -> RasterImage(composite.width, composite.height, composite.rgba) }
|
||||
}
|
||||
|
||||
/** The cached raw crop for a drawable, computed once. */
|
||||
private fun croppedFor(id: DrawableId): RawCrop? = cropCache.getOrPut(id) { buildCrop(id) }
|
||||
|
||||
/**
|
||||
* Crops the drawable's atlas page to its mesh UV bounding box and nearest-downsamples it to fit
|
||||
* [CROP_MAX_DIMENSION], preserving the straight (un-premultiplied) alpha so the silhouette survives.
|
||||
*
|
||||
* @param DrawableId id The drawable to crop.
|
||||
* @return RawCrop? The cropped RGBA region, or null when the drawable is untextured or mesh-less.
|
||||
*/
|
||||
private fun buildCrop(id: DrawableId): RawCrop? {
|
||||
// The atlas mapping is keyed by the source format's ids, so a session-created duplicate resolves
|
||||
// its page through textureSourceId (its source, or the original for a copy of a copy) - mirroring
|
||||
// the GPU upload's resolution in PuppetRenderer.
|
||||
val drawable = drawableById[id] ?: return null
|
||||
val atlasIndex = textures.atlasIndexByDrawableId[(drawable.textureSourceId ?: drawable.id).raw] ?: return null
|
||||
val image = textures.atlases.getOrNull(atlasIndex) ?: return null
|
||||
val uvs = uvsByDrawable[id] ?: return null
|
||||
if (uvs.isEmpty()) {
|
||||
return null
|
||||
}
|
||||
var minU = Float.POSITIVE_INFINITY
|
||||
var maxU = Float.NEGATIVE_INFINITY
|
||||
var minV = Float.POSITIVE_INFINITY
|
||||
var maxV = Float.NEGATIVE_INFINITY
|
||||
var pairIndex = 0
|
||||
while (pairIndex < uvs.size - 1) {
|
||||
val texU = uvs[pairIndex]
|
||||
val texV = uvs[pairIndex + 1]
|
||||
if (texU < minU) {
|
||||
minU = texU
|
||||
}
|
||||
if (texU > maxU) {
|
||||
maxU = texU
|
||||
}
|
||||
if (texV < minV) {
|
||||
minV = texV
|
||||
}
|
||||
if (texV > maxV) {
|
||||
maxV = texV
|
||||
}
|
||||
pairIndex += 2
|
||||
}
|
||||
// UV bounding box → texel rectangle, clamped to the atlas and at least one texel on each side.
|
||||
val cropLeft = floor(minU * image.width).toInt().coerceIn(0, image.width - 1)
|
||||
val cropTop = floor(minV * image.height).toInt().coerceIn(0, image.height - 1)
|
||||
val cropRight = ceil(maxU * image.width).toInt().coerceIn(cropLeft + 1, image.width)
|
||||
val cropBottom = ceil(maxV * image.height).toInt().coerceIn(cropTop + 1, image.height)
|
||||
val cropWidth = cropRight - cropLeft
|
||||
val cropHeight = cropBottom - cropTop
|
||||
// Fit the longest edge into the crop box (never upscale a region already smaller than the box).
|
||||
val scale = (CROP_MAX_DIMENSION.toFloat() / maxOf(cropWidth, cropHeight)).coerceAtMost(1f)
|
||||
val thumbWidth = (cropWidth * scale).toInt().coerceAtLeast(1)
|
||||
val thumbHeight = (cropHeight * scale).toInt().coerceAtLeast(1)
|
||||
val rowBytes = thumbWidth * 4
|
||||
val pixels = ByteArray(rowBytes * thumbHeight)
|
||||
var destRow = 0
|
||||
while (destRow < thumbHeight) {
|
||||
// Nearest-neighbor: map the destination texel back to a source texel within the crop rectangle.
|
||||
val sourceRow = cropTop + (destRow * cropHeight) / thumbHeight
|
||||
var destColumn = 0
|
||||
while (destColumn < thumbWidth) {
|
||||
val sourceColumn = cropLeft + (destColumn * cropWidth) / thumbWidth
|
||||
val sourceOffset = (sourceRow * image.width + sourceColumn) * 4
|
||||
val destOffset = destRow * rowBytes + destColumn * 4
|
||||
pixels[destOffset] = image.rgba[sourceOffset]
|
||||
pixels[destOffset + 1] = image.rgba[sourceOffset + 1]
|
||||
pixels[destOffset + 2] = image.rgba[sourceOffset + 2]
|
||||
pixels[destOffset + 3] = image.rgba[sourceOffset + 3]
|
||||
destColumn += 1
|
||||
}
|
||||
destRow += 1
|
||||
}
|
||||
return RawCrop(pixels, thumbWidth, thumbHeight)
|
||||
}
|
||||
|
||||
/** The cached rest-pose model bounds for a drawable, from its mesh positions. */
|
||||
private fun modelBoundsOf(id: DrawableId): ModelBounds? = boundsCache.getOrPut(id) { computeBounds(id) }
|
||||
|
||||
/**
|
||||
* Computes a drawable's rest-pose model-space bounding box from its mesh positions (interleaved x, y).
|
||||
*
|
||||
* @param DrawableId id The drawable to bound.
|
||||
* @return ModelBounds? The bounds, or null when the drawable is mesh-less or degenerate.
|
||||
*/
|
||||
private fun computeBounds(id: DrawableId): ModelBounds? {
|
||||
val positions = drawableById[id]?.mesh?.positions ?: return null
|
||||
if (positions.size < 2) {
|
||||
return null
|
||||
}
|
||||
var minX = Float.POSITIVE_INFINITY
|
||||
var maxX = Float.NEGATIVE_INFINITY
|
||||
var minY = Float.POSITIVE_INFINITY
|
||||
var maxY = Float.NEGATIVE_INFINITY
|
||||
var pairIndex = 0
|
||||
while (pairIndex < positions.size - 1) {
|
||||
val positionX = positions[pairIndex]
|
||||
val positionY = positions[pairIndex + 1]
|
||||
if (positionX < minX) {
|
||||
minX = positionX
|
||||
}
|
||||
if (positionX > maxX) {
|
||||
maxX = positionX
|
||||
}
|
||||
if (positionY < minY) {
|
||||
minY = positionY
|
||||
}
|
||||
if (positionY > maxY) {
|
||||
maxY = positionY
|
||||
}
|
||||
pairIndex += 2
|
||||
}
|
||||
if (minX > maxX || minY > maxY) {
|
||||
return null
|
||||
}
|
||||
return ModelBounds(minX, minY, maxX, maxY)
|
||||
}
|
||||
|
||||
/** Every part id in a part's subtree (the part itself plus all descendant parts). */
|
||||
private fun partSubtree(rootPartId: PartId): Set<PartId> {
|
||||
val collected = LinkedHashSet<PartId>()
|
||||
val pending = ArrayDeque<PartId>()
|
||||
pending.addLast(rootPartId)
|
||||
while (pending.isNotEmpty()) {
|
||||
val partId = pending.removeLast()
|
||||
if (!collected.add(partId)) {
|
||||
continue
|
||||
}
|
||||
currentPartChildren[partId]?.forEach { childPartId -> pending.addLast(childPartId) }
|
||||
}
|
||||
return collected
|
||||
}
|
||||
|
||||
/**
|
||||
* Composites [members], each a cached crop with its rest-pose model bounds in the model's
|
||||
* back-to-front order (the [PuppetModel.drawables] base order, so a later entry paints in front):
|
||||
* unions the bounds and blits each crop into its mapped rectangle with straight-alpha
|
||||
* over-compositing. Only members with both a crop and bounds belong here, so untextured or
|
||||
* mesh-less layers neither inflate the union nor leave a gap.
|
||||
*
|
||||
* @param List members The crops to place, back to front.
|
||||
* @return RawCrop? The composite, or null when there are no members or their union is degenerate.
|
||||
*/
|
||||
private fun compositeOf(members: List<Pair<RawCrop, ModelBounds>>): RawCrop? {
|
||||
var unionMinX = Float.POSITIVE_INFINITY
|
||||
var unionMaxX = Float.NEGATIVE_INFINITY
|
||||
var unionMinY = Float.POSITIVE_INFINITY
|
||||
var unionMaxY = Float.NEGATIVE_INFINITY
|
||||
for ((_, bounds) in members) {
|
||||
if (bounds.minX < unionMinX) {
|
||||
unionMinX = bounds.minX
|
||||
}
|
||||
if (bounds.maxX > unionMaxX) {
|
||||
unionMaxX = bounds.maxX
|
||||
}
|
||||
if (bounds.minY < unionMinY) {
|
||||
unionMinY = bounds.minY
|
||||
}
|
||||
if (bounds.maxY > unionMaxY) {
|
||||
unionMaxY = bounds.maxY
|
||||
}
|
||||
}
|
||||
if (members.isEmpty()) {
|
||||
return null
|
||||
}
|
||||
val unionWidth = unionMaxX - unionMinX
|
||||
val unionHeight = unionMaxY - unionMinY
|
||||
if (unionWidth <= 0f || unionHeight <= 0f) {
|
||||
return null
|
||||
}
|
||||
val scale = PART_COMPOSITE_MAX_DIMENSION.toFloat() / max(unionWidth, unionHeight)
|
||||
val compositeWidth = (unionWidth * scale).roundToInt().coerceIn(1, PART_COMPOSITE_MAX_DIMENSION)
|
||||
val compositeHeight = (unionHeight * scale).roundToInt().coerceIn(1, PART_COMPOSITE_MAX_DIMENSION)
|
||||
val pixels = ByteArray(compositeWidth * compositeHeight * 4)
|
||||
for ((crop, bounds) in members) {
|
||||
// Map model bounds straight into composite pixels: Cubism's rest-pose mesh Y runs top-down, the
|
||||
// same direction as the atlas crop's rows (which display upright as the single-drawable preview),
|
||||
// so no Y flip - a smaller model Y is nearer the top. Flipping here would invert each layer's
|
||||
// placement (frills jump to the top, stacked eye parts jumble) while leaving symmetric parts fine.
|
||||
val left = (bounds.minX - unionMinX) / unionWidth * compositeWidth
|
||||
val right = (bounds.maxX - unionMinX) / unionWidth * compositeWidth
|
||||
val top = (bounds.minY - unionMinY) / unionHeight * compositeHeight
|
||||
val bottom = (bounds.maxY - unionMinY) / unionHeight * compositeHeight
|
||||
blitOver(pixels, compositeWidth, compositeHeight, crop, left, top, right, bottom)
|
||||
}
|
||||
return RawCrop(pixels, compositeWidth, compositeHeight)
|
||||
}
|
||||
|
||||
/**
|
||||
* Alpha-over-composites a [crop] into the destination buffer over the floating-point rectangle
|
||||
* [leftEdge, rightEdge) x [topEdge, bottomEdge), nearest-sampling the source and clamping to the buffer.
|
||||
* Straight-alpha over: outA = sa + da(1-sa); outRgb = (srcRgb·sa + dstRgb·da(1-sa)) / outA.
|
||||
*
|
||||
* @param ByteArray destination The composite buffer (straight RGBA, top row first).
|
||||
* @param Int destinationWidth The buffer width in pixels.
|
||||
* @param Int destinationHeight The buffer height in pixels.
|
||||
* @param RawCrop crop The source crop to place.
|
||||
* @param Float leftEdge The destination rectangle's left edge, in pixels.
|
||||
* @param Float topEdge The destination rectangle's top edge, in pixels.
|
||||
* @param Float rightEdge The destination rectangle's right edge, in pixels.
|
||||
* @param Float bottomEdge The destination rectangle's bottom edge, in pixels.
|
||||
*/
|
||||
private fun blitOver(
|
||||
destination: ByteArray,
|
||||
destinationWidth: Int,
|
||||
destinationHeight: Int,
|
||||
crop: RawCrop,
|
||||
leftEdge: Float,
|
||||
topEdge: Float,
|
||||
rightEdge: Float,
|
||||
bottomEdge: Float,
|
||||
) {
|
||||
val spanWidth = rightEdge - leftEdge
|
||||
val spanHeight = bottomEdge - topEdge
|
||||
if (spanWidth <= 0f || spanHeight <= 0f) {
|
||||
return
|
||||
}
|
||||
val firstColumn = floor(leftEdge).toInt().coerceIn(0, destinationWidth)
|
||||
val lastColumn = ceil(rightEdge).toInt().coerceIn(0, destinationWidth)
|
||||
val firstRow = floor(topEdge).toInt().coerceIn(0, destinationHeight)
|
||||
val lastRow = ceil(bottomEdge).toInt().coerceIn(0, destinationHeight)
|
||||
var destRow = firstRow
|
||||
while (destRow < lastRow) {
|
||||
val normalizedY = (destRow + 0.5f - topEdge) / spanHeight
|
||||
val sourceRow = (normalizedY * crop.height).toInt().coerceIn(0, crop.height - 1)
|
||||
var destColumn = firstColumn
|
||||
while (destColumn < lastColumn) {
|
||||
val normalizedX = (destColumn + 0.5f - leftEdge) / spanWidth
|
||||
val sourceColumn = (normalizedX * crop.width).toInt().coerceIn(0, crop.width - 1)
|
||||
val sourceOffset = (sourceRow * crop.width + sourceColumn) * 4
|
||||
val sourceAlpha = crop.rgba[sourceOffset + 3].toInt() and 0xFF
|
||||
if (sourceAlpha != 0) {
|
||||
overComposite(destination, (destRow * destinationWidth + destColumn) * 4, crop.rgba, sourceOffset, sourceAlpha)
|
||||
}
|
||||
destColumn += 1
|
||||
}
|
||||
destRow += 1
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Over-composites one source pixel onto one destination pixel, both straight-alpha RGBA.
|
||||
*
|
||||
* @param ByteArray destination The destination buffer.
|
||||
* @param Int destinationOffset The destination pixel's byte offset.
|
||||
* @param ByteArray source The source buffer.
|
||||
* @param Int sourceOffset The source pixel's byte offset.
|
||||
* @param Int sourceAlpha The source pixel's alpha byte (0..255), already known non-zero.
|
||||
*/
|
||||
private fun overComposite(destination: ByteArray, destinationOffset: Int, source: ByteArray, sourceOffset: Int, sourceAlpha: Int) {
|
||||
val sourceAlphaFraction = sourceAlpha / 255f
|
||||
val destinationAlphaFraction = (destination[destinationOffset + 3].toInt() and 0xFF) / 255f
|
||||
val outAlphaFraction = sourceAlphaFraction + destinationAlphaFraction * (1f - sourceAlphaFraction)
|
||||
if (outAlphaFraction <= 0f) {
|
||||
return
|
||||
}
|
||||
var channelIndex = 0
|
||||
while (channelIndex < 3) {
|
||||
val sourceChannel = (source[sourceOffset + channelIndex].toInt() and 0xFF) / 255f
|
||||
val destinationChannel = (destination[destinationOffset + channelIndex].toInt() and 0xFF) / 255f
|
||||
val outChannel = (sourceChannel * sourceAlphaFraction + destinationChannel * destinationAlphaFraction * (1f - sourceAlphaFraction)) / outAlphaFraction
|
||||
destination[destinationOffset + channelIndex] = (outChannel * 255f).roundToInt().coerceIn(0, 255).toByte()
|
||||
channelIndex += 1
|
||||
}
|
||||
destination[destinationOffset + 3] = (outAlphaFraction * 255f).roundToInt().coerceIn(0, 255).toByte()
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps a raw straight-alpha RGBA crop as a Compose bitmap. The bytes are UNPREMUL (straight) so a
|
||||
* transparent texel's leftover matte RGB does not ghost through additively.
|
||||
*
|
||||
* @param RawCrop crop The raw crop to wrap.
|
||||
* @return ImageBitmap The Compose bitmap.
|
||||
*/
|
||||
private fun rawToImage(crop: RawCrop): ImageBitmap = rgbaToImageBitmap(crop.rgba, crop.width, crop.height, RgbaAlphaType.Straight)
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package org.umamo.ui.model
|
||||
|
||||
import androidx.compose.foundation.hoverable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.interaction.collectIsHoveredAsState
|
||||
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 androidx.compose.runtime.staticCompositionLocalOf
|
||||
import androidx.compose.ui.Modifier
|
||||
import org.umamo.edit.KeyformAim
|
||||
import org.umamo.runtime.model.KeyableTarget
|
||||
import org.umamo.runtime.model.KeyformTrackRef
|
||||
import org.umamo.runtime.model.ParameterId
|
||||
|
||||
/**
|
||||
* The keyform track the pointer is currently over - what a keyform insert aims at.
|
||||
*
|
||||
* A TRACK rather than a channel, so the keyform sheet's rows can publish here too: pointing at a
|
||||
* Geometry row and pressing `I` has to mean something, and geometry is not addressable as a channel.
|
||||
*
|
||||
* Hover targeting is what lets `I` work with no prior selection: point at Opacity, press I, done. It
|
||||
* mirrors the shell's existing hovered-surface seam, and like that one it is resolved at DISPATCH time,
|
||||
* never latched at registration - a command reads the live hover when it fires, so it can never act on a
|
||||
* row the pointer left three interactions ago.
|
||||
*
|
||||
* Plain mutable state rather than a flow: it changes on every pointer enter / exit and nothing needs to
|
||||
* observe it reactively, only sample it when a command runs.
|
||||
*/
|
||||
data class KeyformHover(
|
||||
/** The track under the pointer. */
|
||||
val track: KeyformTrackRef,
|
||||
/**
|
||||
* Where along the parameter the pointer sits, or null when the row has no position axis.
|
||||
*
|
||||
* A Properties row is a single value with nowhere to point AT, so it publishes null and a keyframe op
|
||||
* falls back to the pose. A keyform-sheet lane spans the whole parameter, so pointing at a spot on it
|
||||
* is a statement about WHICH spot - and acting on the playhead instead would ignore what was aimed at.
|
||||
*/
|
||||
val position: Float? = null,
|
||||
/** The ordinal of the key under the pointer, or null when the pointer is not on one. */
|
||||
val keyIndex: Int? = null,
|
||||
/**
|
||||
* The parameter [position] and [keyIndex] are measured on, or null when the hover carries no axis of
|
||||
* its own (a Properties row keys the panel's targeted parameter).
|
||||
*
|
||||
* A keyform-sheet lane belongs to one SECTION's parameter, which is not necessarily the selection's
|
||||
* active member - a linked pad targets both of its axes at once. Without this, an insert aimed at the
|
||||
* other section landed its position on the active axis, and a removal applied the hovered ordinal to
|
||||
* the wrong axis's keys.
|
||||
*/
|
||||
val parameterId: ParameterId? = null,
|
||||
/**
|
||||
* The keyform-sheet row the pointer is over, or null when the hover has no sheet row (a Properties row).
|
||||
*
|
||||
* Carried so an authoring op can reconcile the sheet's key selection against what it changed: a removal
|
||||
* renumbers the keys above it, and a selection left alone then names the neighbour rather than the key
|
||||
* the user selected. Row identity is the sheet's to supply - :edit treats a row key as opaque - so it
|
||||
* rides the hover, which every aimed op already goes through.
|
||||
*/
|
||||
val rowKey: String? = null,
|
||||
) {
|
||||
/**
|
||||
* This hover as the aim an authoring op takes: a named place when the pointer is on a positioned row,
|
||||
* else the pose.
|
||||
*
|
||||
* The mapping lives with the fields it reads rather than at the command that passes it on, so the rule
|
||||
* that [keyIndex] only means anything alongside a [position] is stated once (see [KeyformAim]).
|
||||
*/
|
||||
val aim: KeyformAim
|
||||
get() = position?.let { at -> KeyformAim.Position(at, keyIndex) } ?: KeyformAim.Pose
|
||||
}
|
||||
|
||||
class KeyableHover {
|
||||
/** What the pointer is over, or null when it is over nothing keyable. */
|
||||
var hovered: KeyformHover? by mutableStateOf(null)
|
||||
private set
|
||||
|
||||
/**
|
||||
* Records what the pointer is now over.
|
||||
*
|
||||
* Also called as the pointer MOVES along a lane, since the position is part of what is hovered - so
|
||||
* this is a plain assignment rather than an enter-once latch.
|
||||
*
|
||||
* @param KeyformHover hover The track, and where on it, now under the pointer.
|
||||
*/
|
||||
fun enter(hover: KeyformHover) {
|
||||
hovered = hover
|
||||
}
|
||||
|
||||
/**
|
||||
* Records that the pointer left [track].
|
||||
*
|
||||
* Takes the track rather than clearing unconditionally, because enter / exit events for adjacent rows
|
||||
* can interleave - the new row's enter can arrive before the old row's exit, and a blind clear would
|
||||
* then wipe a target the pointer is actually over.
|
||||
*
|
||||
* @param KeyformTrackRef track The track the pointer left.
|
||||
*/
|
||||
fun exit(track: KeyformTrackRef) {
|
||||
if (hovered?.track == track) {
|
||||
hovered = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The shell's keyable-hover holder, or null outside a shell that provides one.
|
||||
*
|
||||
* Static because the holder instance never changes for a shell's lifetime; only its contents do.
|
||||
*/
|
||||
val LocalKeyableHover = staticCompositionLocalOf<KeyableHover?> { null }
|
||||
|
||||
/**
|
||||
* Publishes this composable as the keyable property under the pointer while it is hovered.
|
||||
*
|
||||
* Apply to any row that edits a keyform channel, and `I` will key it with no prior selection - the command
|
||||
* samples the hover when it fires. Uses hoverable / collectIsHoveredAsState rather than raw enter-exit
|
||||
* events so it behaves identically on desktop and on Android, where hover only exists with a stylus.
|
||||
*
|
||||
* Inert (returns the receiver unchanged) outside a shell that provides a holder, so a composable carrying
|
||||
* it stays usable in isolation - a preview, or a test harness.
|
||||
*
|
||||
* @param KeyableTarget target The property this row edits.
|
||||
* @return Modifier The modifier publishing the hover.
|
||||
*/
|
||||
@Composable
|
||||
fun Modifier.keyableTarget(target: KeyableTarget): Modifier = keyableTrack(KeyformTrackRef.Channel(target))
|
||||
|
||||
/**
|
||||
* Publishes this composable as the keyform TRACK under the pointer while it is hovered.
|
||||
*
|
||||
* The general form of [keyableTarget], for callers that can point at a geometry track as well as a
|
||||
* channel - the keyform sheet's rows.
|
||||
*
|
||||
* @param KeyformTrackRef track The track this row edits.
|
||||
* @return Modifier The modifier publishing the hover.
|
||||
*/
|
||||
@Composable
|
||||
fun Modifier.keyableTrack(track: KeyformTrackRef): Modifier {
|
||||
val hover = LocalKeyableHover.current ?: return this
|
||||
val interaction = remember { MutableInteractionSource() }
|
||||
val hovered by interaction.collectIsHoveredAsState()
|
||||
DisposableEffect(hover, track, hovered) {
|
||||
if (hovered) {
|
||||
hover.enter(KeyformHover(track))
|
||||
} else {
|
||||
hover.exit(track)
|
||||
}
|
||||
// Leaving composition mid-hover (the panel switching tabs under the pointer) must not strand the
|
||||
// target, or the next I would key a row that is no longer on screen.
|
||||
onDispose { hover.exit(track) }
|
||||
}
|
||||
return this.hoverable(interaction)
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package org.umamo.ui.model
|
||||
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import org.umamo.edit.Pose
|
||||
import org.umamo.runtime.keyform.keyIndexAt
|
||||
import org.umamo.runtime.model.ChannelValue
|
||||
import org.umamo.runtime.model.KeyableTarget
|
||||
import org.umamo.runtime.model.PuppetModel
|
||||
import org.umamo.runtime.model.channelGridsOf
|
||||
import org.umamo.ui.theme.UmamoColors
|
||||
|
||||
/*
|
||||
* The keyed state of one editable field, and the color that expresses it - Blender's keyframe tinting.
|
||||
*
|
||||
* What it communicates is not decoration: BetweenKeys says "edit here and it is lost unless you key it",
|
||||
* and ModifiedUnkeyed says "that is exactly what has happened". Without them, manual keying silently
|
||||
* discards work on the next scrub, which is the single biggest friction a Cubism migrant hits (Cubism
|
||||
* auto-keys, so the situation never arises there).
|
||||
*/
|
||||
|
||||
/** The keyed state of a field, in the order a rigger encounters them. */
|
||||
enum class KeyedFieldState {
|
||||
/** The channel carries no track at all; the field edits a plain static and behaves like any other. */
|
||||
None,
|
||||
|
||||
/** The channel is keyed and the pose sits exactly on one of its keys - editing writes that key. */
|
||||
OnKey,
|
||||
|
||||
/**
|
||||
* The channel is keyed but the pose is not sitting on one of its keys - an edit here needs an explicit
|
||||
* key to survive. What matters is the TRACK's own axes, not which parameter happens to be targeted:
|
||||
* targeting decides where an insert lands, the track decides whether the value is stored.
|
||||
*/
|
||||
BetweenKeys,
|
||||
|
||||
/** An edit has been made and not keyed; it is showing in the viewport and dies on the next scrub. */
|
||||
ModifiedUnkeyed,
|
||||
}
|
||||
|
||||
/**
|
||||
* The tint for this state, or null for [KeyedFieldState.None] (the field keeps its ordinary colors).
|
||||
*
|
||||
* @param UmamoColors colors The active scheme.
|
||||
* @return Color? The tint, or null when the field is not keyed.
|
||||
*/
|
||||
fun KeyedFieldState.tint(colors: UmamoColors): Color? =
|
||||
when (this) {
|
||||
KeyedFieldState.None -> null
|
||||
KeyedFieldState.OnKey -> colors.keyedOnKey
|
||||
KeyedFieldState.BetweenKeys -> colors.keyedBetween
|
||||
KeyedFieldState.ModifiedUnkeyed -> colors.keyedModified
|
||||
}
|
||||
|
||||
/**
|
||||
* The FILL for this state, or null for [KeyedFieldState.None] (the control keeps its ordinary background).
|
||||
*
|
||||
* A text control expresses its keyed state by tinting its whole background rather than by drawing an
|
||||
* outline: a 1px stroke on a 20dp field is a small thing to read across a column of rows, and the column is
|
||||
* how the state is actually used. Controls whose fill already MEANS something keep the outline instead -
|
||||
* a checkbox's fill is its checked state and a color swatch's fill is the user's own color, so neither has a
|
||||
* background to spend. The token is translucent, so the control's own hover fill still shows through.
|
||||
*
|
||||
* @param UmamoColors colors The active scheme.
|
||||
* @return Color? The fill, or null when the field is not keyed.
|
||||
*/
|
||||
fun KeyedFieldState.backgroundTint(colors: UmamoColors): Color? =
|
||||
when (this) {
|
||||
KeyedFieldState.None -> null
|
||||
KeyedFieldState.OnKey -> colors.keyedOnKeyBackground
|
||||
KeyedFieldState.BetweenKeys -> colors.keyedBetweenBackground
|
||||
KeyedFieldState.ModifiedUnkeyed -> colors.keyedModifiedBackground
|
||||
}
|
||||
|
||||
/**
|
||||
* The keyed state of [target] at [pose].
|
||||
*
|
||||
* The TRACK gates everything: a channel with no track stores an edit in its owner's static, which is a
|
||||
* plain undoable write with nothing uncommitted about it, so such a field is never tinted. It reads the
|
||||
* pending map on every channel while a field is being scrubbed (see previewChannelEdit), so testing that
|
||||
* map before the track gate would paint the orange uncommitted warning across every ordinary drag.
|
||||
*
|
||||
* Past that gate ModifiedUnkeyed wins over the others: a pending edit is the most recent thing the user
|
||||
* did, and it is the state that carries a warning.
|
||||
*
|
||||
* On-key is resolved against the track's OWN axes rather than against whatever parameter is targeted, and
|
||||
* that distinction is the whole difference between the tint answering "is the value under this field
|
||||
* stored" and answering "is it stored on the axis you happen to have clicked". Only the first is what a
|
||||
* rigger reads it as; the second would paint a keyed opacity as unstored whenever the target was the other
|
||||
* half of a linked pad - or nothing at all. A multi-axis track is on-key only when the pose sits on a key
|
||||
* of EVERY axis, because that is exactly when a capture overwrites a cell instead of inserting one. The
|
||||
* comparison uses the evaluator's own EPS_KEY snap tolerance rather than an exact compare, so the tint
|
||||
* agrees with the key the pose actually resolved to instead of flickering a hair either side of one.
|
||||
*
|
||||
* @param PuppetModel puppet The rig.
|
||||
* @param KeyableTarget target The entity and channel the field edits.
|
||||
* @param Pose pose The current pose.
|
||||
* @param Map pendingEdits The session's unkeyed edits.
|
||||
* @return KeyedFieldState The state to tint with.
|
||||
*/
|
||||
fun keyedFieldStateOf(
|
||||
puppet: PuppetModel,
|
||||
target: KeyableTarget,
|
||||
pose: Pose,
|
||||
pendingEdits: Map<KeyableTarget, ChannelValue>,
|
||||
): KeyedFieldState {
|
||||
val track = puppet.channelGridsOf(target.owner)?.get(target.channel) ?: return KeyedFieldState.None
|
||||
if (target in pendingEdits) {
|
||||
return KeyedFieldState.ModifiedUnkeyed
|
||||
}
|
||||
// A zero-axis track holds one value everywhere and keys nothing, so there is no key to be sitting on -
|
||||
// but it still shadows the static, so an edit still needs keying. That is BetweenKeys, not OnKey.
|
||||
if (track.axes.isEmpty()) {
|
||||
return KeyedFieldState.BetweenKeys
|
||||
}
|
||||
val onEveryAxis =
|
||||
track.axes.all { axis ->
|
||||
// A direct lookup, not a defaults map over every parameter: this runs per keyable row per
|
||||
// recomposition, and only this track's own parameters can ever be read.
|
||||
val poseValue =
|
||||
pose[axis.parameterId]
|
||||
?: puppet.parameters.firstOrNull { parameter -> parameter.id == axis.parameterId }?.default
|
||||
?: 0f
|
||||
track.keyIndexAt(axis.parameterId, poseValue) >= 0
|
||||
}
|
||||
return if (onEveryAxis) KeyedFieldState.OnKey else KeyedFieldState.BetweenKeys
|
||||
}
|
||||
@@ -0,0 +1,677 @@
|
||||
package org.umamo.ui.model
|
||||
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.umamo.edit.AdjustableOperation
|
||||
import org.umamo.edit.DocumentChange
|
||||
import org.umamo.edit.NoticePlacement
|
||||
import org.umamo.edit.OperatorParameter
|
||||
import org.umamo.edit.ParameterUnit
|
||||
import org.umamo.edit.commitArtworkMatched
|
||||
import org.umamo.edit.commitArtworkReplaced
|
||||
import org.umamo.edit.floatValue
|
||||
import org.umamo.edit.withArtworkReloaded
|
||||
import org.umamo.format.art.LayerRaster
|
||||
import org.umamo.format.art.SourceArt
|
||||
import org.umamo.format.art.SourceLayerKind
|
||||
import org.umamo.interop.art.ArtSourceDescriptor
|
||||
import org.umamo.interop.art.SourceArtImport
|
||||
import org.umamo.interop.art.SourceArtImportNotice
|
||||
import org.umamo.interop.art.SourceArtImportOptions
|
||||
import org.umamo.reimport.ArtworkReloadPlanner
|
||||
import org.umamo.reimport.InventoryLayerMatcher
|
||||
import org.umamo.reimport.LayerMatch
|
||||
import org.umamo.reimport.ReconcileResult
|
||||
import org.umamo.reimport.confidentMatches
|
||||
import org.umamo.reimport.retirableTiles
|
||||
import org.umamo.reimport.suggestionsAgainstRead
|
||||
import org.umamo.render.DecodedImage
|
||||
import org.umamo.render.PuppetTextures
|
||||
import org.umamo.render.SourceArtRasters
|
||||
import org.umamo.runtime.model.ArtSourceId
|
||||
import org.umamo.runtime.model.ArtSourceLayer
|
||||
import org.umamo.runtime.model.AtlasTileId
|
||||
import org.umamo.runtime.model.DrawableId
|
||||
import org.umamo.runtime.model.PuppetModel
|
||||
import org.umamo.storage.UmamoLog
|
||||
|
||||
/*
|
||||
* Match Automatically and Replace Artwork: the two operations that resolve a binding the file no
|
||||
* longer carries a key for. Match scores every such binding against the file's unbound layers (and
|
||||
* the layers bound only to fresh, untouched drawables, which a match then retires) and rebinds the
|
||||
* confident ones, with the threshold on the operation strip so the same read files re-score at another
|
||||
* bar; Replace repoints one record at another file, reloading what the new file resolves by key,
|
||||
* rebinding what the matcher is confident about at the same threshold row, and leaving the rest for
|
||||
* review. Both pack, commit, and register exactly as a reload does, and both publish the suggestions
|
||||
* they could not apply, scored with the pixels they read, for the Sources space's review chips.
|
||||
*/
|
||||
|
||||
/** The strip row keys the match operation reads its values back by. */
|
||||
internal object MatchParameterKeys {
|
||||
const val THRESHOLD = "match.threshold"
|
||||
}
|
||||
|
||||
/**
|
||||
* Every unresolved binding's best candidate as the flows publish it, keyed by file and lost key.
|
||||
*/
|
||||
typealias SourceSuggestions = Map<Pair<ArtSourceId, String>, LayerMatch>
|
||||
|
||||
/**
|
||||
* The files Match Automatically scores, as read, with the decoded wrapper of every layer raster
|
||||
* minted once so a re-score hands the raster store the same instances.
|
||||
*
|
||||
* @property List entries The present files, each with its art.
|
||||
* @property Float threshold The confidence at or above which a match is applied, 0..1.
|
||||
* @property SourceArtImportOptions options The threshold and margin every re-born quad uses.
|
||||
* @property SourceSuggestions standing The proposals published for the review chips as they
|
||||
* stand: a lost binding the read files offer no unbound candidate for falls back to its standing
|
||||
* proposal when that names a layer bound only to fresh, untouched drawables (a reload minted them
|
||||
* for the re-created layer), and taking it retires those drawables - so a Match after a reload
|
||||
* merges at the bar the way Accept on the row does.
|
||||
*/
|
||||
class MatchArtworkRequest(
|
||||
val entries: List<ReloadEntry>,
|
||||
val threshold: Float,
|
||||
val options: SourceArtImportOptions,
|
||||
val standing: SourceSuggestions = emptyMap(),
|
||||
) {
|
||||
private val decoded = DecodedLayerRasters(entries.flatMap { entry -> entry.art.layers })
|
||||
|
||||
/**
|
||||
* The decoded wrapper of one of the files' layer rasters.
|
||||
*
|
||||
* @param LayerRaster raster The layer's pixels.
|
||||
* @return DecodedImage The wrapper, the same instance on every call.
|
||||
*/
|
||||
internal fun decodedFor(raster: LayerRaster): DecodedImage = decoded.decodedFor(raster)
|
||||
}
|
||||
|
||||
/**
|
||||
* One record to repoint, with the new file as read.
|
||||
*
|
||||
* @property ArtSourceId sourceId The record being repointed.
|
||||
* @property SourceArt art The new file as read.
|
||||
* @property ArtSourceDescriptor descriptor The new file's name, path, and format.
|
||||
* @property String? contentHash The whole-file content hash of the bytes [art] came from.
|
||||
* @property SourceArtImportOptions options The threshold and margin a re-born quad uses.
|
||||
* @property Float threshold The confidence, 0..1, at or above which a binding the new
|
||||
* file does not resolve by key takes its best candidate among the file's layers in the same step.
|
||||
*/
|
||||
class ReplaceArtworkRequest(
|
||||
val sourceId: ArtSourceId,
|
||||
val art: SourceArt,
|
||||
val descriptor: ArtSourceDescriptor,
|
||||
val contentHash: String?,
|
||||
val options: SourceArtImportOptions,
|
||||
val threshold: Float = InventoryLayerMatcher.DEFAULT_THRESHOLD,
|
||||
) {
|
||||
private val decoded = DecodedLayerRasters(art.layers)
|
||||
|
||||
/**
|
||||
* The inventory of [art], computed once for the request's life: the planner, the scorer, and every
|
||||
* strip adjustment over this read want the same rows.
|
||||
*/
|
||||
val inventory: List<ArtSourceLayer> by lazy { SourceArtImport.inventoryOf(art) }
|
||||
|
||||
/**
|
||||
* The decoded wrapper of one of the file's layer rasters.
|
||||
*
|
||||
* @param LayerRaster raster The layer's pixels.
|
||||
* @return DecodedImage The wrapper, the same instance on every call.
|
||||
*/
|
||||
internal fun decodedFor(raster: LayerRaster): DecodedImage = decoded.decodedFor(raster)
|
||||
}
|
||||
|
||||
/** What one match or replace pass produced, or why it produced nothing. */
|
||||
private sealed interface MatchOutcome {
|
||||
/**
|
||||
* Nothing was rebound; the suggestions still stand for the review chips.
|
||||
*
|
||||
* @property SourceSuggestions suggestions The best candidate per unresolved binding.
|
||||
*/
|
||||
class NothingApplied(val suggestions: SourceSuggestions) : MatchOutcome
|
||||
|
||||
/**
|
||||
* The pack could not keep some of the document's own art where it is; nothing was applied.
|
||||
*
|
||||
* @property List refusals The document's tiles the pack could not keep.
|
||||
*/
|
||||
class Refused(val refusals: List<AtlasRepackRefusal>) : MatchOutcome
|
||||
|
||||
/**
|
||||
* The delta applied and packed.
|
||||
*
|
||||
* @property PuppetModel model The base with the delta applied and packed.
|
||||
* @property PuppetTextures? textures The pages the pack composed, index-parallel to the model's, or
|
||||
* null when nothing was packed and the pages stand as they are.
|
||||
* @property Map decodedByTile The new tiles' pixels, for the raster store.
|
||||
* @property List notices The planner's notes plus every new tile the pack left unplaced.
|
||||
* @property List outgrown Drawables whose kept mesh no longer covers the new art.
|
||||
* @property DocumentChange change The step's counts.
|
||||
* @property SourceSuggestions suggestions The best candidate per binding still unresolved.
|
||||
* @property List rebindings What the matcher rebound and retired, for the log.
|
||||
*/
|
||||
class Applied(
|
||||
val model: PuppetModel,
|
||||
val textures: PuppetTextures?,
|
||||
val decodedByTile: Map<AtlasTileId, DecodedImage>,
|
||||
val notices: List<SourceArtImportNotice>,
|
||||
val outgrown: List<DrawableId>,
|
||||
val change: DocumentChange,
|
||||
val suggestions: SourceSuggestions,
|
||||
val rebindings: List<Rebinding>,
|
||||
) : MatchOutcome
|
||||
}
|
||||
|
||||
/**
|
||||
* The strip rows a match registers: the threshold as a percentage beside the import rows.
|
||||
*
|
||||
* @param Float threshold The confidence bar, 0..1.
|
||||
* @param SourceArtImportOptions options The import options the rows carry.
|
||||
* @return List<OperatorParameter> The rows.
|
||||
*/
|
||||
internal fun matchArtworkParameters(threshold: Float, options: SourceArtImportOptions): List<OperatorParameter> =
|
||||
listOf(OperatorParameter.FloatParameter(MatchParameterKeys.THRESHOLD, MatchParameterKeys.THRESHOLD, threshold * 100f, 0f, 100f, step = 5f, unit = ParameterUnit.Percent)) +
|
||||
addArtworkParameters(options, placed = false)
|
||||
|
||||
/**
|
||||
* The threshold [parameters] describe, as a fraction.
|
||||
*
|
||||
* @param List parameters The strip's rows.
|
||||
* @param Float fallback The threshold the first run used.
|
||||
* @return Float The adjusted threshold, 0..1.
|
||||
*/
|
||||
internal fun matchThresholdOf(parameters: List<OperatorParameter>, fallback: Float): Float =
|
||||
(parameters.floatValue(MatchParameterKeys.THRESHOLD, fallback * 100f) / 100f).coerceIn(0f, 1f)
|
||||
|
||||
/**
|
||||
* The document's pixels for a tile as the matcher and planner read them.
|
||||
*
|
||||
* @param SourceArtRasters artRasters The document's raster store.
|
||||
* @return Function The lookup, null for a tile the store cannot decode.
|
||||
*/
|
||||
private fun tileRasterLookup(artRasters: SourceArtRasters): (AtlasTileId) -> LayerRaster? =
|
||||
{ tileId -> artRasters.decodeRaster(tileId)?.let { decoded -> LayerRaster(decoded.width, decoded.height, decoded.rgba) } }
|
||||
|
||||
/**
|
||||
* Scores [sourceId]'s unresolved bindings against [art]: the model's inventory refreshed against the
|
||||
* read art (so a file never reloaded still scores), the tiles' pixels and the art's layers handed
|
||||
* to the matcher - the one scorer the reload planner runs before it mints.
|
||||
*
|
||||
* @param PuppetModel model The model as it stands.
|
||||
* @param ArtSourceId sourceId The file.
|
||||
* @param SourceArt art The file as read.
|
||||
* @param List<ArtSourceLayer> inventory The inventory of [art], computed once by the read.
|
||||
* @param Function tileRaster The document's pixels for a tile.
|
||||
* @return Map<String, LayerMatch> Each unresolved binding's best candidate, by its lost key.
|
||||
*/
|
||||
private fun scoreSource(
|
||||
model: PuppetModel,
|
||||
sourceId: ArtSourceId,
|
||||
art: SourceArt,
|
||||
inventory: List<ArtSourceLayer>,
|
||||
tileRaster: (AtlasTileId) -> LayerRaster?,
|
||||
): Map<String, LayerMatch> {
|
||||
val rasterByKey = art.layers.filter { layer -> layer.kind == SourceLayerKind.Raster }.associate { layer -> layer.id.raw to layer.raster }
|
||||
return suggestionsAgainstRead(model, sourceId, inventory, tileRaster, { key -> rasterByKey[key] }, InventoryLayerMatcher)
|
||||
}
|
||||
|
||||
/**
|
||||
* Scores the unresolved bindings of every file in [entries] against its art as read, with the tiles'
|
||||
* pixels from the store: what a reload publishes for the review chips once it has landed.
|
||||
*
|
||||
* @param AtlasRepackHost host The session and the raster store.
|
||||
* @param List<ReloadEntry> entries The files as read.
|
||||
* @return SourceSuggestions Each unresolved binding's best candidate, by file and lost key.
|
||||
*/
|
||||
suspend fun scoreSourceSuggestions(host: AtlasRepackHost, entries: List<ReloadEntry>): SourceSuggestions =
|
||||
withContext(Dispatchers.Default) {
|
||||
val model = host.session.model.value
|
||||
val tileRaster = tileRasterLookup(host.artRasters)
|
||||
val suggestions = LinkedHashMap<Pair<ArtSourceId, String>, LayerMatch>()
|
||||
for (entry in entries) {
|
||||
for ((lostKey, match) in scoreSource(model, entry.sourceId, entry.art, entry.inventory, tileRaster)) {
|
||||
suggestions[entry.sourceId to lostKey] = match
|
||||
}
|
||||
}
|
||||
suggestions
|
||||
}
|
||||
|
||||
/**
|
||||
* Scores every file in [request] against [base], rebinds the confident matches, and packs the tiles
|
||||
* they replaced around the rest.
|
||||
*
|
||||
* @param PuppetModel base The model the match applies to.
|
||||
* @param MatchArtworkRequest request The files as read.
|
||||
* @param Float threshold The confidence bar, 0..1.
|
||||
* @param SourceArtImportOptions options The threshold and margin to plan with.
|
||||
* @param SourceArtRasters artRasters The document's raster store (read, never written here).
|
||||
* @param Boolean premultipliedAlpha The document's texture-convention flag.
|
||||
* @return MatchOutcome The outcome.
|
||||
*/
|
||||
private fun matchOutcome(
|
||||
base: PuppetModel,
|
||||
request: MatchArtworkRequest,
|
||||
threshold: Float,
|
||||
options: SourceArtImportOptions,
|
||||
artRasters: SourceArtRasters,
|
||||
premultipliedAlpha: Boolean,
|
||||
): MatchOutcome {
|
||||
var model = base
|
||||
val rasters = LinkedHashMap<AtlasTileId, LayerRaster>()
|
||||
val notices = ArrayList<SourceArtImportNotice>()
|
||||
val outgrown = ArrayList<DrawableId>()
|
||||
val remaining = LinkedHashMap<Pair<ArtSourceId, String>, LayerMatch>()
|
||||
val rebindings = ArrayList<Rebinding>()
|
||||
var matched = 0
|
||||
val tileRaster = tileRasterLookup(artRasters)
|
||||
for (entry in request.entries) {
|
||||
val suggestions = LinkedHashMap(scoreSource(model, entry.sourceId, entry.art, entry.inventory, tileRaster))
|
||||
val retirable = standingMerges(model, entry, request.standing, suggestions)
|
||||
val acceptedByLostKey = confidentMatches(suggestions, threshold)
|
||||
for ((lostKey, match) in suggestions) {
|
||||
if (lostKey !in acceptedByLostKey) {
|
||||
remaining[entry.sourceId to lostKey] = match
|
||||
}
|
||||
}
|
||||
if (acceptedByLostKey.isEmpty()) {
|
||||
continue
|
||||
}
|
||||
// Every tile bound to an accepted lost key moves with it.
|
||||
val accepted =
|
||||
model.atlas.tiles.mapNotNull { tile ->
|
||||
val binding = tile.source?.takeIf { source -> source.sourceId == entry.sourceId } ?: return@mapNotNull null
|
||||
acceptedByLostKey[binding.layerKey]?.let { candidateKey -> tile.id to candidateKey }
|
||||
}
|
||||
val retire = acceptedByLostKey.values.flatMapTo(HashSet()) { candidateKey -> retirable[candidateKey].orEmpty() }
|
||||
val plan =
|
||||
ArtworkReloadPlanner.planMatches(model, entry.sourceId, entry.art, accepted, options, tileRaster, entry.contentHash, inventory = entry.inventory, lastModified = entry.lastModified, retire = retire)
|
||||
?: continue
|
||||
val next = model.withArtworkReloaded(plan.reload)
|
||||
if (next === model) {
|
||||
UmamoLog.error("match artwork: the plan for '${plan.reload.source.name}' collides with the document's ids; that file was skipped")
|
||||
continue
|
||||
}
|
||||
// The rebound tiles are the ones the plan replaced; the log names them from the model before.
|
||||
rebindings.addAll(
|
||||
accepted.mapNotNull { (tileId, key) ->
|
||||
val tile = model.atlas.tileById[tileId] ?: return@mapNotNull null
|
||||
val score = tile.source?.layerKey?.let { lostKey -> suggestions[lostKey]?.score } ?: return@mapNotNull null
|
||||
Rebinding.Rebound(tile.name, entry.art.layers.firstOrNull { layer -> layer.id.raw == key }?.name ?: key, score)
|
||||
},
|
||||
)
|
||||
rebindings.addAll(rebindingsOf(plan, model, entry.art).filterIsInstance<Rebinding.Retired>())
|
||||
model = next
|
||||
rasters.putAll(plan.rasterByTile)
|
||||
notices.addAll(plan.notices)
|
||||
outgrown.addAll(plan.reload.outgrown)
|
||||
matched += plan.reload.replacedTiles.size
|
||||
}
|
||||
if (model === base) {
|
||||
return MatchOutcome.NothingApplied(remaining)
|
||||
}
|
||||
val change = DocumentChange.MatchArtwork(matched, remaining.size)
|
||||
return packMatched(model, rasters.mapValues { (_, raster) -> request.decodedFor(raster) }, notices, artRasters, premultipliedAlpha) { packedModel, textures, packedNotices, decodedByTile ->
|
||||
MatchOutcome.Applied(packedModel, textures, decodedByTile, packedNotices, outgrown, change, remaining, rebindings)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The standing proposals that still hold for [entry]'s file, folded into [suggestions] where the read
|
||||
* offered no unbound candidate: the lost key must still be bound, the proposed layer must be present
|
||||
* and bound only to tiles that carry no rig work, and those tiles are what taking the proposal retires.
|
||||
*
|
||||
* @param PuppetModel model The model as it stands.
|
||||
* @param ReloadEntry entry The file as read.
|
||||
* @param SourceSuggestions standing The published proposals.
|
||||
* @param MutableMap suggestions The scored proposals, added to in place.
|
||||
* @return Map<String, List<AtlasTileId>> The tiles to retire per proposed layer key.
|
||||
*/
|
||||
private fun standingMerges(model: PuppetModel, entry: ReloadEntry, standing: SourceSuggestions, suggestions: MutableMap<String, LayerMatch>): Map<String, List<AtlasTileId>> {
|
||||
val retirable = HashMap<String, List<AtlasTileId>>()
|
||||
val boundKeys = model.atlas.tiles.filter { tile -> tile.source?.sourceId == entry.sourceId }.mapNotNullTo(HashSet()) { tile -> tile.source?.layerKey }
|
||||
for ((binding, match) in standing) {
|
||||
val (sourceId, lostKey) = binding
|
||||
if (sourceId != entry.sourceId || lostKey in suggestions || lostKey !in boundKeys || match.key !in boundKeys) {
|
||||
continue
|
||||
}
|
||||
if (entry.inventory.none { row -> row.key == match.key && !row.empty }) {
|
||||
continue
|
||||
}
|
||||
val tiles = model.atlas.tiles.filter { tile -> tile.source?.sourceId == sourceId && tile.source?.layerKey == match.key }.map { tile -> tile.id }
|
||||
val retiring = retirableTiles(model, sourceId, match.key, except = emptySet())
|
||||
if (retiring.size != tiles.size) {
|
||||
// Rig work sits over the proposed layer now: the proposal no longer holds.
|
||||
continue
|
||||
}
|
||||
suggestions[lostKey] = match
|
||||
retirable[match.key] = retiring
|
||||
}
|
||||
return retirable
|
||||
}
|
||||
|
||||
/**
|
||||
* Repoints [request]'s record at its new file over [base]: the bindings the file resolves by key
|
||||
* reload, the confident matches rebind, the rest are flagged, and the still-unresolved ones are
|
||||
* scored against the file's layers.
|
||||
*
|
||||
* @param PuppetModel base The model the replacement applies to.
|
||||
* @param ReplaceArtworkRequest request The record and the new file.
|
||||
* @param SourceArtImportOptions options The threshold and margin to plan with.
|
||||
* @param Float threshold The bar a binding's best candidate must reach.
|
||||
* @param SourceArtRasters artRasters The document's raster store.
|
||||
* @param Boolean premultipliedAlpha The document's texture-convention flag.
|
||||
* @return MatchOutcome The outcome.
|
||||
*/
|
||||
private fun replaceOutcome(
|
||||
base: PuppetModel,
|
||||
request: ReplaceArtworkRequest,
|
||||
options: SourceArtImportOptions,
|
||||
threshold: Float,
|
||||
artRasters: SourceArtRasters,
|
||||
premultipliedAlpha: Boolean,
|
||||
): MatchOutcome {
|
||||
val tileRaster = tileRasterLookup(artRasters)
|
||||
val plan =
|
||||
ArtworkReloadPlanner.plan(base, request.sourceId, request.art, options, tileRaster, request.contentHash, replacement = request.descriptor, inventory = request.inventory, matchThreshold = threshold)
|
||||
?: return MatchOutcome.NothingApplied(emptyMap())
|
||||
val model = base.withArtworkReloaded(plan.reload)
|
||||
if (model === base) {
|
||||
UmamoLog.error("replace artwork: the plan for '${request.descriptor.name}' collides with the document's ids; nothing was applied")
|
||||
return MatchOutcome.NothingApplied(emptyMap())
|
||||
}
|
||||
val suggestions = plan.leftovers.entries.associate { (lostKey, match) -> (request.sourceId to lostKey) to match }
|
||||
val resolvedByKey = plan.report.results.count { result -> result is ReconcileResult.Matched }
|
||||
val rebound = plan.report.results.count { result -> result is ReconcileResult.Rebound }
|
||||
val change = DocumentChange.ReplaceArtwork(request.descriptor.name, resolvedByKey, rebound, plan.report.needsReview.size)
|
||||
val rebindings = rebindingsOf(plan, base, request.art)
|
||||
return packMatched(model, plan.rasterByTile.mapValues { (_, raster) -> request.decodedFor(raster) }, plan.notices, artRasters, premultipliedAlpha) { packedModel, textures, notices, decodedByTile ->
|
||||
MatchOutcome.Applied(packedModel, textures, decodedByTile, notices, plan.reload.outgrown, change, suggestions, rebindings)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Packs the tiles a match or replace minted around the document's art and builds the outcome.
|
||||
*
|
||||
* @param PuppetModel model The model with the delta applied.
|
||||
* @param Map decodedByTile The new tiles' pixels.
|
||||
* @param List notices The notes so far.
|
||||
* @param SourceArtRasters artRasters The document's raster store, for every other tile.
|
||||
* @param Boolean premultipliedAlpha The document's texture-convention flag.
|
||||
* @param Function applied Builds the success outcome from the packed model.
|
||||
* @return MatchOutcome The outcome, refused when the document's own art could not be kept.
|
||||
*/
|
||||
private inline fun packMatched(
|
||||
model: PuppetModel,
|
||||
decodedByTile: Map<AtlasTileId, DecodedImage>,
|
||||
notices: List<SourceArtImportNotice>,
|
||||
artRasters: SourceArtRasters,
|
||||
premultipliedAlpha: Boolean,
|
||||
applied: (PuppetModel, PuppetTextures?, List<SourceArtImportNotice>, Map<AtlasTileId, DecodedImage>) -> MatchOutcome,
|
||||
): MatchOutcome {
|
||||
if (decodedByTile.isEmpty()) {
|
||||
// A replacement that resolved nothing by key mints no tile: the record and the flags land as they are.
|
||||
return applied(model, null, notices, decodedByTile)
|
||||
}
|
||||
val decode: (AtlasTileId) -> DecodedImage? = { tileId -> decodedByTile[tileId] ?: artRasters.decodeRaster(tileId) }
|
||||
return when (val packed = packNewTilesAround(model, decodedByTile.keys, decode, premultipliedAlpha, notices)) {
|
||||
is PackAroundOutcome.Refused -> MatchOutcome.Refused(packed.refusals)
|
||||
is PackAroundOutcome.Packed -> applied(packed.model, packed.textures, packed.notices, decodedByTile)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Matches the document's unresolved bindings to the layers the matcher is confident about as ONE
|
||||
* undo step, registers it on the strip with the threshold row beside the import rows, and publishes
|
||||
* the suggestions it did not apply. Nothing confident enough is a notice, not a step, and the
|
||||
* suggestions are published all the same.
|
||||
*
|
||||
* Runs on the UI thread; the scoring, planning, and pack hop to the default dispatcher. Planned
|
||||
* against the model current at the start, so any edit landing meanwhile supersedes it.
|
||||
*
|
||||
* @param AtlasRepackHost host The session, art, resolver, scope, and shell callbacks.
|
||||
* @param MatchArtworkRequest request The files as read and the threshold.
|
||||
* @param String? areaId The area the strip shows in, or null.
|
||||
* @param Function publish Takes the suggestions for the review chips.
|
||||
* @return Boolean Whether a step landed.
|
||||
*/
|
||||
suspend fun runMatchArtwork(host: AtlasRepackHost, request: MatchArtworkRequest, areaId: String?, publish: (SourceSuggestions) -> Unit): Boolean {
|
||||
val session = host.session
|
||||
val modelAtStart = session.model.value
|
||||
val outcome =
|
||||
withContext(Dispatchers.Default) {
|
||||
matchOutcome(modelAtStart, request, request.threshold, request.options, host.artRasters, host.premultipliedAlpha)
|
||||
}
|
||||
if (!landMatch(host, "match artwork", modelAtStart, outcome, publish) { model -> session.commitArtworkMatched(outcome.appliedChange<DocumentChange.MatchArtwork>(), model) }) {
|
||||
if (outcome is MatchOutcome.NothingApplied) {
|
||||
UmamoLog.info("match artwork: no binding scored at or above ${percentOf(request.threshold)}% across ${request.entries.size} file(s); ${outcome.suggestions.size} suggestion(s) published")
|
||||
// No suggestion at all means no candidate was left to score - every layer is bound to rig
|
||||
// work - which is a different thing to tell a person than a bar nothing reached.
|
||||
session.emitNotice(if (outcome.suggestions.isEmpty()) "notice.match.noCandidates" else "notice.match.nothing", NoticePlacement.StatusBar)
|
||||
}
|
||||
return false
|
||||
}
|
||||
val change = (outcome as MatchOutcome.Applied).change as DocumentChange.MatchArtwork
|
||||
session.emitNotice("notice.match.done", NoticePlacement.StatusBar, listOf(change.matchedCount.toString(), change.remainingCount.toString()))
|
||||
session.registerAdjustableOperation(session.model.value, areaId, matchArtworkParameters(request.threshold, request.options)) { record ->
|
||||
host.scope.launch { adjustMatchArtwork(host, record, request, publish) }
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-scores the match for an adjustment of the strip: the record's threshold and import rows over the
|
||||
* record's base model with the SAME read files, landed over the operation's own step.
|
||||
*
|
||||
* @param AtlasRepackHost host The session, resolver, and shell callbacks the first run had.
|
||||
* @param AdjustableOperation record The record with the adjusted parameters.
|
||||
* @param MatchArtworkRequest request The first run's files.
|
||||
* @param Function publish Takes the suggestions for the review chips.
|
||||
*/
|
||||
internal suspend fun adjustMatchArtwork(host: AtlasRepackHost, record: AdjustableOperation, request: MatchArtworkRequest, publish: (SourceSuggestions) -> Unit) {
|
||||
adjustMatch(host, record, "match artwork", publish) { base, parameters ->
|
||||
val threshold = matchThresholdOf(parameters, request.threshold)
|
||||
val options = addArtworkOptionsOf(parameters, request.options)
|
||||
matchOutcome(base, request, threshold, options, host.artRasters, host.premultipliedAlpha)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lands an adjustment of a match or replace step: [compute] runs over the record's base with the
|
||||
* record's parameters, and the result replaces the operation's own step.
|
||||
*
|
||||
* A pass that applies nothing under the new parameters amends the step back to the base and publishes
|
||||
* its suggestions - a threshold raised past every match must take the earlier rebindings with it, or
|
||||
* the strip would show one bar and the document another. A pass the pack refuses is reported and
|
||||
* leaves the step as it was, and a record cleared while the pass ran makes
|
||||
* [org.umamo.edit.EditorSession.amendLastCommit] drop the result.
|
||||
*
|
||||
* @param AtlasRepackHost host The session, resolver, and shell callbacks the first run had.
|
||||
* @param AdjustableOperation record The record with the adjusted parameters.
|
||||
* @param String operation The log prefix.
|
||||
* @param Function publish Takes the suggestions for the review chips.
|
||||
* @param Function compute The pass over the base model and the record's parameters.
|
||||
*/
|
||||
private suspend fun adjustMatch(
|
||||
host: AtlasRepackHost,
|
||||
record: AdjustableOperation,
|
||||
operation: String,
|
||||
publish: (SourceSuggestions) -> Unit,
|
||||
compute: (PuppetModel, List<OperatorParameter>) -> MatchOutcome,
|
||||
) {
|
||||
val base = record.baseSnapshot.model
|
||||
val outcome = withContext(Dispatchers.Default) { compute(base, record.parameters) }
|
||||
when (outcome) {
|
||||
is MatchOutcome.NothingApplied -> {
|
||||
if (!host.session.amendLastCommit(record, base)) {
|
||||
UmamoLog.info("$operation: the adjustment was superseded before it landed; nothing was applied")
|
||||
return
|
||||
}
|
||||
UmamoLog.info("$operation: under the adjusted settings nothing applies; the step now holds the document as it was, with ${outcome.suggestions.size} suggestion(s) published")
|
||||
publish(outcome.suggestions)
|
||||
}
|
||||
is MatchOutcome.Refused -> host.report(AtlasRepackReport(outcome.refusals))
|
||||
is MatchOutcome.Applied -> {
|
||||
host.artRasters.addDecoded(outcome.decodedByTile)
|
||||
prewarm(host, outcome.model, outcome.textures)
|
||||
if (!host.session.amendLastCommit(record, outcome.model)) {
|
||||
UmamoLog.info("$operation: the adjustment was superseded before it landed; nothing was applied")
|
||||
return
|
||||
}
|
||||
publish(outcome.suggestions)
|
||||
reportMatch(operation, outcome, outcome.model)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Repoints one artwork record at another file as ONE undo step, registered on the strip with the
|
||||
* threshold row ahead of the import rows, and publishes the suggestions for whatever the new file
|
||||
* resolved neither by key nor by a confident match.
|
||||
*
|
||||
* @param AtlasRepackHost host The session, art, resolver, scope, and shell callbacks.
|
||||
* @param ReplaceArtworkRequest request The record and the new file.
|
||||
* @param String? areaId The area the strip shows in, or null.
|
||||
* @param Function publish Takes the suggestions for the review chips.
|
||||
* @return Boolean Whether the step landed.
|
||||
*/
|
||||
suspend fun runReplaceArtwork(host: AtlasRepackHost, request: ReplaceArtworkRequest, areaId: String?, publish: (SourceSuggestions) -> Unit): Boolean {
|
||||
val session = host.session
|
||||
val modelAtStart = session.model.value
|
||||
val outcome =
|
||||
withContext(Dispatchers.Default) {
|
||||
replaceOutcome(modelAtStart, request, request.options, request.threshold, host.artRasters, host.premultipliedAlpha)
|
||||
}
|
||||
if (!landMatch(host, "replace artwork", modelAtStart, outcome, publish) { model -> session.commitArtworkReplaced(outcome.appliedChange<DocumentChange.ReplaceArtwork>(), model) }) {
|
||||
return false
|
||||
}
|
||||
val change = (outcome as MatchOutcome.Applied).change as DocumentChange.ReplaceArtwork
|
||||
session.emitNotice("notice.replace.done", NoticePlacement.StatusBar, listOf(change.matchedCount.toString(), change.reboundCount.toString(), change.missingCount.toString()))
|
||||
session.registerAdjustableOperation(session.model.value, areaId, matchArtworkParameters(request.threshold, request.options)) { record ->
|
||||
host.scope.launch { adjustReplaceArtwork(host, record, request, publish) }
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-plans a replacement for an adjustment of the strip over the record's base.
|
||||
*
|
||||
* @param AtlasRepackHost host The session, resolver, and shell callbacks the first run had.
|
||||
* @param AdjustableOperation record The record with the adjusted parameters.
|
||||
* @param ReplaceArtworkRequest request The first run's request.
|
||||
* @param Function publish Takes the suggestions for the review chips.
|
||||
*/
|
||||
internal suspend fun adjustReplaceArtwork(host: AtlasRepackHost, record: AdjustableOperation, request: ReplaceArtworkRequest, publish: (SourceSuggestions) -> Unit) {
|
||||
adjustMatch(host, record, "replace artwork", publish) { base, parameters ->
|
||||
replaceOutcome(base, request, addArtworkOptionsOf(parameters, request.options), matchThresholdOf(parameters, request.threshold), host.artRasters, host.premultipliedAlpha)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The applied outcome's change as the type the commit expects.
|
||||
*
|
||||
* @return TChange The change.
|
||||
*/
|
||||
private inline fun <reified TChange : DocumentChange> MatchOutcome.appliedChange(): TChange = (this as MatchOutcome.Applied).change as TChange
|
||||
|
||||
/**
|
||||
* Lands a match or replace outcome: the supersede check, the rasters into the store, the commit, the
|
||||
* pre-warm, the log, and the suggestions published. A pass that applied nothing publishes its
|
||||
* suggestions and returns false without a step.
|
||||
*
|
||||
* @param AtlasRepackHost host The session, art, resolver, and shell callbacks.
|
||||
* @param String operation The log prefix.
|
||||
* @param PuppetModel modelAtStart The model the outcome was planned against.
|
||||
* @param MatchOutcome outcome What the pass produced.
|
||||
* @param Function publish Takes the suggestions for the review chips.
|
||||
* @param Function commit Commits the packed model and returns the committed one.
|
||||
* @return Boolean Whether a step landed.
|
||||
*/
|
||||
private inline fun landMatch(
|
||||
host: AtlasRepackHost,
|
||||
operation: String,
|
||||
modelAtStart: PuppetModel,
|
||||
outcome: MatchOutcome,
|
||||
publish: (SourceSuggestions) -> Unit,
|
||||
commit: (PuppetModel) -> PuppetModel,
|
||||
): Boolean {
|
||||
val session = host.session
|
||||
when (outcome) {
|
||||
is MatchOutcome.NothingApplied -> {
|
||||
publish(outcome.suggestions)
|
||||
return false
|
||||
}
|
||||
is MatchOutcome.Refused -> {
|
||||
for (refusal in outcome.refusals) {
|
||||
UmamoLog.warn("$operation: the document's tile '${refusal.tileName}' could not be kept in place (${refusal.reason}); nothing was applied")
|
||||
}
|
||||
host.report(AtlasRepackReport(outcome.refusals))
|
||||
return false
|
||||
}
|
||||
is MatchOutcome.Applied -> Unit
|
||||
}
|
||||
if (session.model.value !== modelAtStart) {
|
||||
UmamoLog.warn("$operation: the document changed while its files were being read; nothing was applied")
|
||||
session.emitNotice("notice.import.artworkSuperseded", NoticePlacement.StatusBar)
|
||||
return false
|
||||
}
|
||||
host.artRasters.addDecoded(outcome.decodedByTile)
|
||||
val committed = commit(outcome.model)
|
||||
prewarm(host, committed, outcome.textures)
|
||||
publish(outcome.suggestions)
|
||||
reportMatch(operation, outcome, committed)
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Pre-warms the session's page resolver with the pages a pass composed, when it composed any.
|
||||
*
|
||||
* @param AtlasRepackHost host The session's resolver.
|
||||
* @param PuppetModel model The model whose atlas the pages belong to.
|
||||
* @param PuppetTextures? textures The pages, or null when the pass packed nothing.
|
||||
*/
|
||||
private fun prewarm(host: AtlasRepackHost, model: PuppetModel, textures: PuppetTextures?) {
|
||||
if (textures != null) {
|
||||
host.sessionAtlasPages?.prewarm(model.atlas, textures)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs one match or replace pass the way the first run and an adjustment both report it.
|
||||
*
|
||||
* @param String operation The log prefix.
|
||||
* @param MatchOutcome.Applied outcome What the pass produced.
|
||||
* @param PuppetModel committed The model that landed.
|
||||
*/
|
||||
private fun reportMatch(operation: String, outcome: MatchOutcome.Applied, committed: PuppetModel) {
|
||||
for (notice in outcome.notices) {
|
||||
UmamoLog.warn("$operation: ${describeImportNotice(notice)}")
|
||||
}
|
||||
for (drawableId in outcome.outgrown) {
|
||||
val name = committed.drawables.firstOrNull { drawable -> drawable.id == drawableId }?.name ?: drawableId.raw
|
||||
UmamoLog.warn("$operation: the new art of '$name' reaches past its edited mesh; re-mesh it or extend the mesh")
|
||||
}
|
||||
for ((binding, match) in outcome.suggestions) {
|
||||
UmamoLog.info("$operation: '${binding.second}' in '${binding.first.raw}' left for review; best candidate '${match.key}' at ${percentOf(match.score)}%")
|
||||
}
|
||||
reportRebindings(operation, outcome.rebindings)
|
||||
when (val change = outcome.change) {
|
||||
is DocumentChange.MatchArtwork ->
|
||||
UmamoLog.info("$operation: ${change.matchedCount} tile(s) rebound, ${change.remainingCount} left for review; now ${committed.atlas.pages.size} page(s); ${outcome.notices.size} note(s)")
|
||||
is DocumentChange.ReplaceArtwork ->
|
||||
UmamoLog.info(
|
||||
"$operation: '${change.sourceName}' -> ${change.matchedCount} tile(s) reloaded by key, ${change.reboundCount} rebound by match," +
|
||||
" ${change.missingCount} left for review; ${outcome.notices.size} note(s)",
|
||||
)
|
||||
else -> UmamoLog.info("$operation: landed")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A confidence as the whole percentage a person reads.
|
||||
*
|
||||
* @param Float score The confidence, 0..1.
|
||||
* @return Int The percentage.
|
||||
*/
|
||||
fun percentOf(score: Float): Int = (score * 100f + 0.5f).toInt().coerceIn(0, 100)
|
||||
@@ -0,0 +1,243 @@
|
||||
package org.umamo.ui.model
|
||||
|
||||
import androidx.compose.runtime.State
|
||||
import androidx.compose.runtime.staticCompositionLocalOf
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import org.umamo.edit.EditorMode
|
||||
import org.umamo.edit.EditorSession
|
||||
import org.umamo.edit.Selection
|
||||
import org.umamo.render.PuppetTextures
|
||||
import org.umamo.render.SourceArtRasters
|
||||
import org.umamo.runtime.model.DrawableId
|
||||
import org.umamo.runtime.model.ParameterId
|
||||
import org.umamo.runtime.model.PartId
|
||||
import org.umamo.runtime.model.PuppetModel
|
||||
import org.umamo.ui.viewport.PuppetViewportService
|
||||
|
||||
/**
|
||||
* The open document's runtime [PuppetModel] for the composition, or null when nothing is open. Panels
|
||||
* (Outliner, Properties, Parameters) read `LocalPuppet.current` to display parts/parameters; the host
|
||||
* app provides it. Kept in `:ui` commonMain (PuppetModel is in `:runtime`, a shared dependency) so the
|
||||
* panels stay common and Android-sharable while only the GL viewport is platform code.
|
||||
*/
|
||||
val LocalPuppet = staticCompositionLocalOf<PuppetModel?> { null }
|
||||
|
||||
/**
|
||||
* The open document's [EditorSession] for the composition, or null when nothing is open. The session is
|
||||
* the single mutable owner of the document model, the editor state (selection, mode), and the undo
|
||||
* history; mutation sites (a visibility toggle, a future rename / reparent) resolve it and call its
|
||||
* mutation API, while [LocalPuppet] is the read-only model projection panels display. The host provides
|
||||
* both from the same session, so a mutation republishes the model and every panel recomposes.
|
||||
*/
|
||||
val LocalEditorSession = staticCompositionLocalOf<EditorSession?> { null }
|
||||
|
||||
/**
|
||||
* A thin, platform-neutral handle for streaming transient preview models to the puppet renderer,
|
||||
* mirroring [LiveParamsHandle]'s preview / commit split for model-shaped edits: [previewModel] pushes
|
||||
* an uncommitted model straight to the render thread every pointer frame (no undo step, no session
|
||||
* write), and the gesture boundary commits through the session as usual - whose model bridge then
|
||||
* republishes the committed model. [resync] restores the renderer to the session's committed model
|
||||
* after a cancelled or torn-down gesture. The UV editor drives its modal G / S / R previews through
|
||||
* this; the viewport's own overlays reach the service directly and do not need it.
|
||||
*
|
||||
* The preview is published to the COMPOSITION as well as to the render thread, through [preview]. It
|
||||
* has to be: a gesture's own area draws from its local preview and the 2D viewport follows the pushes,
|
||||
* but every other read-only surface derives from [LocalPuppet] and would otherwise sit on the committed
|
||||
* model until the gesture confirmed - a second UV area showing the atlas page must move with the mesh
|
||||
* the viewport beside it is moving.
|
||||
*/
|
||||
interface PuppetRenderSync {
|
||||
/**
|
||||
* The uncommitted model a gesture is currently previewing, or null when none is in flight.
|
||||
*
|
||||
* Compose state rather than a flow: it is written from the pointer loop on the main thread and read
|
||||
* during composition, so a surface that reads it recomposes with the gesture and needs no collector.
|
||||
* It is NOT session state - nothing here touches history, dirty, or the committed model - so a
|
||||
* surface that wants the document as SAVED keeps reading [LocalPuppet].
|
||||
*/
|
||||
val preview: State<PuppetModel?>
|
||||
|
||||
/**
|
||||
* Pushes an uncommitted preview model to the renderer (transient; no undo step).
|
||||
*
|
||||
* @param PuppetModel model The preview model to render.
|
||||
*/
|
||||
fun previewModel(model: PuppetModel)
|
||||
|
||||
/** Restores the renderer to the session's committed model (a cancelled / torn-down gesture). */
|
||||
fun resync()
|
||||
}
|
||||
|
||||
/**
|
||||
* The render-sync handle for the composition, or null when no puppet renderer is present (no document,
|
||||
* or a platform without the offscreen service). Preview pushes no-op when it is null - the UV editor
|
||||
* still edits, just without a live GPU preview.
|
||||
*/
|
||||
val LocalPuppetRenderSync = staticCompositionLocalOf<PuppetRenderSync?> { null }
|
||||
|
||||
/**
|
||||
* The platform render service for the composition, or null when no puppet renderer is present (no
|
||||
* document, or a platform without the offscreen GL engine - Android until the GLES sibling lands). The
|
||||
* UV editor requires it: it registers a UV scene - an atlas page or a source layer - to render its
|
||||
* underlay through the same engine the 2D viewport uses, and owns its camera through it; with no service
|
||||
* the UV editor shows the grid placeholder, exactly like the 2D viewport's body.
|
||||
*/
|
||||
val LocalPuppetViewportService = staticCompositionLocalOf<PuppetViewportService?> { null }
|
||||
|
||||
/**
|
||||
* The open document's decoded texture atlas pages for the composition, or null when nothing is open.
|
||||
* The UV editor reads the full page a drawable samples to draw under its wireframe; the thumbnail
|
||||
* provider below serves the cropped-preview case. Provided by the host from the SESSION's effective
|
||||
* page set ([SessionAtlasPages]), which is what the renderer shows - so the value changes when a
|
||||
* repack (or its undo) swaps the pages, and the whole subtree recomposes onto the new set. A repack
|
||||
* is rare, so the static local's wholesale recomposition is the right price for its simplicity.
|
||||
*/
|
||||
val LocalPuppetTextures = staticCompositionLocalOf<PuppetTextures?> { null }
|
||||
|
||||
/**
|
||||
* The session's atlas-page resolver, or null when nothing is open (or the desync guard built a
|
||||
* fallback session). The repack command reads it to pre-warm the page cache with the pages it
|
||||
* composed; everything else reads the resolved pages through [LocalPuppetTextures].
|
||||
*/
|
||||
val LocalSessionAtlasPages = staticCompositionLocalOf<SessionAtlasPages?> { null }
|
||||
|
||||
/**
|
||||
* The open document's source artwork - the layers the puppet was authored against, before packing -
|
||||
* or null when nothing is open. The UV editor's layer view shows one of these under a drawable's
|
||||
* mapping, which is the pre-atlas counterpart of what [LocalPuppetTextures] serves.
|
||||
*
|
||||
* A document whose format retains no source art (a MOC3, the packed endpoint) provides an EMPTY
|
||||
* store rather than null, so a surface distinguishes "no document" from "this document has no source
|
||||
* art" without a second signal. Rasters decode on first request inside the store, so the value
|
||||
* handed here stays stable for the document's life - which matters, because a static local's change
|
||||
* recomposes the whole subtree.
|
||||
*/
|
||||
val LocalSourceArtRasters = staticCompositionLocalOf<SourceArtRasters?> { null }
|
||||
|
||||
/**
|
||||
* A platform-neutral source of small art-mesh previews, mirroring [SelectionHandle] / [LiveParamsHandle].
|
||||
* The Outliner and the Sources space ask for a drawable's thumbnail on hover; the host backs it with the same crop-and-downsample
|
||||
* machinery the viewport's overlap picker uses (the atlas region under the mesh UV bounds). Kept an interface
|
||||
* in `:ui` commonMain so the panels stay common - the desktop wraps its Skiko rasteriser, Android will wrap
|
||||
* its own. A null provider (or a null result) means no preview, so callers simply show nothing.
|
||||
*/
|
||||
interface DrawableThumbnailProvider {
|
||||
/**
|
||||
* The cropped art preview for a drawable, or null when it is untextured, mesh-less, or unknown.
|
||||
*
|
||||
* @param DrawableId id The drawable to preview.
|
||||
* @return ImageBitmap? The preview bitmap, or null when none is available.
|
||||
*/
|
||||
fun thumbnailFor(id: DrawableId): ImageBitmap?
|
||||
|
||||
/**
|
||||
* A combined preview of every art mesh under a part (its own drawables and those of its sub-parts),
|
||||
* assembled in rest-pose model space so it reads like the part's art, or null when the part holds no
|
||||
* textured drawable. Built by placing each drawable's cached crop at its model-space bounding box and
|
||||
* compositing back-to-front, so it reuses the per-drawable previews rather than re-rendering geometry.
|
||||
*
|
||||
* @param PartId id The part to preview.
|
||||
* @return ImageBitmap? The composited preview, or null when the part has no previewable art.
|
||||
*/
|
||||
fun partThumbnailFor(id: PartId): ImageBitmap?
|
||||
}
|
||||
|
||||
/**
|
||||
* The drawable-thumbnail provider for the composition, or null when none is wired (e.g. no document open,
|
||||
* or a platform without the renderer). The Outliner and Sources hover previews no-op when it is null.
|
||||
*/
|
||||
val LocalDrawableThumbnails = staticCompositionLocalOf<DrawableThumbnailProvider?> { null }
|
||||
|
||||
/**
|
||||
* A thin, platform-neutral handle for reading and writing live parameter values (the pose) from common
|
||||
* UI (the Parameters sliders) without `:ui` knowing how the value reaches the GL render thread or how it
|
||||
* is recorded for undo. Scrubbing is a two-phase gesture: [preview] streams the in-progress value
|
||||
* straight to the renderer every frame (transient — no undo step, no recompose churn), and [commit]
|
||||
* records one undo step at the gesture boundary (drag release, a typed value, a reset). So a whole slider
|
||||
* drag is a single undo step. The desktop implementation writes its volatile LiveParams hand-off on
|
||||
* preview and routes commit through the EditorSession; Android will wrap its own.
|
||||
*/
|
||||
interface LiveParamsHandle {
|
||||
/** The current parameter values (parameter id → value). */
|
||||
val values: Map<ParameterId, Float>
|
||||
|
||||
/**
|
||||
* The same values, read as Compose state so whatever reads them recomposes when the pose moves -
|
||||
* including mid-scrub, where [values] is a plain volatile read that no observer ever sees change.
|
||||
*
|
||||
* Deliberately a second property rather than making [values] observable. The scrub path writes on
|
||||
* every pointer move, so a caller that only needs the pose once (seeding a control, constructing a
|
||||
* session) must be able to read it WITHOUT taking a per-frame recomposition dependency on it.
|
||||
*/
|
||||
val observedValues: Map<ParameterId, Float>
|
||||
|
||||
/**
|
||||
* Previews one parameter's live value toward the renderer without recording an undo step. Called every
|
||||
* frame of a scrub gesture; the matching [commit] records the single step on release.
|
||||
*
|
||||
* @param ParameterId id The parameter to set.
|
||||
* @param Float value The new value.
|
||||
*/
|
||||
fun preview(id: ParameterId, value: Float)
|
||||
|
||||
/**
|
||||
* Records the current pose as one undo step, ending a scrub gesture. The values previewed since the
|
||||
* gesture began are captured as a single step labelled by which parameters [changedIds] moved.
|
||||
*
|
||||
* @param Set<ParameterId> changedIds The parameters this gesture moved (for the history-panel label).
|
||||
*/
|
||||
fun commit(changedIds: Set<ParameterId>)
|
||||
}
|
||||
|
||||
/**
|
||||
* The live-parameter handle for the composition, or null when no posable document is open. The
|
||||
* Parameters space writes slider changes here; the host wires it to the renderer.
|
||||
*/
|
||||
val LocalLiveParams = staticCompositionLocalOf<LiveParamsHandle?> { null }
|
||||
|
||||
/**
|
||||
* A thin, platform-neutral handle for reading and writing the current object-mode [Selection] from
|
||||
* common UI, mirroring [LiveParamsHandle]. The Outliner and viewport write gestures through it; the
|
||||
* Properties panel and the highlight bridge read it. The desktop implementation backs it with Compose state
|
||||
* so panels recompose on change; Android will wrap its own.
|
||||
*/
|
||||
interface SelectionHandle {
|
||||
/** The current selection. */
|
||||
val selection: Selection
|
||||
|
||||
/**
|
||||
* Replaces the current selection.
|
||||
*
|
||||
* @param Selection selection The new selection.
|
||||
*/
|
||||
fun set(selection: Selection)
|
||||
}
|
||||
|
||||
/**
|
||||
* The selection handle for the composition, or null when no document is open. Panels read
|
||||
* `LocalSelection.current?.selection`; gesture sites call `set`.
|
||||
*/
|
||||
val LocalSelection = staticCompositionLocalOf<SelectionHandle?> { null }
|
||||
|
||||
/**
|
||||
* A platform-neutral handle for reading and setting the current [EditorMode], mirroring
|
||||
* [SelectionHandle]. The mode-toggle command and, later, the radial menu write it; the viewport pick
|
||||
* router and the Properties panel read it.
|
||||
*/
|
||||
interface EditorModeHandle {
|
||||
/** The current editor mode. */
|
||||
val mode: EditorMode
|
||||
|
||||
/**
|
||||
* Sets the editor mode.
|
||||
*
|
||||
* @param EditorMode mode The new mode.
|
||||
*/
|
||||
fun set(mode: EditorMode)
|
||||
}
|
||||
|
||||
/**
|
||||
* The editor-mode handle for the composition, or null when no document is open. A null handle is
|
||||
* treated as [EditorMode.Object] by callers.
|
||||
*/
|
||||
val LocalEditorMode = staticCompositionLocalOf<EditorModeHandle?> { null }
|
||||
@@ -0,0 +1,88 @@
|
||||
package org.umamo.ui.model
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import org.jetbrains.compose.resources.stringResource
|
||||
import org.umamo.ui.resources.*
|
||||
|
||||
/**
|
||||
* Maps a [org.umamo.edit.Notice.messageKey] to its localized message. The keys mirror those emitted by
|
||||
* :edit (which stays presentation-free, so it cannot hold display strings itself - the same pattern as
|
||||
* the history labels); an unmapped key falls back to a generic message so a newly added notice never
|
||||
* renders blank.
|
||||
*
|
||||
* @param String messageKey The notice's stable message key.
|
||||
* @param List<String> arguments The values a formatting message substitutes, in placeholder order.
|
||||
* @return String The localized notice message.
|
||||
*/
|
||||
@Composable
|
||||
fun noticeText(messageKey: String, arguments: List<String> = emptyList()): String =
|
||||
when (messageKey) {
|
||||
"notice.transform.onlyDrawables" -> stringResource(Res.string.notice_transform_only_drawables)
|
||||
"notice.transform.deformed" -> stringResource(Res.string.notice_transform_deformed)
|
||||
"notice.deformer.createWarp.none" -> stringResource(Res.string.notice_deformer_create_warp_none)
|
||||
"notice.keyform.noTarget" -> stringResource(Res.string.notice_keyform_no_target)
|
||||
"notice.keyform.noParameter" -> stringResource(Res.string.notice_keyform_no_parameter)
|
||||
"notice.merge.needsVertices" -> stringResource(Res.string.notice_merge_needs_vertices)
|
||||
"notice.connect.needsTwoVertices" -> stringResource(Res.string.notice_connect_needs_two_vertices)
|
||||
"notice.connect.refused" -> stringResource(Res.string.notice_connect_refused)
|
||||
"notice.addVertex.refused" -> stringResource(Res.string.notice_add_vertex_refused)
|
||||
"notice.rip.nothing" -> stringResource(Res.string.notice_rip_nothing)
|
||||
"notice.uv.noUvs" -> stringResource(Res.string.notice_uv_no_uvs)
|
||||
"notice.uv.noSelection" -> stringResource(Res.string.notice_uv_no_selection)
|
||||
"notice.uv.placement.layerAddressed" -> stringResource(Res.string.notice_uv_placement_layer_addressed)
|
||||
"notice.uv.placement.noPlacedArt" -> stringResource(Res.string.notice_uv_placement_no_placed_art)
|
||||
"notice.uv.placement.pageViewOnly" -> stringResource(Res.string.notice_uv_placement_page_view_only)
|
||||
"notice.uv.placement.notOnPage" -> stringResource(Res.string.notice_uv_placement_not_on_page)
|
||||
"notice.uv.placement.notDerivable" -> stringResource(Res.string.notice_uv_placement_not_derivable)
|
||||
"notice.uv.placement.overlap" -> stringResource(Res.string.notice_uv_placement_overlap)
|
||||
"notice.uv.placement.offPage" -> stringResource(Res.string.notice_uv_placement_off_page)
|
||||
"notice.uv.placement.pinned" -> stringResource(Res.string.notice_uv_placement_pinned)
|
||||
"notice.edit.noEditableGeometry" -> stringResource(Res.string.notice_edit_no_editable_geometry)
|
||||
"notice.display.partialSourceArtwork" -> stringResource(Res.string.notice_display_partial_source_artwork)
|
||||
"notice.display.sourceArtworkUnavailable" -> stringResource(Res.string.notice_display_source_artwork_unavailable)
|
||||
"notice.atlas.repacked" -> stringResource(Res.string.notice_atlas_repacked)
|
||||
"notice.import.artworkNotes" -> stringResource(Res.string.notice_import_artwork_notes)
|
||||
"notice.import.artworkAdded" -> stringResource(Res.string.notice_import_artwork_added)
|
||||
"notice.document.saving" -> stringResource(Res.string.notice_document_saving)
|
||||
"notice.document.saved" -> stringResource(Res.string.notice_document_saved, arguments.firstOrNull().orEmpty())
|
||||
"notice.document.saveBusy" -> stringResource(Res.string.notice_document_save_busy)
|
||||
"notice.document.exportingImage" -> stringResource(Res.string.notice_document_exporting_image)
|
||||
"notice.document.exportedImage" -> stringResource(Res.string.notice_document_exported_image, arguments.firstOrNull().orEmpty())
|
||||
"notice.document.waitingForSave" -> stringResource(Res.string.notice_document_waiting_for_save)
|
||||
"notice.document.cmo3Loss" -> stringResource(Res.string.notice_document_cmo3_loss)
|
||||
"notice.document.moc3Loss" -> stringResource(Res.string.notice_document_moc3_loss)
|
||||
"notice.import.artworkSuperseded" -> stringResource(Res.string.notice_import_artwork_superseded)
|
||||
"notice.import.noArtLayers" -> stringResource(Res.string.notice_import_no_art_layers)
|
||||
"notice.reload.done" -> stringResource(Res.string.notice_reload_done, *countArguments(arguments, 3))
|
||||
"notice.reload.notes" -> stringResource(Res.string.notice_reload_notes, *countArguments(arguments, 4))
|
||||
"notice.reload.outgrown" -> stringResource(Res.string.notice_reload_outgrown, *countArguments(arguments, 4))
|
||||
"notice.watch.changed" -> stringResource(Res.string.notice_watch_changed, *countArguments(arguments, 1))
|
||||
"notice.watch.staleAtOpen" -> stringResource(Res.string.notice_watch_stale_at_open, *countArguments(arguments, 1))
|
||||
"notice.watch.missing" -> stringResource(Res.string.notice_watch_missing, arguments.firstOrNull().orEmpty())
|
||||
"notice.reload.noChanges" -> stringResource(Res.string.notice_reload_no_changes)
|
||||
"notice.reload.noFiles" -> stringResource(Res.string.notice_reload_no_files)
|
||||
"notice.relink.pulled" -> stringResource(Res.string.notice_relink_pulled)
|
||||
"notice.relink.bindingOnly" -> stringResource(Res.string.notice_relink_binding_only)
|
||||
"notice.match.done" -> stringResource(Res.string.notice_match_done, *countArguments(arguments, 2))
|
||||
"notice.match.nothing" -> stringResource(Res.string.notice_match_nothing)
|
||||
"notice.match.noCandidates" -> stringResource(Res.string.notice_match_no_candidates)
|
||||
"notice.replace.done" -> stringResource(Res.string.notice_replace_done, *countArguments(arguments, 3))
|
||||
"notice.atlas.repackSuperseded" -> stringResource(Res.string.notice_atlas_repack_superseded)
|
||||
"notice.atlas.repackUnchanged" -> stringResource(Res.string.notice_atlas_repack_unchanged)
|
||||
"notice.proportional.on" -> stringResource(Res.string.notice_proportional_on)
|
||||
"notice.proportional.off" -> stringResource(Res.string.notice_proportional_off)
|
||||
"notice.proportional.connected.on" -> stringResource(Res.string.notice_proportional_connected_on)
|
||||
"notice.proportional.connected.off" -> stringResource(Res.string.notice_proportional_connected_off)
|
||||
else -> stringResource(Res.string.notice_unknown)
|
||||
}
|
||||
|
||||
/**
|
||||
* The first [count] arguments as integers for a message that formats counts, zero for any the notice
|
||||
* did not carry - a placeholder must never go unfilled.
|
||||
*
|
||||
* @param List<String> arguments The notice's arguments.
|
||||
* @param Int count How many the message formats.
|
||||
* @return Array<Any> The values to substitute.
|
||||
*/
|
||||
private fun countArguments(arguments: List<String>, count: Int): Array<Any> =
|
||||
Array(count) { index -> arguments.getOrNull(index)?.toIntOrNull() ?: 0 }
|
||||
@@ -0,0 +1,184 @@
|
||||
package org.umamo.ui.model
|
||||
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.focusable
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.IntrinsicSize
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
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
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.input.key.Key
|
||||
import androidx.compose.ui.input.key.KeyEventType
|
||||
import androidx.compose.ui.input.key.key
|
||||
import androidx.compose.ui.input.key.onPreviewKeyEvent
|
||||
import androidx.compose.ui.input.key.type
|
||||
import androidx.compose.ui.input.pointer.PointerEventType
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.unit.IntOffset
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Popup
|
||||
import androidx.compose.ui.window.PopupProperties
|
||||
import org.umamo.runtime.model.DrawableId
|
||||
import org.umamo.ui.kit.AtPointPositionProvider
|
||||
import org.umamo.ui.kit.Surface
|
||||
import org.umamo.ui.kit.Text
|
||||
import org.umamo.ui.kit.ThumbnailSlot
|
||||
import org.umamo.ui.theme.LocalUmamoColors
|
||||
import org.umamo.ui.theme.LocalUmamoShapes
|
||||
import org.umamo.ui.theme.LocalUmamoTypography
|
||||
|
||||
/**
|
||||
* One row of the overlap picker: a drawable to select, its display label, and an optional layer-art
|
||||
* thumbnail (shown in the row's leading slot when present, or an empty slot when null).
|
||||
*
|
||||
* @property DrawableId id The drawable this row selects.
|
||||
* @property String label The display label (the Outliner shows the same).
|
||||
* @property ImageBitmap? thumbnail A layer-art thumbnail for the leading slot, or null.
|
||||
*/
|
||||
data class OverlapEntry(val id: DrawableId, val label: String, val thumbnail: ImageBitmap? = null)
|
||||
|
||||
/**
|
||||
* A command-palette-styled popup for choosing among art meshes stacked under the cursor, when a single
|
||||
* click is ambiguous. Anchored at [anchor]; lists [entries] front-to-back with [defaultIndex] (the most
|
||||
* "unambiguously clicked" mesh) pre-highlighted. There is exactly one highlight state (Blender-style,
|
||||
* no separate hover): moving the mouse over a row and pressing Up/Down both drive it, Enter or a click
|
||||
* picks it, Escape or a click outside dismisses. The popup itself is shared, ordinary Compose content;
|
||||
* desktop's Object gizmo triggers it with an Alt-click, and Android's own trigger (a pen long-press) is
|
||||
* intended for once its GLES viewport and gizmo overlay land. The popup never touches the selection
|
||||
* state; it reports the chosen drawable through [onPick] and closure through [onDismiss].
|
||||
*
|
||||
* @param IntOffset anchor The cursor position to anchor the popup at, local to the popup's
|
||||
* parent layout node (AtPointPositionProvider offsets from the
|
||||
* parent's bounds, clamped into the window).
|
||||
* @param List entries The candidates, front-to-back.
|
||||
* @param Int defaultIndex The pre-highlighted row (the centrality winner).
|
||||
* @param Function onPick Called with the chosen drawable id.
|
||||
* @param Function onDismiss Called to close without choosing.
|
||||
*/
|
||||
@Composable
|
||||
fun OverlapPickerPopup(
|
||||
anchor: IntOffset,
|
||||
entries: List<OverlapEntry>,
|
||||
defaultIndex: Int,
|
||||
onPick: (DrawableId) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
if (entries.isEmpty()) {
|
||||
return
|
||||
}
|
||||
val colors = LocalUmamoColors.current
|
||||
val typography = LocalUmamoTypography.current
|
||||
var highlighted by remember(entries) { mutableStateOf(defaultIndex.coerceIn(0, entries.size - 1)) }
|
||||
val focusRequester = remember { FocusRequester() }
|
||||
// Grab focus on open so the navigation keys reach onPreviewKeyEvent (the popup has no text field to
|
||||
// hold focus, unlike the command palette).
|
||||
LaunchedEffect(Unit) {
|
||||
focusRequester.requestFocus()
|
||||
}
|
||||
Popup(
|
||||
popupPositionProvider = AtPointPositionProvider(anchor),
|
||||
onDismissRequest = onDismiss,
|
||||
properties = PopupProperties(focusable = true),
|
||||
) {
|
||||
Surface(
|
||||
modifier =
|
||||
Modifier
|
||||
.focusRequester(focusRequester)
|
||||
.focusable()
|
||||
.onPreviewKeyEvent { event ->
|
||||
if (event.type != KeyEventType.KeyDown) {
|
||||
false
|
||||
} else {
|
||||
when (event.key) {
|
||||
Key.DirectionDown -> {
|
||||
highlighted = (highlighted + 1) % entries.size
|
||||
true
|
||||
}
|
||||
|
||||
Key.DirectionUp -> {
|
||||
highlighted = (highlighted - 1 + entries.size) % entries.size
|
||||
true
|
||||
}
|
||||
|
||||
Key.Enter, Key.NumPadEnter -> {
|
||||
onPick(entries[highlighted].id)
|
||||
true
|
||||
}
|
||||
|
||||
Key.Escape -> {
|
||||
onDismiss()
|
||||
true
|
||||
}
|
||||
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
},
|
||||
color = colors.menuBackground,
|
||||
shape = LocalUmamoShapes.current.medium,
|
||||
border = BorderStroke(1.dp, colors.panelBorder),
|
||||
shadowElevation = 8.dp,
|
||||
) {
|
||||
Column(modifier = Modifier.width(IntrinsicSize.Max)) {
|
||||
entries.forEachIndexed { index, entry ->
|
||||
val isHighlighted = index == highlighted
|
||||
Row(
|
||||
modifier =
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 4.dp, vertical = 4.dp)
|
||||
.background(
|
||||
if (isHighlighted) colors.selection else Color.Transparent,
|
||||
shape = LocalUmamoShapes.current.small,
|
||||
)
|
||||
.pointerInput(index) {
|
||||
awaitPointerEventScope {
|
||||
while (true) {
|
||||
val event = awaitPointerEvent()
|
||||
// Move only, deliberately not Enter: the popup opens under a
|
||||
// stationary cursor, and a synthesized hover on open would stomp
|
||||
// the pre-highlighted centrality winner. Real movement over a row
|
||||
// steals the single highlight the arrow keys also drive.
|
||||
if (event.type == PointerEventType.Move) {
|
||||
highlighted = index
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.clickable { onPick(entry.id) }
|
||||
.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
// Leading layer-art thumbnail. A checker backdrop sits behind it so transparent art reads as
|
||||
// a clear silhouette; an untextured drawable leaves the slot empty so label-only rows align.
|
||||
ThumbnailSlot(thumbnail = entry.thumbnail)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text(
|
||||
text = entry.label,
|
||||
style = typography.bodyMedium,
|
||||
color = if (isHighlighted) colors.selectionText else colors.text,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,695 @@
|
||||
package org.umamo.ui.model
|
||||
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.umamo.edit.AdjustableOperation
|
||||
import org.umamo.edit.DocumentChange
|
||||
import org.umamo.edit.NoticePlacement
|
||||
import org.umamo.edit.commitArtworkRelinked
|
||||
import org.umamo.edit.commitArtworkReloaded
|
||||
import org.umamo.edit.setTileSources
|
||||
import org.umamo.edit.withArtworkReloaded
|
||||
import org.umamo.format.art.LayerRaster
|
||||
import org.umamo.format.art.SourceArt
|
||||
import org.umamo.interop.art.SourceArtImport
|
||||
import org.umamo.interop.art.SourceArtImportNotice
|
||||
import org.umamo.interop.art.SourceArtImportOptions
|
||||
import org.umamo.reimport.ArtworkReloadPlanner
|
||||
import org.umamo.reimport.InventoryLayerMatcher
|
||||
import org.umamo.reimport.LayerMatch
|
||||
import org.umamo.reimport.ReconcileResult
|
||||
import org.umamo.reimport.ReloadPlan
|
||||
import org.umamo.render.DecodedImage
|
||||
import org.umamo.render.PuppetTextures
|
||||
import org.umamo.render.SourceArtRasters
|
||||
import org.umamo.runtime.model.ArtSourceId
|
||||
import org.umamo.runtime.model.ArtSourceLayer
|
||||
import org.umamo.runtime.model.AtlasTileId
|
||||
import org.umamo.runtime.model.DrawableId
|
||||
import org.umamo.runtime.model.PuppetModel
|
||||
import org.umamo.runtime.model.SourceLayerRef
|
||||
import org.umamo.storage.UmamoLog
|
||||
|
||||
/*
|
||||
* Reloading the document's artwork files, and relinking a tile with the layer's art pulled in: the
|
||||
* planner's delta applied to the live model, the changed tiles packed into the gaps around the art
|
||||
* that did not change, committed as one undo step and registered on the operation settings strip.
|
||||
* Add Artwork's shape throughout - the same pack-around primitive, the same supersede check, the
|
||||
* same amend-in-place adjustment - because a reload is an import of the layers that changed.
|
||||
*
|
||||
* A reloaded tile is a NEW tile (see AtlasTile.replaces): its pixels join the raster store beside the
|
||||
* old tile's, so an undo shows the old art again by pure snapshot, and nothing here ever overwrites
|
||||
* a raster the document already holds.
|
||||
*/
|
||||
|
||||
/**
|
||||
* One listed file to re-read.
|
||||
*
|
||||
* @property ArtSourceId sourceId The file's record in the model.
|
||||
* @property SourceArt art The file as just read.
|
||||
* @property String? contentHash The whole-file content hash of the bytes it was read from, recorded
|
||||
* on the refreshed source so the watcher knows this save was taken; null keeps the record's.
|
||||
* @property Long? lastModified The file's modification time when read, recorded beside the hash;
|
||||
* null keeps the record's.
|
||||
*/
|
||||
class ReloadEntry(
|
||||
val sourceId: ArtSourceId,
|
||||
val art: SourceArt,
|
||||
val contentHash: String? = null,
|
||||
val lastModified: Long? = null,
|
||||
) {
|
||||
/**
|
||||
* The inventory of [art], computed once for the entry's life: it hashes every layer's pixels, and
|
||||
* the planner, the scorer, and every strip adjustment over this read want the same rows.
|
||||
*/
|
||||
val inventory: List<ArtSourceLayer> by lazy { SourceArtImport.inventoryOf(art) }
|
||||
}
|
||||
|
||||
/** How a reload ended - what the watcher needs to know to wait, retry, or let go. */
|
||||
enum class ReloadArtworkResult {
|
||||
/** The reload landed as one undo step. */
|
||||
Applied,
|
||||
|
||||
/** The files were read and nothing in them changed the document. */
|
||||
NothingChanged,
|
||||
|
||||
/** The pack could not keep the document's own art in place; the person was shown the report. */
|
||||
Refused,
|
||||
|
||||
/** An edit landed while the reload was being planned; nothing was applied. */
|
||||
Superseded,
|
||||
}
|
||||
|
||||
/**
|
||||
* The files a reload re-reads, as read from disk, with the decoded wrapper of every layer raster
|
||||
* minted once so a re-run hands the raster store the same instances (the renderer's texture cache
|
||||
* keys on that identity).
|
||||
*
|
||||
* @property List entries The files, each with its art.
|
||||
* @property SourceArtImportOptions options The threshold and margin the first run uses.
|
||||
* @property Float matchThreshold The confidence, 0..1, at or above which a lost binding
|
||||
* takes the layer that re-created it in the same step.
|
||||
*/
|
||||
class ReloadArtworkRequest(
|
||||
val entries: List<ReloadEntry>,
|
||||
val options: SourceArtImportOptions,
|
||||
val matchThreshold: Float = InventoryLayerMatcher.DEFAULT_THRESHOLD,
|
||||
) {
|
||||
private val decoded = DecodedLayerRasters(entries.flatMap { entry -> entry.art.layers })
|
||||
|
||||
/**
|
||||
* The decoded wrapper of one of the files' layer rasters.
|
||||
*
|
||||
* @param LayerRaster raster The layer's pixels.
|
||||
* @return DecodedImage The wrapper, the same instance on every call.
|
||||
*/
|
||||
internal fun decodedFor(raster: LayerRaster): DecodedImage = decoded.decodedFor(raster)
|
||||
}
|
||||
|
||||
/**
|
||||
* The tiles to rebind to one layer, with the layer's file as read when it could be. One tile for the
|
||||
* tile chip and a drop; every tile bound to a lost key for a review row's accepted proposal or relink
|
||||
* by hand, so those move as one step.
|
||||
*
|
||||
* @property List<AtlasTileId> tileIds The tiles, in any order.
|
||||
* @property SourceLayerRef ref The binding they take.
|
||||
* @property SourceArt? art The file [ref] names, or null when it could not be read
|
||||
* (missing, unreadable, or a platform uri) - the bindings then change alone.
|
||||
* @property SourceArtImportOptions options The threshold and margin a re-born quad uses.
|
||||
* @property List<AtlasTileId> retire The tiles bound to the target layer that go with the move -
|
||||
* the fresh drawable a reload minted for it, named by the proposal being accepted; each is re-checked
|
||||
* for rig work before it leaves. Empty for a relink by hand or a drop.
|
||||
*/
|
||||
class RelinkArtworkRequest(
|
||||
val tileIds: List<AtlasTileId>,
|
||||
val ref: SourceLayerRef,
|
||||
val art: SourceArt?,
|
||||
val options: SourceArtImportOptions,
|
||||
val retire: List<AtlasTileId> = emptyList(),
|
||||
) {
|
||||
/**
|
||||
* The one-tile form.
|
||||
*
|
||||
* @param AtlasTileId tileId The tile.
|
||||
* @param SourceLayerRef ref The binding it takes.
|
||||
* @param SourceArt? art The file [ref] names, or null when it could not be read.
|
||||
* @param SourceArtImportOptions options The threshold and margin a re-born quad uses.
|
||||
*/
|
||||
constructor(tileId: AtlasTileId, ref: SourceLayerRef, art: SourceArt?, options: SourceArtImportOptions) : this(listOf(tileId), ref, art, options)
|
||||
|
||||
/**
|
||||
* The inventory of [art], computed once for the request's life; empty without the file.
|
||||
*/
|
||||
val inventory: List<ArtSourceLayer> by lazy { art?.let(SourceArtImport::inventoryOf).orEmpty() }
|
||||
|
||||
private val decoded = DecodedLayerRasters(art?.layers.orEmpty())
|
||||
|
||||
/**
|
||||
* The decoded wrapper of one of the file's layer rasters.
|
||||
*
|
||||
* @param LayerRaster raster The layer's pixels.
|
||||
* @return DecodedImage The wrapper, the same instance on every call.
|
||||
*/
|
||||
internal fun decodedFor(raster: LayerRaster): DecodedImage = decoded.decodedFor(raster)
|
||||
}
|
||||
|
||||
/** What one reload pass produced, or why it produced nothing. */
|
||||
private sealed interface ReloadOutcome {
|
||||
/** No file changed in any way the document records. */
|
||||
data object NothingChanged : ReloadOutcome
|
||||
|
||||
/**
|
||||
* The pack could not keep some of the document's own art where it is; nothing was applied.
|
||||
*
|
||||
* @property List refusals The document's tiles the pack could not keep.
|
||||
*/
|
||||
class Refused(val refusals: List<AtlasRepackRefusal>) : ReloadOutcome
|
||||
|
||||
/**
|
||||
* The delta applied and packed.
|
||||
*
|
||||
* @property PuppetModel model The base with the reload applied and packed.
|
||||
* @property PuppetTextures? textures The pages the pack composed, index-parallel to the model's, or
|
||||
* null when the pass minted no tile and so packed nothing - the pages stand as they are.
|
||||
* @property Map decodedByTile The new tiles' pixels, for the raster store.
|
||||
* @property List notices The planner's notes plus every new tile the pack left unplaced.
|
||||
* @property List outgrown Drawables whose kept mesh no longer covers the new art.
|
||||
* @property DocumentChange.ReloadArtwork change The step's counts.
|
||||
* @property List rebindings What the matcher rebound and retired, for the log.
|
||||
* @property SourceSuggestions suggestions The proposals the matcher made but did not apply, by file
|
||||
* and lost key, scored before the pass minted anything - for the review chips.
|
||||
*/
|
||||
class Reloaded(
|
||||
val model: PuppetModel,
|
||||
val textures: PuppetTextures?,
|
||||
val decodedByTile: Map<AtlasTileId, DecodedImage>,
|
||||
val notices: List<SourceArtImportNotice>,
|
||||
val outgrown: List<DrawableId>,
|
||||
val change: DocumentChange.ReloadArtwork,
|
||||
val rebindings: List<Rebinding> = emptyList(),
|
||||
val suggestions: SourceSuggestions = emptyMap(),
|
||||
) : ReloadOutcome
|
||||
}
|
||||
|
||||
/**
|
||||
* One thing a reload, replace, match, or relink did beyond the art itself, as the log tells it: a lost
|
||||
* layer's tile rebound to the layer that re-created it, a fresh drawable retired because a rigged tile
|
||||
* claimed its layer, or a drawable whose visibility followed its layer's eye toggle in the file.
|
||||
*/
|
||||
internal sealed interface Rebinding {
|
||||
/**
|
||||
* A tile rebound by the matcher.
|
||||
*
|
||||
* @property String tileName The tile as it was named.
|
||||
* @property String layerName The layer it moved to.
|
||||
* @property Float score The matcher's confidence, 0..1.
|
||||
*/
|
||||
class Rebound(val tileName: String, val layerName: String, val score: Float) : Rebinding
|
||||
|
||||
/**
|
||||
* A fresh drawable removed with its tile because a rigged tile took its layer.
|
||||
*
|
||||
* @property String drawableName The drawable that went.
|
||||
* @property String layerName The layer it sat over.
|
||||
*/
|
||||
class Retired(val drawableName: String, val layerName: String) : Rebinding
|
||||
|
||||
/**
|
||||
* A drawable whose visibility followed its layer's eye toggle in the file.
|
||||
*
|
||||
* @property String drawableName The drawable.
|
||||
* @property Boolean visible The visibility it took.
|
||||
*/
|
||||
class VisibilityFollowed(val drawableName: String, val visible: Boolean) : Rebinding
|
||||
}
|
||||
|
||||
/**
|
||||
* The rebindings one plan made, named from the model it was planned against and the art it read.
|
||||
*
|
||||
* @param ReloadPlan plan The plan.
|
||||
* @param PuppetModel base The model the plan applies to (the names before the step).
|
||||
* @param SourceArt art The file as read, for the layer names.
|
||||
* @return List<Rebinding> The rebound tiles, then the retired drawables, then the drawables that had their visibility changed.
|
||||
*/
|
||||
internal fun rebindingsOf(plan: ReloadPlan, base: PuppetModel, art: SourceArt): List<Rebinding> {
|
||||
val layerNameByKey = art.layers.associate { layer -> layer.id.raw to layer.name }
|
||||
val rebound =
|
||||
plan.report.results.filterIsInstance<ReconcileResult.Rebound>().flatMap { result ->
|
||||
base.atlas.tiles
|
||||
.filter { tile -> tile.source == result.binding }
|
||||
.map { tile -> Rebinding.Rebound(tile.name, layerNameByKey[result.layerKey] ?: result.layerKey, result.score) }
|
||||
}
|
||||
val retired =
|
||||
plan.reload.retiredTiles.flatMap { tileId ->
|
||||
val tile = base.atlas.tileById[tileId]
|
||||
val layerName = tile?.source?.layerKey?.let { key -> layerNameByKey[key] ?: key } ?: tileId.raw
|
||||
base.drawables.filter { drawable -> drawable.atlasTileId == tileId }.map { drawable -> Rebinding.Retired(drawable.name, layerName) }
|
||||
}
|
||||
val followed =
|
||||
plan.reload.drawableVisibility.map { (drawableId, visible) ->
|
||||
Rebinding.VisibilityFollowed(base.drawables.firstOrNull { drawable -> drawable.id == drawableId }?.name ?: drawableId.raw, visible)
|
||||
}
|
||||
return rebound + retired + followed
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs each rebinding under [operation].
|
||||
*
|
||||
* @param String operation The log prefix.
|
||||
* @param List<Rebinding> rebindings What the matcher did.
|
||||
*/
|
||||
internal fun reportRebindings(operation: String, rebindings: List<Rebinding>) {
|
||||
for (rebinding in rebindings) {
|
||||
when (rebinding) {
|
||||
is Rebinding.Rebound -> UmamoLog.info("$operation: '${rebinding.tileName}' rebound to layer '${rebinding.layerName}' at ${percentOf(rebinding.score)}%")
|
||||
is Rebinding.Retired -> UmamoLog.info("$operation: the new drawable '${rebinding.drawableName}' over layer '${rebinding.layerName}' was removed; a rebound tile took the layer")
|
||||
is Rebinding.VisibilityFollowed ->
|
||||
UmamoLog.info("$operation: '${rebinding.drawableName}' is now ${if (rebinding.visible) "shown" else "hidden"}, following its layer's eye toggle in the file")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The document's pixels for a tile as the planner reads them: the raster store's decoded image,
|
||||
* rewrapped.
|
||||
*
|
||||
* @param SourceArtRasters artRasters The document's raster store.
|
||||
* @return Function The lookup, null for a tile the store cannot decode.
|
||||
*/
|
||||
private fun oldRasterLookup(artRasters: SourceArtRasters): (AtlasTileId) -> LayerRaster? =
|
||||
{ tileId -> artRasters.decodeRaster(tileId)?.let { decoded -> LayerRaster(decoded.width, decoded.height, decoded.rgba) } }
|
||||
|
||||
/**
|
||||
* Applies [request]'s files to [base] one after another and packs the tiles they replaced or added
|
||||
* into the gaps around the rest.
|
||||
*
|
||||
* @param PuppetModel base The model the reload applies to.
|
||||
* @param ReloadArtworkRequest request The files as read.
|
||||
* @param SourceArtImportOptions options The threshold and margin to plan with.
|
||||
* @param Float matchThreshold The bar a lost binding's best candidate must reach.
|
||||
* @param SourceArtRasters artRasters The document's raster store (read, never written here).
|
||||
* @param Boolean premultipliedAlpha The document's texture-convention flag.
|
||||
* @return ReloadOutcome The outcome.
|
||||
*/
|
||||
private fun reloadOutcome(
|
||||
base: PuppetModel,
|
||||
request: ReloadArtworkRequest,
|
||||
options: SourceArtImportOptions,
|
||||
matchThreshold: Float,
|
||||
artRasters: SourceArtRasters,
|
||||
premultipliedAlpha: Boolean,
|
||||
): ReloadOutcome {
|
||||
var model = base
|
||||
val rasters = LinkedHashMap<AtlasTileId, LayerRaster>()
|
||||
val notices = ArrayList<SourceArtImportNotice>()
|
||||
val outgrown = ArrayList<DrawableId>()
|
||||
val rebindings = ArrayList<Rebinding>()
|
||||
val suggestions = LinkedHashMap<Pair<ArtSourceId, String>, LayerMatch>()
|
||||
var replaced = 0
|
||||
var added = 0
|
||||
var matched = 0
|
||||
var missing = 0
|
||||
var visibility = 0
|
||||
val oldRasterOf = oldRasterLookup(artRasters)
|
||||
for (entry in request.entries) {
|
||||
val plan =
|
||||
ArtworkReloadPlanner.plan(model, entry.sourceId, entry.art, options, oldRasterOf, entry.contentHash, inventory = entry.inventory, lastModified = entry.lastModified, matchThreshold = matchThreshold)
|
||||
?: continue
|
||||
val next = model.withArtworkReloaded(plan.reload)
|
||||
if (next === model) {
|
||||
UmamoLog.error("reload artwork: the plan for '${plan.reload.source.name}' collides with the document's ids; that file was skipped")
|
||||
continue
|
||||
}
|
||||
rebindings.addAll(rebindingsOf(plan, model, entry.art))
|
||||
for ((lostKey, match) in plan.leftovers) {
|
||||
suggestions[entry.sourceId to lostKey] = match
|
||||
}
|
||||
model = next
|
||||
rasters.putAll(plan.rasterByTile)
|
||||
notices.addAll(plan.notices)
|
||||
outgrown.addAll(plan.reload.outgrown)
|
||||
replaced += plan.reload.replacedTiles.size
|
||||
added += plan.reload.additions?.drawables?.size ?: 0
|
||||
matched += plan.report.results.count { result -> result is ReconcileResult.Rebound }
|
||||
missing += plan.report.needsReview.size
|
||||
visibility += plan.reload.drawableVisibility.size
|
||||
}
|
||||
if (model === base) {
|
||||
return ReloadOutcome.NothingChanged
|
||||
}
|
||||
val change = DocumentChange.ReloadArtwork(request.entries.size, replaced, added, matched, missing, visibility)
|
||||
return packReloaded(model, rasters.mapValues { (_, raster) -> request.decodedFor(raster) }, notices, artRasters, premultipliedAlpha) { packedModel, textures, packedNotices, decodedByTile ->
|
||||
ReloadOutcome.Reloaded(packedModel, textures, decodedByTile, packedNotices, outgrown, change, rebindings, suggestions)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Packs the tiles a reload or relink minted (all of them unplaced) around the document's art and
|
||||
* builds the outcome from the result. A pass that minted no tile - a layer the file lost, an
|
||||
* inventory refresh - packs nothing at all: the pack would resize a page whose art did not change,
|
||||
* and a placement is only ever moved by the operation that put a tile there.
|
||||
*
|
||||
* @param PuppetModel model The model with the delta applied.
|
||||
* @param Map decodedByTile The new tiles' pixels.
|
||||
* @param List notices The notes so far.
|
||||
* @param SourceArtRasters artRasters The document's raster store, for every other tile.
|
||||
* @param Boolean premultipliedAlpha The document's texture-convention flag.
|
||||
* @param Function reloaded Builds the success outcome from the packed model.
|
||||
* @return ReloadOutcome The outcome, refused when the document's own art could not be kept.
|
||||
*/
|
||||
private inline fun packReloaded(
|
||||
model: PuppetModel,
|
||||
decodedByTile: Map<AtlasTileId, DecodedImage>,
|
||||
notices: List<SourceArtImportNotice>,
|
||||
artRasters: SourceArtRasters,
|
||||
premultipliedAlpha: Boolean,
|
||||
reloaded: (PuppetModel, PuppetTextures?, List<SourceArtImportNotice>, Map<AtlasTileId, DecodedImage>) -> ReloadOutcome,
|
||||
): ReloadOutcome {
|
||||
if (decodedByTile.isEmpty()) {
|
||||
return reloaded(model, null, notices, decodedByTile)
|
||||
}
|
||||
val decode: (AtlasTileId) -> DecodedImage? = { tileId -> decodedByTile[tileId] ?: artRasters.decodeRaster(tileId) }
|
||||
return when (val packed = packNewTilesAround(model, decodedByTile.keys, decode, premultipliedAlpha, notices)) {
|
||||
is PackAroundOutcome.Refused -> ReloadOutcome.Refused(packed.refusals)
|
||||
is PackAroundOutcome.Packed -> reloaded(packed.model, packed.textures, packed.notices, decodedByTile)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reloads the document's artwork files as ONE undo step and registers it on the operation settings
|
||||
* strip (Match Threshold - the bar a lost layer's re-creation must reach to be rebound in the step -
|
||||
* then Alpha Threshold and Birth Mesh Margin, the rows every re-born quad and added layer take).
|
||||
*
|
||||
* Runs on the UI thread; the planning and the pack hop to the default dispatcher. The delta is
|
||||
* planned against the model current at the start, so any edit landing meanwhile supersedes it. The
|
||||
* new rasters join the store only once the commit is certain. A reload that lands publishes the
|
||||
* proposals its matcher left under the bar (scored before it minted anything, so a lost row can still
|
||||
* offer the layer the reload minted a fresh drawable for); one that lands nothing publishes nothing.
|
||||
*
|
||||
* @param AtlasRepackHost host The session, art, resolver, scope, and shell callbacks.
|
||||
* @param ReloadArtworkRequest request The files as read.
|
||||
* @param String? areaId The area the strip shows in, or null.
|
||||
* @param Function publish Takes the proposals left under the bar, for the review chips.
|
||||
* @return ReloadArtworkResult How the reload ended.
|
||||
*/
|
||||
suspend fun runReloadArtwork(host: AtlasRepackHost, request: ReloadArtworkRequest, areaId: String?, publish: (SourceSuggestions) -> Unit = {}): ReloadArtworkResult {
|
||||
val session = host.session
|
||||
val modelAtStart = session.model.value
|
||||
val outcome =
|
||||
withContext(Dispatchers.Default) {
|
||||
reloadOutcome(modelAtStart, request, request.options, request.matchThreshold, host.artRasters, host.premultipliedAlpha)
|
||||
}
|
||||
when (outcome) {
|
||||
ReloadOutcome.NothingChanged -> {
|
||||
UmamoLog.info("reload artwork: nothing changed in ${request.entries.size} file(s)")
|
||||
session.emitNotice("notice.reload.noChanges", NoticePlacement.StatusBar)
|
||||
return ReloadArtworkResult.NothingChanged
|
||||
}
|
||||
is ReloadOutcome.Refused -> {
|
||||
for (refusal in outcome.refusals) {
|
||||
UmamoLog.warn("reload artwork: the document's tile '${refusal.tileName}' could not be kept in place (${refusal.reason}); nothing was applied")
|
||||
}
|
||||
host.report(AtlasRepackReport(outcome.refusals))
|
||||
return ReloadArtworkResult.Refused
|
||||
}
|
||||
is ReloadOutcome.Reloaded -> Unit
|
||||
}
|
||||
if (session.model.value !== modelAtStart) {
|
||||
UmamoLog.warn("reload artwork: the document changed while its files were being reloaded; nothing was applied")
|
||||
session.emitNotice("notice.import.artworkSuperseded", NoticePlacement.StatusBar)
|
||||
return ReloadArtworkResult.Superseded
|
||||
}
|
||||
host.artRasters.addDecoded(outcome.decodedByTile)
|
||||
val committed = session.commitArtworkReloaded(outcome.change, outcome.model)
|
||||
prewarmPages(host, committed, outcome.textures)
|
||||
publish(outcome.suggestions)
|
||||
reportReload(outcome, committed)
|
||||
val change = outcome.change
|
||||
session.emitNotice(
|
||||
when {
|
||||
outcome.outgrown.isNotEmpty() -> "notice.reload.outgrown"
|
||||
outcome.notices.isNotEmpty() || change.missingCount > 0 -> "notice.reload.notes"
|
||||
else -> "notice.reload.done"
|
||||
},
|
||||
NoticePlacement.StatusBar,
|
||||
// "Updated" counts the tiles that took new art and the drawables that had their visibility changed..
|
||||
listOf((change.replacedCount + change.visibilityCount).toString(), change.addedCount.toString(), change.matchedCount.toString(), change.missingCount.toString()),
|
||||
)
|
||||
session.registerAdjustableOperation(committed, areaId, matchArtworkParameters(request.matchThreshold, request.options)) { record ->
|
||||
host.scope.launch { adjustReloadArtwork(host, record, request, publish) }
|
||||
}
|
||||
return ReloadArtworkResult.Applied
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-plans the reload for an adjustment of the strip: the record's rows become the options, the SAME
|
||||
* read files are planned again over the record's base model, packed, and landed over the operation's
|
||||
* own step. A record cleared while the pass ran makes [org.umamo.edit.EditorSession.amendLastCommit]
|
||||
* drop the result.
|
||||
*
|
||||
* @param AtlasRepackHost host The session, resolver, and shell callbacks the first run had.
|
||||
* @param AdjustableOperation record The record with the adjusted parameters.
|
||||
* @param ReloadArtworkRequest request The first run's files.
|
||||
* @param Function publish Takes the proposals left under the adjusted bar.
|
||||
*/
|
||||
internal suspend fun adjustReloadArtwork(host: AtlasRepackHost, record: AdjustableOperation, request: ReloadArtworkRequest, publish: (SourceSuggestions) -> Unit = {}) {
|
||||
val base = record.baseSnapshot.model
|
||||
val options = addArtworkOptionsOf(record.parameters, request.options)
|
||||
val matchThreshold = matchThresholdOf(record.parameters, request.matchThreshold)
|
||||
val outcome =
|
||||
withContext(Dispatchers.Default) {
|
||||
reloadOutcome(base, request, options, matchThreshold, host.artRasters, host.premultipliedAlpha)
|
||||
}
|
||||
when (outcome) {
|
||||
ReloadOutcome.NothingChanged -> {
|
||||
UmamoLog.warn("reload artwork: under the adjusted options nothing changes; the previous result stands")
|
||||
return
|
||||
}
|
||||
is ReloadOutcome.Refused -> {
|
||||
host.report(AtlasRepackReport(outcome.refusals))
|
||||
return
|
||||
}
|
||||
is ReloadOutcome.Reloaded -> Unit
|
||||
}
|
||||
host.artRasters.addDecoded(outcome.decodedByTile)
|
||||
prewarmPages(host, outcome.model, outcome.textures)
|
||||
if (!host.session.amendLastCommit(record, outcome.model)) {
|
||||
UmamoLog.info("reload artwork: the adjustment was superseded before it landed; nothing was applied")
|
||||
return
|
||||
}
|
||||
publish(outcome.suggestions)
|
||||
reportReload(outcome, outcome.model)
|
||||
}
|
||||
|
||||
/**
|
||||
* Pre-warms the session's page resolver with the pages a pass composed, when it composed any; a pass
|
||||
* that packed nothing leaves the resolver to the pages it already holds.
|
||||
*
|
||||
* @param AtlasRepackHost host The session's resolver.
|
||||
* @param PuppetModel model The model whose atlas the pages belong to.
|
||||
* @param PuppetTextures? textures The pages, or null when the pass packed nothing.
|
||||
*/
|
||||
private fun prewarmPages(host: AtlasRepackHost, model: PuppetModel, textures: PuppetTextures?) {
|
||||
if (textures != null) {
|
||||
host.sessionAtlasPages?.prewarm(model.atlas, textures)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs one reload pass the way the first run and an adjustment both report it.
|
||||
*
|
||||
* @param ReloadOutcome.Reloaded outcome What the pass produced.
|
||||
* @param PuppetModel committed The model that landed.
|
||||
*/
|
||||
private fun reportReload(outcome: ReloadOutcome.Reloaded, committed: PuppetModel) {
|
||||
for (notice in outcome.notices) {
|
||||
UmamoLog.warn("reload artwork: ${describeImportNotice(notice)}")
|
||||
}
|
||||
for (drawableId in outcome.outgrown) {
|
||||
val name = committed.drawables.firstOrNull { drawable -> drawable.id == drawableId }?.name ?: drawableId.raw
|
||||
UmamoLog.warn("reload artwork: the new art of '$name' reaches past its edited mesh; re-mesh it or extend the mesh")
|
||||
}
|
||||
reportRebindings("reload artwork", outcome.rebindings)
|
||||
val change = outcome.change
|
||||
UmamoLog.info(
|
||||
"reload artwork: ${change.fileCount} file(s) -> ${change.replacedCount} tile(s) updated, ${change.addedCount} drawable(s) added," +
|
||||
" ${change.matchedCount} rebound by match, ${change.missingCount} layer(s) missing, ${change.visibilityCount} visibility change, ${outcome.outgrown.size} outgrown;" +
|
||||
" now ${committed.atlas.pages.size} page(s); ${outcome.notices.size} note(s)",
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Rebinds one or more tiles to another source layer, pulling the layer's art in when the file could
|
||||
* be read: each tile is replaced with the layer's art and its drawables carried over it, all as ONE
|
||||
* undo step, packed beside the rest and registered on the strip like a reload; without the file, or
|
||||
* when the layer has no art to give, only the bindings change (still one step) and the notice says so.
|
||||
*
|
||||
* @param AtlasRepackHost host The session, art, resolver, scope, and shell callbacks.
|
||||
* @param RelinkArtworkRequest request The tiles, their new binding, and the file when read.
|
||||
* @param String? areaId The area the strip shows in, or null.
|
||||
* @return Boolean Whether the art was pulled (a binding-only change returns false).
|
||||
*/
|
||||
suspend fun runRelinkArtwork(host: AtlasRepackHost, request: RelinkArtworkRequest, areaId: String?): Boolean {
|
||||
val session = host.session
|
||||
val modelAtStart = session.model.value
|
||||
val plan =
|
||||
withContext(Dispatchers.Default) {
|
||||
planRelinkOf(modelAtStart, request, request.options, host.artRasters)
|
||||
}
|
||||
if (plan == null) {
|
||||
val unchanged = request.tileIds.filter { tileId -> modelAtStart.atlas.tileById[tileId]?.source == request.ref }
|
||||
val toRebind = request.tileIds - unchanged.toSet()
|
||||
if (toRebind.isEmpty()) {
|
||||
UmamoLog.info("relink artwork: ${describeTiles(request.tileIds)} already holds this binding and this art; nothing to pull")
|
||||
return false
|
||||
}
|
||||
session.setTileSources(toRebind, request.ref)
|
||||
UmamoLog.warn("relink artwork: ${describeTiles(toRebind)} rebound to '${request.ref.layerKey}' without its art (the file could not be read, or the layer has none)")
|
||||
session.emitNotice("notice.relink.bindingOnly", NoticePlacement.StatusBar)
|
||||
return false
|
||||
}
|
||||
val outcome =
|
||||
withContext(Dispatchers.Default) {
|
||||
relinkOutcome(modelAtStart, plan, request, host.artRasters, host.premultipliedAlpha)
|
||||
}
|
||||
if (!landRelink(host, request, modelAtStart, outcome) { model -> session.commitArtworkRelinked(request.tileIds.first(), model) }) {
|
||||
return false
|
||||
}
|
||||
session.registerAdjustableOperation(session.model.value, areaId, addArtworkParameters(request.options, placed = false)) { record ->
|
||||
host.scope.launch { adjustRelinkArtwork(host, record, request) }
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Plans [request]'s tiles onto their new layer over [base]: every tile paired with the one key, so
|
||||
* the tiles bound to a lost key move in one plan. Null without the file or when nothing pulls.
|
||||
*
|
||||
* @param PuppetModel base The model the relink applies to.
|
||||
* @param RelinkArtworkRequest request The tiles and their binding.
|
||||
* @param SourceArtImportOptions options The threshold and margin to plan with.
|
||||
* @param SourceArtRasters artRasters The document's raster store.
|
||||
* @return ReloadPlan? The plan, or null when there is nothing to pull.
|
||||
*/
|
||||
private fun planRelinkOf(base: PuppetModel, request: RelinkArtworkRequest, options: SourceArtImportOptions, artRasters: SourceArtRasters): ReloadPlan? {
|
||||
val art = request.art ?: return null
|
||||
val pairs = request.tileIds.map { tileId -> tileId to request.ref.layerKey }
|
||||
return ArtworkReloadPlanner.planMatches(base, request.ref.sourceId, art, pairs, options, oldRasterLookup(artRasters), inventory = request.inventory, retire = request.retire.toSet())
|
||||
}
|
||||
|
||||
/**
|
||||
* The tiles of a relink as the log names them.
|
||||
*
|
||||
* @param List<AtlasTileId> tileIds The tiles.
|
||||
* @return String One id quoted, or a count.
|
||||
*/
|
||||
private fun describeTiles(tileIds: List<AtlasTileId>): String = tileIds.singleOrNull()?.let { tileId -> "'${tileId.raw}'" } ?: "${tileIds.size} tiles"
|
||||
|
||||
/**
|
||||
* Applies a relink plan to [base] and packs its one new tile.
|
||||
*
|
||||
* @param PuppetModel base The model the relink applies to.
|
||||
* @param ReloadPlan plan The planner's delta for the tile.
|
||||
* @param RelinkArtworkRequest request The request, for the decoded wrappers.
|
||||
* @param SourceArtRasters artRasters The document's raster store.
|
||||
* @param Boolean premultipliedAlpha The document's texture-convention flag.
|
||||
* @return ReloadOutcome The outcome.
|
||||
*/
|
||||
private fun relinkOutcome(
|
||||
base: PuppetModel,
|
||||
plan: ReloadPlan,
|
||||
request: RelinkArtworkRequest,
|
||||
artRasters: SourceArtRasters,
|
||||
premultipliedAlpha: Boolean,
|
||||
): ReloadOutcome {
|
||||
val model = base.withArtworkReloaded(plan.reload)
|
||||
if (model === base) {
|
||||
UmamoLog.error("relink artwork: the plan for ${describeTiles(request.tileIds)} collides with the document's ids; nothing was applied")
|
||||
return ReloadOutcome.NothingChanged
|
||||
}
|
||||
val change = DocumentChange.ReloadArtwork(1, plan.reload.replacedTiles.size, 0, 0, 0)
|
||||
val rebindings = request.art?.let { art -> rebindingsOf(plan, base, art) }.orEmpty()
|
||||
return packReloaded(model, plan.rasterByTile.mapValues { (_, raster) -> request.decodedFor(raster) }, plan.notices, artRasters, premultipliedAlpha) { packedModel, textures, notices, decodedByTile ->
|
||||
ReloadOutcome.Reloaded(packedModel, textures, decodedByTile, notices, plan.reload.outgrown, change, rebindings)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lands a relink outcome: the supersede check, the rasters into the store, the commit, the pre-warm,
|
||||
* the log, and the notice.
|
||||
*
|
||||
* @param AtlasRepackHost host The session, art, resolver, and shell callbacks.
|
||||
* @param RelinkArtworkRequest request The request, for the log.
|
||||
* @param PuppetModel modelAtStart The model the outcome was planned against.
|
||||
* @param ReloadOutcome outcome What the pass produced.
|
||||
* @param Function commit Commits the packed model and returns the committed one.
|
||||
* @return Boolean Whether the outcome landed.
|
||||
*/
|
||||
private inline fun landRelink(
|
||||
host: AtlasRepackHost,
|
||||
request: RelinkArtworkRequest,
|
||||
modelAtStart: PuppetModel,
|
||||
outcome: ReloadOutcome,
|
||||
commit: (PuppetModel) -> PuppetModel,
|
||||
): Boolean {
|
||||
val session = host.session
|
||||
when (outcome) {
|
||||
ReloadOutcome.NothingChanged -> return false
|
||||
is ReloadOutcome.Refused -> {
|
||||
host.report(AtlasRepackReport(outcome.refusals))
|
||||
return false
|
||||
}
|
||||
is ReloadOutcome.Reloaded -> Unit
|
||||
}
|
||||
if (session.model.value !== modelAtStart) {
|
||||
UmamoLog.warn("relink artwork: the document changed while ${describeTiles(request.tileIds)} was being relinked; nothing was applied")
|
||||
session.emitNotice("notice.import.artworkSuperseded", NoticePlacement.StatusBar)
|
||||
return false
|
||||
}
|
||||
host.artRasters.addDecoded(outcome.decodedByTile)
|
||||
val committed = commit(outcome.model)
|
||||
prewarmPages(host, committed, outcome.textures)
|
||||
reportReload(outcome, committed)
|
||||
session.emitNotice(if (outcome.outgrown.isEmpty()) "notice.relink.pulled" else "notice.reload.outgrown", NoticePlacement.StatusBar)
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-plans a relink for an adjustment of the strip over the record's base, landing through
|
||||
* [org.umamo.edit.EditorSession.amendLastCommit].
|
||||
*
|
||||
* @param AtlasRepackHost host The session, resolver, and shell callbacks the first run had.
|
||||
* @param AdjustableOperation record The record with the adjusted parameters.
|
||||
* @param RelinkArtworkRequest request The first run's request.
|
||||
*/
|
||||
internal suspend fun adjustRelinkArtwork(host: AtlasRepackHost, record: AdjustableOperation, request: RelinkArtworkRequest) {
|
||||
if (request.art == null) {
|
||||
return
|
||||
}
|
||||
val base = record.baseSnapshot.model
|
||||
val options = addArtworkOptionsOf(record.parameters, request.options)
|
||||
val outcome =
|
||||
withContext(Dispatchers.Default) {
|
||||
val plan = planRelinkOf(base, request, options, host.artRasters)
|
||||
if (plan == null) ReloadOutcome.NothingChanged else relinkOutcome(base, plan, request, host.artRasters, host.premultipliedAlpha)
|
||||
}
|
||||
when (outcome) {
|
||||
ReloadOutcome.NothingChanged -> {
|
||||
UmamoLog.warn("relink artwork: under the adjusted options nothing changes; the previous result stands")
|
||||
return
|
||||
}
|
||||
is ReloadOutcome.Refused -> {
|
||||
host.report(AtlasRepackReport(outcome.refusals))
|
||||
return
|
||||
}
|
||||
is ReloadOutcome.Reloaded -> Unit
|
||||
}
|
||||
host.artRasters.addDecoded(outcome.decodedByTile)
|
||||
prewarmPages(host, outcome.model, outcome.textures)
|
||||
if (!host.session.amendLastCommit(record, outcome.model)) {
|
||||
UmamoLog.info("relink artwork: the adjustment was superseded before it landed; nothing was applied")
|
||||
return
|
||||
}
|
||||
reportReload(outcome, outcome.model)
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package org.umamo.ui.model
|
||||
|
||||
import androidx.compose.runtime.State
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.collectLatest
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.umamo.edit.EditorSession
|
||||
import org.umamo.render.PuppetTextures
|
||||
import org.umamo.render.SourceArtRasters
|
||||
import org.umamo.render.deriveAtlasTextures
|
||||
import org.umamo.runtime.model.PuppetAtlas
|
||||
import org.umamo.runtime.model.PuppetModel
|
||||
import org.umamo.storage.UmamoLog
|
||||
import org.umamo.ui.viewport.AtlasPageBinding
|
||||
|
||||
/**
|
||||
* The session's effective atlas pages: which pixels the model's current atlas value denotes.
|
||||
*
|
||||
* Pages are DERIVED state, not history state - a snapshot must never hold pixels - so this follows
|
||||
* the session's model and resolves each atlas value to a page set: the document's imported baseline
|
||||
* short-circuits to its own decoded pages (byte-exact originals, nothing composed on open), and a
|
||||
* generated value (a repack's) composes through deriveAtlasTextures. Undo and redo therefore swap
|
||||
* pages with no help from anyone: restoring the model IS the trigger.
|
||||
*
|
||||
* Resolution is memoized by ATLAS IDENTITY, which the model's copy-on-write discipline makes exact:
|
||||
* every non-atlas edit passes `atlas` through by reference, and undo restores the very instance the
|
||||
* snapshot holds. The cache is the baseline plus ONE derived entry - a page set is hundreds of
|
||||
* megabytes at full size, so holding generations would be ruinous; the single slot gives redo its
|
||||
* free round trip, and an older generation re-derives off-thread while the current pages keep
|
||||
* rendering. The repack pre-warms the slot with the pages it already composed, so the commit that
|
||||
* publishes its model cache-hits instead of composing twice.
|
||||
*
|
||||
* UI-thread confined (the binding is Compose state); only the derivation itself runs on the default
|
||||
* dispatcher.
|
||||
*
|
||||
* @property EditorSession session The session whose model drives the resolution.
|
||||
* @property PuppetAtlas baselineAtlas The imported document's atlas value.
|
||||
* @property PuppetTextures baselineTextures The imported document's decoded pages.
|
||||
* @property SourceArtRasters artRasters The source-art pixels a generated value composes from.
|
||||
*/
|
||||
class SessionAtlasPages(
|
||||
private val session: EditorSession,
|
||||
baselineAtlas: PuppetAtlas,
|
||||
baselineTextures: PuppetTextures,
|
||||
private val artRasters: SourceArtRasters,
|
||||
) {
|
||||
private val baseline = AtlasPageBinding(baselineAtlas, baselineTextures)
|
||||
|
||||
// The one derived generation kept beyond baseline; replaced wholesale on the next derivation.
|
||||
private var derived: AtlasPageBinding? = null
|
||||
|
||||
private val mutableBinding = mutableStateOf(baseline)
|
||||
|
||||
/** The pages the current model's atlas denotes, paired with that atlas value. */
|
||||
val binding: State<AtlasPageBinding> get() = mutableBinding
|
||||
|
||||
/**
|
||||
* Seeds the derived slot with pages the caller already composed for [atlas], so the model commit
|
||||
* that follows resolves by cache hit instead of composing the same pages again.
|
||||
*
|
||||
* @param PuppetAtlas atlas The atlas value the pages belong to.
|
||||
* @param PuppetTextures textures The composed pages.
|
||||
*/
|
||||
fun prewarm(atlas: PuppetAtlas, textures: PuppetTextures) {
|
||||
derived = AtlasPageBinding(atlas, textures)
|
||||
}
|
||||
|
||||
/**
|
||||
* Follows the session's model until cancelled, publishing the binding for every atlas change.
|
||||
* Launched once by the host beside the other session collectors.
|
||||
*/
|
||||
suspend fun follow() {
|
||||
session.model
|
||||
.distinctUntilChanged { previous, next -> previous.atlas === next.atlas }
|
||||
.collectLatest { model -> publishFor(model) }
|
||||
}
|
||||
|
||||
private suspend fun publishFor(model: PuppetModel) {
|
||||
val atlas = model.atlas
|
||||
if (mutableBinding.value.atlas === atlas) {
|
||||
return
|
||||
}
|
||||
if (atlas === baseline.atlas || atlas == baseline.atlas) {
|
||||
mutableBinding.value = baseline
|
||||
return
|
||||
}
|
||||
derived?.let { cached ->
|
||||
if (cached.atlas === atlas) {
|
||||
mutableBinding.value = cached
|
||||
return
|
||||
}
|
||||
}
|
||||
val textures =
|
||||
withContext(Dispatchers.Default) {
|
||||
deriveAtlasTextures(model, artRasters, baseline.textures.premultipliedAlpha)
|
||||
}
|
||||
val next =
|
||||
if (textures != null) {
|
||||
AtlasPageBinding(atlas, textures)
|
||||
} else {
|
||||
// Unreachable for an atlas the repack authored (its placements derive by construction).
|
||||
// Publishing the previous pixels under the NEW atlas keeps the engine's model/pages pairing
|
||||
// from holding forever: wrong pixels beat a frozen viewport, and the log names the fault.
|
||||
UmamoLog.error("atlas pages: the current atlas is not derivable; keeping the previous pages")
|
||||
AtlasPageBinding(atlas, mutableBinding.value.textures)
|
||||
}
|
||||
derived = next
|
||||
mutableBinding.value = next
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package org.umamo.ui.model
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.State
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.remember
|
||||
import org.umamo.edit.EditorMode
|
||||
import org.umamo.edit.EditorSession
|
||||
import org.umamo.edit.Selection
|
||||
|
||||
/**
|
||||
* Backs the common [SelectionHandle] and [EditorModeHandle] with an [EditorSession], so every selection
|
||||
* gesture and mode toggle the panels make flows through the session — which records selection as an undo
|
||||
* step (the chosen Blender-faithful granularity) and republishes through its flows. Reads go through
|
||||
* Compose [State] mirrors of the session's flows, so panels recompose on change, including when undo /
|
||||
* redo restore a prior selection.
|
||||
*
|
||||
* Keeps :edit free of Compose (its module mandate): the session exposes coroutines flows, and this thin
|
||||
* :ui adapter is the only place they become Compose-observable state. Writes are one-way to the session,
|
||||
* which is the single source of truth; the mirrors only follow it.
|
||||
*
|
||||
* 共通の選択/モードハンドルを EditorSession に接続する :ui 側アダプタ。読みは Compose State ミラー、
|
||||
* 書きはセッションへ一方向(取り消しに記録される)。
|
||||
*/
|
||||
class SessionEditorState internal constructor(
|
||||
private val session: EditorSession,
|
||||
private val selectionMirror: State<Selection>,
|
||||
private val modeMirror: State<EditorMode>,
|
||||
) : SelectionHandle, EditorModeHandle {
|
||||
override val selection: Selection get() = selectionMirror.value
|
||||
|
||||
/**
|
||||
* Routes a selection gesture to the session, which records it as an undo step.
|
||||
*
|
||||
* @param Selection selection The new selection.
|
||||
*/
|
||||
override fun set(selection: Selection) {
|
||||
session.setSelection(selection)
|
||||
}
|
||||
|
||||
override val mode: EditorMode get() = modeMirror.value
|
||||
|
||||
/**
|
||||
* Routes a mode change to the session (transient — not an undo step).
|
||||
*
|
||||
* @param EditorMode mode The new mode.
|
||||
*/
|
||||
override fun set(mode: EditorMode) {
|
||||
session.setMode(mode)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remembers a [SessionEditorState] over [session], collecting its selection and mode flows into Compose
|
||||
* state so the returned handle's reads are observable. Stable while [session] is, so providing it into
|
||||
* [LocalSelection] / [LocalEditorMode] does not thrash the composition.
|
||||
*
|
||||
* @param EditorSession session The open document's session.
|
||||
* @return SessionEditorState The session-backed selection + mode handle.
|
||||
*/
|
||||
@Composable
|
||||
fun rememberSessionEditorState(session: EditorSession): SessionEditorState {
|
||||
val selectionMirror = session.selection.collectAsState()
|
||||
val modeMirror = session.mode.collectAsState()
|
||||
return remember(session) { SessionEditorState(session, selectionMirror, modeMirror) }
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package org.umamo.ui.model
|
||||
|
||||
import androidx.compose.runtime.staticCompositionLocalOf
|
||||
import org.umamo.storage.UmamoLog
|
||||
import kotlin.concurrent.Volatile
|
||||
|
||||
/**
|
||||
* Whether an artwork file is still where the document last read it: true when present, false when
|
||||
* missing, null when the platform cannot say (a content uri, a path it will not probe).
|
||||
*
|
||||
* @param String path The advisory path the model recorded.
|
||||
* @return Boolean? The answer, or null for unknown.
|
||||
*/
|
||||
typealias SourceFilePresence = (path: String) -> Boolean?
|
||||
|
||||
/**
|
||||
* The app's file-presence probe for the Sources space, or null on a platform without one. A probe
|
||||
* that answers null for a path leaves that source's status Unknown; without a probe every source
|
||||
* reads Unknown, never Missing - the space must not accuse a file it cannot check.
|
||||
*/
|
||||
val LocalSourceFilePresence = staticCompositionLocalOf<SourceFilePresence?> { null }
|
||||
|
||||
/**
|
||||
* The presence probe with a log line the first time a path is asked about and whenever its answer
|
||||
* changes - found, missing, or unknowable - so a document whose recorded path is wrong shows the
|
||||
* exact path being checked. The Sources space asks on every refresh and the watcher every second,
|
||||
* so only a change earns a line. Shared across documents for the app's life, like the probe itself.
|
||||
*
|
||||
* @property SourceFilePresence answers The probe the answers come from.
|
||||
*/
|
||||
internal class LoggedSourceFilePresence(
|
||||
private val answers: SourceFilePresence,
|
||||
) {
|
||||
/** The last answer per path; copy-on-write, since the watcher asks off the UI thread. */
|
||||
@Volatile
|
||||
private var lastAnswerByPath: Map<String, Boolean?> = emptyMap()
|
||||
|
||||
/**
|
||||
* Answers for [path], logging when the answer is new.
|
||||
*
|
||||
* @param String path The advisory path the model recorded.
|
||||
* @return Boolean? The answer: present, missing, or null for unknown.
|
||||
*/
|
||||
fun probe(path: String): Boolean? {
|
||||
val answer = answers(path)
|
||||
val known = lastAnswerByPath
|
||||
if (path !in known || known[path] != answer) {
|
||||
lastAnswerByPath = known + (path to answer)
|
||||
when (answer) {
|
||||
true -> UmamoLog.info("source artwork: found at $path")
|
||||
false -> UmamoLog.warn("source artwork: missing at $path")
|
||||
null -> UmamoLog.info("source artwork: presence unknown at $path (not a file path this platform can probe)")
|
||||
}
|
||||
}
|
||||
return answer
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package org.umamo.ui.model
|
||||
|
||||
import androidx.compose.runtime.staticCompositionLocalOf
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import org.umamo.reimport.LayerMatch
|
||||
import org.umamo.runtime.model.ArtSourceId
|
||||
|
||||
/**
|
||||
* The pixel-scored suggestions the last operation that read a file published for its unresolved
|
||||
* bindings, keyed by file and lost layer key: what the Sources space prefers over the ranking it can
|
||||
* make from the model alone. Read-only here; the app publishes into it after a reload, a replace, or
|
||||
* a Match Automatically, and clears it on a document swap.
|
||||
*
|
||||
* @property StateFlow suggestions The best candidate per lost binding, by (file, lost key).
|
||||
*/
|
||||
class SourceSuggestionState(
|
||||
val suggestions: StateFlow<Map<Pair<ArtSourceId, String>, LayerMatch>>,
|
||||
)
|
||||
|
||||
/** The open document's published suggestions, or null when none were published (no document, or outside the app). */
|
||||
val LocalSourceSuggestions = staticCompositionLocalOf<SourceSuggestionState?> { null }
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user