feat: restore five themes and native LUT thumbnail library with source-frame previews

这个提交包含在:
mac 于 2026-10-31 03:39:46 +08:00 提交
1 父节点 c5441fab87
当前提交 61ea1c64a0
17 个文件已更改
+4944 -95

没有与搜索条件相匹配的文件

文件差异过大,未显示。 加载差异
+50
查看文件
@@ -0,0 +1,50 @@
# LumiGrade 主题和 LUT 浏览库补充分析
目标仍为已安装 LumiGrade 3.0(56),arm64 分析切片 SHA256 `c04e911e449e888eb0d8c10f7bcf2b6bc2c4153b9ba86c1952ddf210c96c5e97`。本记录基于 Ghidra 12.1.4 的静态反编译、原文件资源清单和 Swift 符号;静态布局常量不表示已经观测到窗口在宿主实际弹出。完整的 35 条新增 Evidence 位于 `ThemeLUT-analysis.json`。`ThemePalette.json` 是从原双精度常量逐值解码的颜色数据,不是截图估色。
## 主题
- `ThemePreference.selectedIndex`(`0x100059374`,`ev_a8688461143765f6d38667a24dc736bcfcce133f76c6c1003b3e2d86ee6bfc67`)读取 `NSUserDefaults.standard`,合法整数为 0–4;缺失、错误类型、越界均回到 1。`refreshFromDisk` 为真时先 `synchronize`。
- `ThemePreference.select`(`0x1000594c4`,`ev_5dcc78a25578273dc8d179c57dc0afd79cf31d176d3cd88f806ab3a060f387df`)仅写合法索引,写后 `synchronize`,并向普通和分布式通知中心发布同一通知。因此原版主题是跨实例、跨进程的全局偏好,不是逐滤镜的可动画调色参数。
- 原偏好键 `LumiGrade.globalThemeIndex`(`ev_2dea9886c635b29b0e21643ccb31c1264ffd35280494e35f03405af8202bb692`),通知 `LumiGradeGlobalThemeDidChange`(`ev_fd94a34bf03cae7ae8a372d5c9b5b60a322d1e238115dac8e7996f8baa3b6ae5`)。复刻应使用产品自己的命名空间,不改原厂偏好。
- 依 `family(for:)`(`0x100059cec`)的比较常量和界面观测,五个色块顺序为灰、蓝、紫、绿、橙;这五个中文名称是说明性名称,不主张它们是原版 tooltip 文案。色块 RGB 分别为 `(0.30,0.33,0.38)`、`(0.28,0.72,1)`、`(0.58,0.52,1)`、`(0.30,0.86,0.52)`、`(1,0.61,0.28)`,默认蓝。
- `chromeAccent`(`0x10005b1bc`,`ev_e814744aa17fdd27bbd3b46f60561201c4bdebf068a430b2007006b5c51ee7f2`)另将灰转为 `(0.72,0.77,0.84)`、蓝转为 `(0.22,0.67,1)`,其余三个保持对应主题色。不能直接把灰色块的暗灰当文字和工具图标 tint。
- `palette`(`0x10005a028`,`ev_0a2bea4354863fd7685a919ca6dae83ba5cf582f12cd0592edb24f0816eee35a`)生成每主题 17 色,使用 `colorWithCalibratedRed:green:blue:alpha:`。数组按原 Palette 存储顺序保留。消费者确认的槽含义如下。
| 槽 | 实际用途 | 消费函数 |
| --- | --- | --- |
| 1 | 整体面板底色 | InspectorView.applyAccent,`0x10001c9a4` |
| 3 | section 内容底色 | SectionView.applyAccent,`0x100022d98` |
| 6、7 | section 标题胶囊渐变 | SectionTitleButton.applyAccent,`0x100049e6c` |
| 8、9 | 普通滑条轨道渐变 | SliderCell.drawTrackBackground,`0x100041fa8` |
| 10、11 | 普通滑条活动段渐变 | SliderCell.drawBar,`0x10006c9c0` |
| 14 | Logo 和 section 标题文字 | InspectorView / SectionTitleButton.applyAccent |
| 15 | 参数行、输入和 LUT 标签 | InspectorView.applyAccent |
| 16 | 版本文字 | InspectorView.applyAccent |
Section 描边使用 chrome accent 的 alpha 0.38;可见性、展开和其他工具按钮常用 alpha 0.92。普通滑条高度 5、圆角 2.5、黑色描边 alpha 0.28 / 线宽 0.6。其余槽在本次有完整颜色值,但不额外猜测语义。
## LUT 库发现与入口
- `userLookLUTFolderURL`(`0x100070058`,`ev_9a37e0a0dcdc73db9e2c58ceb5d34dfbbe0629d4b59cc2c082f68ac7d69c5c56`)使用用户 Movies 目录,回退 `~/Movies`,再拼接 `梁哥调色LUT/look LUTs`。复刻使用自己的目录,不修改原厂库。
- `lookLUTFolders`(`0x1000822b4`,`ev_abc8f7799dfd67b519733d2de59c75c013b02dd07b59f009a770fa6ab41c76b0`)另加入插件 bundleForClass 和 mainBundle 的 `Resources/LUTs/Look`,再加入用户目录。
- `discoverLookLUTOptions`(`0x100070bc8`)读取目录内容,跳过隐藏内容(options=4),文件扩展名小写比较 `cube`。顶层目录分别递归枚举;顶层文件进入「未分类」,以路径去重,再排序。此次安装包里的 17 个 `.cube` 全部为输入相机配置;清单中没有 `LUTs/Look` 内置风格文件。未在此调查中读取用户 LUT 文件内容。
- `lookLUTMenuGroups`(`0x100090360`,`ev_db2b7ee3dceb2a58706ee4515113437a34f4199bcc0508ab053933fa590529ad`)排除第 0 个「无」选项,以已有 group title 分组,无 group 时归「未分类」,保留 selection index 给点击回写。
- `openLookLUTFolder`(`0x100066c10`,`ev_82b900e1fdd53b69048bcf894b4fba6bff9f958acdbc26c4e7b7bc58320eab67`)创建用户目录并调用 `NSWorkspace.openURL`;右侧文件夹图标用于在 Finder 打开文件夹,未显示选择根目录的 open panel。
## 浏览器布局、选择和缩略图
- `showLookLUTPreviewBrowser`(`0x10001ee8c`,`ev_7e6daea432f64c3380b5399e539dcf6abaafc0fe4ad7efe3d507121a1d722813`)以 **760×560** 展示 `LookLUTBrowserView`;可按宿主选择原生 host presentation 或 anchored `NSPopover`。Popover behavior=1,锚在入口按钮。
- `build`(`0x10004f9fc`,`ev_70bccecb4b8d036ad6303ee9fa6b2c34dd9768db7a0a5f9428db4a4d81c4329d`)浏览器底色固定 Calibrated RGB `(0.035,0.08,0.12)`;整体内边距 12、纵间距 10;左目录宽 150,顶部左标题宽 145,右网格容器宽 560,最小高 240;左右列间距 12。顶部同时显示库标题、当前目录及文件数和缩略图大小滑杆。标题 14 semibold;文件数 10 medium。
- initializer(`0x100066534`,`ev_98b1bcc280692122ab576ba2cf0062846372dfee4db01a703307f2c4ac5d8e3d`)创建 size slider:默认 **96**、最小 **70**、最大 **255**,宽 150。读取 `LumiGrade.lookLUTPreview.thumbnailSize`(无有效正数时为 96)及 `LumiGrade.lookLUTPreview.selectedFolder`。该偏好同样应在复刻中使用独立键。
- `thumbnailClicked`(`0x100052784`,`ev_cc54cc6744ddd7a436ee769e86209c3306f4576995f7033b108ea225d803bd6f`)单击即设置所选 index、更新 tile 选择边框并调用 onSelect;该函数没有关闭浏览器。未发现必须双击才应用的路径。
- Tile initializer(`0x100066338`)设置宽度为缩略图大小,高度为 `size×9/16+24`。图像为 16:9,下方额外 24 像素放名称。
- `sizeChanged`(`0x100052814`,`ev_083dcc84539e4a5e2e388f33f77929bc857b3ef6651054aab08593f6fcd1c52a`)保存偏好,取消旧 work item,**0.22 秒 debounce** 后重建。
- `reloadThumbnails`(`0x100051238`)按当前尺寸重新分行,每行 spacing 10;后台 previewQueue 逐项生成,generationID 与弱引用用于抛弃旧代、已关闭视图或过期 tile 的结果。UI 更新回主线程。
- `currentLookLUTPreviewItem`(`0x10007f148`)缓存键为 `frameVersion|Int(size)|LUT path`,超过 600 项清空缓存;用 currentPreviewFrame 或 fallbackPreviewFrame,对每个候选施加对应 LUT。
- `currentPreviewFrame`(`0x10007f4f4`,`ev_7f13d031b53f51bd16e7cea9755f085d590d702c7dc993a31040568a17b4d9b9`)在缩略图 LUT 前先处理当前输入 LUT 及其强度,并按源帧版本缓存结果。`capturePreviewFrameIfNeeded`(`0x1000833ec`)捕获节流 **0.35 秒**;输入路径/强度变化立即递增版本并失效 processedPreviewFrame。
- `thumbnailImage`(`0x100091a04`,`ev_47a86ed56280777069e755d726b84701244573dceed4b182f9ec8de02d12fc40`)宽 `max(64,Int(size))`,高 `max(40,Int(width×9/16))`;先转 RGBA8,以每通道 `/255` 经 CubeLUT.sample,然后 clamp/量化回显示字节。此浏览器缩略图并非整套基础调色和五层 LUT 合成后的画面。
## 证据边界
地址对应本次 arm64 切片,不能当作其他版本地址。Ghidra 对 Swift 参数和 SIMD 值有类型恢复误差,本文仅将直接常量、可见 API、字段读写及可验证的堆栈偏移用作实现规格。颜色槽用途按原存储偏移与具体消费者对应;布局常量仍需正式宿主进行视觉核对。浏览器没有从此静态清单中推断出网络商店、账号收藏、搜索框或动态商业 LUT 下载功能。已关闭本次 REA 原生会话;可复用的完整 session snapshot 保存在本机产品缓存 `research/ThemeLUT-snapshot.json`。
+599
查看文件
@@ -0,0 +1,599 @@
{
"sourceAddress": "0x10005a028",
"evidenceID": "ev_0a2bea4354863fd7685a919ca6dae83ba5cf582f12cd0592edb24f0816eee35a",
"paletteSlotOrder": "Native Palette struct slots 0..16; semantic names require usage confirmation. Slots 0..15 RGBA; slot16 RGB with alpha 1.",
"themeIndexOrder": [
"gray",
"blue",
"purple",
"green",
"orange"
],
"swatchRGB": [
[
0.3,
0.33,
0.38
],
[
0.28,
0.72,
1
],
[
0.58,
0.52,
1
],
[
0.3,
0.86,
0.52
],
[
1,
0.61,
0.28
]
],
"defaultIndex": 1,
"palettes": {
"orange": [
[
0.23,
0.15,
0.08,
1.0
],
[
0.16,
0.1,
0.05,
1.0
],
[
0.35,
0.22,
0.11,
1.0
],
[
0.26,
0.16,
0.08,
1.0
],
[
0.45,
0.28,
0.14,
1.0
],
[
0.36,
0.22,
0.1,
1.0
],
[
0.72,
0.44,
0.18,
1.0
],
[
0.56,
0.32,
0.12,
1.0
],
[
0.29,
0.18,
0.09,
1.0
],
[
0.2,
0.12,
0.06,
1.0
],
[
0.98,
0.67,
0.31,
1.0
],
[
0.86,
0.47,
0.17,
1.0
],
[
1.0,
0.86,
0.57,
1.0
],
[
0.93,
0.59,
0.22,
1.0
],
[
1.0,
0.96,
0.9,
1.0
],
[
0.97,
0.9,
0.82,
1.0
],
[
0.8,
0.7,
0.58
]
],
"purple": [
[
0.11,
0.09,
0.17,
1.0
],
[
0.07,
0.06,
0.12,
1.0
],
[
0.18,
0.14,
0.28,
1.0
],
[
0.13,
0.1,
0.21,
1.0
],
[
0.27,
0.22,
0.42,
1.0
],
[
0.2,
0.16,
0.31,
1.0
],
[
0.43,
0.34,
0.68,
1.0
],
[
0.31,
0.23,
0.52,
1.0
],
[
0.22,
0.18,
0.31,
1.0
],
[
0.15,
0.12,
0.23,
1.0
],
[
0.78,
0.71,
1.0,
1.0
],
[
0.5,
0.42,
0.93,
1.0
],
[
0.95,
0.9,
1.0,
1.0
],
[
0.63,
0.5,
0.95,
1.0
],
[
0.98,
0.95,
1.0,
1.0
],
[
0.9,
0.86,
0.97,
1.0
],
[
0.7,
0.66,
0.82
]
],
"gray": [
[
0.11,
0.12,
0.14,
1.0
],
[
0.075,
0.08,
0.095,
1.0
],
[
0.17,
0.18,
0.21,
1.0
],
[
0.12,
0.13,
0.15,
1.0
],
[
0.27,
0.29,
0.33,
1.0
],
[
0.2,
0.22,
0.25,
1.0
],
[
0.36,
0.39,
0.44,
1.0
],
[
0.25,
0.28,
0.32,
1.0
],
[
0.21,
0.23,
0.26,
1.0
],
[
0.15,
0.17,
0.2,
1.0
],
[
0.78,
0.83,
0.9,
1.0
],
[
0.55,
0.61,
0.7,
1.0
],
[
1.0,
1.0,
1.0,
1.0
],
[
0.78,
0.82,
0.88,
1.0
],
[
0.96,
0.97,
0.98,
1.0
],
[
0.86,
0.89,
0.92,
1.0
],
[
0.67,
0.72,
0.77
]
],
"green": [
[
0.08,
0.17,
0.1,
1.0
],
[
0.05,
0.12,
0.07,
1.0
],
[
0.12,
0.27,
0.15,
1.0
],
[
0.09,
0.2,
0.11,
1.0
],
[
0.16,
0.35,
0.2,
1.0
],
[
0.12,
0.27,
0.15,
1.0
],
[
0.21,
0.57,
0.31,
1.0
],
[
0.14,
0.4,
0.21,
1.0
],
[
0.14,
0.27,
0.16,
1.0
],
[
0.1,
0.2,
0.11,
1.0
],
[
0.54,
0.96,
0.64,
1.0
],
[
0.22,
0.75,
0.35,
1.0
],
[
0.91,
1.0,
0.93,
1.0
],
[
0.28,
0.8,
0.42,
1.0
],
[
0.95,
1.0,
0.96,
1.0
],
[
0.86,
0.96,
0.88,
1.0
],
[
0.66,
0.8,
0.68
]
],
"blue": [
[
0.031,
0.086,
0.148,
1.0
],
[
0.025,
0.075,
0.13,
1.0
],
[
0.07,
0.155,
0.235,
1.0
],
[
0.045,
0.12,
0.19,
1.0
],
[
0.115,
0.22,
0.33,
1.0
],
[
0.07,
0.15,
0.24,
1.0
],
[
0.15,
0.33,
0.5,
1.0
],
[
0.08,
0.24,
0.36,
1.0
],
[
0.23,
0.32,
0.41,
1.0
],
[
0.18,
0.26,
0.35,
1.0
],
[
0.38,
0.76,
1.0,
1.0
],
[
0.23,
0.64,
0.97,
1.0
],
[
0.96,
0.98,
1.0,
1.0
],
[
0.62,
0.7,
0.76,
1.0
],
[
0.88,
0.96,
1.0,
1.0
],
[
0.82,
0.9,
0.96,
1.0
],
[
0.58,
0.7,
0.78
]
]
},
"preferenceKey": "LumiGrade.globalThemeIndex",
"notificationName": "LumiGradeGlobalThemeDidChange",
"chromeAccentRGB": [
[
0.72,
0.77,
0.84
],
[
0.22,
0.67,
1
],
[
0.58,
0.52,
1
],
[
0.3,
0.86,
0.52
],
[
1,
0.61,
0.28
]
],
"confirmedSlotUsages": {
"panelBackground": 1,
"sectionBackground": 3,
"sectionTitleGradientStart": 6,
"sectionTitleGradientEnd": 7,
"sliderTrackGradientStart": 8,
"sliderTrackGradientEnd": 9,
"sliderActiveGradientStart": 10,
"sliderActiveGradientEnd": 11,
"logoAndSectionTitleText": 14,
"rowLabelText": 15,
"versionText": 16
}
}
+1 -1
查看文件
@@ -91,7 +91,7 @@ def main():
run('pluginkit','-a',str(DEST/PLUGIN));registry=run('pluginkit','-m','-A','-D','-v','-i','com.dayu.color.XPC')
entries=[l for l in registry.splitlines() if 'com.dayu.color.XPC(' in l]
if len(entries)!=1 or not entries[0].rstrip().endswith('\t'+str(DEST/PLUGIN)):raise RuntimeError('PluginKit发现多份/错误版本: '+registry)
record=dict(status='installed-awaiting-host-verification',path=str(DEST),bundleID='com.dayu.color',version='1.0.0',build=plistlib.loads((DEST/'Contents/Info.plist').read_bytes())['CFBundleVersion'],team='B3W25FX5H5',notaryID=result['id'],notaryStatus=result['status'],gatekeeper=gate,sourceCommit=run('git','rev-parse','HEAD'),templatePath=str(TEMPLATE),templateSHA256=hashlib.sha256(TEMPLATE.read_bytes()).hexdigest(),shaderSHA256=hashlib.sha256((DEST/PLUGIN/'Contents/Resources/default.metallib').read_bytes()).hexdigest())
record=dict(status='installed-awaiting-host-verification',path=str(DEST),bundleID='com.dayu.color',version=plistlib.loads((DEST/'Contents/Info.plist').read_bytes())['CFBundleShortVersionString'],build=plistlib.loads((DEST/'Contents/Info.plist').read_bytes())['CFBundleVersion'],team='B3W25FX5H5',notaryID=result['id'],notaryStatus=result['status'],gatekeeper=gate,sourceCommit=run('git','rev-parse','HEAD'),templatePath=str(TEMPLATE),templateSHA256=hashlib.sha256(TEMPLATE.read_bytes()).hexdigest(),shaderSHA256=hashlib.sha256((DEST/PLUGIN/'Contents/Resources/default.metallib').read_bytes()).hexdigest())
output=ROOT/'verification/Delivery.json';output.write_text(json.dumps(record,ensure_ascii=False,indent=2)+'\n')
run('open',str(DEST));print('FORMAL_INSTALLED. Run installed self-test and host verification; type complete only after success. Type leave to preserve pending state.',flush=True)
for decision in sys.stdin:
+118
查看文件
@@ -0,0 +1,118 @@
#import <AppKit/AppKit.h>
#import "../大鱼调色/Plugin/DYLUTLibrary.h"
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <atomic>
static NSUInteger checkCount=0;
static NSMutableArray *results;
static void require(BOOL condition,NSString *label) {
++checkCount;[results addObject:@{@"name":label,@"pass":@(condition)}];
if(!condition){fprintf(stderr,"FAIL: %s\n",label.UTF8String);exit(1);}
}
static BOOL near(float a,float b){return fabsf(a-b)<1e-6f;}
static NSString *cube(float redGain=1,NSString *domain=@"") {
NSMutableString *text=[NSMutableString stringWithFormat:@"TITLE \"Dayu test only\"\nLUT_3D_SIZE 2\n%@",domain];
for(int b=0;b<2;b++)for(int g=0;g<2;g++)for(int r=0;r<2;r++)[text appendFormat:@"%.8f %d %d\n",r*redGain,g,b];return text;
}
static NSURL *write(NSURL *root,NSString *relative,NSString *text) {
NSURL *url=[root URLByAppendingPathComponent:relative];NSError *error=nil;
require([NSFileManager.defaultManager createDirectoryAtURL:url.URLByDeletingLastPathComponent withIntermediateDirectories:YES attributes:nil error:&error],@"create fixture directory");
require([text writeToURL:url atomically:YES encoding:NSUTF8StringEncoding error:&error],@"write fixture");return url;
}
static NSData *sample(float r,float g,float b,float a=1) {float p[]={r,g,b,a};return [NSData dataWithBytes:p length:sizeof(p)];}
int main(int argc,const char **argv){@autoreleasepool{
results=[NSMutableArray new];
NSURL *temporary=[NSURL fileURLWithPath:[NSTemporaryDirectory()stringByAppendingPathComponent:[@"dayu-lut-library-" stringByAppendingString:NSUUID.UUID.UUIDString]] isDirectory:YES];
NSFileManager *fm=NSFileManager.defaultManager;NSError *error=nil;
require([fm createDirectoryAtURL:temporary withIntermediateDirectories:YES attributes:nil error:&error],@"isolated temporary directory");
NSURL *source=[temporary URLByAppendingPathComponent:@"Sources"],*libraryURL=[temporary URLByAppendingPathComponent:@"Library"];
NSURL *identity=write(source,@"Identity.cube",cube()),*red=write(source,@"Red.cube",cube(1.5f));
NSURL *domain=write(source,@"Domain.cube",cube(1,@"DOMAIN_MIN 0 0 0\nDOMAIN_MAX 2 2 2\n"));
std::vector<float> values;NSUInteger n=0;
require(DYLUTReadCube(identity.path,values,n,&error)&&n==2&&values.size()==32,@"identity Cube parses");
for(int b=0;b<2;b++)for(int g=0;g<2;g++)for(int r=0;r<2;r++) {
NSUInteger i=((b*2+g)*2+r)*4;
require(near(values[i],r)&&near(values[i+1],g)&&near(values[i+2],b)&&near(values[i+3],1),@"Cube order is red-fastest");
}
NSData *input=sample(.37,.28,.81,.6);const float *out;
NSData *neutral=DYLUTTransformRGBA(input,1,1,identity.path,&error);out=(const float *)neutral.bytes;
require(neutral&&near(out[0],.37)&&near(out[1],.28)&&near(out[2],.81)&&near(out[3],.6),@"identity interpolation and alpha");
NSData *gain=DYLUTTransformRGBA(input,1,1,red.path,&error);out=(const float *)gain.bytes;
require(gain&&near(out[0],.555)&&near(out[1],.28)&&near(out[2],.81),@"red gain trilinear interpolation");
NSData *ranged=DYLUTTransformRGBA(input,1,1,domain.path,&error);out=(const float *)ranged.bytes;
require(ranged&&near(out[0],.185)&&near(out[1],.14)&&near(out[2],.405),@"DOMAIN normalization resamples Cube");
NSData *clear=DYLUTTransformRGBA(sample(NAN,.2,.3),1,1,nil,&error);out=(const float *)clear.bytes;
require(clear&&out[0]==0&&out[1]==0&&out[2]==0&&out[3]==0,@"invalid float samples become clear");
require(!DYLUTTransformRGBA([NSData data],1,1,nil,&error),@"reject malformed float RGBA length");
require(!DYLUTTransformRGBA(input,0,1,nil,&error),@"reject zero image width");
NSImage *thumbnail=DYLUTThumbnail(red.path,input,1,1,NSMakeSize(64,36),&error);
require(thumbnail&&NSEqualSizes(thumbnail.size,NSMakeSize(64,36)),@"thumbnail bitmap generated without GUI");
NSBitmapImageRep *rep=(NSBitmapImageRep *)thumbnail.representations.firstObject;
require(rep.pixelsWide==64&&rep.pixelsHigh==36&&abs(rep.bitmapData[0]-142)<=1&&abs(rep.bitmapData[3]-153)<=1,@"thumbnail reflects LUT colors and alpha");
require(DYLUTThumbnail(identity.path,nil,0,0,NSMakeSize(80,45),&error)!=nil,@"authored fallback chart thumbnail");
require(!DYLUTThumbnail(nil,nil,0,0,NSMakeSize(0,45),&error),@"reject invalid thumbnail size");
NSDictionary *oldAttributes=[fm attributesOfItemAtPath:red.path error:&error];
require([cube(1.6f)writeToURL:red atomically:NO encoding:NSUTF8StringEncoding error:&error],@"rewrite LUT in place");
NSDate *preciseChange=[oldAttributes[NSFileModificationDate]dateByAddingTimeInterval:.005];
require([fm setAttributes:@{NSFileModificationDate:preciseChange}ofItemAtPath:red.path error:&error],@"preserve subsecond modification distinction");
require(DYLUTReadCube(red.path,values,n,&error)&&near(values[4],1.6),@"cache invalidates same-size in-place rewrite");
std::atomic_bool parallelOK{true};std::atomic_bool *parallelState=&parallelOK;
dispatch_apply(64,dispatch_get_global_queue(QOS_CLASS_USER_INITIATED,0),^(size_t index){@autoreleasepool{
(void)index;std::vector<float> local;NSUInteger dimension=0;
if(!DYLUTReadCube(red.path,local,dimension,NULL)||dimension!=2||!near(local[4],1.6))parallelState->store(false);
}});
require(parallelOK,@"concurrent table cache reads stay consistent");
NSArray *invalid=@[@"LUT_3D_SIZE 1\n0 0 0\n",@"LUT_3D_SIZE 129\n",@"LUT_3D_SIZE 2\n0 0 0\n",@"LUT_1D_SIZE 2\n0 0 0\n1 1 1\n",@"LUT_3D_SIZE 2\nNaN 0 0\n",[cube() stringByAppendingString:@"0 0 0\n"],[cube() stringByAppendingString:@"DOMAIN_MAX 0 1 1\n"],[cube() stringByAppendingString:@"garbage\n"],[cube() stringByAppendingString:@"LUT_3D_SIZE 2\n"]];
NSUInteger invalidIndex=0;
for(NSString *text in invalid) {
NSURL *url=write(temporary,[NSString stringWithFormat:@"Invalid%lu.cube",(unsigned long)invalidIndex++],text);
require(!DYLUTReadCube(url.path,values,n,&error)&&values.empty()&&n==0,@"reject invalid Cube and clear output");
}
DYLUTLibrary *library=[[[DYLUTLibrary alloc]initWithRootURL:libraryURL]autorelease];
require([DYLUTLibrary.defaultRootURL.path hasSuffix:@"/Movies/大鱼调色LUT/look LUTs"],@"default library follows product Movies structure");
require([library reload:&error]&&library.entries.count==0&&![fm fileExistsAtPath:libraryURL.path],@"scan missing root is read only and empty");
NSArray *imported=[library importURLs:@[identity] error:&error];
require(imported.count==1&&library.entries.count==1,@"single LUT import and scan");
NSString *firstPath=imported[0][@"path"];NSData *firstContents=[NSData dataWithContentsOfFile:firstPath];
NSArray *duplicate=[library importURLs:@[identity] error:&error];
require(duplicate.count==1&&![duplicate[0][@"path"]isEqual:firstPath]&&library.entries.count==2,@"name collision creates unique copy");
require([[NSData dataWithContentsOfFile:firstPath]isEqual:firstContents],@"existing LUT remains byte-for-byte unchanged");
require([fm fileExistsAtPath:identity.path],@"import keeps original file");
NSURL *folder=write(source,@"Cinema/Warm/Amber.cube",cube(1.2));
write(source,@"Cinema/Cool/Blue.cube",cube(.8));write(source,@"Cinema/notes.txt",@"not a LUT");
NSURL *link=[source URLByAppendingPathComponent:@"Cinema/Linked.cube"];
require([fm createSymbolicLinkAtURL:link withDestinationURL:identity error:&error],@"create symlink fixture");
NSArray *recursive=[library importURLs:@[[folder URLByDeletingLastPathComponent].URLByDeletingLastPathComponent] error:&error];
require(recursive.count==2&&library.entries.count==4,@"directory recursively imports Cube only and skips symlinks");
require([library.folders containsObject:@"Cinema/Warm"]&&[library.folders containsObject:@"Cinema/Cool"],@"nested folder structure preserved");
require([library.entries[2][@"name"]length]>0&&[library.entries[2][@"relativeFolder"]isKindOfClass:NSString.class],@"entry has browser metadata");
require(![library importURLs:@[link] error:&error],@"direct symbolic link import rejected");
require(![library importURLs:@[[NSURL fileURLWithPath:firstPath]] error:&error],@"self library import rejected");
require(![library importURLs:@[[NSURL URLWithString:@"https://example.com/a.cube"]] error:&error],@"remote URL import rejected");
NSURL *invalidFolder=[temporary URLByAppendingPathComponent:@"InvalidPack"];
write(invalidFolder,@"Good.cube",cube());write(invalidFolder,@"Bad.cube",@"invalid");
NSUInteger before=library.entries.count;
require(![library importURLs:@[invalidFolder] error:&error]&&library.entries.count==before,@"invalid folder preflight prevents partial imports");
NSURL *blocked=write(source,@"Blocked/One.cube",cube());
NSURL *outside=[temporary URLByAppendingPathComponent:@"Outside" isDirectory:YES];
require([fm createDirectoryAtURL:outside withIntermediateDirectories:YES attributes:nil error:&error],@"create outside destination fixture");
NSURL *destinationLink=[library.rootURL URLByAppendingPathComponent:@"Blocked"];
require([fm createSymbolicLinkAtURL:destinationLink withDestinationURL:outside error:&error],@"create destination directory symlink fixture");
require(![library importURLs:@[red,blocked.URLByDeletingLastPathComponent] error:&error],@"linked destination rejected and new files rolled back");
require(![fm fileExistsAtPath:[[outside URLByAppendingPathComponent:@"One.cube"]path]],@"import cannot escape via existing directory link");
require([library reload:&error]&&library.entries.count==before,@"rollback preserves previous library contents");
require([library setFavorite:YES forPath:firstPath error:&error]&&[library isFavoritePath:firstPath],@"favorite is persisted");
DYLUTLibrary *second=[[[DYLUTLibrary alloc]initWithRootURL:libraryURL]autorelease];
require([second isFavoritePath:firstPath],@"favorite survives library recreation");
require([second setFavorite:NO forPath:firstPath error:&error]&&![second isFavoritePath:firstPath],@"favorite removal persists");
require(![second setFavorite:YES forPath:identity.path error:&error],@"favorite outside root rejected");
NSDictionary *report=@{@"pass":@YES,@"checks":@(checkCount),@"results":results,@"scope":@"Standalone library/parser/bitmap checks on synthetic LUT files in an isolated temporary directory. No GUI or user library modified."};
NSData *json=[NSJSONSerialization dataWithJSONObject:report options:NSJSONWritingPrettyPrinted error:&error];
if(argc>1)require([json writeToFile:[NSString stringWithUTF8String:argv[1]] atomically:YES],@"write test report");
fwrite(json.bytes,1,json.length,stdout);puts("");
require([fm removeItemAtURL:temporary error:&error],@"clean isolated temporary fixtures");[results release];return 0;
}}
+375
查看文件
@@ -0,0 +1,375 @@
{
"results" : [
{
"name" : "isolated temporary directory",
"pass" : true
},
{
"name" : "create fixture directory",
"pass" : true
},
{
"name" : "write fixture",
"pass" : true
},
{
"name" : "create fixture directory",
"pass" : true
},
{
"name" : "write fixture",
"pass" : true
},
{
"name" : "create fixture directory",
"pass" : true
},
{
"name" : "write fixture",
"pass" : true
},
{
"name" : "identity Cube parses",
"pass" : true
},
{
"name" : "Cube order is red-fastest",
"pass" : true
},
{
"name" : "Cube order is red-fastest",
"pass" : true
},
{
"name" : "Cube order is red-fastest",
"pass" : true
},
{
"name" : "Cube order is red-fastest",
"pass" : true
},
{
"name" : "Cube order is red-fastest",
"pass" : true
},
{
"name" : "Cube order is red-fastest",
"pass" : true
},
{
"name" : "Cube order is red-fastest",
"pass" : true
},
{
"name" : "Cube order is red-fastest",
"pass" : true
},
{
"name" : "identity interpolation and alpha",
"pass" : true
},
{
"name" : "red gain trilinear interpolation",
"pass" : true
},
{
"name" : "DOMAIN normalization resamples Cube",
"pass" : true
},
{
"name" : "invalid float samples become clear",
"pass" : true
},
{
"name" : "reject malformed float RGBA length",
"pass" : true
},
{
"name" : "reject zero image width",
"pass" : true
},
{
"name" : "thumbnail bitmap generated without GUI",
"pass" : true
},
{
"name" : "thumbnail reflects LUT colors and alpha",
"pass" : true
},
{
"name" : "authored fallback chart thumbnail",
"pass" : true
},
{
"name" : "reject invalid thumbnail size",
"pass" : true
},
{
"name" : "rewrite LUT in place",
"pass" : true
},
{
"name" : "preserve subsecond modification distinction",
"pass" : true
},
{
"name" : "cache invalidates same-size in-place rewrite",
"pass" : true
},
{
"name" : "concurrent table cache reads stay consistent",
"pass" : true
},
{
"name" : "create fixture directory",
"pass" : true
},
{
"name" : "write fixture",
"pass" : true
},
{
"name" : "reject invalid Cube and clear output",
"pass" : true
},
{
"name" : "create fixture directory",
"pass" : true
},
{
"name" : "write fixture",
"pass" : true
},
{
"name" : "reject invalid Cube and clear output",
"pass" : true
},
{
"name" : "create fixture directory",
"pass" : true
},
{
"name" : "write fixture",
"pass" : true
},
{
"name" : "reject invalid Cube and clear output",
"pass" : true
},
{
"name" : "create fixture directory",
"pass" : true
},
{
"name" : "write fixture",
"pass" : true
},
{
"name" : "reject invalid Cube and clear output",
"pass" : true
},
{
"name" : "create fixture directory",
"pass" : true
},
{
"name" : "write fixture",
"pass" : true
},
{
"name" : "reject invalid Cube and clear output",
"pass" : true
},
{
"name" : "create fixture directory",
"pass" : true
},
{
"name" : "write fixture",
"pass" : true
},
{
"name" : "reject invalid Cube and clear output",
"pass" : true
},
{
"name" : "create fixture directory",
"pass" : true
},
{
"name" : "write fixture",
"pass" : true
},
{
"name" : "reject invalid Cube and clear output",
"pass" : true
},
{
"name" : "create fixture directory",
"pass" : true
},
{
"name" : "write fixture",
"pass" : true
},
{
"name" : "reject invalid Cube and clear output",
"pass" : true
},
{
"name" : "create fixture directory",
"pass" : true
},
{
"name" : "write fixture",
"pass" : true
},
{
"name" : "reject invalid Cube and clear output",
"pass" : true
},
{
"name" : "default library follows product Movies structure",
"pass" : true
},
{
"name" : "scan missing root is read only and empty",
"pass" : true
},
{
"name" : "single LUT import and scan",
"pass" : true
},
{
"name" : "name collision creates unique copy",
"pass" : true
},
{
"name" : "existing LUT remains byte-for-byte unchanged",
"pass" : true
},
{
"name" : "import keeps original file",
"pass" : true
},
{
"name" : "create fixture directory",
"pass" : true
},
{
"name" : "write fixture",
"pass" : true
},
{
"name" : "create fixture directory",
"pass" : true
},
{
"name" : "write fixture",
"pass" : true
},
{
"name" : "create fixture directory",
"pass" : true
},
{
"name" : "write fixture",
"pass" : true
},
{
"name" : "create symlink fixture",
"pass" : true
},
{
"name" : "directory recursively imports Cube only and skips symlinks",
"pass" : true
},
{
"name" : "nested folder structure preserved",
"pass" : true
},
{
"name" : "entry has browser metadata",
"pass" : true
},
{
"name" : "direct symbolic link import rejected",
"pass" : true
},
{
"name" : "self library import rejected",
"pass" : true
},
{
"name" : "remote URL import rejected",
"pass" : true
},
{
"name" : "create fixture directory",
"pass" : true
},
{
"name" : "write fixture",
"pass" : true
},
{
"name" : "create fixture directory",
"pass" : true
},
{
"name" : "write fixture",
"pass" : true
},
{
"name" : "invalid folder preflight prevents partial imports",
"pass" : true
},
{
"name" : "create fixture directory",
"pass" : true
},
{
"name" : "write fixture",
"pass" : true
},
{
"name" : "create outside destination fixture",
"pass" : true
},
{
"name" : "create destination directory symlink fixture",
"pass" : true
},
{
"name" : "linked destination rejected and new files rolled back",
"pass" : true
},
{
"name" : "import cannot escape via existing directory link",
"pass" : true
},
{
"name" : "rollback preserves previous library contents",
"pass" : true
},
{
"name" : "favorite is persisted",
"pass" : true
},
{
"name" : "favorite survives library recreation",
"pass" : true
},
{
"name" : "favorite removal persists",
"pass" : true
},
{
"name" : "favorite outside root rejected",
"pass" : true
}
],
"scope" : "Standalone library\/parser\/bitmap checks on synthetic LUT files in an isolated temporary directory. No GUI or user library modified.",
"pass" : true,
"checks" : 92
}
+4 -1
查看文件
@@ -53,13 +53,16 @@
04962E923095058F009952AA /* Exceptions for "大鱼调色" folder in "Wrapper Application" target */ = {
isa = PBXFileSystemSynchronizedBuildFileExceptionSet;
membershipExceptions = (
"Plugin/DYDiagnostics.mm",
"/Localized: Plugin/InfoPlist.strings",
"/Localized: Plugin/Localizable.strings",
Plugin/DYAutoGrade.mm,
Plugin/DYColorTables.mm,
Plugin/DYDiagnostics.mm,
Plugin/DYGrade.metal,
Plugin/DYInspector.mm,
Plugin/DYTheme.mm,
Plugin/DYLUTLibrary.mm,
Plugin/DYLUTBrowser.mm,
Plugin/DYModel.mm,
Plugin/DYPlugIn.mm,
Plugin/DYRenderer.mm,
+157 -56
查看文件
@@ -33,13 +33,13 @@ static NSString *DYNumber(double value,NSDictionary *d) {
@implementation DYBlueSliderCell
- (void)drawBarInside:(NSRect)rect flipped:(BOOL)flipped {
NSRect track=NSMakeRect(rect.origin.x,NSMidY(rect)-2,rect.size.width,4);
[DYThemeColor(@"field") setFill];[[NSBezierPath bezierPathWithRoundedRect:track xRadius:2 yRadius:2] fill];
[DYThemeColor(@"track") setFill];[[NSBezierPath bezierPathWithRoundedRect:track xRadius:2 yRadius:2] fill];
double fraction=(self.doubleValue-self.minValue)/fmax(.000001,self.maxValue-self.minValue);
NSRect active=track;active.size.width*=fmax(0,fmin(1,fraction));[DYAccent() setFill];[[NSBezierPath bezierPathWithRoundedRect:active xRadius:2 yRadius:2] fill];
NSRect active=track;active.size.width*=fmax(0,fmin(1,fraction));NSGradient *g=[[[NSGradient alloc]initWithStartingColor:DYThemePalette()[@"activeTop"] endingColor:DYThemePalette()[@"activeBottom"]]autorelease];[g drawInBezierPath:[NSBezierPath bezierPathWithRoundedRect:active xRadius:2 yRadius:2] angle:90];
}
- (void)drawKnob:(NSRect)knobRect {
NSRect circle=NSInsetRect(knobRect,1,1);
[[DYThemePalette()[@"accent"] blendedColorWithFraction:.7 ofColor:NSColor.whiteColor] setFill];[[NSBezierPath bezierPathWithOvalInRect:circle] fill];
[DYThemeColor(@"knob") setFill];[[NSBezierPath bezierPathWithOvalInRect:circle] fill];
[DYAccent() setStroke];NSBezierPath *ring=[NSBezierPath bezierPathWithOvalInRect:circle];ring.lineWidth=.7;[ring stroke];
}
@end
@@ -110,8 +110,7 @@ static NSArray *DYAccessibleSubviews(NSView *view, BOOL visibleOnly) {
@implementation DYHeader
- (void)drawRect:(NSRect)dirtyRect {
NSRect r=NSInsetRect(self.bounds,.5,2);
NSColor *accent=DYThemePalette()[@"accent"],*card=DYThemePalette()[@"card"];
NSGradient *g=[[[NSGradient alloc]initWithStartingColor:[card blendedColorWithFraction:.43 ofColor:accent] endingColor:[card blendedColorWithFraction:.16 ofColor:accent]]autorelease];
NSGradient *g=[[[NSGradient alloc]initWithStartingColor:DYThemePalette()[@"headerTop"] endingColor:DYThemePalette()[@"headerBottom"]]autorelease];
[g drawInBezierPath:[NSBezierPath bezierPathWithRoundedRect:r xRadius:8 yRadius:8] angle:90];
[self.title drawInRect:NSInsetRect(r,9,5) withAttributes:@{NSFontAttributeName:self.font,NSForegroundColorAttributeName:DYInk()}];
}
@@ -349,27 +348,42 @@ static NSImage *DYWheelImage(void) {
NSMutableDictionary *_assetButtons;
NSMutableArray *_graphics;
NSColorSampler *_sampler;
DYRenderer *_renderer;
DYLUTLibrary *_library;
DYLUTBrowser *_browser;
NSArray *_themeButtons;
NSMutableDictionary *_tabs;
NSInteger _visibleLooks;
BOOL _refreshing;
}
@end
@implementation DYInspector
- (instancetype)initWithAPIManager:(id<PROAPIAccessing>)manager {
return [self initWithAPIManager:manager renderer:nil];
}
- (instancetype)initWithAPIManager:(id<PROAPIAccessing>)manager renderer:(DYRenderer *)renderer {
if((self=[super initWithFrame:NSMakeRect(0,0,360,780)])) {
_manager=manager; _sections=[DYSections() copy];
_manager=manager; _renderer=[renderer retain];_library=[DYLUTLibrary new];_tabs=[NSMutableDictionary new];_visibleLooks=1;
_sections=[DYPresentationSections() copy];
_cards=[[NSMutableArray alloc] init]; _controls=[[NSMutableDictionary alloc] init];
_assetButtons=[[NSMutableDictionary alloc] init]; _graphics=[[NSMutableArray alloc] init];
self.autoresizingMask=NSViewWidthSizable;
self.clipsToBounds=YES;
self.wantsLayer=YES; self.layer.masksToBounds=YES;
self.layer.backgroundColor=[[NSColor colorWithSRGBRed:.018 green:.074 blue:.12 alpha:1] CGColor];
_brand=[DYLabel(@"大鱼调色",20) retain]; _brand.font=[NSFont boldSystemFontOfSize:20];
_subtitle=[DYLabel(@"颜色 · 光影 · 风格",10) retain]; _subtitle.textColor=DYAccent();
_resetAll=[DYButton(@"全部还原",self,@selector(resetAll:)) retain]; _resetAll.toolTip=@"恢复全部调色参数与 LUT";
self.layer.backgroundColor=[DYThemePalette()[@"background"] CGColor];
self.appearance=[NSAppearance appearanceNamed:NSAppearanceNameDarkAqua];
_brand=[DYLabel(@"◒ 大鱼调色",16) retain]; _brand.font=[NSFont boldSystemFontOfSize:16];
_subtitle=[DYLabel(@"1.1",9) retain]; _subtitle.textColor=DYThemeColor(@"secondary");
_resetAll=[DYButton(@"↺",self,@selector(resetAll:)) retain]; _resetAll.toolTip=@"恢复全部调色参数与 LUT";_resetAll.accessibilityLabel=@"全部还原";
_save=[DYButton(@"保存预设",self,@selector(savePreset:)) retain];
_load=[DYButton(@"载入预设",self,@selector(loadPreset:)) retain];
_export=[DYButton(@"导出 LUT",self,@selector(exportLUT:)) retain];
for(NSView *v in @[_brand,_subtitle,_resetAll,_save,_load,_export]) [self addSubview:v];
NSMutableArray *themes=[NSMutableArray array];for(NSInteger i=0;i<5;i++){
DYSwatchButton *b=[[[DYSwatchButton alloc]initWithFrame:NSZeroRect]autorelease];[b setButtonType:NSButtonTypePushOnPushOff];b.swatch=DYThemeSwatch(i);b.tag=i;b.target=self;b.action=@selector(selectTheme:);b.title=@"";b.bordered=NO;
b.toolTip=[DYThemeNames()[i] stringByAppendingString:@"主题"];b.accessibilityLabel=b.toolTip;[self addSubview:b];[themes addObject:b];
}_themeButtons=[themes copy];
_scroll=[[DYInspectorScrollView alloc] initWithFrame:NSZeroRect];
_scroll.hasVerticalScroller=YES; _scroll.hasHorizontalScroller=NO; _scroll.drawsBackground=NO;
_scroll.autohidesScrollers=YES; _scroll.borderType=NSNoBorder;
@@ -382,6 +396,9 @@ static NSImage *DYWheelImage(void) {
_scroll.documentView=_document; [self addSubview:_scroll];
[self buildCards];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(modelChanged:) name:@"DYModelChanged" object:_manager];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(themeChanged:) name:DYThemeDidChange object:nil];
if(_renderer)[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(previewChanged:) name:@"DYPreviewDidChange" object:_renderer];
[self themeChanged:nil];
[self setAccessibilityLabel:@"大鱼调色检查器"];
[self setNeedsLayout:YES];
}
@@ -391,6 +408,7 @@ static NSImage *DYWheelImage(void) {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[_brand release]; [_subtitle release]; [_resetAll release]; [_save release]; [_load release]; [_export release];
[_scroll release]; [_document release]; [_sections release]; [_cards release]; [_controls release]; [_assetButtons release]; [_graphics release]; [_sampler release];
[_browser close];[_browser release];[_renderer release];[_library release];[_themeButtons release];[_tabs release];
[super dealloc];
}
- (BOOL)isFlipped { return YES; }
@@ -411,6 +429,21 @@ static NSImage *DYWheelImage(void) {
if([NSThread isMainThread]) [self refresh];
else dispatch_async(dispatch_get_main_queue(),^{ [self refresh]; });
}
- (void)selectTheme:(NSButton *)button {DYSetThemeIndex(button.tag);}
- (void)redrawTree:(NSView *)view { [view setNeedsDisplay:YES];for(NSView *child in view.subviews)[self redrawTree:child]; }
- (void)themeChanged:(NSNotification *)notification {
self.layer.backgroundColor=[DYThemePalette()[@"background"] CGColor];
for(NSButton *b in _themeButtons)b.state=b.tag==DYThemeIndex()?NSControlStateValueOn:NSControlStateValueOff;
for(NSDictionary *r in _controls.allValues)[r[@"field"] setBackgroundColor:DYThemeColor(@"field")];
[_browser updatePalette:DYThemePalette()];[self redrawTree:self];
}
- (void)tabChanged:(NSControl *)sender {
if([sender isKindOfClass:NSSegmentedControl.class])_tabs[sender.identifier]=@([(NSSegmentedControl *)sender selectedSegment]);
else {_tabs[@"hsl"]=@(sender.tag);for(NSView *v in sender.superview.subviews)if([v isKindOfClass:DYSwatchButton.class])[(NSButton *)v setState:v.tag==sender.tag?NSControlStateValueOn:NSControlStateValueOff];}
[self setNeedsLayout:YES];NSAccessibilityPostNotification(self,NSAccessibilityLayoutChangedNotification);
}
- (void)addLook:(id)sender {_visibleLooks=MIN(5,_visibleLooks+1);[self setNeedsLayout:YES];}
- (void)previewChanged:(NSNotification *)note {if(_browser.window.visible)[_browser updatePreview:[_renderer preview]];}
- (void)buildCards {
NSInteger index=0;
for(NSDictionary *section in _sections) {
@@ -418,12 +451,12 @@ static NSImage *DYWheelImage(void) {
card.accessibilityLabel=section[@"title"];
[_document addSubview:card];
DYHeader *header=[[[DYHeader alloc] initWithFrame:NSZeroRect] autorelease];
header.title=[@"▾ " stringByAppendingString:section[@"title"]?:@""];
header.title=[section[@"key"] isEqual:@"skin"]?@"肤色保护设置":section[@"title"];
header.bordered=NO; header.alignment=NSTextAlignmentLeft; header.font=[NSFont boldSystemFontOfSize:12];
header.contentTintColor=DYInk(); header.target=self; header.action=@selector(toggleSection:); header.tag=index;
header.doubleClickAction=@selector(resetSection:); header.toolTip=@"点击折叠;双击还原本组";
[card addSubview:header];
NSButton *enabled=[NSButton checkboxWithTitle:@"" target:self action:@selector(groupEnabled:)];
NSButton *enabled=DYButton(@"",self,@selector(groupEnabled:));enabled.bordered=NO;[enabled setButtonType:NSButtonTypePushOnPushOff];enabled.image=[NSImage imageWithSystemSymbolName:@"eye" accessibilityDescription:@"启用本组"];
enabled.tag=index; enabled.contentTintColor=DYAccent(); enabled.toolTip=@"启用或旁路本组";
enabled.accessibilityLabel=[section[@"title"] stringByAppendingString:@"启用"];
[card addSubview:enabled]; enabled.hidden=section[@"enabled"]==nil;
@@ -433,7 +466,7 @@ static NSImage *DYWheelImage(void) {
NSMutableArray *body=[NSMutableArray array];
NSString *key=section[@"key"]?:@"";
if([key localizedCaseInsensitiveContainsString:@"input"]) {
[body addObject:[self assetRowForKey:@"input" title:@"输入 LUT" inCard:card]];
[body addObject:[self assetRowForKey:@"input" title:@"输入色彩" inCard:card]];
}
if([key localizedCaseInsensitiveContainsString:@"look"]) {
for(NSInteger i=0;i<5;i++) {
@@ -449,9 +482,15 @@ static NSImage *DYWheelImage(void) {
[card addSubview:actions];[body addObject:actions];
}
if([key isEqual:@"hsl"]) {
DYFlippedView *tabs=[[[DYFlippedView alloc]initWithFrame:NSZeroRect]autorelease];tabs.identifier=@"hslTabs";
for(NSInteger i=0;i<9;i++){DYSwatchButton *b=[[[DYSwatchButton alloc]initWithFrame:NSZeroRect]autorelease];[b setButtonType:NSButtonTypePushOnPushOff];b.swatch=i<8?[NSColor colorWithSRGBRed:((double[]){1,1,1,.15,0,0,.75,1})[i] green:((double[]){.2,.55,.84,.76,.76,.47,.15,.15})[i] blue:((double[]){.25,.12,0,.25,.8,1,.9,.65})[i] alpha:1]:DYAccent();b.title=@"";b.tag=i;b.target=self;b.action=@selector(tabChanged:);b.state=i==0?NSControlStateValueOn:NSControlStateValueOff;b.accessibilityLabel=[@[@"红",@"橙",@"黄",@"绿",@"青",@"蓝",@"紫",@"洋红",@"自定义"][i] stringByAppendingString:@" HSL"];[tabs addSubview:b];}
[card addSubview:tabs];[body addObject:tabs];
DYFlippedView *actions=[[[DYFlippedView alloc]initWithFrame:NSZeroRect]autorelease];actions.identifier=@"sampleControls";
NSButton *picker=DYButton(@"吸取自定义 HSL 颜色",self,@selector(sampleCustomColor:));[actions addSubview:picker];[card addSubview:actions];[body addObject:actions];
}
if([key isEqual:@"levels"]||[key isEqual:@"balance"]) {
NSSegmentedControl *tabs=[NSSegmentedControl segmentedControlWithLabels:[key isEqual:@"levels"]?@[@"RGB",@"红",@"绿",@"蓝"]:@[@"阴影",@"中间调",@"高光"] trackingMode:NSSegmentSwitchTrackingSelectOne target:self action:@selector(tabChanged:)];tabs.identifier=key;tabs.selectedSegment=0;tabs.controlSize=NSControlSizeSmall;tabs.accessibilityLabel=[section[@"title"] stringByAppendingString:@"通道"];[card addSubview:tabs];[body addObject:tabs];
}
if([key isEqual:@"curve"]) {
DYCurvePanel *graph=[[[DYCurvePanel alloc]initWithFrame:NSZeroRect]autorelease];graph.delegate=self;graph.identifier=@"curveGraph";[card addSubview:graph];[body addObject:graph];[_graphics addObject:graph];
}
@@ -460,6 +499,7 @@ static NSImage *DYWheelImage(void) {
}
for(NSDictionary *d in section[@"rows"]) {
DYFlippedView *row=[[[DYFlippedView alloc] initWithFrame:NSZeroRect] autorelease];
row.identifier=d[@"key"];
row.accessibilityLabel=d[@"title"];
[card addSubview:row]; [body addObject:row];
NSNumber *pid=d[@"pid"]; if(!pid)continue;
@@ -487,7 +527,7 @@ static NSImage *DYWheelImage(void) {
slider.accessibilityLabel=d[@"title"]; [row addSubview:slider]; record[@"slider"]=slider;
NSTextField *field=[[[NSTextField alloc] initWithFrame:NSZeroRect] autorelease];
field.font=[NSFont monospacedDigitSystemFontOfSize:11 weight:NSFontWeightMedium];
field.textColor=DYInk(); field.backgroundColor=[NSColor colorWithSRGBRed:.08 green:.20 blue:.28 alpha:1];
field.textColor=DYInk(); field.backgroundColor=DYThemeColor(@"field");
field.bezeled=YES; field.bezelStyle=NSTextFieldRoundedBezel;
field.alignment=NSTextAlignmentRight; field.target=self; field.action=@selector(scalarChanged:);
field.tag=[pid integerValue]; field.accessibilityLabel=[d[@"title"] stringByAppendingString:@"数值"];
@@ -499,66 +539,88 @@ static NSImage *DYWheelImage(void) {
[row addSubview:itemReset]; record[@"reset"]=itemReset;
_controls[pid]=record;
}
[_cards addObject:[NSMutableDictionary dictionaryWithDictionary:@{@"section":section,@"view":card,@"header":header,@"enabled":enabled,@"reset":reset,@"body":body,@"collapsed":@NO}]];
if([key isEqual:@"look"]){
NSMutableArray *ordered=[NSMutableArray array];for(NSInteger slot=0;slot<5;slot++){
[ordered addObject:_assetButtons[[NSString stringWithFormat:@"look%ld",(long)slot]][@"row"]];NSString *strength=slot==0?@"postLUTStrength":[NSString stringWithFormat:@"look%ldStrength",(long)slot+1];
for(NSView *row in body)if([row.identifier isEqual:strength])[ordered addObject:row];
}
for(NSView *row in body)if(![ordered containsObject:row])row.hidden=YES;body=ordered;
}
NSMutableDictionary *record=[NSMutableDictionary dictionaryWithDictionary:@{@"section":section,@"view":card,@"header":header,@"enabled":enabled,@"reset":reset,@"body":body,@"collapsed":@([key isEqual:@"skin"])}];
if([key isEqual:@"look"]){NSButton *add=DYButton(@"+",self,@selector(addLook:));add.bordered=NO;add.font=[NSFont boldSystemFontOfSize:20];add.accessibilityLabel=@"添加风格 LUT";[card addSubview:add];record[@"add"]=add;}
[_cards addObject:record];
index++;
}
}
- (NSView *)assetRowForKey:(NSString *)key title:(NSString *)title inCard:(NSView *)card {
DYFlippedView *row=[[[DYFlippedView alloc] initWithFrame:NSZeroRect] autorelease]; [card addSubview:row];
DYFlippedView *row=[[[DYFlippedView alloc] initWithFrame:NSZeroRect] autorelease];row.identifier=[@"asset:" stringByAppendingString:key]; [card addSubview:row];
NSTextField *label=DYLabel(title,11); [row addSubview:label];
NSButton *choose=DYButton(@"无 · 点击选择…",self,@selector(chooseAsset:)); choose.identifier=key;
NSButton *browse=DYButton(@"▦",self,@selector(browseAsset:));browse.identifier=key;browse.bordered=NO;browse.font=[NSFont systemFontOfSize:19];browse.accessibilityLabel=[title stringByAppendingString:@"缩略图浏览库"];[row addSubview:browse];
NSButton *choose=DYButton(@"无",self,@selector(chooseAsset:)); choose.identifier=key;
choose.alignment=NSTextAlignmentLeft; choose.accessibilityLabel=title; [row addSubview:choose];
NSButton *remove=DYButton(@"×",self,@selector(removeAsset:)); remove.identifier=key;
remove.toolTip=@"移除此 LUT"; remove.accessibilityLabel=[title stringByAppendingString:@"移除"]; [row addSubview:remove];
_assetButtons[key]=@{@"row":row,@"label":label,@"choose":choose,@"remove":remove};
NSButton *folder=DYButton(@"",self,@selector(openLibraryFolder:));folder.identifier=key;folder.bordered=NO;folder.image=[NSImage imageWithSystemSymbolName:@"folder" accessibilityDescription:@"LUT文件夹"];folder.accessibilityLabel=[title stringByAppendingString:@"文件夹"];[row addSubview:folder];
_assetButtons[key]=@{@"row":row,@"label":label,@"choose":choose,@"remove":remove,@"browse":browse,@"folder":folder};
return row;
}
- (BOOL)showRow:(NSView *)row section:(NSString *)section {
NSString *key=row.identifier?:@"";NSInteger tab=[_tabs[section]integerValue];
if([section isEqual:@"curve"] && ![key isEqual:@"curveGraph"])return NO;
if([section isEqual:@"hsl"]) {
int axis=0,color=0;if(sscanf(key.UTF8String,"hsl%d_%d",&axis,&color)==2)return color==tab;
if([key hasPrefix:@"sample"]||[key hasPrefix:@"custom"]||[key hasPrefix:@"range"]||[key isEqual:@"hslVisualize"])return tab==8;
}
if([section isEqual:@"grading"]){int wheel=0,axis=0;if(sscanf(key.UTF8String,"grade%d_%d",&wheel,&axis)==2)return axis==2;}
if([section isEqual:@"levels"]){int channel=0,axis=0;if(sscanf(key.UTF8String,"level%d_%d",&channel,&axis)==2)return channel==tab;}
if([section isEqual:@"balance"]){int channel=0,axis=0;if(sscanf(key.UTF8String,"balance%d_%d",&channel,&axis)==2)return channel==tab;}
if([section isEqual:@"look"]){int slot=0;if(sscanf(key.UTF8String,"asset:look%d",&slot)==1)return slot<_visibleLooks;if([key isEqual:@"postLUTStrength"])return YES;int number=0;if(sscanf(key.UTF8String,"look%dStrength",&number)==1)return number-1<_visibleLooks;return NO;}
return YES;
}
- (CGFloat)heightForRow:(NSView *)row {return [row.identifier isEqual:@"curveGraph"]?240:[row.identifier isEqual:@"gradingWheels"]?292:32;}
- (void)layout {
[super layout];
CGFloat w=MAX(240,self.bounds.size.width),h=self.bounds.size.height;
_brand.frame=NSMakeRect(16,13,w-124,28); _subtitle.frame=NSMakeRect(17,43,w-124,16);
_resetAll.frame=NSMakeRect(w-101,23,86,28);
CGFloat gap=6,bw=(w-32-gap*2)/3;
_save.frame=NSMakeRect(16,66,bw,27); _load.frame=NSMakeRect(16+bw+gap,66,bw,27); _export.frame=NSMakeRect(16+(bw+gap)*2,66,bw,27);
_scroll.frame=NSMakeRect(0,104,w,MAX(80,h-104));
CGFloat cw=MAX(220,_scroll.contentSize.width-24),y=7;
CGFloat w=MAX(280,self.bounds.size.width),h=self.bounds.size.height;
_brand.frame=NSMakeRect(16,14,112,26);_subtitle.frame=NSMakeRect(130,21,23,13);
for(NSInteger i=0;i<5;i++)[_themeButtons[i]setFrame:NSMakeRect(w-146+i*22,17,21,22)];
_resetAll.frame=NSMakeRect(w-33,16,23,24);
CGFloat gap=7,bw=(w-32-gap*2)/3;
_save.frame=NSMakeRect(16,50,bw,27); _load.frame=NSMakeRect(16+bw+gap,50,bw,27); _export.frame=NSMakeRect(16+(bw+gap)*2,50,bw,27);
_scroll.frame=NSMakeRect(0,88,w,MAX(80,h-88));
CGFloat cw=MAX(244,_scroll.contentSize.width-32),y=8;
for(NSMutableDictionary *c in _cards) {
DYCard *card=c[@"view"]; BOOL collapsed=[c[@"collapsed"] boolValue];
DYCard *card=c[@"view"];BOOL collapsed=[c[@"collapsed"]boolValue];NSString *key=c[@"section"][@"key"];
NSArray *body=c[@"body"];CGFloat contentHeight=0;
for(NSView *row in body)contentHeight+=[row.identifier isEqual:@"curveGraph"]?240:[row.identifier isEqual:@"gradingWheels"]?292:35;
CGFloat bh=collapsed?0:contentHeight+9;
card.frame=NSMakeRect(12,y,cw,43+bh); y+=card.frame.size.height+12;
[c[@"enabled"] setFrame:NSMakeRect(12,12,20,20)];
[c[@"header"] setFrame:NSMakeRect(36,8,cw-82,28)];
[c[@"reset"] setFrame:NSMakeRect(cw-39,10,27,24)];
for(NSView *row in body)if([self showRow:row section:key])contentHeight+=[self heightForRow:row];
card.frame=NSMakeRect(16,y,cw,43+(collapsed?0:contentHeight+8));y+=card.frame.size.height+12;
[c[@"enabled"]setFrame:NSMakeRect(12,12,20,20)];
CGFloat titleWidth=MIN(cw-104,MAX(80,[[(NSButton *)c[@"header"]title]sizeWithAttributes:@{NSFontAttributeName:[NSFont boldSystemFontOfSize:12]}].width+22));
[c[@"header"]setFrame:NSMakeRect(42,8,titleWidth,28)];
[c[@"reset"]setFrame:NSMakeRect(cw-36,10,24,24)];
[c[@"add"]setFrame:NSMakeRect(cw-64,10,24,24)];[c[@"add"]setEnabled:_visibleLooks<5];
CGFloat rowY=43;
for(NSView *row in body) {
CGFloat rh=[row.identifier isEqual:@"curveGraph"]?240:[row.identifier isEqual:@"gradingWheels"]?292:35;row.hidden=collapsed;row.frame=NSMakeRect(10,rowY,cw-20,rh-2);rowY+=rh;
BOOL show=!collapsed&&[self showRow:row section:key];row.hidden=!show;if(!show)continue;
CGFloat rh=[self heightForRow:row];row.frame=NSMakeRect(12,rowY,cw-24,rh-1);rowY+=rh;
if([row.identifier isEqual:@"autoControls"]||[row.identifier isEqual:@"sampleControls"]) {
CGFloat buttonWidth=(row.bounds.size.width-8-4*(row.subviews.count-1))/MAX((NSUInteger)1,row.subviews.count);NSInteger buttonIndex=0;
for(NSView *button in row.subviews)[button setFrame:NSMakeRect(4+(buttonWidth+4)*buttonIndex++,4,buttonWidth,26)];
CGFloat buttonWidth=(row.bounds.size.width-4*(row.subviews.count-1))/MAX((NSUInteger)1,row.subviews.count);NSInteger i=0;
for(NSView *button in row.subviews)[button setFrame:NSMakeRect((buttonWidth+4)*i++,3,buttonWidth,25)];
}
if([row.identifier isEqual:@"hslTabs"]){CGFloat width=row.bounds.size.width/9;NSInteger i=0;for(NSView *button in row.subviews)[button setFrame:NSMakeRect(i++*width,1,width-1,27)];}
}
}
for(NSDictionary *record in _controls.allValues) {
CGFloat rw=[record[@"row"] bounds].size.width;
CGFloat lw=MIN(111,MAX(76,rw*.34));
CGFloat eyeWidth=record[@"itemEnabled"]?20:0;
[record[@"itemEnabled"] setFrame:NSMakeRect(0,6,20,20)];
[record[@"label"] setFrame:NSMakeRect(5+eyeWidth,8,lw-eyeWidth,18)];
[record[@"reset"] setFrame:NSMakeRect(rw-27,5,25,24)];
if(record[@"toggle"]) [record[@"toggle"] setFrame:NSMakeRect(lw+12,6,45,22)];
if(record[@"popup"]) [record[@"popup"] setFrame:NSMakeRect(lw+8,5,rw-lw-41,25)];
if(record[@"slider"]) {
[record[@"slider"] setFrame:NSMakeRect(lw+8,8,MAX(25,rw-lw-103),18)];
[record[@"field"] setFrame:NSMakeRect(rw-88,5,57,24)];
}
CGFloat rw=[record[@"row"]bounds].size.width,lw=MIN(103,MAX(77,rw*.34)),eyeWidth=record[@"itemEnabled"]?20:0;
[record[@"itemEnabled"]setFrame:NSMakeRect(0,6,18,18)];
[record[@"label"]setFrame:NSMakeRect(2+eyeWidth,7,lw-eyeWidth,18)];
[record[@"reset"]setFrame:NSMakeRect(rw-23,4,22,24)];
if(record[@"toggle"])[record[@"toggle"]setFrame:NSMakeRect(lw+8,5,45,22)];
if(record[@"popup"])[record[@"popup"]setFrame:NSMakeRect(lw+7,3,rw-lw-34,25)];
if(record[@"slider"]){[record[@"slider"]setFrame:NSMakeRect(lw+7,7,MAX(25,rw-lw-94),18)];[record[@"field"]setFrame:NSMakeRect(rw-81,4,54,24)];}
}
for(NSDictionary *record in _assetButtons.allValues) {
CGFloat rw=[record[@"row"] bounds].size.width;
[record[@"label"] setFrame:NSMakeRect(5,8,88,18)];
[record[@"choose"] setFrame:NSMakeRect(95,4,MAX(80,rw-127),26)];
[record[@"remove"] setFrame:NSMakeRect(rw-27,5,25,24)];
for(NSString *key in _assetButtons){NSDictionary *r=_assetButtons[key];CGFloat rw=[r[@"row"]bounds].size.width;BOOL input=[key isEqual:@"input"];
[r[@"browse"]setHidden:input];[r[@"browse"]setFrame:NSMakeRect(0,4,20,24)];[r[@"label"]setFrame:NSMakeRect(input?2:25,7,input?86:69,18)];
[r[@"choose"]setFrame:NSMakeRect(97,3,MAX(65,rw-152),26)];[r[@"folder"]setFrame:NSMakeRect(rw-51,4,24,24)];[r[@"remove"]setFrame:NSMakeRect(rw-23,4,22,24)];
}
[_document setFrameSize:NSMakeSize(_scroll.contentSize.width,MAX(y,_scroll.contentSize.height))];
}
@@ -587,14 +649,19 @@ static NSImage *DYWheelImage(void) {
NSNumber *pid=c[@"section"][@"enabled"];
double v=1;if(pid)[get getFloatValue:&v fromParameter:pid.unsignedIntValue atTime:t];
[c[@"enabled"] setState:v>=.5?NSControlStateValueOn:NSControlStateValueOff];
[c[@"enabled"]setImage:[NSImage imageWithSystemSymbolName:v>=.5?@"eye":@"eye.slash" accessibilityDescription:v>=.5?@"启用本组":@"旁路本组"]];
for(NSView *row in c[@"body"])row.alphaValue=v>=.5?1:.45;
}
DYAssetState *assets=DYReadAssets(_manager,t);
for(NSString *key in _assetButtons) {
NSString *path=assets.paths[key]; NSButton *button=_assetButtons[key][@"choose"];
button.title=path.length?path.lastPathComponent:@"无 · 点击选择…"; button.toolTip=path.length?path:@"选择 .cube 立体 LUT";
NSString *name=path.length?path.lastPathComponent.stringByDeletingPathExtension:@"无";
if([key isEqual:@"input"]&&!path.length){double profile=0;[get getFloatValue:&profile fromParameter:2013 atTime:t];for(NSDictionary *d in DYDescriptors())if([d[@"key"]isEqual:@"inputProfile"]){NSArray *options=d[@"options"];NSInteger index=MAX(0,MIN((NSInteger)llround(profile),(NSInteger)options.count-1));name=options[index];break;}}
button.title=name; button.toolTip=path.length?path:@"选择输入转换或 LUT;点击网格图标浏览缩略图";
[_assetButtons[key][@"remove"] setEnabled:path.length>0];
}
for(NSInteger i=1;i<5;i++)if([assets.paths[[NSString stringWithFormat:@"look%ld",(long)i]]length])_visibleLooks=MAX(_visibleLooks,i+1);
[self setNeedsLayout:YES];
} @finally { [action endAction:self]; _refreshing=NO; }
}
- (void)postChanged { [[NSNotificationCenter defaultCenter] postNotificationName:@"DYModelChanged" object:_manager]; }
@@ -607,7 +674,10 @@ static NSImage *DYWheelImage(void) {
else {
if([sender isKindOfClass:[NSTextField class]]) {
NSScanner *scanner=[NSScanner scannerWithString:sender.stringValue];
NSString *text=[sender.stringValue stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];BOOL percent=[text hasSuffix:@"%"];
if(percent)text=[text substringToIndex:text.length-1];scanner=[NSScanner scannerWithString:text];
if(![scanner scanDouble:&v]||!scanner.isAtEnd||!std::isfinite(v)){NSBeep();[self refresh];return;}
if([d[@"key"]hasSuffix:@"Strength"])v/=100.;
} else v=sender.doubleValue;
}
v=fmax([d[@"min"] doubleValue],fmin([d[@"max"] doubleValue],v));
@@ -629,7 +699,7 @@ static NSImage *DYWheelImage(void) {
NSDictionary *d=_controls[@(sender.tag)][@"descriptor"];NSNumber *pid=d[@"enabled"];if(!pid)return;
id<FxCustomParameterActionAPI_v4> action=[self actionAPI];if(!action)return;
[action startAction:self];
@try {id<FxParameterSettingAPI_v6> set=[_manager apiForProtocol:@protocol(FxParameterSettingAPI_v6)];[set setFloatValue:sender.state==NSControlStateValueOn?1:0 toParameter:pid.unsignedIntValue atTime:action.currentTime];}
@try {id<FxParameterSettingAPI_v6> set=[_manager apiForProtocol:@protocol(FxParameterSettingAPI_v6)];double value=sender.state==NSControlStateValueOn?1:0;[set setFloatValue:value toParameter:pid.unsignedIntValue atTime:action.currentTime];NSNumber *extra=_cards[sender.tag][@"section"][@"extraEnabled"];if(extra)[set setFloatValue:value toParameter:extra.unsignedIntValue atTime:action.currentTime];}
@finally {[action endAction:self];}
[self postChanged];
}
@@ -655,7 +725,7 @@ static NSImage *DYWheelImage(void) {
- (void)toggleSection:(NSButton *)sender {
if(sender.tag>=_cards.count)return;
NSMutableDictionary *card=_cards[sender.tag];BOOL collapsed=![card[@"collapsed"] boolValue];card[@"collapsed"]=@(collapsed);
sender.title=[(collapsed?@"▸ ":@"▾ ") stringByAppendingString:card[@"section"][@"title"]?:@""];
[sender setNeedsDisplay:YES];
[self setNeedsLayout:YES];
NSAccessibilityPostNotification(self,NSAccessibilityLayoutChangedNotification);
}
@@ -668,6 +738,7 @@ static NSImage *DYWheelImage(void) {
CMTime t=action.currentTime;id<FxParameterSettingAPI_v6> set=[_manager apiForProtocol:@protocol(FxParameterSettingAPI_v6)];
for(NSDictionary *d in section[@"rows"]) {[set setFloatValue:[d[@"default"] doubleValue] toParameter:[d[@"pid"] unsignedIntValue] atTime:t];if(d[@"enabled"])[set setFloatValue:1 toParameter:[d[@"enabled"] unsignedIntValue] atTime:t];}
NSNumber *enabled=section[@"enabled"];if(enabled)[set setFloatValue:1 toParameter:enabled.unsignedIntValue atTime:t];
NSNumber *extra=section[@"extraEnabled"];if(extra)[set setFloatValue:1 toParameter:extra.unsignedIntValue atTime:t];
NSString *key=section[@"key"]?:@"";
if([key localizedCaseInsensitiveContainsString:@"input"]||[key localizedCaseInsensitiveContainsString:@"look"]) {
DYAssetState *assets=[[DYReadAssets(_manager,t) copy] autorelease];
@@ -692,13 +763,43 @@ static NSImage *DYWheelImage(void) {
[self postChanged];
}
- (void)chooseAsset:(NSButton *)sender {
[_library reload:NULL];NSMenu *menu=[[[NSMenu alloc]initWithTitle:@"LUT"]autorelease];
NSMenuItem *none=[menu addItemWithTitle:@"无" action:@selector(assetMenuItem:) keyEquivalent:@""];none.target=self;none.representedObject=@{@"key":sender.identifier,@"path":@"",@"profile":@0};
if([sender.identifier isEqual:@"input"]){for(NSDictionary *d in DYDescriptors())if([d[@"key"]isEqual:@"inputProfile"]){NSInteger i=0;for(NSString *title in d[@"options"]){if(i){NSMenuItem *item=[menu addItemWithTitle:title action:@selector(assetMenuItem:) keyEquivalent:@""];item.target=self;item.representedObject=@{@"key":@"input",@"profile":@(i),@"path":@""};}i++;}break;}}
[menu addItem:NSMenuItem.separatorItem];NSMenuItem *browser=[menu addItemWithTitle:@"缩略图浏览库…" action:@selector(assetMenuBrowse:) keyEquivalent:@""];browser.target=self;browser.representedObject=sender.identifier;
NSMenuItem *file=[menu addItemWithTitle:@"载入 LUT 文件…" action:@selector(assetMenuFile:) keyEquivalent:@""];file.target=self;file.representedObject=sender.identifier;
NSMutableDictionary *folders=[NSMutableDictionary dictionary];NSUInteger count=0;
for(NSDictionary *entry in _library.entries){if(count++>=1000)break;NSString *folder=entry[@"relativeFolder"];NSMenu *parent=menu;
if(folder.length){parent=folders[folder];if(!parent){NSMenuItem *group=[menu addItemWithTitle:folder action:nil keyEquivalent:@""];parent=[[[NSMenu alloc]initWithTitle:folder]autorelease];group.submenu=parent;folders[folder]=parent;}}
NSMenuItem *item=[parent addItemWithTitle:entry[@"name"] action:@selector(assetMenuItem:) keyEquivalent:@""];item.target=self;item.representedObject=@{@"key":sender.identifier,@"path":entry[@"path"]};
}
[menu popUpMenuPositioningItem:nil atLocation:NSMakePoint(0,sender.bounds.size.height) inView:sender];
}
- (void)assetMenuBrowse:(NSMenuItem *)item {NSButton *button=_assetButtons[item.representedObject][@"browse"];[self browseAsset:button];}
- (void)assetMenuFile:(NSMenuItem *)item {[self chooseFileForKey:item.representedObject];}
- (void)assetMenuItem:(NSMenuItem *)item {
NSString *key=item.representedObject[@"key"],*path=item.representedObject[@"path"];
[self setAssetPath:path forKey:key];
if([key isEqual:@"input"]&&item.representedObject[@"profile"]){id<FxCustomParameterActionAPI_v4> a=[self actionAPI];[a startAction:self];@try{[[_manager apiForProtocol:@protocol(FxParameterSettingAPI_v6)]setFloatValue:[item.representedObject[@"profile"]doubleValue] toParameter:2013 atTime:a.currentTime];}@finally{[a endAction:self];}[self postChanged];}
}
- (void)chooseFileForKey:(NSString *)key {
NSOpenPanel *panel=[NSOpenPanel openPanel];panel.allowedFileTypes=@[@"cube"];panel.allowsMultipleSelection=NO;
panel.canChooseDirectories=NO;panel.message=@"选择 .cube 立体 LUT";
if([panel runModal]!=NSModalResponseOK)return;
[self setAssetPath:panel.URL.path forKey:sender.identifier];
[self setAssetPath:panel.URL.path forKey:key];
}
- (void)browseAsset:(NSButton *)sender {
[_browser close];[_browser release];_browser=nil;
id<FxCustomParameterActionAPI_v4> a=[self actionAPI];if(!a)return;[a startAction:self];NSString *selected=nil;@try{selected=[DYReadAssets(_manager,a.currentTime).paths[sender.identifier]copy];}@finally{[a endAction:self];}
__block DYInspector *owner=self;NSString *key=[[sender.identifier copy]autorelease];
_browser=[[DYLUTBrowser alloc]initWithLibrary:_library preview:[_renderer preview] selectedPath:selected palette:DYThemePalette() selection:^(NSString *path){[owner setAssetPath:path forKey:key];}];[selected release];[_browser showRelativeToView:sender];
}
- (void)openLibraryFolder:(id)sender {
NSError *error=nil;if(![[NSFileManager defaultManager]createDirectoryAtURL:_library.rootURL withIntermediateDirectories:YES attributes:nil error:&error]){[self showError:error.localizedDescription];return;}[[NSWorkspace sharedWorkspace]openURL:_library.rootURL];
}
- (void)removeAsset:(NSButton *)sender { [self setAssetPath:nil forKey:sender.identifier]; }
- (void)setAssetPath:(NSString *)path forKey:(NSString *)key {
if(path.length){std::vector<float> values;NSUInteger size=0;NSError *error=nil;if(!DYLUTReadCube(path,values,size,&error)){[self showError:error.localizedDescription];return;}}
id<FxCustomParameterActionAPI_v4> action=[self actionAPI];if(!action)return;
[action startAction:self];
@try {
+18
查看文件
@@ -0,0 +1,18 @@
#import <AppKit/AppKit.h>
@class DYLUTLibrary;
/// A nonmodal browser. Selecting a validated thumbnail applies that LUT.
/// All UI and selection callbacks run on the main thread.
@interface DYLUTBrowser : NSWindowController
- (instancetype)initWithLibrary:(DYLUTLibrary *)library
preview:(NSData *)rgba
selectedPath:(NSString *)path
palette:(NSDictionary *)palette
selection:(void (^)(NSString *path))selection;
- (void)showRelativeToView:(NSView *)view;
- (void)updatePalette:(NSDictionary *)palette;
/// Replace the source frame after the renderer captures a new playhead image.
/// Passing identical bytes keeps the current thumbnail jobs and cache intact.
- (void)updatePreview:(NSData *)rgba;
@end
+353
查看文件
@@ -0,0 +1,353 @@
#import "DYLUTBrowser.h"
#import "DYLUTLibrary.h"
#import <QuartzCore/QuartzCore.h>
#include <cmath>
static NSColor *DYBrowserColor(NSDictionary *palette, NSString *key) {
NSColor *color=palette[key];
if([color isKindOfClass:NSColor.class])return color;
if([key isEqualToString:@"text"])return [NSColor colorWithWhite:.92 alpha:1];
if([key isEqualToString:@"secondary"])return [NSColor colorWithWhite:.65 alpha:1];
if([key isEqualToString:@"accent"])return [NSColor colorWithSRGBRed:.32 green:.75 blue:.97 alpha:1];
if([key isEqualToString:@"border"])return [NSColor colorWithWhite:.30 alpha:1];
return [NSColor colorWithWhite:.12 alpha:1];
}
static NSString *const DYBrowserSizePreference=@"com.dayu.color.lookLUTPreview.thumbnailSize";
static NSString *const DYBrowserFolderPreference=@"com.dayu.color.lookLUTPreview.selectedFolder";
@interface DYBrowserCanvas : NSView
@property(copy) NSDictionary *palette;
@property(copy) NSString *fillKey;
@end
@implementation DYBrowserCanvas
- (BOOL)isFlipped{return YES;}
- (BOOL)isAccessibilityElement{return YES;}
- (NSAccessibilityRole)accessibilityRole{return NSAccessibilityGroupRole;}
- (NSArray *)accessibilityChildren{return NSAccessibilityUnignoredChildren(self.subviews);}
- (NSArray *)accessibilityVisibleChildren{
NSMutableArray *result=[NSMutableArray array];
for(NSView *child in self.subviews)if(!child.hidden&&NSIntersectsRect(child.frame,self.visibleRect))[result addObject:child];
return NSAccessibilityUnignoredChildren(result);
}
- (void)drawRect:(NSRect)dirty{[DYBrowserColor(_palette,_fillKey?:@"background") setFill];NSRectFill(self.bounds);}
- (void)dealloc{[_palette release];[_fillKey release];[super dealloc];}
@end
@interface DYBrowserTile : NSButton
@property(retain) NSImage *thumbnail;
@property(copy) NSString *displayName;
@property(copy) NSString *failure;
@property(copy) NSDictionary *palette;
@property BOOL chosen;
@property BOOL doubleClicked;
@end
@implementation DYBrowserTile
- (BOOL)isFlipped{return YES;}
- (instancetype)initWithFrame:(NSRect)frame{
if((self=[super initWithFrame:frame])){self.bordered=NO;self.title=@"";self.imagePosition=NSNoImage;self.focusRingType=NSFocusRingTypeExterior;}
return self;
}
- (void)dealloc{[_thumbnail release];[_displayName release];[_failure release];[_palette release];[super dealloc];}
- (NSString *)accessibilityLabel{return _displayName?:@"LUT";}
- (id)accessibilityValue{return _chosen?@"已选择":_failure.length?@"LUT 无效":_thumbnail?@"可应用":@"正在生成缩略图";}
- (NSString *)accessibilityHelp{return _failure?:@"单击应用此 LUT,双击应用并关闭浏览器";}
- (void)drawRect:(NSRect)dirty{
NSRect bounds=NSInsetRect(self.bounds,1,1);
NSBezierPath *outline=[NSBezierPath bezierPathWithRoundedRect:bounds xRadius:7 yRadius:7];
[DYBrowserColor(_palette,_chosen?@"field":@"card") setFill];[outline fill];
NSRect imageRect=NSMakeRect(2,2,MAX(1,bounds.size.width-2),MAX(1,bounds.size.height-25));
if(_thumbnail){
[NSGraphicsContext saveGraphicsState];
[[NSBezierPath bezierPathWithRoundedRect:imageRect xRadius:4 yRadius:4]addClip];
NSSize size=_thumbnail.size;CGFloat scale=MAX(imageRect.size.width/MAX(1,size.width),imageRect.size.height/MAX(1,size.height));
NSRect dest=NSMakeRect(NSMidX(imageRect)-size.width*scale/2,NSMidY(imageRect)-size.height*scale/2,size.width*scale,size.height*scale);
[_thumbnail drawInRect:dest fromRect:NSZeroRect operation:NSCompositingOperationSourceOver fraction:1 respectFlipped:YES hints:nil];
[NSGraphicsContext restoreGraphicsState];
}else{
[DYBrowserColor(_palette,@"background")setFill];NSRectFill(imageRect);
NSString *message=_failure.length?@"无法预览":@"生成预览…";
NSDictionary *attributes=@{NSFontAttributeName:[NSFont systemFontOfSize:11],NSForegroundColorAttributeName:DYBrowserColor(_palette,@"secondary")};
NSSize size=[message sizeWithAttributes:attributes];
[message drawAtPoint:NSMakePoint(NSMidX(imageRect)-size.width/2,NSMidY(imageRect)-size.height/2) withAttributes:attributes];
}
NSMutableParagraphStyle *paragraph=[[[NSMutableParagraphStyle alloc]init]autorelease];paragraph.alignment=NSTextAlignmentCenter;paragraph.lineBreakMode=NSLineBreakByTruncatingMiddle;
[_displayName drawInRect:NSMakeRect(7,NSMaxY(bounds)-24,bounds.size.width-14,18) withAttributes:@{NSFontAttributeName:[NSFont systemFontOfSize:11 weight:_chosen?NSFontWeightSemibold:NSFontWeightRegular],NSForegroundColorAttributeName:DYBrowserColor(_palette,@"text"),NSParagraphStyleAttributeName:paragraph}];
[DYBrowserColor(_palette,_chosen?@"accent":@"border")setStroke];outline.lineWidth=_chosen?2:1;[outline stroke];
}
- (void)mouseDown:(NSEvent *)event{self.doubleClicked=event.clickCount>1;[super mouseDown:event];}
@end
@interface DYBrowserFolderButton : NSButton
@property(copy) NSDictionary *palette;
@property BOOL chosen;
@end
@implementation DYBrowserFolderButton
- (BOOL)isFlipped{return YES;}
- (void)dealloc{[_palette release];[super dealloc];}
- (void)drawRect:(NSRect)dirty{
if(_chosen){[DYBrowserColor(_palette,@"field")setFill];[[NSBezierPath bezierPathWithRoundedRect:NSInsetRect(self.bounds,1,1) xRadius:5 yRadius:5]fill];}
NSMutableParagraphStyle *paragraph=[[[NSMutableParagraphStyle alloc]init]autorelease];paragraph.lineBreakMode=NSLineBreakByTruncatingMiddle;
[self.title drawInRect:NSInsetRect(self.bounds,9,8) withAttributes:@{NSFontAttributeName:[NSFont systemFontOfSize:11 weight:_chosen?NSFontWeightSemibold:NSFontWeightRegular],NSForegroundColorAttributeName:DYBrowserColor(_palette,_chosen?@"accent":@"text"),NSParagraphStyleAttributeName:paragraph}];
}
@end
@class DYLUTBrowser;
/// The jobs own this token, never the browser or its host selection block.
@interface DYBrowserWork : NSObject
@property(assign) DYLUTBrowser *owner;
@property BOOL cancelled;
@end
@implementation DYBrowserWork @end
@interface DYLUTBrowser () <NSWindowDelegate,NSSearchFieldDelegate> {
DYLUTLibrary *_library;
NSData *_preview;
NSString *_selectedPath,*_folder;
NSDictionary *_palette;
void (^_selection)(NSString *);
DYBrowserCanvas *_root,*_folderDocument,*_gridDocument;
NSScrollView *_folderScroll,*_gridScroll;
NSTextField *_titleLabel,*_countLabel,*_statusLabel,*_sizeLabel,*_emptyLabel;
NSSearchField *_search;
NSButton *_importFiles,*_importFolder,*_reveal,*_refresh,*_none,*_done;
NSSlider *_sizeSlider;
NSMutableArray *_folderButtons;
NSMutableDictionary *_tiles;
NSArray *_visibleEntries;
NSMutableSet *_queuedPaths;
NSCache *_thumbnailCache;
dispatch_queue_t _previewQueue;
DYBrowserWork *_work;
BOOL _closed,_sizing;
}
@end
@implementation DYLUTBrowser
static NSTextField *BrowserLabel(NSString *title,CGFloat size){NSTextField *label=[NSTextField labelWithString:title];label.font=[NSFont systemFontOfSize:size];label.lineBreakMode=NSLineBreakByTruncatingTail;return label;}
static NSButton *BrowserButton(NSString *title,id target,SEL action){NSButton *button=[NSButton buttonWithTitle:title target:target action:action];button.font=[NSFont systemFontOfSize:11];button.bezelStyle=NSBezelStyleRounded;return button;}
- (instancetype)initWithLibrary:(DYLUTLibrary *)library preview:(NSData *)rgba selectedPath:(NSString *)path palette:(NSDictionary *)palette selection:(void (^)(NSString *))selection{
NSPanel *panel=[[[NSPanel alloc]initWithContentRect:NSMakeRect(0,0,760,560) styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskClosable|NSWindowStyleMaskResizable backing:NSBackingStoreBuffered defer:NO]autorelease];
if((self=[super initWithWindow:panel])){
NSString *savedFolder=[[NSUserDefaults standardUserDefaults]stringForKey:DYBrowserFolderPreference];
_library=[library retain];_preview=[rgba copy];_selectedPath=[path copy];_folder=[(savedFolder?:@"*") copy];_selection=[selection copy];
_folderButtons=[NSMutableArray new];_tiles=[NSMutableDictionary new];_queuedPaths=[NSMutableSet new];_thumbnailCache=[NSCache new];_thumbnailCache.countLimit=600;_thumbnailCache.totalCostLimit=64*1024*1024;_previewQueue=dispatch_queue_create("com.dayu.color.lut-thumbnails",DISPATCH_QUEUE_SERIAL);
panel.title=@"风格 LUT";panel.minSize=NSMakeSize(760,420);panel.releasedWhenClosed=NO;panel.hidesOnDeactivate=NO;panel.delegate=self;
_root=[[DYBrowserCanvas alloc]initWithFrame:NSMakeRect(0,0,760,560)];_root.accessibilityLabel=@"LUT 缩略图浏览库";panel.contentView=_root;
_titleLabel=[BrowserLabel(@"LUT 文件夹",14)retain];_titleLabel.font=[NSFont systemFontOfSize:14 weight:NSFontWeightSemibold];
_countLabel=[BrowserLabel(@"0 个 LUT",11)retain];
_statusLabel=[BrowserLabel(@"单击缩略图应用 LUT",11)retain];
_sizeLabel=[BrowserLabel(@"缩略图大小",11)retain];
_emptyLabel=[BrowserLabel(@"此文件夹还没有 LUT。\n点“导入文件”或“导入文件夹”添加 .cube 文件。",13)retain];_emptyLabel.maximumNumberOfLines=3;_emptyLabel.alignment=NSTextAlignmentCenter;
_search=[[NSSearchField alloc]initWithFrame:NSZeroRect];_search.placeholderString=@"搜索 LUT";_search.accessibilityLabel=@"搜索 LUT";_search.delegate=self;_search.target=self;_search.action=@selector(searchChanged:);
_importFiles=[BrowserButton(@"导入文件…",self,@selector(importFiles:))retain];_importFiles.accessibilityLabel=@"导入 LUT 文件";
_importFolder=[BrowserButton(@"导入文件夹…",self,@selector(importFolder:))retain];_importFolder.accessibilityLabel=@"导入 LUT 文件夹";
_reveal=[BrowserButton(@"打开文件夹",self,@selector(revealLibrary:))retain];
_refresh=[BrowserButton(@"刷新",self,@selector(reloadLibrary:))retain];
_none=[BrowserButton(@"无 LUT",self,@selector(clearSelection:))retain];
_done=[BrowserButton(@"完成",self,@selector(done:))retain];_done.keyEquivalent=@"\r";
double size=[[NSUserDefaults standardUserDefaults]objectForKey:DYBrowserSizePreference]?[[NSUserDefaults standardUserDefaults]doubleForKey:DYBrowserSizePreference]:96;
if(!std::isfinite(size))size=96;
_sizeSlider=[[NSSlider alloc]initWithFrame:NSZeroRect];_sizeSlider.minValue=70;_sizeSlider.maxValue=255;_sizeSlider.doubleValue=fmax(70,fmin(255,size));_sizeSlider.continuous=YES;_sizeSlider.target=self;_sizeSlider.action=@selector(sizeChanged:);_sizeSlider.accessibilityLabel=@"LUT 缩略图大小";
_folderScroll=[[NSScrollView alloc]initWithFrame:NSZeroRect];_folderScroll.hasVerticalScroller=YES;_folderScroll.autohidesScrollers=YES;_folderScroll.borderType=NSNoBorder;_folderScroll.drawsBackground=NO;_folderScroll.accessibilityLabel=@"LUT 文件夹列表";
_gridScroll=[[NSScrollView alloc]initWithFrame:NSZeroRect];_gridScroll.hasVerticalScroller=YES;_gridScroll.autohidesScrollers=YES;_gridScroll.borderType=NSNoBorder;_gridScroll.drawsBackground=NO;_gridScroll.accessibilityLabel=@"LUT 缩略图网格";
_folderDocument=[[DYBrowserCanvas alloc]initWithFrame:NSZeroRect];_folderDocument.fillKey=@"card";_folderDocument.palette=_palette;_folderDocument.accessibilityLabel=@"LUT 文件夹";_folderScroll.documentView=_folderDocument;
_gridDocument=[[DYBrowserCanvas alloc]initWithFrame:NSZeroRect];_gridDocument.palette=_palette;_gridDocument.accessibilityLabel=@"LUT 缩略图";_gridScroll.documentView=_gridDocument;
_gridScroll.contentView.postsBoundsChangedNotifications=YES;
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(gridScrolled:) name:NSViewBoundsDidChangeNotification object:_gridScroll.contentView];
for(NSView *view in @[_titleLabel,_countLabel,_statusLabel,_sizeLabel,_search,_importFiles,_importFolder,_reveal,_refresh,_none,_done,_sizeSlider,_folderScroll,_gridScroll])[_root addSubview:view];
[_gridDocument addSubview:_emptyLabel];
[self reloadLibrary:nil];[self updatePalette:palette];[self layoutBrowser];
}
return self;
}
- (void)dealloc{
[NSObject cancelPreviousPerformRequestsWithTarget:self];[[NSNotificationCenter defaultCenter]removeObserver:self];
_work.cancelled=YES;_work.owner=nil;[_work release];self.window.delegate=nil;
[_library release];[_preview release];[_selectedPath release];[_folder release];[_palette release];[_selection release];
[_root release];[_folderDocument release];[_gridDocument release];[_folderScroll release];[_gridScroll release];
[_titleLabel release];[_countLabel release];[_statusLabel release];[_sizeLabel release];[_emptyLabel release];[_search release];
[_importFiles release];[_importFolder release];[_reveal release];[_refresh release];[_none release];[_done release];[_sizeSlider release];
[_folderButtons release];[_tiles release];[_visibleEntries release];[_queuedPaths release];[_thumbnailCache release];
dispatch_release(_previewQueue);[super dealloc];
}
- (void)showRelativeToView:(NSView *)view{
if(_closed)return;
NSWindow *parent=view.window;
if(parent){
NSRect frame=self.window.frame,parentFrame=parent.frame;
NSScreen *screen=parent.screen?:NSScreen.mainScreen;NSRect safe=screen.visibleFrame;
NSPoint p=NSMakePoint(NSMidX(parentFrame)-frame.size.width/2,NSMidY(parentFrame)-frame.size.height/2);
p.x=MAX(NSMinX(safe),MIN(p.x,NSMaxX(safe)-frame.size.width));p.y=MAX(NSMinY(safe),MIN(p.y,NSMaxY(safe)-frame.size.height));[self.window setFrameOrigin:p];
}else [self.window center];
[self showWindow:nil];[self.window makeKeyAndOrderFront:nil];
}
- (void)windowDidResize:(NSNotification *)notification{[self layoutBrowser];}
- (void)windowWillClose:(NSNotification *)notification{
[NSObject cancelPreviousPerformRequestsWithTarget:self];
_closed=YES;_work.cancelled=YES;_work.owner=nil;
[_selection release];_selection=nil;
}
- (void)layoutBrowser{
CGFloat w=_root.bounds.size.width,h=_root.bounds.size.height,left=162;
_titleLabel.frame=NSMakeRect(12,15,145,20);_countLabel.frame=NSMakeRect(12,39,145,18);
_search.frame=NSMakeRect(left+14,14,MAX(125,w-left-351),24);
_importFiles.frame=NSMakeRect(w-322,12,100,28);_importFolder.frame=NSMakeRect(w-218,12,113,28);_refresh.frame=NSMakeRect(w-101,12,82,28);
_folderScroll.frame=NSMakeRect(12,66,150,MAX(80,h-121));_gridScroll.frame=NSMakeRect(left+12,50,MAX(80,w-left-26),MAX(80,h-105));
_reveal.frame=NSMakeRect(14,h-44,left-23,27);_none.frame=NSMakeRect(left+13,h-44,75,27);
_sizeLabel.frame=NSMakeRect(left+101,h-39,74,18);_sizeSlider.frame=NSMakeRect(left+173,h-41,MAX(70,MIN(150,w-left-420)),20);
_done.frame=NSMakeRect(w-98,h-44,78,27);
CGFloat statusX=NSMaxX(_sizeSlider.frame)+14;_statusLabel.frame=NSMakeRect(statusX,h-39,MAX(0,w-statusX-112),18);
CGFloat fy=4,fw=MAX(100,_folderScroll.contentSize.width);
for(DYBrowserFolderButton *button in _folderButtons){button.frame=NSMakeRect(4,fy,fw-8,33);fy+=35;}
_folderDocument.frame=NSMakeRect(0,0,fw,MAX(fy,_folderScroll.contentSize.height));
CGFloat available=MAX(80,_gridScroll.contentSize.width),tileWidth=_sizeSlider.doubleValue,gap=10;
NSInteger columns=MAX(1,(NSInteger)floor((available+gap)/(tileWidth+gap)));tileWidth=MIN(tileWidth,(available-gap*(columns-1)-14)/columns);tileWidth=MAX(70,tileWidth);
CGFloat tileHeight=ceil(tileWidth*9/16)+24,x=7,y=8;NSInteger index=0;
for(NSDictionary *entry in _visibleEntries){DYBrowserTile *tile=_tiles[entry[@"path"]];NSInteger col=index%columns,row=index/columns;tile.frame=NSMakeRect(x+col*(tileWidth+gap),y+row*(tileHeight+gap),tileWidth,tileHeight);index++;}
NSInteger rows=(_visibleEntries.count+columns-1)/columns;CGFloat contentHeight=MAX(_gridScroll.contentSize.height,rows*(tileHeight+gap)+12);
_gridDocument.frame=NSMakeRect(0,0,available,contentHeight);_emptyLabel.frame=NSMakeRect(20,MAX(36,_gridScroll.contentSize.height/2-45),MAX(50,available-40),90);
if(!_sizing)[self generateVisibleThumbnails];
}
- (void)updatePalette:(NSDictionary *)palette{
NSMutableDictionary *browserPalette=[NSMutableDictionary dictionaryWithDictionary:palette?:@{}];
browserPalette[@"background"]=[NSColor colorWithCalibratedRed:.035 green:.08 blue:.12 alpha:1];
[_palette release];_palette=[browserPalette copy];_root.palette=_palette;_folderDocument.palette=_palette;_gridDocument.palette=_palette;
self.window.backgroundColor=DYBrowserColor(_palette,@"background");self.window.appearance=[NSAppearance appearanceNamed:NSAppearanceNameDarkAqua];
for(NSTextField *label in @[_titleLabel,_countLabel,_statusLabel,_sizeLabel,_emptyLabel])label.textColor=DYBrowserColor(_palette,label==_titleLabel?@"text":@"secondary");
for(NSButton *button in @[_importFiles,_importFolder,_reveal,_refresh,_none,_done])button.contentTintColor=DYBrowserColor(_palette,@"accent");
_search.textColor=DYBrowserColor(_palette,@"text");_search.backgroundColor=DYBrowserColor(_palette,@"field");
for(DYBrowserFolderButton *button in _folderButtons){button.palette=_palette;[button setNeedsDisplay:YES];}
for(DYBrowserTile *tile in _tiles.allValues){tile.palette=_palette;[tile setNeedsDisplay:YES];}
[_root setNeedsDisplay:YES];[_folderDocument setNeedsDisplay:YES];[_gridDocument setNeedsDisplay:YES];
}
- (void)updatePreview:(NSData *)rgba{
if(_closed||_preview==rgba||[_preview isEqualToData:rgba])return;
if(rgba&&rgba.length!=320*180*16)return;
[_preview release];_preview=[rgba copy];[_thumbnailCache removeAllObjects];
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(refreshThumbnailSize) object:nil];
[self refreshThumbnailSize];
}
- (void)setStatus:(NSString *)status{_statusLabel.stringValue=status?:@"";_statusLabel.toolTip=status;}
- (void)rebuildFolders{
for(NSView *view in _folderButtons)[view removeFromSuperview];[_folderButtons removeAllObjects];
NSMutableArray *paths=[NSMutableArray arrayWithObject:@"*"];
for(NSString *folder in _library.folders){NSString *top=folder.length?[folder componentsSeparatedByString:@"/"].firstObject:@"";if(![paths containsObject:top])[paths addObject:top];}
if(![paths containsObject:_folder]){[_folder release];_folder=[@"*" copy];}
for(NSString *path in paths){
DYBrowserFolderButton *button=[[[DYBrowserFolderButton alloc]initWithFrame:NSZeroRect]autorelease];button.bordered=NO;button.target=self;button.action=@selector(folderClicked:);button.identifier=path;
button.title=[path isEqualToString:@"*"]?@"全部 LUT":path.length?[@"▸ " stringByAppendingString:path]:@"未分类";button.toolTip=path.length?path:_library.rootURL.path;button.palette=_palette;button.chosen=[path isEqualToString:_folder];button.accessibilityLabel=[@"LUT 文件夹:" stringByAppendingString:button.title];
[_folderDocument addSubview:button];[_folderButtons addObject:button];
}
}
- (void)reloadLibrary:(id)sender{
[_thumbnailCache removeAllObjects];
NSError *error=nil;
if(![_library reload:&error]&&error)[self setStatus:error.localizedDescription];
else [self setStatus:@"单击缩略图应用 LUT"];
[self rebuildFolders];[self rebuildGrid];
}
- (void)folderClicked:(NSButton *)sender{
[_folder release];_folder=[sender.identifier copy];
[[NSUserDefaults standardUserDefaults]setObject:_folder forKey:DYBrowserFolderPreference];
for(DYBrowserFolderButton *button in _folderButtons){button.chosen=[button.identifier isEqualToString:_folder];[button setNeedsDisplay:YES];}
[self rebuildGrid];
}
- (void)searchChanged:(id)sender{[self rebuildGrid];}
- (void)controlTextDidChange:(NSNotification *)notification{if(notification.object==_search)[self rebuildGrid];}
- (void)sizeChanged:(id)sender{
[[NSUserDefaults standardUserDefaults]setDouble:_sizeSlider.doubleValue forKey:DYBrowserSizePreference];
_sizing=YES;[self layoutBrowser];
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(refreshThumbnailSize) object:nil];
[self performSelector:@selector(refreshThumbnailSize) withObject:nil afterDelay:.22];
}
- (void)refreshThumbnailSize{
if(_closed)return;_sizing=NO;
_work.cancelled=YES;_work.owner=nil;[_work release];_work=[DYBrowserWork new];_work.owner=self;[_queuedPaths removeAllObjects];
for(DYBrowserTile *tile in _tiles.allValues){tile.thumbnail=nil;tile.failure=nil;tile.enabled=NO;[tile setNeedsDisplay:YES];}
[self generateVisibleThumbnails];
}
- (void)gridScrolled:(NSNotification *)notification{if(!_sizing)[self generateVisibleThumbnails];}
- (void)generateVisibleThumbnails{
if(_closed||!_work)return;
NSRect visible=NSInsetRect(_gridScroll.contentView.bounds,-30,-180);
NSUInteger width=MAX((NSUInteger)64,(NSUInteger)llround(_sizeSlider.doubleValue)),height=MAX((NSUInteger)40,(NSUInteger)llround(width*9./16));
for(NSDictionary *entry in _visibleEntries){
NSString *path=entry[@"path"];DYBrowserTile *tile=_tiles[path];
if(!NSIntersectsRect(tile.frame,visible)){if(tile.thumbnail){tile.thumbnail=nil;tile.enabled=NO;}continue;}
if(tile.thumbnail||tile.failure.length)continue;
NSDictionary *attributes=[[NSFileManager defaultManager]attributesOfItemAtPath:path error:nil];
NSString *cacheKey=[NSString stringWithFormat:@"%lu|%@|%.9f|%@|%@",(unsigned long)width,path,[attributes[NSFileModificationDate]timeIntervalSinceReferenceDate],attributes[NSFileSize],attributes[NSFileSystemFileNumber]];
NSDictionary *cached=[_thumbnailCache objectForKey:cacheKey];
if(cached){tile.thumbnail=cached[@"image"];tile.failure=cached[@"error"];tile.enabled=tile.thumbnail!=nil;if(tile.failure.length)tile.toolTip=tile.failure;[tile setNeedsDisplay:YES];continue;}
if([_queuedPaths containsObject:cacheKey])continue;[_queuedPaths addObject:cacheKey];
DYBrowserWork *work=_work;NSData *preview=_preview;
dispatch_async(_previewQueue,^{@autoreleasepool{
if(work.cancelled)return;
NSError *error=nil;NSImage *image=DYLUTThumbnail(path,preview,320,180,NSMakeSize(width,height),&error);NSString *failure=error.localizedDescription;
dispatch_async(dispatch_get_main_queue(),^{
DYLUTBrowser *owner=work.owner;if(work.cancelled||!owner)return;
[owner->_queuedPaths removeObject:cacheKey];
NSDictionary *result=image?@{@"image":image}:@{@"error":failure?:@"无法预览此 LUT"};
[owner->_thumbnailCache setObject:result forKey:cacheKey cost:image?width*height*4:128];
DYBrowserTile *current=owner->_tiles[path];if(!current||!NSIntersectsRect(current.frame,NSInsetRect(owner->_gridScroll.contentView.bounds,-30,-180)))return;
current.thumbnail=image;current.failure=failure;current.enabled=image!=nil;if(failure.length)current.toolTip=failure;[current setNeedsDisplay:YES];
});
}});
}
}
- (void)rebuildGrid{
_work.cancelled=YES;_work.owner=nil;[_work release];_work=[DYBrowserWork new];_work.owner=self;
[_queuedPaths removeAllObjects];
for(NSView *tile in _tiles.allValues)[tile removeFromSuperview];[_tiles removeAllObjects];
NSString *query=[_search.stringValue stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];NSMutableArray *entries=[NSMutableArray array];
for(NSDictionary *entry in _library.entries){
NSString *folder=entry[@"relativeFolder"]?:@"";
BOOL folderMatch=[_folder isEqualToString:@"*"]||[folder isEqualToString:_folder]||(_folder.length&&[folder hasPrefix:[_folder stringByAppendingString:@"/"]]);
if(folderMatch&&(!query.length||[entry[@"name"]localizedCaseInsensitiveContainsString:query]||[entry[@"relativePath"]localizedCaseInsensitiveContainsString:query]))[entries addObject:entry];
}
[_visibleEntries release];_visibleEntries=[entries copy];_countLabel.stringValue=[NSString stringWithFormat:@"%lu 个 LUT",(unsigned long)entries.count];_emptyLabel.hidden=entries.count>0;
for(NSDictionary *entry in entries){
NSString *path=entry[@"path"];DYBrowserTile *tile=[[[DYBrowserTile alloc]initWithFrame:NSZeroRect]autorelease];tile.identifier=path;tile.displayName=entry[@"name"];tile.toolTip=entry[@"relativePath"]?:path;tile.palette=_palette;tile.chosen=[path isEqualToString:_selectedPath];tile.target=self;tile.action=@selector(thumbnailClicked:);tile.enabled=NO;[_gridDocument addSubview:tile];_tiles[path]=tile;
}
[self layoutBrowser];[_gridScroll.contentView scrollToPoint:NSZeroPoint];[_gridScroll reflectScrolledClipView:_gridScroll.contentView];
NSAccessibilityPostNotification(_gridDocument,NSAccessibilityLayoutChangedNotification);
}
- (void)thumbnailClicked:(DYBrowserTile *)sender{
if(!sender.enabled||!sender.thumbnail||sender.failure.length)return;
std::vector<float> values;NSUInteger dimension=0;NSError *error=nil;
if(!DYLUTReadCube(sender.identifier,values,dimension,&error)){
sender.failure=error.localizedDescription?:@"LUT 文件已失效,请刷新浏览库";sender.enabled=NO;[sender setNeedsDisplay:YES];[self setStatus:sender.failure];return;
}
[_selectedPath release];_selectedPath=[sender.identifier copy];
for(DYBrowserTile *tile in _tiles.allValues){tile.chosen=[tile.identifier isEqualToString:_selectedPath];[tile setNeedsDisplay:YES];}
[self setStatus:[NSString stringWithFormat:@"已应用 %@",sender.displayName]];
if(_selection)_selection(_selectedPath);
if(sender.doubleClicked)[self close];
}
- (void)clearSelection:(id)sender{
[_selectedPath release];_selectedPath=nil;
for(DYBrowserTile *tile in _tiles.allValues){tile.chosen=NO;[tile setNeedsDisplay:YES];}
if(_selection)_selection(nil);[self setStatus:@"已移除 LUT"];
}
- (void)done:(id)sender{[self close];}
- (void)showImportError:(NSError *)error{
if(!error)return;NSAlert *alert=[[[NSAlert alloc]init]autorelease];alert.messageText=@"LUT 导入未完成";alert.informativeText=error.localizedDescription?:@"请选择有效的 .cube LUT 文件。";[alert addButtonWithTitle:@"好"];[alert beginSheetModalForWindow:self.window completionHandler:nil];
}
- (void)importPanelForFolders:(BOOL)folders{
NSOpenPanel *panel=[NSOpenPanel openPanel];panel.canChooseFiles=!folders;panel.canChooseDirectories=folders;panel.allowsMultipleSelection=YES;panel.title=folders?@"导入 LUT 文件夹":@"导入 LUT 文件";panel.message=folders?@"所选文件夹中的 .cube 文件会按目录复制到大鱼调色 LUT 库。":@"选择要复制到大鱼调色 LUT 库的 .cube 文件。";
if(!folders)panel.allowedFileTypes=@[@"cube"];
[panel beginSheetModalForWindow:self.window completionHandler:^(NSModalResponse response){
if(response!=NSModalResponseOK||_closed)return;NSError *error=nil;NSArray *imported=[_library importURLs:panel.URLs error:&error];
if(!imported){[self showImportError:error];return;}
[self rebuildFolders];[self rebuildGrid];[self setStatus:[NSString stringWithFormat:@"已导入 %lu 个 LUT",(unsigned long)imported.count]];
}];
}
- (void)importFiles:(id)sender{[self importPanelForFolders:NO];}
- (void)importFolder:(id)sender{[self importPanelForFolders:YES];}
- (void)revealLibrary:(id)sender{
NSError *error=nil;
if(![[NSFileManager defaultManager]createDirectoryAtURL:_library.rootURL withIntermediateDirectories:YES attributes:nil error:&error]){[self showImportError:error];return;}
if(![[NSWorkspace sharedWorkspace]openURL:_library.rootURL])[self setStatus:@"无法打开 LUT 文件夹"];
}
@end
+47
查看文件
@@ -0,0 +1,47 @@
#import <AppKit/AppKit.h>
#ifdef __cplusplus
#include <vector>
#endif
NS_ASSUME_NONNULL_BEGIN
#ifdef __cplusplus
/// Same red-fastest 3D Cube table and DOMAIN resampling used by the renderer.
/// Output is cleared on failure. Built-in .dylut tables are also supported.
FOUNDATION_EXPORT BOOL DYLUTReadCube(NSString *path, std::vector<float>& values,
NSUInteger& dimension, NSError * _Nullable * _Nullable error);
#endif
/// Float RGBA in display-encoded RGB, matching the renderer's 320×180 preview.
/// Empty path means identity. Alpha is preserved; invalid samples become clear.
FOUNDATION_EXPORT NSData * _Nullable DYLUTTransformRGBA(NSData *sourceRGBA,
NSUInteger width, NSUInteger height, NSString * _Nullable path, NSError * _Nullable * _Nullable error);
/// Uses sourceRGBA when supplied. Otherwise draws an authored neutral test chart.
/// The bitmap is safe to prepare on the browser's background preview queue.
FOUNDATION_EXPORT NSImage * _Nullable DYLUTThumbnail(NSString * _Nullable path,
NSData * _Nullable sourceRGBA, NSUInteger sourceWidth, NSUInteger sourceHeight,
NSSize outputSize, NSError * _Nullable * _Nullable error);
@interface DYLUTLibrary : NSObject
@property(nonatomic,readonly,copy) NSURL *rootURL;
/// Each item has name (without extension), path, relativeFolder, relativePath.
@property(nonatomic,readonly,copy) NSArray<NSDictionary<NSString *,NSString *> *> *entries;
/// Relative folder names, including the root empty string; sorted naturally.
@property(nonatomic,readonly,copy) NSArray<NSString *> *folders;
@property(nonatomic,readonly,copy) NSSet<NSString *> *favoritePaths;
+ (NSURL *)defaultRootURL;
- (instancetype)init;
- (instancetype)initWithRootURL:(NSURL *)rootURL NS_DESIGNATED_INITIALIZER;
/// Does not follow symbolic links or create a missing root directory.
- (BOOL)reload:(NSError * _Nullable * _Nullable)error;
/// Copies Cube files (recursing into folders) into the library. No existing file
/// is replaced. Names receive numeric suffixes on collision. Source data stays put.
/// Returns imported entry dictionaries, or nil on preflight/copy failure.
- (NSArray<NSDictionary<NSString *,NSString *> *> * _Nullable)importURLs:(NSArray<NSURL *> *)urls
error:(NSError * _Nullable * _Nullable)error;
- (BOOL)isFavoritePath:(NSString *)path;
- (BOOL)setFavorite:(BOOL)favorite forPath:(NSString *)path error:(NSError * _Nullable * _Nullable)error;
@end
NS_ASSUME_NONNULL_END
+340
查看文件
@@ -0,0 +1,340 @@
#import "DYLUTLibrary.h"
#include <algorithm>
#include <cmath>
#include <cstring>
#include <limits>
#include <limits.h>
#include <stdlib.h>
#include <zlib.h>
static NSString *const DYLUTLibraryErrorDomain=@"com.dayu.color.LUTLibrary";
static NSURL *DYLUTCanonicalURL(NSURL *url) {
// Foundation deliberately abbreviates /private/var back to /var in some
// URL normalization APIs; its enumerator returns the POSIX canonical path.
NSString *path=url.path.stringByStandardizingPath;
NSMutableArray *missing=[NSMutableArray array];char resolved[PATH_MAX];
while(path.length&&!realpath(path.fileSystemRepresentation,resolved)) {
NSString *parent=path.stringByDeletingLastPathComponent;
if([parent isEqual:path])return [NSURL fileURLWithPath:url.path.stringByStandardizingPath];
[missing insertObject:path.lastPathComponent atIndex:0];path=parent;
}
NSString *canonical=[[NSFileManager defaultManager]stringWithFileSystemRepresentation:resolved length:strlen(resolved)];
for(NSString *component in missing)canonical=[canonical stringByAppendingPathComponent:component];
return [NSURL fileURLWithPath:canonical];
}
static BOOL DYLUTFail(NSError **error,NSString *message) {
if(error)*error=[NSError errorWithDomain:DYLUTLibraryErrorDomain code:1
userInfo:@{NSLocalizedDescriptionKey:message?:@"LUT 操作未完成"}];
return NO;
}
@interface DYLUTTable : NSObject {
@public std::vector<float> values;
@public NSUInteger dimension;
}
@end
@implementation DYLUTTable @end
static NSCache *DYLUTTableCache(void) {
static NSCache *cache;static dispatch_once_t once;
dispatch_once(&once,^{cache=[NSCache new];cache.countLimit=12;cache.totalCostLimit=96*1024*1024;});
return cache;
}
static void DYLUTSample(const std::vector<float>& table,NSUInteger n,const float rgb[3],float out[3]) {
float fraction[3];NSUInteger index[3];
for(int c=0;c<3;c++) {
float scaled=std::min(1.f,std::max(0.f,rgb[c]))*float(n-1);
index[c]=std::min(n-2,(NSUInteger)scaled);fraction[c]=scaled-float(index[c]);
}
for(int c=0;c<3;c++) {
float sum=0;
for(int k=0;k<8;k++) {
int x=k&1,y=(k>>1)&1,z=(k>>2)&1;
sum+=table[(((index[2]+z)*n+index[1]+y)*n+index[0]+x)*4+c]
*(x?fraction[0]:1-fraction[0])*(y?fraction[1]:1-fraction[1])*(z?fraction[2]:1-fraction[2]);
}
out[c]=sum;
}
}
static BOOL DYLUTParse(NSString *path,std::vector<float>& data,NSUInteger& size,NSError **error) {
data.clear();size=0;
NSDictionary *attributes=[[NSFileManager defaultManager]attributesOfItemAtPath:path error:error];
if(!attributes)return NO;
if(![attributes[NSFileType]isEqual:NSFileTypeRegular])return DYLUTFail(error,@"LUT 必须是普通文件");
if([attributes[NSFileSize]unsignedLongLongValue]>256ULL*1024*1024)return DYLUTFail(error,@"LUT 文件超过 256 MB 限制");
NSData *bytes=[NSData dataWithContentsOfFile:path options:NSDataReadingMappedIfSafe error:error];
if(!bytes)return NO;
if([path.pathExtension.lowercaseString isEqual:@"dylut"]) {
if(bytes.length<36||memcmp(bytes.bytes,"DYLT",4))return DYLUTFail(error,@"输入 LUT 格式损坏");
uint32_t n=0,count=0;memcpy(&n,(const uint8_t *)bytes.bytes+4,4);memcpy(&count,(const uint8_t *)bytes.bytes+8,4);
if(n<2||n>128||count!=n*n*n*16)return DYLUTFail(error,@"输入 LUT 尺寸无效");
data.resize(count/4);uLongf length=count;
if(uncompress((Bytef *)data.data(),&length,(const Bytef *)bytes.bytes+36,bytes.length-36)!=Z_OK||length!=count)
return DYLUTFail(error,@"输入 LUT 解压失败");
for(float v:data)if(!std::isfinite(v))return DYLUTFail(error,@"输入 LUT 含无效数字");
size=n;return YES;
}
NSString *text=[[[NSString alloc]initWithData:bytes encoding:NSUTF8StringEncoding]autorelease];
if(!text)return DYLUTFail(error,@"LUT 必须是 UTF-8 文本");
float domainMin[3]={0,0,0},domainMax[3]={1,1,1};
BOOL foundSize=NO;
for(NSString *line in [text componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet]) {
NSString *clean=[[[line componentsSeparatedByString:@"#"]firstObject]stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];
if(!clean.length)continue;
const char *c=clean.UTF8String;int n=0;float r,g,b;
if(sscanf(c,"LUT_3D_SIZE %d",&n)==1) {
if(foundSize||n<2||n>128)return DYLUTFail(error,@"LUT 尺寸应为 2–128,且只能声明一次");
size=n;foundSize=YES;data.reserve(size*size*size*4);
} else if(sscanf(c,"DOMAIN_MIN %f %f %f",&r,&g,&b)==3) {
domainMin[0]=r;domainMin[1]=g;domainMin[2]=b;
} else if(sscanf(c,"DOMAIN_MAX %f %f %f",&r,&g,&b)==3) {
domainMax[0]=r;domainMax[1]=g;domainMax[2]=b;
} else if(sscanf(c,"%f %f %f",&r,&g,&b)==3) {
if(!std::isfinite(r)||!std::isfinite(g)||!std::isfinite(b))return DYLUTFail(error,@"LUT 含无效数字");
data.insert(data.end(),{r,g,b,1});
if(data.size()>128*128*128*4)return DYLUTFail(error,@"LUT 数据过多");
} else if([clean hasPrefix:@"LUT_1D_SIZE"])return DYLUTFail(error,@"请选择三维 .cube LUT");
else if(![clean hasPrefix:@"TITLE"]&&![clean hasPrefix:@"LUT_3D_INPUT_RANGE"])
return DYLUTFail(error,[NSString stringWithFormat:@"无法解析 LUT 行:%@",[clean substringToIndex:MIN(clean.length,(NSUInteger)80)]]);
}
if(size<2||data.size()!=size*size*size*4)return DYLUTFail(error,@"LUT 数据数量与尺寸不符");
bool resample=false;
for(int c=0;c<3;c++) {
if(!std::isfinite(domainMin[c])||!std::isfinite(domainMax[c])||domainMax[c]<=domainMin[c])return DYLUTFail(error,@"LUT DOMAIN 范围无效");
resample|=domainMin[c]!=0||domainMax[c]!=1;
}
if(resample) {
std::vector<float> original=data;
for(NSUInteger z=0;z<size;z++)for(NSUInteger y=0;y<size;y++)for(NSUInteger x=0;x<size;x++) {
float rgb[3]={(float(x)/(size-1)-domainMin[0])/(domainMax[0]-domainMin[0]),
(float(y)/(size-1)-domainMin[1])/(domainMax[1]-domainMin[1]),
(float(z)/(size-1)-domainMin[2])/(domainMax[2]-domainMin[2])};
float sample[3];DYLUTSample(original,size,rgb,sample);
size_t dest=((z*size+y)*size+x)*4;for(int c=0;c<3;c++)data[dest+c]=sample[c];
}
}
return YES;
}
BOOL DYLUTReadCube(NSString *path,std::vector<float>& data,NSUInteger& size,NSError **error) {
data.clear();size=0;
if(!path.length)return DYLUTFail(error,@"未选择 LUT 文件");
NSDictionary *a=[[NSFileManager defaultManager]attributesOfItemAtPath:path error:error];
if(!a)return NO;
NSString *key=[NSString stringWithFormat:@"%@|%.9f|%@|%@",path.stringByStandardizingPath,[a[NSFileModificationDate]timeIntervalSinceReferenceDate],a[NSFileSize],a[NSFileSystemFileNumber]];
DYLUTTable *cached=[DYLUTTableCache()objectForKey:key];
if(cached){data=cached->values;size=cached->dimension;return YES;}
std::vector<float> parsed;NSUInteger n=0;
if(!DYLUTParse(path,parsed,n,error))return NO;
DYLUTTable *table=[[[DYLUTTable alloc]init]autorelease];table->values=std::move(parsed);table->dimension=n;
[DYLUTTableCache()setObject:table forKey:key cost:table->values.size()*sizeof(float)];
data=table->values;size=n;return YES;
}
NSData *DYLUTTransformRGBA(NSData *source,NSUInteger width,NSUInteger height,NSString *path,NSError **error) {
if(!width||!height||width>8192||height>8192||width*height>8192*8192||source.length!=width*height*16) {
DYLUTFail(error,@"缩略图源必须是有效的 float RGBA 图像");return nil;
}
std::vector<float> table;NSUInteger n=0;
if(path.length&&!DYLUTReadCube(path,table,n,error))return nil;
NSMutableData *result=[NSMutableData dataWithLength:source.length];
const float *input=(const float *)source.bytes;float *output=(float *)result.mutableBytes;
for(NSUInteger i=0;i<width*height;i++) {
const float *p=input+i*4;float *q=output+i*4;
if(!std::isfinite(p[0])||!std::isfinite(p[1])||!std::isfinite(p[2])||!std::isfinite(p[3])||p[3]<=0)continue;
if(n)DYLUTSample(table,n,p,q);else for(int c=0;c<3;c++)q[c]=p[c];
q[3]=std::min(1.f,std::max(0.f,p[3]));
}
return result;
}
static NSData *DYLUTFallback(void) {
static NSData *chart;static dispatch_once_t once;
dispatch_once(&once,^{
NSMutableData *data=[NSMutableData dataWithLength:320*180*16];float *p=(float *)data.mutableBytes;
const float swatches[][3]={{.74,.43,.33},{.49,.31,.25},{.95,.80,.67},{.82,.71,.51},{.16,.51,.75},{.24,.67,.35},{.94,.22,.18},{.14,.18,.33}};
for(NSUInteger y=0;y<180;y++)for(NSUInteger x=0;x<320;x++) {
float t=float(x)/319;float *q=p+(y*320+x)*4;
if(y<45)q[0]=q[1]=q[2]=t;
else if(y<90){q[0]=t;q[1]=1-t;q[2]=.31;}
else if(y<135){for(int c=0;c<3;c++)q[c]=swatches[std::min((NSUInteger)7,x*8/320)][c];}
else{q[0]=t;q[1]=t*t;q[2]=sqrtf(t);}
q[3]=1;
}
chart=[data copy];
});return chart;
}
NSImage *DYLUTThumbnail(NSString *path,NSData *source,NSUInteger sourceWidth,NSUInteger sourceHeight,NSSize outputSize,NSError **error) {
if(!std::isfinite(outputSize.width)||!std::isfinite(outputSize.height)||outputSize.width<1||outputSize.height<1||outputSize.width>2048||outputSize.height>2048) {
DYLUTFail(error,@"缩略图尺寸无效");return nil;
}
if(!source){source=DYLUTFallback();sourceWidth=320;sourceHeight=180;}
NSData *transformed=DYLUTTransformRGBA(source,sourceWidth,sourceHeight,path,error);if(!transformed)return nil;
NSUInteger width=(NSUInteger)llround(outputSize.width),height=(NSUInteger)llround(outputSize.height);
NSBitmapImageRep *bitmap=[[[NSBitmapImageRep alloc]initWithBitmapDataPlanes:NULL pixelsWide:width pixelsHigh:height
bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES isPlanar:NO colorSpaceName:NSDeviceRGBColorSpace
bitmapFormat:NSBitmapFormatAlphaNonpremultiplied bytesPerRow:width*4 bitsPerPixel:32]autorelease];
if(!bitmap){DYLUTFail(error,@"无法分配缩略图位图");return nil;}
const float *p=(const float *)transformed.bytes;uint8_t *q=bitmap.bitmapData;
for(NSUInteger y=0;y<height;y++)for(NSUInteger x=0;x<width;x++) {
// Center-aligned bilinear scaling, independent of NSGraphicsContext.
float fx=(float(x)+.5f)*sourceWidth/width-.5f,fy=(float(y)+.5f)*sourceHeight/height-.5f;
fx=std::max(0.f,std::min(float(sourceWidth-1),fx));fy=std::max(0.f,std::min(float(sourceHeight-1),fy));
NSUInteger x0=(NSUInteger)fx,y0=(NSUInteger)fy,x1=std::min(sourceWidth-1,x0+1),y1=std::min(sourceHeight-1,y0+1);
float tx=fx-x0,ty=fy-y0;
for(int c=0;c<4;c++) {
float v=(p[(y0*sourceWidth+x0)*4+c]*(1-tx)+p[(y0*sourceWidth+x1)*4+c]*tx)*(1-ty)
+(p[(y1*sourceWidth+x0)*4+c]*(1-tx)+p[(y1*sourceWidth+x1)*4+c]*tx)*ty;
q[(y*width+x)*4+c]=(uint8_t)lroundf(std::max(0.f,std::min(1.f,v))*255);
}
}
NSImage *image=[[[NSImage alloc]initWithSize:NSMakeSize(width,height)]autorelease];[image addRepresentation:bitmap];return image;
}
static NSString *DYLUTRelativeFolder(NSString *path,NSString *root) {
NSString *parent=path.stringByDeletingLastPathComponent;
if([parent isEqual:root])return @"";
NSString *prefix=[root stringByAppendingString:@"/"];
return [parent hasPrefix:prefix]?[parent substringFromIndex:prefix.length]:@"";
}
static NSDictionary *DYLUTEntry(NSURL *url,NSURL *root) {
NSString *path=url.path,*base=root.path;
NSString *relative=[path hasPrefix:[base stringByAppendingString:@"/"]]?[path substringFromIndex:base.length+1]:path.lastPathComponent;
return @{@"name":path.lastPathComponent.stringByDeletingPathExtension,@"path":path,
@"relativeFolder":DYLUTRelativeFolder(path,base),@"relativePath":relative};
}
static BOOL DYLUTOrdinaryURL(NSURL *url,BOOL *directory,NSError **error) {
NSNumber *isDirectory=nil,*isRegular=nil,*isLink=nil;
if(![url getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:error]||
![url getResourceValue:&isRegular forKey:NSURLIsRegularFileKey error:error]||
![url getResourceValue:&isLink forKey:NSURLIsSymbolicLinkKey error:error])return NO;
if(isLink.boolValue||(!isDirectory.boolValue&&!isRegular.boolValue))return DYLUTFail(error,@"不导入符号链接或特殊文件");
if(directory)*directory=isDirectory.boolValue;return YES;
}
static BOOL DYLUTEnsureDirectory(NSURL *directory,NSURL *root,NSError **error) {
NSString *prefix=[root.path stringByAppendingString:@"/"];
if(![directory.path isEqual:root.path]&&![directory.path hasPrefix:prefix])return DYLUTFail(error,@"LUT 目标路径超出目录边界");
NSFileManager *fm=NSFileManager.defaultManager;
if(![fm fileExistsAtPath:root.path]&&![fm createDirectoryAtURL:root withIntermediateDirectories:YES attributes:nil error:error])return NO;
NSDictionary *attributes=[fm attributesOfItemAtPath:root.path error:error];
if(![attributes[NSFileType]isEqual:NSFileTypeDirectory])return DYLUTFail(error,@"LUT 库根目录不是普通文件夹");
NSString *relative=[directory.path isEqual:root.path]?@"":[directory.path substringFromIndex:prefix.length];
NSURL *current=root;
for(NSString *component in relative.pathComponents) {
if(!component.length)continue;
current=[current URLByAppendingPathComponent:component isDirectory:YES];
NSDictionary *existing=[fm attributesOfItemAtPath:current.path error:NULL];
if(existing) {
if(![existing[NSFileType]isEqual:NSFileTypeDirectory])return DYLUTFail(error,@"LUT 目标文件夹含符号链接或非目录项");
} else if(![fm createDirectoryAtURL:current withIntermediateDirectories:NO attributes:nil error:error])return NO;
}
return YES;
}
@interface DYLUTLibrary () {
NSURL *_rootURL;
NSArray *_entries,*_folders;
NSMutableSet *_favoritePaths;
}
@end
@implementation DYLUTLibrary
+ (NSURL *)defaultRootURL {return [NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Movies/大鱼调色LUT/look LUTs"] isDirectory:YES];}
- (instancetype)init {return [self initWithRootURL:self.class.defaultRootURL];}
- (instancetype)initWithRootURL:(NSURL *)rootURL {
if(!rootURL.isFileURL||!rootURL.path.length){[self release];return nil;}
if((self=[super init])) {
_rootURL=[DYLUTCanonicalURL(rootURL)copy];_entries=[@[]copy];_folders=[@[@""]copy];_favoritePaths=[NSMutableSet new];
NSDictionary *saved=[NSDictionary dictionaryWithContentsOfURL:[_rootURL URLByAppendingPathComponent:@".favorites.plist"]];
NSArray *relativePaths=[saved[@"relativePaths"]isKindOfClass:NSArray.class]?saved[@"relativePaths"]:@[];
for(NSString *path in relativePaths)if([path isKindOfClass:NSString.class]&&![path isAbsolutePath]&&![path.pathComponents containsObject:@".."]) [_favoritePaths addObject:[_rootURL.path stringByAppendingPathComponent:path]];
}return self;
}
- (void)dealloc {[_rootURL release];[_entries release];[_folders release];[_favoritePaths release];[super dealloc];}
- (NSURL *)rootURL {return [[_rootURL copy]autorelease];}
- (NSArray *)entries {@synchronized(self){return [[_entries copy]autorelease];}}
- (NSArray *)folders {@synchronized(self){return [[_folders copy]autorelease];}}
- (NSSet *)favoritePaths {@synchronized(self){return [[_favoritePaths copy]autorelease];}}
- (BOOL)reload:(NSError **)error {@synchronized(self){
BOOL isDirectory=NO;NSFileManager *fm=NSFileManager.defaultManager;
if(![fm fileExistsAtPath:_rootURL.path isDirectory:&isDirectory]){[_entries release];_entries=[@[]copy];[_folders release];_folders=[@[@""]copy];return YES;}
if(!isDirectory||!DYLUTOrdinaryURL(_rootURL,NULL,error))return DYLUTFail(error,@"LUT 库目录无效");
NSMutableArray *entries=[NSMutableArray array];NSMutableSet *folders=[NSMutableSet setWithObject:@""];
__block NSError *scanError=nil;
NSDirectoryEnumerator *enumerator=[fm enumeratorAtURL:_rootURL includingPropertiesForKeys:@[NSURLIsDirectoryKey,NSURLIsRegularFileKey,NSURLIsSymbolicLinkKey] options:NSDirectoryEnumerationSkipsHiddenFiles|NSDirectoryEnumerationSkipsPackageDescendants errorHandler:^BOOL(NSURL *url,NSError *e){(void)url;scanError=e;return NO;}];
for(NSURL *url in enumerator) {
NSNumber *link=nil;[url getResourceValue:&link forKey:NSURLIsSymbolicLinkKey error:NULL];
if(link.boolValue){[enumerator skipDescendants];continue;}
BOOL directory=NO;if(!DYLUTOrdinaryURL(url,&directory,NULL))continue;
if(![url.path hasPrefix:[_rootURL.path stringByAppendingString:@"/"]])return DYLUTFail(error,@"LUT 库文件路径超出目录边界");
if(directory){NSString *relative=[url.path substringFromIndex:_rootURL.path.length+1];[folders addObject:relative];continue;}
if([url.pathExtension.lowercaseString isEqual:@"cube"])[entries addObject:DYLUTEntry(url,_rootURL)];
if(entries.count>10000)return DYLUTFail(error,@"LUT 库超过 10,000 个文件限制");
}
if(scanError){if(error)*error=scanError;return NO;}
[entries sortUsingComparator:^NSComparisonResult(NSDictionary *a,NSDictionary *b){return [a[@"relativePath"]localizedStandardCompare:b[@"relativePath"]];}];
[_entries release];_entries=[entries copy];[_folders release];_folders=[[folders.allObjects sortedArrayUsingSelector:@selector(localizedStandardCompare:)]copy];return YES;
}}
- (NSArray *)importURLs:(NSArray<NSURL *> *)urls error:(NSError **)error {@synchronized(self){
NSFileManager *fm=NSFileManager.defaultManager;NSMutableArray *plans=[NSMutableArray array];
NSString *root=_rootURL.path;
for(NSURL *sourceURL in urls) {
if(!sourceURL.isFileURL){DYLUTFail(error,@"只能导入本机 LUT 文件");return nil;}
NSURL *source=[sourceURL URLByStandardizingPath];BOOL directory=NO;
if(!DYLUTOrdinaryURL(source,&directory,error))return nil;
// NSDirectoryEnumerator canonicalizes /var to /private/var on macOS.
// Canonicalize both sides before calculating a relative path.
source=DYLUTCanonicalURL(source);
if([source.path isEqual:root]||[source.path hasPrefix:[root stringByAppendingString:@"/"]]){DYLUTFail(error,@"此 LUT 已位于浏览库中");return nil;}
if(!directory) {
if(![source.pathExtension.lowercaseString isEqual:@"cube"]){DYLUTFail(error,@"请选择 .cube 文件或包含它们的文件夹");return nil;}
[plans addObject:@{@"source":source,@"relative":source.lastPathComponent}];
} else {
__block NSError *scanError=nil;
NSDirectoryEnumerator *enumerator=[fm enumeratorAtURL:source includingPropertiesForKeys:@[NSURLIsSymbolicLinkKey,NSURLIsDirectoryKey,NSURLIsRegularFileKey] options:NSDirectoryEnumerationSkipsHiddenFiles|NSDirectoryEnumerationSkipsPackageDescendants errorHandler:^BOOL(NSURL *url,NSError *e){(void)url;scanError=e;return NO;}];
for(NSURL *file in enumerator) {
NSNumber *link=nil;[file getResourceValue:&link forKey:NSURLIsSymbolicLinkKey error:NULL];
if(link.boolValue){[enumerator skipDescendants];continue;}
BOOL subdirectory=NO;if(!DYLUTOrdinaryURL(file,&subdirectory,NULL)||subdirectory||![file.pathExtension.lowercaseString isEqual:@"cube"])continue;
if(![file.path hasPrefix:[source.path stringByAppendingString:@"/"]]){DYLUTFail(error,@"导入文件路径超出目录边界");return nil;}
NSString *relative=[source.lastPathComponent stringByAppendingPathComponent:[file.path substringFromIndex:source.path.length+1]];
[plans addObject:@{@"source":file,@"relative":relative}];
if(plans.count>10000){DYLUTFail(error,@"单次导入超过 10,000 个 LUT 限制");return nil;}
}
if(scanError){if(error)*error=scanError;return nil;}
}
}
if(!plans.count){DYLUTFail(error,@"没有找到可导入的 .cube 文件");return nil;}
// Validate every source before writing the library, preserving existing files.
for(NSDictionary *plan in plans){std::vector<float> values;NSUInteger n=0;if(!DYLUTReadCube([plan[@"source"]path],values,n,error))return nil;}
if(!DYLUTEnsureDirectory(_rootURL,_rootURL,error))return nil;
NSMutableArray *created=[NSMutableArray array],*imported=[NSMutableArray array];BOOL success=YES;
for(NSDictionary *plan in plans) {
NSURL *destination=[_rootURL URLByAppendingPathComponent:plan[@"relative"]];
if(!DYLUTEnsureDirectory(destination.URLByDeletingLastPathComponent,_rootURL,error)){success=NO;break;}
NSString *stem=destination.path.stringByDeletingPathExtension,*extension=destination.pathExtension;
NSUInteger suffix=1;
while([fm fileExistsAtPath:destination.path])destination=[NSURL fileURLWithPath:[NSString stringWithFormat:@"%@ %lu.%@",stem,(unsigned long)++suffix,extension]];
if(![fm copyItemAtURL:plan[@"source"] toURL:destination error:error]){success=NO;break;}
[created addObject:destination];
std::vector<float> values;NSUInteger n=0;if(!DYLUTReadCube(destination.path,values,n,error)){success=NO;break;}
[imported addObject:DYLUTEntry(destination,_rootURL)];
}
if(!success){for(NSURL *url in created)[fm removeItemAtURL:url error:NULL];return nil;}
if(![self reload:error])return nil;return imported;
}}
- (BOOL)isFavoritePath:(NSString *)path {@synchronized(self){return [_favoritePaths containsObject:path];}}
- (BOOL)setFavorite:(BOOL)favorite forPath:(NSString *)path error:(NSError **)error {@synchronized(self){
NSString *prefix=[_rootURL.path stringByAppendingString:@"/"];
if(![path hasPrefix:prefix]||[path.pathComponents containsObject:@".."])return DYLUTFail(error,@"只能收藏浏览库中的 LUT");
NSMutableSet *next=[[_favoritePaths mutableCopy]autorelease];if(favorite)[next addObject:path];else[next removeObject:path];
NSMutableArray *relative=[NSMutableArray array];for(NSString *p in next)[relative addObject:[p substringFromIndex:prefix.length]];
[relative sortUsingSelector:@selector(localizedStandardCompare:)];
if(!DYLUTEnsureDirectory(_rootURL,_rootURL,error))return NO;
NSData *data=[NSPropertyListSerialization dataWithPropertyList:@{@"relativePaths":relative} format:NSPropertyListXMLFormat_v1_0 options:0 error:error];
if(!data||![data writeToURL:[_rootURL URLByAppendingPathComponent:@".favorites.plist"] options:NSDataWritingAtomic error:error])return NO;
[_favoritePaths release];_favoritePaths=[next mutableCopy];return YES;
}}
@end
+1 -1
查看文件
@@ -13,7 +13,7 @@
- (BOOL)properties:(NSDictionary**)p error:(NSError**)e{*p=@{kFxPropertyKey_MayRemapTime:@NO,kFxPropertyKey_PixelTransformSupport:@(kFxPixelTransform_ScaleTranslate),kFxPropertyKey_VariesWhenParamsAreStatic:@NO,kFxPropertyKey_DesiredProcessingColorInfo:@(kFxImageColorInfo_RGB_LINEAR),kFxPropertyKey_NeedsFullBuffer:@YES};return YES;}
- (BOOL)addParametersWithError:(NSError**)e{return DYCreateParameters(_apiManager,e);}
- (NSSet<Class>*)classesForCustomParameterID:(UInt32)pid{return pid==DYAssetsParameterID?[NSSet setWithObjects:DYAssetState.class,NSDictionary.class,NSString.class,nil]:[NSSet setWithObject:DYInspectorToken.class];}
- (NSView*)createViewForParameterID:(UInt32)pid{return pid==DYInspectorParameterID?[[DYInspector alloc]initWithAPIManager:_apiManager]:[[NSView alloc]initWithFrame:NSZeroRect];}
- (NSView*)createViewForParameterID:(UInt32)pid{return pid==DYInspectorParameterID?[[DYInspector alloc]initWithAPIManager:_apiManager renderer:_renderer]:[[NSView alloc]initWithFrame:NSZeroRect];}
- (BOOL)parameterChanged:(UInt32)pid atTime:(CMTime)t error:(NSError**)e{if(pid==2013||pid==2014||pid==DYAssetsParameterID)[_renderer invalidatePreview];dispatch_async(dispatch_get_main_queue(),^{[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:self.apiManager];});return YES;}
- (BOOL)pluginState:(NSData**)state atTime:(CMTime)t quality:(FxQuality)q error:(NSError**)e{
DYUniforms u;DYReadUniforms(_apiManager,t,&u);DYAssetState*a=DYReadAssets(_apiManager,t);double copyAuto=0;[[_apiManager apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)]getFloatValue:&copyAuto fromParameter:8800 atTime:t];NSDictionary*s=@{@"schema":@1,@"copyAuto":@(copyAuto>.5),@"uniforms":[NSData dataWithBytes:&u length:sizeof(u)],@"paths":a.paths?:@{}};*state=[NSPropertyListSerialization dataWithPropertyList:s format:NSPropertyListBinaryFormat_v1_0 options:0 error:e];return *state!=nil;
+4 -24
查看文件
@@ -1,5 +1,6 @@
#import "DYRenderer.h"
#import "DYColorTables.h"
#import "DYLUTLibrary.h"
#import <QuartzCore/QuartzCore.h>
#include <zlib.h>
#include <vector>
@@ -7,27 +8,6 @@
static BOOL fail(NSError**e,NSString*m){if(e)*e=[NSError errorWithDomain:@"com.dayu.color" code:1 userInfo:@{NSLocalizedDescriptionKey:m?:@"Metal 调色失败"}];return NO;}
static NSArray *inputFiles(){return @[@"",@"apple_log_to_rec709",@"arri_logc3_to_rec709",@"arri_logc4_to_rec709",@"blackmagic_film_gen5_to_rec709",@"canon_clog_bt709_to_rec709",@"canon_clog2_cinema_gamut_to_rec709",@"canon_clog3_cinema_gamut_to_rec709",@"dji_dlog_to_rec709",@"dji_dlog_m_to_rec709",@"fujifilm_flog_to_rec709",@"fujifilm_flog2_to_rec709",@"nikon_nlog_to_rec709",@"panasonic_vlog_vgamut_to_rec709",@"red_log3g10_rwg_to_rec709",@"sony_slog2_sgamut_to_rec709",@"sony_slog3_sgamut3cine_to_rec709",@"sony_hlg_bt2020_to_rec709"];}
static id<MTLTexture> texture3D(id<MTLDevice>d,const float*values,NSUInteger n){MTLTextureDescriptor*t=[MTLTextureDescriptor new];t.textureType=MTLTextureType3D;t.pixelFormat=MTLPixelFormatRGBA32Float;t.width=n;t.height=n;t.depth=n;t.storageMode=MTLStorageModeShared;t.usage=MTLTextureUsageShaderRead;id<MTLTexture>x=[d newTextureWithDescriptor:t];[t release];if(x)[x replaceRegion:MTLRegionMake3D(0,0,0,n,n,n) mipmapLevel:0 slice:0 withBytes:values bytesPerRow:n*16 bytesPerImage:n*n*16];return [x autorelease];}
static BOOL loadCube(NSString*path,std::vector<float>&data,NSUInteger&size,NSError**err){
NSData*b=[NSData dataWithContentsOfFile:path options:NSDataReadingMappedIfSafe error:err];if(!b)return NO;
if([path.pathExtension.lowercaseString isEqual:@"dylut"]){
if(b.length<36||memcmp(b.bytes,"DYLT",4))return fail(err,@"输入 LUT 格式损坏");uint32_t n=0,bytes=0;memcpy(&n,(uint8_t*)b.bytes+4,4);memcpy(&bytes,(uint8_t*)b.bytes+8,4);if(n<2||n>128||bytes!=n*n*n*16)return fail(err,@"输入 LUT 尺寸无效");data.resize(bytes/4);uLongf len=bytes;if(uncompress((Bytef*)data.data(),&len,(Bytef*)b.bytes+36,b.length-36)!=Z_OK||len!=bytes)return fail(err,@"输入 LUT 解压失败");size=n;return YES;
}
NSString*s=[[[NSString alloc]initWithData:b encoding:NSUTF8StringEncoding]autorelease];if(!s)return fail(err,@"LUT 必须是 UTF-8 文本");
size=0;float domainMin[3]={0,0,0},domainMax[3]={1,1,1};
for(NSString*line in [s componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet]){
NSString*clean=[[[line componentsSeparatedByString:@"#"]firstObject]stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];if(!clean.length)continue;
const char*c=clean.UTF8String;int n=0;float r,g,bl;
if(sscanf(c,"LUT_3D_SIZE %d",&n)==1){if(n<2||n>128)return fail(err,@"LUT 尺寸应为 2–128");size=n;}
else if(sscanf(c,"DOMAIN_MIN %f %f %f",&r,&g,&bl)==3){domainMin[0]=r;domainMin[1]=g;domainMin[2]=bl;}
else if(sscanf(c,"DOMAIN_MAX %f %f %f",&r,&g,&bl)==3){domainMax[0]=r;domainMax[1]=g;domainMax[2]=bl;}
else if(sscanf(c,"%f %f %f",&r,&g,&bl)==3){if(!std::isfinite(r)||!std::isfinite(g)||!std::isfinite(bl))return fail(err,@"LUT 含无效数字");data.insert(data.end(),{r,g,bl,1});if(data.size()>128*128*128*4)return fail(err,@"LUT 数据过多");}
else if([clean hasPrefix:@"LUT_1D_SIZE"])return fail(err,@"请选择三维 .cube LUT");
}
if(size<2||data.size()!=size*size*size*4)return fail(err,@"LUT 数据数量与尺寸不符");
bool resample=false;for(int c=0;c<3;c++){if(!std::isfinite(domainMin[c])||!std::isfinite(domainMax[c])||domainMax[c]<=domainMin[c])return fail(err,@"LUT DOMAIN 范围无效");resample|=domainMin[c]!=0||domainMax[c]!=1;}
if(resample){std::vector<float>src=data;for(NSUInteger z=0;z<size;z++)for(NSUInteger y=0;y<size;y++)for(NSUInteger x=0;x<size;x++){float v[3];NSUInteger i[3];NSUInteger pos[3]={x,y,z};for(int c=0;c<3;c++){v[c]=fminf(1,fmaxf(0,(float(pos[c])/(size-1)-domainMin[c])/(domainMax[c]-domainMin[c])))*(size-1);i[c]=fmin(size-2,(NSUInteger)v[c]);v[c]-=i[c];}size_t dest=((z*size+y)*size+x)*4;for(int c=0;c<3;c++){float sum=0;for(int k=0;k<8;k++){int a=k&1,b=(k>>1)&1,d=(k>>2)&1;sum+=src[(((i[2]+d)*size+i[1]+b)*size+i[0]+a)*4+c]*(a?v[0]:1-v[0])*(b?v[1]:1-v[1])*(d?v[2]:1-v[2]);}data[dest+c]=sum;}}}
return YES;
}
@interface DYRenderer(){
NSMutableDictionary *_devices,*_luts;
DYColorTables *_tables;
@@ -53,8 +33,8 @@ static BOOL loadCube(NSString*path,std::vector<float>&data,NSUInteger&size,NSErr
- (id<MTLTexture>)lut:(NSString*)path entry:(NSDictionary*)e error:(NSError**)err{
if(!path.length)return e[@"identity"];
NSDictionary*attrs=[[NSFileManager defaultManager]attributesOfItemAtPath:path error:err];if(!attrs)return nil;
NSString*key=[NSString stringWithFormat:@"%llu|%@|%@|%@",[e[@"device"]registryID],path,attrs[NSFileModificationDate],attrs[NSFileSize]];id<MTLTexture>t=_luts[key];if(t)return t;
std::vector<float>v;NSUInteger n=0;if(!loadCube(path,v,n,err))return nil;t=texture3D(e[@"device"],v.data(),n);if(!t){fail(err,@"LUT 纹理分配失败");return nil;}if(_luts.count>=12)[_luts removeAllObjects];_luts[key]=t;return t;
NSString*key=[NSString stringWithFormat:@"%llu|%@|%.9f|%@|%@",[e[@"device"]registryID],path,[attrs[NSFileModificationDate]timeIntervalSinceReferenceDate],attrs[NSFileSize],attrs[NSFileSystemFileNumber]];id<MTLTexture>t=_luts[key];if(t)return t;
std::vector<float>v;NSUInteger n=0;if(!DYLUTReadCube(path,v,n,err))return nil;t=texture3D(e[@"device"],v.data(),n);if(!t){fail(err,@"LUT 纹理分配失败");return nil;}if(_luts.count>=12)[_luts removeAllObjects];_luts[key]=t;return t;
}
- (NSArray*)textures:(NSDictionary*)paths uniforms:(DYUniforms*)u entry:(NSDictionary*)e error:(NSError**)err{
NSString*input=paths[@"input"];int profile=(int)roundf(u->inputProfile);
@@ -80,7 +60,7 @@ static BOOL loadCube(NSString*path,std::vector<float>&data,NSUInteger&size,NSErr
DYVertex2D vs[]={{{w/2,-h/2},{r,bottom}},{{-w/2,-h/2},{l,bottom}},{{w/2,h/2},{r,top}},{{-w/2,h/2},{l,top}}};
if(dst.imageOrigin==kFxImageOrigin_BOTTOM_LEFT)for(int i=0;i<4;i++)vs[i].position.y=-vs[i].position.y;
vector_uint2 vp={(unsigned)output.width,(unsigned)output.height};[re setVertexBytes:vs length:sizeof(vs) atIndex:0];[re setVertexBytes:&vp length:sizeof(vp) atIndex:1];[re setViewport:(MTLViewport){0,0,w,h,0,1}];[re setFragmentTexture:straight atIndex:0];for(NSUInteger i=0;i<ts.count;i++)[re setFragmentTexture:ts[i] atIndex:i+1];[re setFragmentBytes:&u length:sizeof(u) atIndex:0];[re setFragmentBuffer:scene offset:0 atIndex:1];DYRenderOptions options={1,0,0,0};[re setFragmentBytes:&options length:sizeof(options) atIndex:2];[re drawPrimitives:MTLPrimitiveTypeTriangleStrip vertexStart:0 vertexCount:4];[re endEncoding];[cb commit];[cb waitUntilCompleted];BOOL ok=cb.status==MTLCommandBufferStatusCompleted;
if(ok&&pb){[_preview release];_preview=[[NSData alloc]initWithBytes:pb.contents length:320*180*16];_lastPreview=CACurrentMediaTime();}
if(ok&&pb){[_preview release];_preview=[[NSData alloc]initWithBytes:pb.contents length:320*180*16];_lastPreview=CACurrentMediaTime();dispatch_async(dispatch_get_main_queue(),^{[[NSNotificationCenter defaultCenter]postNotificationName:@"DYPreviewDidChange" object:self];});}
if(!ok)fail(err,cb.error.localizedDescription);[pb release];[straight release];[scene release];return ok;
}}}
- (BOOL)exportLUT:(NSURL*)url uniforms:(DYUniforms)u paths:(NSDictionary*)paths error:(NSError**)err{@synchronized(self){
+15 -8
查看文件
@@ -3,7 +3,7 @@
NSString *const DYThemeDidChange=@"DYThemeDidChange";
static NSString *const preferenceDomain=@"com.dayu.color.preferences";
static NSString *const distributedChange=@"com.dayu.color.theme.changed";
static NSColor *rgb(double r,double g,double b){return [NSColor colorWithSRGBRed:r green:g blue:b alpha:1];}
static NSColor *rgb(double r,double g,double b){return [NSColor colorWithCalibratedRed:r green:g blue:b alpha:1];}
@interface DYThemeStore : NSObject
@property(nonatomic,retain) NSUserDefaults *defaults;
@end
@@ -24,13 +24,20 @@ static NSColor *rgb(double r,double g,double b){return [NSColor colorWithSRGBRed
@end
static DYThemeStore *store(void){static DYThemeStore *s;static dispatch_once_t once;dispatch_once(&once,^{s=[DYThemeStore new];});return s;}
NSArray<NSString *> *DYThemeNames(void){return @[@"深空灰",@"冰川蓝",@"薰衣草紫",@"翡翠绿",@"琥珀橙"];}
NSInteger DYThemeIndex(void){return MAX(0,MIN(4,[store().defaults integerForKey:@"themeIndex"]));}
NSColor *DYThemeSwatch(NSInteger index){switch(index){case 0:return rgb(.36,.40,.45);case 2:return rgb(.67,.58,.97);case 3:return rgb(.29,.83,.57);case 4:return rgb(1,.66,.32);default:return rgb(.27,.73,.97);}}
void DYSetThemeIndex(NSInteger index){index=MAX(0,MIN(4,index));[store().defaults setInteger:index forKey:@"themeIndex"];[store().defaults synchronize];[[NSNotificationCenter defaultCenter]postNotificationName:DYThemeDidChange object:nil];[[NSDistributedNotificationCenter defaultCenter]postNotificationName:distributedChange object:preferenceDomain userInfo:nil deliverImmediately:YES];}
NSInteger DYThemeIndex(void){NSInteger i=[store().defaults integerForKey:@"themeIndex"];return i>=0&&i<5?i:1;}
static const double paletteRGB[5][17][3]={
{{0.11,0.12,0.14},{0.075,0.08,0.095},{0.17,0.18,0.21},{0.12,0.13,0.15},{0.27,0.29,0.33},{0.2,0.22,0.25},{0.36,0.39,0.44},{0.25,0.28,0.32},{0.21,0.23,0.26},{0.15,0.17,0.2},{0.78,0.83,0.9},{0.55,0.61,0.7},{1.0,1.0,1.0},{0.78,0.82,0.88},{0.96,0.97,0.98},{0.86,0.89,0.92},{0.67,0.72,0.77}},
{{0.031,0.086,0.148},{0.025,0.075,0.13},{0.07,0.155,0.235},{0.045,0.12,0.19},{0.115,0.22,0.33},{0.07,0.15,0.24},{0.15,0.33,0.5},{0.08,0.24,0.36},{0.23,0.32,0.41},{0.18,0.26,0.35},{0.38,0.76,1.0},{0.23,0.64,0.97},{0.96,0.98,1.0},{0.62,0.7,0.76},{0.88,0.96,1.0},{0.82,0.9,0.96},{0.58,0.7,0.78}},
{{0.11,0.09,0.17},{0.07,0.06,0.12},{0.18,0.14,0.28},{0.13,0.1,0.21},{0.27,0.22,0.42},{0.2,0.16,0.31},{0.43,0.34,0.68},{0.31,0.23,0.52},{0.22,0.18,0.31},{0.15,0.12,0.23},{0.78,0.71,1.0},{0.5,0.42,0.93},{0.95,0.9,1.0},{0.63,0.5,0.95},{0.98,0.95,1.0},{0.9,0.86,0.97},{0.7,0.66,0.82}},
{{0.08,0.17,0.1},{0.05,0.12,0.07},{0.12,0.27,0.15},{0.09,0.2,0.11},{0.16,0.35,0.2},{0.12,0.27,0.15},{0.21,0.57,0.31},{0.14,0.4,0.21},{0.14,0.27,0.16},{0.1,0.2,0.11},{0.54,0.96,0.64},{0.22,0.75,0.35},{0.91,1.0,0.93},{0.28,0.8,0.42},{0.95,1.0,0.96},{0.86,0.96,0.88},{0.66,0.8,0.68}},
{{0.23,0.15,0.08},{0.16,0.1,0.05},{0.35,0.22,0.11},{0.26,0.16,0.08},{0.45,0.28,0.14},{0.36,0.22,0.1},{0.72,0.44,0.18},{0.56,0.32,0.12},{0.29,0.18,0.09},{0.2,0.12,0.06},{0.98,0.67,0.31},{0.86,0.47,0.17},{1.0,0.86,0.57},{0.93,0.59,0.22},{1.0,0.96,0.9},{0.97,0.9,0.82},{0.8,0.7,0.58}}
};
NSColor *DYThemeSwatch(NSInteger index){static const double values[5][3]={{.30,.33,.38},{.28,.72,1},{.58,.52,1},{.30,.86,.52},{1,.61,.28}};index=MAX(0,MIN(4,index));return rgb(values[index][0],values[index][1],values[index][2]);}
void DYSetThemeIndex(NSInteger index){if(index<0||index>4)return;[store().defaults setInteger:index forKey:@"themeIndex"];[store().defaults synchronize];[[NSNotificationCenter defaultCenter]postNotificationName:DYThemeDidChange object:nil];[[NSDistributedNotificationCenter defaultCenter]postNotificationName:distributedChange object:preferenceDomain userInfo:nil deliverImmediately:YES];}
NSDictionary<NSString *,NSColor *> *DYThemePalette(void){
NSInteger index=DYThemeIndex();NSColor *accent=DYThemeSwatch(index);
double background[5][3]={{.085,.09,.10},{.018,.074,.12},{.065,.042,.13},{.022,.10,.073},{.14,.073,.028}};
double card[5][3]={{.14,.15,.17},{.045,.135,.20},{.12,.084,.21},{.044,.17,.12},{.21,.126,.063}};
return @{@"background":rgb(background[index][0],background[index][1],background[index][2]),@"card":rgb(card[index][0],card[index][1],card[index][2]),@"border":[accent colorWithAlphaComponent:.42],@"text":rgb(.86,.93,.97),@"secondary":rgb(.61,.71,.78),@"accent":accent,@"field":[rgb(card[index][0],card[index][1],card[index][2]) blendedColorWithFraction:.14 ofColor:accent]};
NSInteger index=DYThemeIndex();const double (*p)[3]=paletteRGB[index];
NSMutableDictionary *d=[NSMutableDictionary dictionary];for(int i=0;i<17;i++)d[[NSString stringWithFormat:@"slot%d",i]]=rgb(p[i][0],p[i][1],p[i][2]);
NSColor *accent=index==0?rgb(.72,.77,.84):index==1?rgb(.22,.67,1):DYThemeSwatch(index);
[d addEntriesFromDictionary:@{@"background":d[@"slot1"],@"card":d[@"slot3"],@"border":[accent colorWithAlphaComponent:.38],@"text":d[@"slot14"],@"secondary":d[@"slot16"],@"accent":accent,@"field":d[@"slot4"],@"headerTop":d[@"slot6"],@"headerBottom":d[@"slot7"],@"track":d[@"slot8"],@"activeTop":d[@"slot10"],@"activeBottom":d[@"slot11"],@"knob":d[@"slot12"]}];return d;
}
NSColor *DYThemeColor(NSString *role){return [NSColor colorWithName:[@"Dayu." stringByAppendingString:role] dynamicProvider:^NSColor *(NSAppearance *appearance){return DYThemePalette()[role]?:[NSColor whiteColor];}];}
+2 -2
查看文件
@@ -17,9 +17,9 @@
<key>CFBundlePackageType</key>
<string>XPC!</string>
<key>CFBundleShortVersionString</key>
<string>1.0.0</string>
<string>1.1.0</string>
<key>CFBundleVersion</key>
<string>2</string>
<string>3</string>
<key>NSHumanReadableCopyright</key>
<string></string>
<key>PlugInKit</key>
+2 -2
查看文件
@@ -17,9 +17,9 @@
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0.0</string>
<string>1.1.0</string>
<key>CFBundleVersion</key>
<string>2</string>
<string>3</string>
<key>LSMinimumSystemVersion</key>
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
<key>NSHumanReadableCopyright</key>